Programs & Examples On #Dns

Use this tag for programming questions related to writing code that interacts with the Domain Name System (DNS); for example, writing code that uses gethostbyname()

Set up DNS based URL forwarding in Amazon Route53

If you're still having issues with the simple approach, creating an empty bucket then Redirect all requests to another host name under Static web hosting in properties via the console. Ensure that you have set 2 A records in route53, one for final-destination.com and one for redirect-to.final-destination.com. The settings for each of these will be identical, but the name will be different so it matches the names that you set for your buckets / URLs.

How do I solve the "server DNS address could not be found" error on Windows 10?

Steps to manually configure DNS:

  1. You can access Network and Sharing center by right clicking on the Network icon on the taskbar.

  2. Now choose adapter settings from the side menu.

  3. This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.

  4. In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.

  5. Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.

    Select ‘use the following DNS address’ option. Now fill the following fields as given here.

    Preferred DNS server: 208.67.222.222

    Alternate DNS server : 208.67.220.220

    This is an available Open DNS address. You may also use google DNS server addresses.

    After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.

You have to add this DNS server address in the router configuration also (by referring the router manual for more information).

Refer : for above method & alternative

If none of this works, then open command prompt(Run as Administrator) and run these:

ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit

Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).

Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue

How do I get a list of all subdomains of a domain?

You can use:

$ host -l domain.com

Under the hood, this uses the AXFR query mentioned above. You might not be allowed to do this though. In that case, you'll get a transfer failed message.

jquery, domain, get URL

Similar to the answer before there there is

location.host

The location global has more fun facts about the current url as well. ( protocol, host, port, pathname, search, hash )

How to force DNS refresh for a website?

If both of your servers are using WHM, I think we can reduce the time to nil. Create your domain in the new server and set everything ready. Go to the previous server and delete the account corresponding to that domain. Until now I have got no errors by doing this and felt the update instantaneous. FYI I used hostgator hosting (both dedicated servers). And I really dont know why it is so. It's supposed to be not like that until the TTL is over.

htaccess redirect all pages to single page

Are you trying to get visitors to old.com/about.htm to go to new.com/about.htm? If so, you can do this with a mod_rewrite rule in .htaccess:

RewriteEngine on

RewriteRule ^(.*)$ http://www.thenewdomain.com/$1 [R=permanent,L]

How can I list ALL DNS records?

For Windows:

You may find the need to check the status of your domains DNS records, or check the Name Servers to see which records the servers are pulling.

  1. Launch Windows Command Prompt by navigating to Start > Command Prompt or via Run > CMD.

  2. Type NSLOOKUP and hit Enter. The default Server is set to your local DNS, the Address will be your local IP.

  3. Set the DNS Record type you wish to lookup by typing set type=## where ## is the record type, then hit Enter. You may use ANY, A, AAAA, A+AAAA, CNAME, MX, NS, PTR, SOA, or SRV as the record type.

  4. Now enter the domain name you wish to query then hit Enter.. In this example, we will use Managed.com.

  5. NSLOOKUP will now return the record entries for the domain you entered.

  6. You can also change the Name Servers which you are querying. This is useful if you are checking the records before DNS has fully propagated. To change the Name Server type server [name server]. Replace [name server] with the Name Servers you wish to use. In this example, we will set these as NSA.managed.com.

  7. Once changed, change the query type (Step 3) if needed then enter new a new domain (Step 4.)

For Linux:

1) Check DNS Records Using Dig Command Dig stands for domain information groper is a flexible tool for interrogating DNS name servers. It performs DNS lookups and displays the answers that are returned from the name server(s) that were queried. Most DNS administrators use dig to troubleshoot DNS problems because of its flexibility, ease of use and clarity of output. Other lookup tools tend to have less functionality than dig.

2) Check DNS Records Using NSlookup Command Nslookup is a program to query Internet domain name servers. Nslookup has two modes interactive and non-interactive.

Interactive mode allows the user to query name servers for information about various hosts and domains or to print a list of hosts in a domain.

Non-interactive mode is used to print just the name and requested information for a host or domain. It’s network administration tool which will help them to check and troubleshoot DNS related issues.

3) Check DNS Records Using Host Command host is a simple utility for performing DNS lookups. It is normally used to convert names to IP addresses and vice versa. When no arguments or options are given, host prints a short summary of its command line arguments and options.

DNS problem, nslookup works, ping doesn't

Do you have an entry for weddinglist in your hosts file? You can find this in:

C:\WINDOWS\system32\drivers\etc

nslookup always uses DNS whereas ping uses other methods for finding hostnames as well.

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

Using dig to search for SPF records

I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:

dig @ns1.nameserver1.com domain.com txt

How to redirect DNS to different ports

Since I had troubles understanding this post here is a simple explanation for people like me. It is useful if:

  • You DO NOT need Load Balacing.
  • You DO NOT want to use nginx to do port forwarding.
  • You DO want to do PORT FORWARDING according to specific subdomains using SRV record.

Then here is what you need to do:

SRV records:

_minecraft._tcp.1.12          IN SRV    1 100 25567 1.12.<your-domain-name.com>.
_minecraft._tcp.1.13          IN SRV    1 100 25566 1.13.<your-domain-name.com>.

(I did not need a srv record for 1.14 since my 1.14 minecraft server was already on the 25565 port which is the default port of minecraft.)

And the A records:

1.12                          IN A      <your server IP>
1.13                          IN A      <your server IP>
1.14                          IN A      <your server IP>

Does hosts file exist on the iPhone? How to change it?

It might exist, but you cannot change it on a non-jailbreaked iPhone.

Assuming that your development webserver is on a Mac, why don't you simply use its Bonjour name (e.g. MyMac.local.) instead of myrealwebserverontheinternet.com?

How to make Java honor the DNS Caching Timeout?

Per Byron's answer, you can't set networkaddress.cache.ttl or networkaddress.cache.negative.ttl as System Properties by using the -D flag or calling System.setProperty because these are not System properties - they are Security properties.

If you want to use a System property to trigger this behavior (so you can use the -D flag or call System.setProperty), you will want to set the following System property:

-Dsun.net.inetaddr.ttl=0

This system property will enable the desired effect.

But be aware: if you don't use the -D flag when starting the JVM process and elect to call this from code instead:

java.security.Security.setProperty("networkaddress.cache.ttl" , "0")

This code must execute before any other code in the JVM attempts to perform networking operations.

This is important because, for example, if you called Security.setProperty in a .war file and deployed that .war to Tomcat, this wouldn't work: Tomcat uses the Java networking stack to initialize itself much earlier than your .war's code is executed. Because of this 'race condition', it is usually more convenient to use the -D flag when starting the JVM process.

If you don't use -Dsun.net.inetaddr.ttl=0 or call Security.setProperty, you will need to edit $JRE_HOME/lib/security/java.security and set those security properties in that file, e.g.

networkaddress.cache.ttl = 0
networkaddress.cache.negative.ttl = 0

But pay attention to the security warnings in the comments surrounding those properties. Only do this if you are reasonably confident that you are not susceptible to DNS spoofing attacks.

Is it possible to have SSL certificate for IP address, not domain name?

Yep. Cloudflare uses it for its DNS instructions homepage: https://1.1.1.1

Get domain name

If you want specific users to have access to all or part of the WMI object space, you need to permission them as shown here. Note that you have to be running on as an admin to perform this setting.

Get IPv4 addresses from Dns.GetHostEntry()

    public static string GetIPAddress(string hostname)
    {
        IPHostEntry host;
        host = Dns.GetHostEntry(hostname);

        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            {
                //System.Diagnostics.Debug.WriteLine("LocalIPadress: " + ip);
                return ip.ToString();
            }
        }
        return string.Empty;
    }

Custom domain for GitHub project pages

The selected answer is the good one, but is long, so you might not read the key point:

I got an error with the SSL when accesign www.example.com but it worked fine if I go to example.com

If it happens the same to you, probably your error is that in the DNS configuration you have set:

CNAME www.example.com --> example.com  (WRONG)

But, what you have to do is:

CNAME www.example.com --> username.github.io  (GOOD)

or

CNAME www.example.com --> organization.github.io  (GOOD)

That was my error

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

If you're tired of this error. You can make Chrome not act out like this. I'm not saying it's the best way just saying it's a way.

As a workaround, a Windows registry key can be created to allow Google Chrome to use the commonName of a server certificate to match a hostname if the certificate is missing a subjectAlternativeName extension, as long as it successfully validates and chains to a locally-installed CA certificates.

Data type: Boolean [Windows:REG_DWORD] Windows registry location: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome Windows/Mac/Linux/Android preference name: EnableCommonNameFallbackForLocalAnchors Value: 0x00000001 (Windows), true(Linux), true (Android), (Mac) To create a Windows registry key, simply follow these steps:

Open Notepad Copy and paste the following content into notepad Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome] "EnableCommonNameFallbackForLocalAnchors"=dword:00000001 Go to File > Save as Filename: any_filename.reg Save as type: All Files

Select a preferred location for the file

Click on Save

Double click on the saved file to run

Click on Yes on the Registry Editor warning

Found this information on Symantec support page: https://support.symantec.com/en_US/article.TECH240507.html

what is the multicast doing on 224.0.0.251?

I deactivated my "Arno's Iptables Firewall" for testing, and then the messages are gone

Switch firefox to use a different DNS than what is in the windows.host file

I use this to override system's DNS with localserver
in about:config
change this value:

  • network.dns.forceResolve
  • network.dns.ipv4OnlyDomains
  • network.dns.localDomains
  • with IP address of local DNS server (for exsample 192.168.1.88)
    Sorry for my english

    How to redirect siteA to siteB with A or CNAME records

    Try changing it to "subdomain -> subdomain.hosttwo.com"

    The CNAME is an alias for a certain domain, so when you go to the control panel for hostone.com, you shouldn't have to enter the whole name into the CNAME alias.

    As far as the error you are getting, can you log onto subdomain.hostwo.com and check the logs?

    How do browser cookie domains work?

    The last (third to be exactly) RFC for this issue is RFC-6265 (Obsoletes RFC-2965 that in turn obsoletes RFC-2109).

    According to it if the server omits the Domain attribute, the user agent will return the cookie only to the origin server (the server on which a given resource resides). But it's also warning that some existing user agents treat an absent Domain attribute as if the Domain attribute were present and contained the current host name (For example, if example.com returns a Set-Cookie header without a Domain attribute, these user agents will erroneously send the cookie to www.example.com as well).

    When the Domain attribute have been specified, it will be treated as complete domain name (if there is the leading dot in attribute it will be ignored). Server should match the domain specified in attribute (have exactly the same domain name or to be a subdomain of it) to get this cookie. More accurately it specified here.

    So, for example:

    • cookie attribute Domain=.example.com is equivalent to Domain=example.com
    • cookies with such Domain attributes will be available for example.com and www.example.com
    • cookies with such Domain attributes will be not available for another-example.com
    • specifying cookie attribute like Domain=www.example.com will close the way for www4.example.com

    PS: trailing comma in Domain attribute will cause the user agent to ignore the attribute =(

    Wildcards in a Windows hosts file

    Acrylic DNS Proxy (free, open source) does the job. It creates a proxy DNS server (on your own computer) with its own hosts file. The hosts file accepts wildcards.

    Download from the offical website

    http://mayakron.altervista.org/support/browse.php?path=Acrylic&name=Home

    Configuring Acrylic DNS Proxy

    To configure Acrylic DNS Proxy, install it from the above link then go to:

    1. Start
    2. Programs
    3. Acrylic DNS Proxy
    4. Config
    5. Edit Custom Hosts File (AcrylicHosts.txt)

    Add the folowing lines on the end of the file:

    127.0.0.1   *.localhost
    127.0.0.1   *.local
    127.0.0.1   *.lc
    

    Restart the Acrylic DNS Proxy service:

    1. Start
    2. Programs
    3. Acrilic DNS Proxy
    4. Config
    5. Restart Acrylic Service

    You will also need to adjust your DNS setting in you network interface settings:

    1. Start
    2. Control Panel
    3. Network and Internet
    4. Network Connections
    5. Local Area Connection Properties
    6. TCP/IPv4

    Set "Use the following DNS server address":

    Preferred DNS Server: 127.0.0.1
    

    If you then combine this answer with jeremyasnyder's answer (using VirtualDocumentRoot) you can then automatically setup domains/virtual hosts by simply creating a directory.

    Python lookup hostname from IP with 1 second timeout

    What you're trying to accomplish is called Reverse DNS lookup.

    socket.gethostbyaddr("IP") 
    # => (hostname, alias-list, IP)
    

    http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

    However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

    How can I do DNS lookups in Python, including referring to /etc/hosts?

    Sounds like you don't want to resolve dns yourself (this might be the wrong nomenclature) dnspython appears to be a standalone dns client that will understandably ignore your operating system because its bypassing the operating system's utillities.

    We can look at a shell utility named getent to understand how the (debian 11 alike) operating system resolves dns for programs, this is likely the standard for all *nix like systems that use a socket implementation.

    see man getent's "hosts" section, which mentions the use of getaddrinfo, which we can see as man getaddrinfo

    and to use it in python, we have to extract some info from the data structures

    .

    import socket
    
    def get_ipv4_by_hostname(hostname):
        # see `man getent` `/ hosts `
        # see `man getaddrinfo`
    
        return list(
            i        # raw socket structure
                [4]  # internet protocol info
                [0]  # address
            for i in 
            socket.getaddrinfo(
                hostname,
                0  # port, required
            )
            if i[0] is socket.AddressFamily.AF_INET  # ipv4
    
            # ignore duplicate addresses with other socket types
            and i[1] is socket.SocketKind.SOCK_RAW  
        )
    
    print(get_ipv4_by_hostname('localhost'))
    print(get_ipv4_by_hostname('google.com'))
    

    Get protocol, domain, and port from URL

    window.location.origin will be enough to get the same.

    SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

    Do you specify a user name and password to log on? What exactly is your complete command line?

    If you're running on your own box, you can either specify a username/password, or use the -E parameter to log on with your Windows credentials (if those are permitted in your SQL server installation).

    Marc

    Can (domain name) subdomains have an underscore "_" in it?

    Just created local project (with vagrant) and it was working perfectly when accessed over ip address. Then I added some_name.test to hosts file and tried accessing it that way, but I was getting "bad request - 400" all the time. Wasted hours until I figured out that just changing domain name to some-name.test solves the problem. So at least locally on Mac OS it's not working.

    Regular expression to match DNS hostname or IP Address?

    To match a valid IP address use the following regex:

    (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}
    

    instead of:

    ([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3}
    

    Explanation

    Many regex engine match the first possibility in the OR sequence. For instance, try the following regex:

    10.48.0.200
    

    Test

    Test the difference between good vs bad

    How do I find the authoritative name-server for a domain name?

    The term you should be googling is "authoritative," not "definitive".

    On Linux or Mac you can use the commands whois, dig, host, nslookup or several others. nslookup might also work on Windows.

    An example:

    $ whois stackoverflow.com
    [...]
       Domain servers in listed order:
          NS51.DOMAINCONTROL.COM
          NS52.DOMAINCONTROL.COM
    

    As for the extra credit: Yes, it is possible.


    aryeh is definitely wrong, as his suggestion usually will only give you the IP address for the hostname. If you use dig, you have to look for NS records, like so:

    dig ns stackoverflow.com
    

    Keep in mind that this may ask your local DNS server and thus may give wrong or out-of-date answers that it has in its cache.

    .htaccess rewrite subdomain to directory

    For any sub domain request, use this:

    RewriteEngine on 
    RewriteCond %{HTTP_HOST} !^www\.band\.s\.co 
    RewriteCond %{HTTP_HOST} ^(.*)\.band\.s\.co 
    RewriteCond %{REQUEST_URI} !^/([a-zA-Z0-9-z\-]+) 
    RewriteRule ^(.*)$ /%1/$1 [L] 
    

    Just make some folder same as sub domain name you need. Folder must be exist like this: domain.com/sub for sub.domain.com.

    How can I set / change DNS using the command-prompt at windows 8

    Here is your new friend: QuickSetDNS, by NirSoft, amazing as usual.

    screenshot

    It also can be used in command line :) with these advantages over netsh:

    • easier syntax, in particular for setting the alternate server
    • automatically asks for privilege elevation


    Just a few caveats:

    • supports only setting of IPv4, not of IPv6
    • in command line, the adapter UUID should be used, not the friendly name (e.g. "Local Area Connection") since QuickSetDNS 1.21, connection names are also supported ;)

    How to simulate browsing from various locations?

    This is a bit of self promotion, but I built a tool to do just this that you might find useful, called GeoPeeker.

    It remotely accesses a site from servers spread around the world, renders the page with webkit and sends back an image. It will also report the IP address and DNS information of the site as it appears from that location.

    There are no ads, and it's very stream-lined to serve this one purpose. It's still in development, and feedback is welcome. Here's hoping somebody besides myself finds it useful!

    How to enable named/bind/DNS full logging?

    Run command rndc querylog on or add querylog yes; to options{}; section in named.conf to activate that channel.

    Also make sure you’re checking correct directory if your bind is chrooted.

    How to use Google App Engine with my own naked domain (not subdomain)?

    [update 2015-09-28] Now Google lets you add custom domains (including naked domains) and setup SSL without the need of Google Apps. For details refer to here: https://cloud.google.com/appengine/docs/using-custom-domains-and-ssl?hl=en

    I just discovered today (as of 2014-04-11) a new custom domain settings page is available from Google Developers Console:

    1. Go to https://console.developers.google.com/project 2. Click on your project 3. On the left click "App Engine" 4. Click "Settings"

    There you go! You can configure custom domain without the need of Google App account!

    How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

    I am now using Google Apps (for Email) and Heroku as web server. I am using Google Apps 301 Permanent Redirect feature to redirect the naked domain to WWW.your_domain.com

    You can find the step-by-step instructions here https://stackoverflow.com/a/20115583/1440255

    How is VIP swapping + CNAMEs better than IP swapping + A records?

    A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

    How to overcome root domain CNAME restrictions?

    The reason this question still often arises is because, as you mentioned, somewhere somehow someone presumed as important wrote that the RFC states domain names without subdomain in front of them are not valid. If you read the RFC carefully, however, you'll find that this is not exactly what it says. In fact, RFC 1912 states:

    Don't go overboard with CNAMEs. Use them when renaming hosts, but plan to get rid of them (and inform your users).

    Some DNS hosts provide a way to get CNAME-like functionality at the zone apex (the root domain level, for the naked domain name) using a custom record type. Such records include, for example:

    • ALIAS at DNSimple
    • ANAME at DNS Made Easy
    • ANAME at easyDNS
    • CNAME at CloudFlare

    For each provider, the setup is similar: point the ALIAS or ANAME entry for your apex domain to example.domain.com, just as you would with a CNAME record. Depending on the DNS provider, an empty or @ Name value identifies the zone apex.

    ALIAS or ANAME or @ example.domain.com.

    If your DNS provider does not support such a record-type, and you are unable to switch to one that does, you will need to use subdomain redirection, which is not that hard, depending on the protocol or server software that needs to do it.

    I strongly disagree with the statement that it's done only by "amateur admins" or such ideas. It's a simple "What does the name and its service need to do?" deal, and then to adapt your DNS config to serve those wishes; If your main services are web and e-mail, I don' t see any VALID reason why dropping the CNAMEs for-good would be problematic. After all, who would prefer @subdomain.domain.org over @domain.org ? Who needs "www" if you're already set with the protocol itself? It's illogical to assume that use of a root-domainname would be invalid.

    How to find Port number of IP address?

     domain = self.env['ir.config_parameter'].get_param('web.base.url')
    

    I got the hostname and port number using this.

    DNS caching in linux

    Here are two other software packages which can be used for DNS caching on Linux:

    • dnsmasq
    • bind

    After configuring the software for DNS forwarding and caching, you then set the system's DNS resolver to 127.0.0.1 in /etc/resolv.conf.

    If your system is using NetworkManager you can either try using the dns=dnsmasq option in /etc/NetworkManager/NetworkManager.conf or you can change your connection settings to Automatic (Address Only) and then use a script in the /etc/NetworkManager/dispatcher.d directory to get the DHCP nameserver, set it as the DNS forwarding server in your DNS cache software and then trigger a configuration reload.

    Is it possible that one domain name has multiple corresponding IP addresses?

    Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.

    Can I map a hostname *and* a port with /etc/hosts?

    If you really need to do this, use reverse proxy.

    For example, with nginx as reverse proxy

    server {
      listen       api.mydomain.com:80;
      server_name  api.mydomain.com;
      location / {
        proxy_pass http://127.0.0.1:8000;
      }
    }
    

    ping: google.com: Temporary failure in name resolution

    I've faced the exactly same problem but I've fixed it with another approache.

    Using Ubuntu 18.04, first disable systemd-resolved service.

    sudo systemctl disable systemd-resolved.service

    Stop the service

    sudo systemctl stop systemd-resolved.service

    Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

    sudo rm /etc/resolv.conf

    Add a manually created resolv.conf in /etc/

    sudo vim /etc/resolv.conf

    Add your prefered DNS server there

    nameserver 208.67.222.222

    I've tested this with success.

    How to configure heroku application DNS to Godaddy Domain?

    I pointed the non-www to 54.243.64.13 and the www.domain.com to the alias.herokuapp.com and all worked nicely.

    Found the IP only after pointing www.domain.com and then running the dig command on the www.domain.com and it showed:

    ;; ANSWER SECTION:
    www.domain.com. 14400  IN      CNAME   aliasat.herokuapp.com.
    aliasat.herokuapp.com. 300 IN CNAME us-east-1-a.route.herokuapp.com.
    us-east-1-a.route.herokuapp.com. 60 IN  A       54.235.186.37
    
    ;; AUTHORITY SECTION:
    herokuapp.com.          900     IN      NS      ns-1378.awsdns-44.org.
    herokuapp.com.          900     IN      NS      ns-1624.awsdns-11.co.uk.
    herokuapp.com.          900     IN      NS      ns-505.awsdns-63.com.
    herokuapp.com.          900     IN      NS      ns-662.awsdns-18.net.
    

    May not be ideal but worked.

    What is the difference between 127.0.0.1 and localhost

    some applications will treat "localhost" specially. the mysql client will treat localhost as a request to connect to the local unix domain socket instead of using tcp to connect to the server on 127.0.0.1. This may be faster, and may be in a different authentication zone.

    I don't know of other apps that treat localhost differently than 127.0.0.1, but there probably are some.

    How to filter wireshark to see only dns queries that are sent/received from/by my computer?

    Rather than using a DisplayFilter you could use a very simple CaptureFilter like

    port 53
    

    See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.

    Android: Flush DNS

    You have a few options:

    • Release an update for your app that uses a different hostname that isn't in anyone's cache.
    • Same thing, but using the IP address of your server
    • Have your users go into settings -> applications -> Network Location -> Clear data.

    You may want to check that last step because i don't know for a fact that this is the appropriate service. I can't really test that right now. Good luck!

    What's the source of Error: getaddrinfo EAI_AGAIN?

    As xerq's excellent answer explains, this is a DNS timeout issue.

    I wanted to contribute another possible answer for those of you using Windows Subsystem for Linux - there are some cases where something seems to be askew in the client OS after Windows resumes from sleep. Restarting the host OS will fix these issues (it's also likely restarting the WSL service will do the same).

    Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

    I know this question was asked a very long time ago, but I figured I'd offer a more recent answer.

    DNS over HTTPS (DoH)

    You can send DNS queries over HTTPS to DNS resolvers that support it. The standard for DOH is described in RFC 8484.

    This is a similar thing to what all the other answers suggest, only that DoH is actually the DNS protocol over HTTPS. It's also a "proposed" Internet standard and it's becoming quite popular. For example, some major browsers either support it or have plans to support it (Chrome, Edge, Firefox), and Microsoft is in the process of building it into their operating system.

    One of the purposes of DoH is:

    allowing web applications to access DNS information via existing browser APIs in a safe way consistent with Cross Origin Resource Sharing (CORS)

    There's an open source tool made especially for doing DNS lookups from web applications called dohjs. It does DNS over HTTPS (DoH) wireformat queries as described in RFC 8484. It supports both GET and POST methods.

    Full disclosure: I am a contributor to dohjs.

    Another JavaScript library with similar features is found here - https://github.com/sc0Vu/doh-js-client. I haven't used this one personally, but I think it would work client side as well.

    DNS over HTTPS JSON APIs

    If you don't want to bother with DNS wireformat, both Google and Cloudflare offer JSON APIs for DNS over HTTPS.

    Example Javascript code to lookup example.com with Google's JSON DOH API:

    var response = await fetch('https://dns.google/resolve?name=example.com');
    var json = await response.json();
    console.log(json);
    

    Examples from the RFC for DOH GET and POST with wireformat

    Here are the examples the RFC gives for both GET and POST (see https://tools.ietf.org/html/rfc8484#section-4.1.1):

    GET example:

    The first example request uses GET to request "www.example.com".

    :method = GET
    :scheme = https
    :authority = dnsserver.example.net
    :path = /dns-query?dns=AAABAAABAAAAAAAAA3d3dwdleGFtcGxlA2NvbQAAAQAB
    accept = application/dns-message

    POST example:

    The same DNS query for "www.example.com", using the POST method would be:

    :method = POST
    :scheme = https
    :authority = dnsserver.example.net
    :path = /dns-query
    accept = application/dns-message
    content-type = application/dns-message
    content-length = 33

    <33 bytes represented by the following hex encoding> 00 00 01 00 00 01 00 00 00 00 00 00 03 77 77 77 07 65 78 61 6d 70 6c 65 03 63 6f 6d 00 00 01 00 01

    Other places to send DOH queries

    You can find a list of some public DNS resolvers that support DNS over HTTPS in a couple places:

    Of the above resources, I'd say that the list on Curl's wiki and the DNSCrypt list are are probably the most complete and the most frequently updated. Curl's page also includes a list of open source tools for DoH (servers, proxies, client libs, etc).

    Reverse ip, find domain names on ip address

    You can use nslookup on the IP. Reverse DNS is defined with the .in-addr.arpa domain.

    Example:

    nslookup somedomain.com
    

    yields 123.21.2.3, and then you do:

    nslookup 123.21.2.3
    

    this will ask 3.2.21.123.in-addr.arpa and yield the domain name (if there is one defined for reverse DNS).

    ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

    I have the exact same configuration. This answer pertains specifically to connecting to a raspberry pi from inside the local network (not outside). I have A raspberry pi ssh server, and a macbook pro, both connected to a a router. On a test router, my mac connects perfectly when I use ssh danran@mypiserver, however, when I use ssh danran@mypiserver on my main router, i get the error

    ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

    Just as you have gotten. It seems, the solution for me at least, was to add a .local extension to the hostname when connecting from my mac via ssh.

    So, to solve this, i used the command ssh [email protected] (remember to replace the "danran" with your username and the "mypiserver" with your hostname) instead of using ssh danran@mypiserver.

    To anyone reading this, try adding a .local as the suffix to your hostname you are trying to connect to. That should solve the issue on a local network.

    Can I configure a subdomain to point to a specific port on my server

    If you only got one IP on the server, there is no chance to do that. DNS is a simple name to number (IP) resolver. If you have two IPs on the server, you can point each subdomain to each of the IP-addresses and run both servers on the default port on each IP.
    one.example.com -> 127.0.0.1 (server: 127.0.0.1:25565)
    two.example.com -> 127.0.0.2 (server: 127.0.0.2:25565)

    Enable Hibernate logging

    We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.

    On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:

    ### log just the SQL
    log4j.logger.org.hibernate.SQL=debug
    
    ### log JDBC bind parameters ###
    log4j.logger.org.hibernate.type=debug
    

    However, the JDBC bind parameters are not being logged.

    Templated check for the existence of a class member function?

    Now this was a nice little puzzle - great question!

    Here's an alternative to Nicola Bonelli's solution that does not rely on the non-standard typeof operator.

    Unfortunately, it does not work on GCC (MinGW) 3.4.5 or Digital Mars 8.42n, but it does work on all versions of MSVC (including VC6) and on Comeau C++.

    The longer comment block has the details on how it works (or is supposed to work). As it says, I'm not sure which behavior is standards compliant - I'd welcome commentary on that.


    update - 7 Nov 2008:

    It looks like while this code is syntactically correct, the behavior that MSVC and Comeau C++ show does not follow the standard (thanks to Leon Timmermans and litb for pointing me in the right direction). The C++03 standard says the following:

    14.6.2 Dependent names [temp.dep]

    Paragraph 3

    In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

    So, it looks like that when MSVC or Comeau consider the toString() member function of T performing name lookup at the call site in doToString() when the template is instantiated, that is incorrect (even though it's actually the behavior I was looking for in this case).

    The behavior of GCC and Digital Mars looks to be correct - in both cases the non-member toString() function is bound to the call.

    Rats - I thought I might have found a clever solution, instead I uncovered a couple compiler bugs...


    #include <iostream>
    #include <string>
    
    struct Hello
    {
        std::string toString() {
            return "Hello";
        }
    };
    
    struct Generic {};
    
    
    // the following namespace keeps the toString() method out of
    //  most everything - except the other stuff in this
    //  compilation unit
    
    namespace {
        std::string toString()
        {
            return "toString not defined";
        }
    
        template <typename T>
        class optionalToStringImpl : public T
        {
        public:
            std::string doToString() {
    
                // in theory, the name lookup for this call to 
                //  toString() should find the toString() in 
                //  the base class T if one exists, but if one 
                //  doesn't exist in the base class, it'll 
                //  find the free toString() function in 
                //  the private namespace.
                //
                // This theory works for MSVC (all versions
                //  from VC6 to VC9) and Comeau C++, but
                //  does not work with MinGW 3.4.5 or 
                //  Digital Mars 8.42n
                //
                // I'm honestly not sure what the standard says 
                //  is the correct behavior here - it's sort 
                //  of like ADL (Argument Dependent Lookup - 
                //  also known as Koenig Lookup) but without
                //  arguments (except the implied "this" pointer)
    
                return toString();
            }
        };
    }
    
    template <typename T>
    std::string optionalToString(T & obj)
    {
        // ugly, hacky cast...
        optionalToStringImpl<T>* temp = reinterpret_cast<optionalToStringImpl<T>*>( &obj);
    
        return temp->doToString();
    }
    
    
    
    int
    main(int argc, char *argv[])
    {
        Hello helloObj;
        Generic genericObj;
    
        std::cout << optionalToString( helloObj) << std::endl;
        std::cout << optionalToString( genericObj) << std::endl;
        return 0;
    }
    

    PHP string concatenation

    while ($personCount < 10) {
        $result .= ($personCount++)." people ";
    }
    
    echo $result;
    

    How to add a form load event (currently not working)

    You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

     public class ProgramViwer : Form{
      public ProgramViwer()
      {
           InitializeComponent();
           Load += new EventHandler(ProgramViwer_Load);
      }
      private void ProgramViwer_Load(object sender, System.EventArgs e)
      {
           formPanel.Controls.Clear();
           formPanel.Controls.Add(wel);
      }
    }
    

    Convert DataSet to List

    Use the code below:

    using Newtonsoft.Json;
    string JSONString = string.Empty;
    JSONString = JsonConvert.SerializeObject(ds.Tables[0]);
    

    UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

    You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

    Pick an encoding and stick with it:

    f.write(printinfo.encode('utf8') + '\n')
    

    or use io.open() to create a file object that'll encode for you as you write to the file:

    import io
    
    f = io.open(filename, 'w', encoding='utf8')
    

    You may want to read:

    before continuing.

    Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

    You can use LOG such as :

    Log.e(String, String) (error)
    Log.w(String, String) (warning)
    Log.i(String, String) (information)
    Log.d(String, String) (debug)
    Log.v(String, String) (verbose)
    

    example code:

    private static final String TAG = "MyActivity";
    ...
    Log.i(TAG, "MyClass.getView() — get item number " + position);
    

    IE Enable/Disable Proxy Settings via Registry

    The problem is that IE won't reset the proxy settings until it either

    1. closes, or
    2. has its configuration refreshed.

    Below is the code that I've used to get this working:

    function Refresh-System
    {
      $signature = @'
    [DllImport("wininet.dll", SetLastError = true, CharSet=CharSet.Auto)]
    public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
    '@
    
    $INTERNET_OPTION_SETTINGS_CHANGED   = 39
    $INTERNET_OPTION_REFRESH            = 37
    $type = Add-Type -MemberDefinition $signature -Name wininet -Namespace pinvoke -PassThru
    $a = $type::InternetSetOption(0, $INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
    $b = $type::InternetSetOption(0, $INTERNET_OPTION_REFRESH, 0, 0)
    return $a -and $b
    }
    

    Loop through properties in JavaScript object with Lodash

    In ES6, it is also possible to iterate over the values of an object using the for..of loop. This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object. This works as follows:

    • The for..of loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop.
    • The iterator object is obtained by invoking the function defined in the @@iterator property, or Symbol.iterator property, of obj1. This is the function you must define yourself, and it should return an iterator object

    Here is an example:

    const obj1 = {
      a: 5,
      b: "hello",
      [Symbol.iterator]: function() {
        const thisObj = this;
        let index = 0;
        return {
          next() {
            let keys = Object.keys(thisObj);
            return {
              value: thisObj[keys[index++]],
              done: (index > keys.length)
            };
          }
        };
      }
    };
    

    Now we can use the for..of loop:

    for (val of obj1) {
      console.log(val);
    }    // 5 hello
    

    How do I retrieve query parameters in Spring Boot?

    In Spring boot: 2.1.6, you can use like below:

        @GetMapping("/orders")
        @ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
        public List<OrderResponse> getOrders(
                @RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
                @RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
                @RequestParam(value = "location_id", required = true) String location_id) {
    
            // TODO...
    
            return response;
    

    @ApiOperation is an annotation that comes from Swagger api, It is used for documenting the apis.

    MySQL show current connection info

    You can use the status command in MySQL client.

    mysql> status;
    --------------
    mysql  Ver 14.14 Distrib 5.5.8, for Win32 (x86)
    
    Connection id:          1
    Current database:       test
    Current user:           ODBC@localhost
    SSL:                    Not in use
    Using delimiter:        ;
    Server version:         5.5.8 MySQL Community Server (GPL)
    Protocol version:       10
    Connection:             localhost via TCP/IP
    Server characterset:    latin1
    Db     characterset:    latin1
    Client characterset:    gbk
    Conn.  characterset:    gbk
    TCP port:               3306
    Uptime:                 7 min 16 sec
    
    Threads: 1  Questions: 21  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.48
    --------------
    
    mysql>
    

    How to remove files from git staging area?

    You could use

    git reset HEAD
    

    then add the specific files you want with

    git add [directory/]filename
    

    Send data from activity to fragment in Android

    Very old post, still I dare to add a little explanation that would had been helpful for me.

    Technically you can directly set members of any type in a fragment from activity.
    So why Bundle?
    The reason is very simple - Bundle provides uniform way to handle:
    -- creating/opening fragment
    -- reconfiguration (screen rotation) - just add initial/updated bundle to outState in onSaveInstanceState()
    -- app restoration after being garbage collected in background (as with reconfiguration).

    You can (if you like experiments) create a workaround in simple situations but Bundle-approach just doesn't see difference between one fragment and one thousand on a backstack - it stays simple and straightforward.
    That's why the answer by @Elenasys is the most elegant and universal solution.
    And that's why the answer given by @Martin has pitfalls

    How to find time complexity of an algorithm

    O(n) is big O notation used for writing time complexity of an algorithm. When you add up the number of executions in an algoritm you'll get an expression in result like 2N+2, in this expression N is the dominating term(the term having largest effect on expression if its value increases or decreases). Now O(N) is the time comlexity while N is dominating term. Example

    For i= 1 to n;
      j= 0;
    while(j<=n);
      j=j+1;
    

    here total number of executions for inner loop are n+1 and total number of executions for outer loop are n(n+1)/2, so total number of executions for whole algorithm are n+1+n(n+1/2) = (n^2+3n)/2. here n^2 is the dominating term so the time complexity for this algorithm is O(n^2)

    Setting width and height

    You can override the canvas style width !important ...

    canvas{
    
      width:1000px !important;
      height:600px !important;
    
    }
    

    also

    specify responsive:true, property under options..

    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
    

    update under options added : maintainAspectRatio: false,

    link : http://codepen.io/theConstructor/pen/KMpqvo

    Understanding the main method of python

    If you import the module (.py) file you are creating now from another python script it will not execute the code within

    if __name__ == '__main__':
        ...
    

    If you run the script directly from the console, it will be executed.

    Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.

    This is expanded upon a little more at python.berkely.edu

    Android emulator-5554 offline

    If the emulator is already open or executing it will tell you is offline. You can double check on the Command Line (Ubuntu) and execute:

     adb devices
    

    You must see your emulator offline, you have to close the running instance of the emulator (since the port will show as busy) and after that you can run your application. Hope this helps someone.

    Bootstrap 3 - How to load content in modal body via AJAX?

    create an empty modal box on the current page and below is the ajax call you can see how to fetch the content in result from another html page.

     $.ajax({url: "registration.html", success: function(result){
                //alert("success"+result);
                  $("#contentBody").html(result);
                $("#myModal").modal('show'); 
    
            }});
    

    once the call is done you will get the content of the page by the result to then you can insert the code in you modal's content id using.

    You can call controller and get the page content and you can show that in your modal.

    below is the example of Bootstrap 3 modal in that we are loading content from registration.html page...

    index.html
    ------------------------------------------------
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
    <script type="text/javascript">
    function loadme(){
        //alert("loadig");
    
        $.ajax({url: "registration.html", success: function(result){
            //alert("success"+result);
              $("#contentBody").html(result);
            $("#myModal").modal('show'); 
    
        }});
    }
    </script>
    </head>
    <body>
    
    <!-- Trigger the modal with a button -->
    <button type="button" class="btn btn-info btn-lg" onclick="loadme()">Load me</button>
    
    
    <!-- Modal -->
    <div id="myModal" class="modal fade" role="dialog">
      <div class="modal-dialog">
    
        <!-- Modal content-->
        <div class="modal-content" >
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Modal Header</h4>
          </div>
          <div class="modal-body" id="contentBody">
    
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
    
      </div>
    </div>
    
    </body>
    </html>
    
    registration.html
    -------------------- 
    <!DOCTYPE html>
    <html>
    <style>
    body {font-family: Arial, Helvetica, sans-serif;}
    
    form {
        border: 3px solid #f1f1f1;
        font-family: Arial;
    }
    
    .container {
        padding: 20px;
        background-color: #f1f1f1;
        width: 560px;
    }
    
    input[type=text], input[type=submit] {
        width: 100%;
        padding: 12px;
        margin: 8px 0;
        display: inline-block;
        border: 1px solid #ccc;
        box-sizing: border-box;
    }
    
    input[type=checkbox] {
        margin-top: 16px;
    }
    
    input[type=submit] {
        background-color: #4CAF50;
        color: white;
        border: none;
    }
    
    input[type=submit]:hover {
        opacity: 0.8;
    }
    </style>
    <body>
    
    <h2>CSS Newsletter</h2>
    
    <form action="/action_page.php">
      <div class="container">
        <h2>Subscribe to our Newsletter</h2>
        <p>Lorem ipsum text about why you should subscribe to our newsletter blabla. Lorem ipsum text about why you should subscribe to our newsletter blabla.</p>
      </div>
    
      <div class="container" style="background-color:white">
        <input type="text" placeholder="Name" name="name" required>
        <input type="text" placeholder="Email address" name="mail" required>
        <label>
          <input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
        </label>
      </div>
    
      <div class="container">
        <input type="submit" value="Subscribe">
      </div>
    </form>
    
    </body>
    </html>
    

    Implementing multiple interfaces with Java - is there a way to delegate?

    There is one way to implement multiple interface.

    Just extend one interface from another or create interface that extends predefined interface Ex:

    public interface PlnRow_CallBack extends OnDateSetListener {
        public void Plan_Removed();
        public BaseDB getDB();
    }
    

    now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces

    public class Calculator extends FragmentActivity implements PlnRow_CallBack {
    
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    
        }
    
        @Override
        public void Plan_Removed() {
    
        }
    
        @Override
        public BaseDB getDB() {
    
        }
    }
    

    hope this helps

    How to loop through an array containing objects and access their properties

    Looping through an array of objects is a pretty fundamental functionality. This is what works for me.

    _x000D_
    _x000D_
    var person = [];_x000D_
    person[0] = {_x000D_
      firstName: "John",_x000D_
      lastName: "Doe",_x000D_
      age: 60_x000D_
    };_x000D_
    _x000D_
    var i, item;_x000D_
    _x000D_
    for (i = 0; i < person.length; i++) {_x000D_
      for (item in person[i]) {_x000D_
        document.write(item + ": " + person[i][item] + "<br>");_x000D_
      }_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    How do I invert BooleanToVisibilityConverter?

    Implement your own implementation of IValueConverter. A sample implementation is at

    http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

    In your Convert method, have it return the values you'd like instead of the defaults.

    How do I use variables in Oracle SQL Developer?

    Use the next query:

    DECLARE 
      EmpIDVar INT;
    
    BEGIN
      EmpIDVar := 1234;
    
      SELECT *
      FROM Employees
      WHERE EmployeeID = EmpIDVar;
    END;
    

    Function return value in PowerShell

    The following simply returns 4 as an answer. When you replace the add expressions for strings it returns the first string.

    Function StartingMain {
      $a = 1 + 3
      $b = 2 + 5
      $c = 3 + 7
      Return $a
    }
    
    Function StartingEnd($b) {
      Write-Host $b
    }
    
    StartingEnd(StartingMain)
    

    This can also be done for an array. The example below will return "Text 2"

    Function StartingMain {
      $a = ,@("Text 1","Text 2","Text 3")
      Return $a
    }
    
    Function StartingEnd($b) {
      Write-Host $b[1]
    }
    
    StartingEnd(StartingMain)
    

    Note that you have to call the function below the function itself. Otherwise, the first time it runs it will return an error that it doesn't know what "StartingMain" is.

    How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

    By using synchronized on a static method lock you will synchronize the class methods and attributes ( as opposed to instance methods and attributes )

    So your assumption is correct.

    I am wondering if making the method synchronized is the right approach to ensure thread-safety.

    Not really. You should let your RDBMS do that work instead. They are good at this kind of stuff.

    The only thing you will get by synchronizing the access to the database is to make your application terribly slow. Further more, in the code you posted you're building a Session Factory each time, that way, your application will spend more time accessing the DB than performing the actual job.

    Imagine the following scenario:

    Client A and B attempt to insert different information into record X of table T.

    With your approach the only thing you're getting is to make sure one is called after the other, when this would happen anyway in the DB, because the RDBMS will prevent them from inserting half information from A and half from B at the same time. The result will be the same but only 5 times ( or more ) slower.

    Probably it could be better to take a look at the "Transactions and Concurrency" chapter in the Hibernate documentation. Most of the times the problems you're trying to solve, have been solved already and a much better way.

    Disable dragging an image from an HTML page

    This code does exactly what you want. It prevents the image from dragging while allowing any other actions that depend on the event.

    $("img").mousedown(function(e){
        e.preventDefault()
    });
    

    MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

    Before increasing the max_connections variable, you have to check how many non-interactive connection you have by running show processlist command.

    If you have many sleep connection, you have to decrease the value of the "wait_timeout" variable to close non-interactive connection after waiting some times.

    • To show the wait_timeout value:

    SHOW SESSION VARIABLES LIKE 'wait_timeout';

    +---------------+-------+

    | Variable_name | Value |

    +---------------+-------+

    | wait_timeout | 28800 |

    +---------------+-------+

    the value is in second, it means that non-interactive connection still up to 8 hours.

    • To change the value of "wait_timeout" variable:

    SET session wait_timeout=600; Query OK, 0 rows affected (0.00 sec)

    After 10 minutes if the sleep connection still sleeping the mysql or MariaDB drop that connection.

    Changing default startup directory for command prompt in Windows 7

    Bit late but ignore the registry mods. Simply change the shortcut target to:

    cmd /k "command"
    

    i.e.

    cmd /k "cd\myStartUpFolder"
    

    Voila!

    Auto highlight text in a textbox control

    On events "Enter" (for example: press Tab key) or "First Click" all text will be selected. dotNET 4.0

    public static class TbHelper
    {
        // Method for use
        public static void SelectAllTextOnEnter(TextBox Tb)
        {
            Tb.Enter += new EventHandler(Tb_Enter);
            Tb.Click += new EventHandler(Tb_Click);
        }
    
        private static TextBox LastTb;
    
        private static void Tb_Enter(object sender, EventArgs e)
        {
            var Tb = (TextBox)sender;
            Tb.SelectAll();
            LastTb = Tb;
        }
    
        private static void Tb_Click(object sender, EventArgs e)
        {
            var Tb = (TextBox)sender;
            if (LastTb == Tb)
            {
                Tb.SelectAll();
                LastTb = null;
            }
        }
    }
    

    What's the difference between HEAD^ and HEAD~ in Git?

    ^ BRANCH Selector
    git checkout HEAD^2
    Selects the 2nd branch of a (merge) commit by moving onto the selected branch (one step backwards on the commit-tree)

    ~ COMMIT Selector
    git checkout HEAD~2
    Moves 2 commits backwards on the default/selected branch


    Defining both ~ and ^ relative refs as PARENT selectors is far the dominant definition published everywhere on the internet I have come across so far - including the official Git Book. Yes they are PARENT selectors, but the problem with this "explanation" is that it is completely against our goal: which is how to distinguish the two... :)

    The other problem is when we are encouraged to use the ^ BRANCH selector for COMMIT selection (aka HEAD^ === HEAD~).
    Again, yes, you can use it this way, but this is not its designed purpose. The ^ BRANCH selector's backwards move behaviour is a side effect not its purpose.

    At merged commits only, can a number be assigned to the ^ BRANCH selector. Thus its full capacity can only be utilised where there is a need for selecting among branches. And the most straightforward way to express a selection in a fork is by stepping onto the selected path / branch - that's for the one step backwards on the commit-tree. It is a side effect only, not its main purpose.

    Detect if a jQuery UI dialog box is open

    If you read the docs.

    $('#mydialog').dialog('isOpen')
    

    This method returns a Boolean (true or false), not a jQuery object.

    How exactly does the android:onClick XML attribute differ from setOnClickListener?

    Suppose, You want to add click event like this main.xml

    <Button
        android:id="@+id/btn_register"
        android:layout_margin="1dp"
        android:layout_marginLeft="3dp"
        android:layout_marginTop="10dp"
        android:layout_weight="2"
        android:onClick="register"
        android:text="Register"
        android:textColor="#000000"/>
    

    In java file, you have to write a method like this method.

    public void register(View view) {
    }
    

    Update label from another thread

    You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.

     private void AggiornaContatore()
     {         
         if(this.lblCounter.InvokeRequired)
         {
             this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});    
         }
         else
         {
             this.lblCounter.Text = this.index.ToString(); ;
         }
     }
    

    Please go through this chapter and more from this book to get a clear picture about threading:

    http://www.albahari.com/threading/part2.aspx#_Rich_Client_Applications

    How to Add Stacktrace or debug Option when Building Android Studio Project

    What I use for debugging purposes is running the gradle task with stacktrace directly in terminal. Then you don't affect your normal compiles.

    From your project root directory, via terminal you can use:

    ./gradlew assembleMyBuild --stacktrace
    

    PHP namespaces and "use"

    If you need to order your code into namespaces, just use the keyword namespace:

    file1.php

    namespace foo\bar;
    

    In file2.php

    $obj = new \foo\bar\myObj();
    

    You can also use use. If in file2 you put

    use foo\bar as mypath;

    you need to use mypath instead of bar anywhere in the file:

    $obj  = new mypath\myObj();
    

    Using use foo\bar; is equal to use foo\bar as bar;.

    Installing Numpy on 64bit Windows 7 with Python 2.7.3

    Assuming you have python 2.7 64bit on your computer and have downloaded numpy from here, follow the steps below (changing numpy-1.9.2+mkl-cp27-none-win_amd64.whl as appropriate).

    1. Download (by right click and "save target") get-pip to local drive.

    2. At the command prompt, navigate to the directory containing get-pip.py and run

      python get-pip.py

      which creates files in C:\Python27\Scripts, including pip2, pip2.7 and pip.

    3. Copy the downloaded numpy-1.9.2+mkl-cp27-none-win_amd64.whl into the above directory (C:\Python27\Scripts)

    4. Still at the command prompt, navigate to the above directory and run:

      pip2.7.exe install "numpy-1.9.2+mkl-cp27-none-win_amd64.whl"

    How to call a Python function from Node.js

    Easiest way I know of is to use "child_process" package which comes packaged with node.

    Then you can do something like:

    const spawn = require("child_process").spawn;
    const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);
    

    Then all you have to do is make sure that you import sys in your python script, and then you can access arg1 using sys.argv[1], arg2 using sys.argv[2], and so on.

    To send data back to node just do the following in the python script:

    print(dataToSendBack)
    sys.stdout.flush()
    

    And then node can listen for data using:

    pythonProcess.stdout.on('data', (data) => {
        // Do something with the data returned from python script
    });
    

    Since this allows multiple arguments to be passed to a script using spawn, you can restructure a python script so that one of the arguments decides which function to call, and the other argument gets passed to that function, etc.

    Hope this was clear. Let me know if something needs clarification.

    How do I find out what version of WordPress is running?

    Because I can not comment to @Michelle 's answer, I post my trick here.

    Instead of checking the version on meta tag that usually is removed by a customized theme.

    Check the rss feed by append /feed to almost any link from that site, then search for some keywords (wordpress, generator), you will have a better chance.

    <lastBuildDate>Fri, 29 May 2015 10:08:40 +0000</lastBuildDate>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <generator>http://wordpress.org/?v=4.2.2</generator>
    

    nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

    First change apache listen port 80 to 8080 apache in /etc/apache2/ports.conf include

    Listen 1.2.3.4:80 to 1.2.3.4:8080
    sudo service apache2 restart 
    

    or

    sudo service httpd restart    // in case of centos
    

    then add nginx as reverse proxy server that will listen apache port

    server {
     listen   1.2.3.4:80;
     server_name  some.com;
    
     access_log  /var/log/nginx/something-access.log;
    
     location / {
      proxy_pass http://localhost:8080;
      proxy_redirect off;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     }
    
    
    location ~* ^.+\.(jpg|js|jpeg|png)$ {
       root /usr/share/nginx/html/;
    }
    
    location /404.html {
      root /usr/share/nginx/html/40x.html;
    }
    
    error_page 404 /404.html;
        location = /40x.html {
    }
    
    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
    
    # put code for static content like js/css/images/fonts
    }
    

    After changes restart nginx server

    sudo service nginx restart
    

    Now all traffic will be handled by nginx server and send all dynamic request to apache and static conten is served by nginx server.

    For advance configuration like cache :

    https://www.linode.com/docs/web-servers/nginx/slightly-more-advanced-configurations-for-nginx/#basic-nginx-caching

    Jquery assiging class to th in a table

    You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

    $('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

    Fiddle

    Is using 'var' to declare variables optional?

    They are not the same.

    Undeclared variable (without var) are treated as properties of the global object. (Usually the window object, unless you're in a with block)

    Variables declared with var are normal local variables, and are not visible outside the function they're declared in. (Note that Javascript does not have block scope)

    Update: ECMAScript 2015

    let was introduced in ECMAScript 2015 to have block scope.

    PHP PDO with foreach and fetch

    A PDOStatement (which you have in $users) is a forward-cursor. That means, once consumed (the first foreach iteration), it won't rewind to the beginning of the resultset.

    You can close the cursor after the foreach and execute the statement again:

    $users       = $dbh->query($sql);
    foreach ($users as $row) {
        print $row["name"] . "-" . $row["sex"] ."<br/>";
    }
    
    $users->execute();
    
    foreach ($users as $row) {
        print $row["name"] . "-" . $row["sex"] ."<br/>";
    }
    

    Or you could cache using tailored CachingIterator with a fullcache:

    $users       = $dbh->query($sql);
    
    $usersCached = new CachedPDOStatement($users);
    
    foreach ($usersCached as $row) {
        print $row["name"] . "-" . $row["sex"] ."<br/>";
    }
    foreach ($usersCached as $row) {
        print $row["name"] . "-" . $row["sex"] ."<br/>";
    }
    

    You find the CachedPDOStatement class as a gist. The caching itertor is probably more sane than storing the resultset into an array because it still offers all properties and methods of the PDOStatement object it has wrapped.

    What does PHP keyword 'var' do?

    I quote from http://www.php.net/manual/en/language.oop5.visibility.php

    Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.

    Activity has leaked window that was originally added

    This happened to me when i am using ProgressDialog in AsyncTask. Actually i am using hide() method in onPostExecute. Based on the answer of @Alex Volovoy i need to use dismiss() with ProgressDialog to remove it in onPostExecute and its done.

    progressDialog.hide(); // Don't use it, it gives error
    
    progressDialog.dismiss(); // Use it
    

    How do I trap ctrl-c (SIGINT) in a C# console app

    I'd like to add to Jonas' answer. Spinning on a bool will cause 100% CPU utilization, and waste a bunch of energy doing a lot of nothing while waiting for CTRL+C.

    The better solution is to use a ManualResetEvent to actually "wait" for the CTRL+C:

    static void Main(string[] args) {
        var exitEvent = new ManualResetEvent(false);
    
        Console.CancelKeyPress += (sender, eventArgs) => {
                                      eventArgs.Cancel = true;
                                      exitEvent.Set();
                                  };
    
        var server = new MyServer();     // example
        server.Run();
    
        exitEvent.WaitOne();
        server.Stop();
    }
    

    Just what is an IntPtr exactly?

    Here's an example:

    I'm writing a C# program that interfaces with a high-speed camera. The camera has its own driver that acquires images and loads them into the computer's memory for me automatically.

    So when I'm ready to bring the latest image into my program to work with, the camera driver provides me with an IntPtr to where the image is ALREADY stored in physical memory, so I don't have to waste time/resources creating another block of memory to store an image that's in memory already. The IntPtr just shows me where the image already is.

    Wait some seconds without blocking UI execution

    Omar's solution is decent* if you cannot upgrade your environment to .NET 4.5 in order to gain access to the async and await APIs. That said, there here is one important change that should be made in order to avoid poor performance. A slight delay should be added between calls to Application.DoEvents() in order to prevent excessive CPU usage. By adding

    Thread.Sleep(1);
    

    before the call to Application.DoEvents(), you can add such a delay (1 millisecond) and prevent the application from using all of the cpu cycles available to it.

    private void WaitNSeconds(int seconds)
    {
        if (seconds < 1) return;
        DateTime _desired = DateTime.Now.AddSeconds(seconds);
        while (DateTime.Now < _desired) {
             Thread.Sleep(1);
             System.Windows.Forms.Application.DoEvents();
        }
    }
    

    *See https://blog.codinghorror.com/is-doevents-evil/ for a more detailed discussion on the potential pitfalls of using Application.DoEvents().

    How to remove a directory from git repository?

    for deleting Empty folders

    i wanted to delete an empty directory(folder) i created, git can not delete it, after some research i learned Git doesn't track empty directories. If you have an empty directory in your working tree you should simply removed it with

    rm -r folderName
    

    There is no need to involve Git.

    App can't be opened because it is from an unidentified developer

    Right-click (or control-click) the application in question and choose "Open"

    How to convert an enum type variable to a string?

    Assuming that your enum is already defined, you can create an array of pairs:

    std::pair<QTask::TASK, QString> pairs [] = {
    std::pair<OS_type, string>(Linux, "Linux"),
    std::pair<OS_type, string>(Windows, "Windows"),
    std::pair<OS_type, string>(Apple, "Apple"),
    };
    

    Now, you can create a map:

    std::map<OS_type, std::string> stdmap(pairs, pairs + sizeof(pairs) / sizeof(pairs[0]));
    

    Now, you can use the map. If your enum is changed, you have to add/remove pair from array pairs[]. I thinkk that it is the most elegant way to obtain a string from enum in C++.

    Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

    Correcting gradle settings is quite difficult. If you don't know much about Gradle it requires you to learn alot. Instead you can do the following:

    1) Start a new project in a new folder. Choose the same settings with your project with gradle problem but keep it simple: Choose an empty main activity. 2) Delete all the files in ...\NewProjectName\app\src\main folder 3) Copy all the files in ...\ProjectWithGradleProblem\app\src\main folder to ...\NewProjectName\app\src\main folder. 4) If you are using the Test project (\ProjectWithGradleProblem\app\src\AndroidTest) you can do the same for that too.

    this method works fine if your Gradle installation is healthy. If you just installed Android studio and did not modify it, the Gradle installation should be fine.

    What equivalents are there to TortoiseSVN, on Mac OSX?

    I use svnX (http://code.google.com/p/svnx/downloads/list), it is free and usable, but not as user friendly as tortoise. It shows you the review before commit with diff for every file... but sometimes I still had to go to command line to fix some things

    Django TemplateDoesNotExist?

    Works on Django 3

    I found I believe good way, I have the base.html in root folder, and all other html files in App folders, I settings.py

    import os
    
    # This settings are to allow store templates,static and media files in root folder
    
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
    STATIC_DIR = os.path.join(BASE_DIR,'static')
    MEDIA_DIR = os.path.join(BASE_DIR,'media')
    
    # This is default path from Django, must be added 
    #AFTER our BASE_DIR otherwise DB will be broken.
    BASE_DIR = Path(__file__).resolve().parent.parent
    
    # add your apps to Installed apps
    INSTALLED_APPS = [
        'main',
        'weblogin',
         ..........
    ]
    
    # Now add TEMPLATE_DIR to  'DIRS' where in TEMPLATES like bellow
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [TEMPLATE_DIR, BASE_DIR,],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    # On end of Settings.py put this refferences to Static and Media files
    STATICFILES_DIRS = [STATIC_DIR,]
    STATIC_URL = '/static/'
    
    MEDIA_ROOT = [MEDIA_DIR,]
    MEDIA_URL = '/media/'
    

    If you have problem with Database, please check if you put the original BASE_DIR bellow the new BASE_DIR otherwise change

    # Original
    'NAME': BASE_DIR / 'db.sqlite3',
    # to
    'NAME': os.path.join(BASE_DIR,'db.sqlite3'),
    

    Django now will be able to find the HTML and Static files both in the App folders and in Root folder without need of adding the name of App folder in front of the file.

    Struture:
    -DjangoProject
        -static(css,JS ...)
        -templates(base.html, ....)
        -other django files like (manage.py, ....)
        -App1
            -templates(index1.html, other html files can extend now base.html too)
            -other App1 files
        -App2
            -templates(index2.html, other html files can extend now base.html too)
            -other App2 files
    

    Maximum size of an Array in Javascript

    You could try something like this to test and trim the length:

    http://jsfiddle.net/orolo/wJDXL/

    _x000D_
    _x000D_
    var longArray = [1, 2, 3, 4, 5, 6, 7, 8];_x000D_
    _x000D_
    if (longArray.length >= 6) {_x000D_
      longArray.length = 3;_x000D_
    }_x000D_
    _x000D_
    alert(longArray); //1, 2, 3
    _x000D_
    _x000D_
    _x000D_

    How to simulate a click with JavaScript?

    const Discord = require("discord.js");
    const superagent = require("superagent");
    
    module.exports = {
        name: "hug",
        category: "action",
        description: "hug a user!",
        usage: "hug <user>",
        run: async (client, message, args) => {
        let hugUser = message.mentions.users.first() 
        if(!hugUser) return message.channel.send("You forgot to mention somebody.");
        let hugEmbed2 = new Discord.MessageEmbed()
        .setColor("#36393F")
        .setDescription(`**${message.author.username}** hugged **himself**`)
        .setImage("https://i.kym-cdn.com/photos/images/original/000/859/605/3e7.gif")
         .setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
      if (hugUser.id === message.author.id) return message.channel.send(hugEmbed2);
        const {body} = await superagent
        .get(`https://nekos.life/api/v2/img/hug`);
    
        let hugEmbed = new Discord.MessageEmbed()
        .setDescription(`**${message.author.username}** hugged **${message.mentions.users.first().username}**`)
        .setImage(body.url)
        .setColor("#36393F")
         .setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
        message.channel.send(hugEmbed)
    }
    }
    

    Slide up/down effect with ng-show and ng-animate

    This can actually be done in CSS and very minimal JS just by adding a CSS class (don't set styles directly in JS!) with e.g. a ng-clickevent. The principle is that one can't animate height: 0; to height: auto; but this can be tricked by animating the max-height property. The container will expand to it's "auto-height" value when .foo-open is set - no need for fixed height or positioning.

    .foo {
        max-height: 0;
    }
    
    .foo--open {
        max-height: 1000px; /* some arbitrary big value */
        transition: ...
    }
    

    see this fiddle by the excellent Lea Verou

    As a concern raised in the comments, note that while this animation works perfectly with linear easing, any exponential easing will produce a behaviour different from what could be expected - due to the fact that the animated property is max-height and not height itself; specifically, only the height fraction of the easing curve of max-height will be displayed.

    How to exit in Node.js

    From the official nodejs.org documentation:

    process.exit(code)
    

    Ends the process with the specified code. If omitted, exit uses the 'success' code 0.

    To exit with a 'failure' code:

    process.exit(1);
    

    Enable UTF-8 encoding for JavaScript

    For others, I just had a similar problem and had to copy all code from my file, put it to simple notepad, save it with utf-8 coding and then replace my original file.

    The problem at my side was caused by using PSpad editor.

    CSS override rules and specificity

    The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have a class selector, but the first one also has two tag selectors.

    To make the second one override the first one, you can make more specific by adding information of it's parents:

    table.rule1 tr td.rule2 {
        background-color: #ffff00;
    }
    

    Here is a nice article for more information on selector precedence.

    SyntaxError: Unexpected Identifier in Chrome's Javascript console

    copy this line and replace in your project

    var myNewString = myOldString.replace ("username", visitorName);
    

    there is a simple problem with coma (,)

    Android: install .apk programmatically

    For ICS I´ve implemented your code and made a class that extends AsyncTask. I hope you appreciate it! Thanks for your code and solution.

    public class UpdateApp extends AsyncTask<String,Void,Void>{
        private Context context;
        public void setContext(Context contextf){
            context = contextf;
        }
    
        @Override
        protected Void doInBackground(String... arg0) {
            try {
                URL url = new URL(arg0[0]);
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
    
                String PATH = "/mnt/sdcard/Download/";
                File file = new File(PATH);
                file.mkdirs();
                File outputFile = new File(file, "update.apk");
                if(outputFile.exists()){
                    outputFile.delete();
                }
                FileOutputStream fos = new FileOutputStream(outputFile);
    
                InputStream is = c.getInputStream();
    
                byte[] buffer = new byte[1024];
                int len1 = 0;
                while ((len1 = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);
                }
                fos.close();
                is.close();
    
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
                context.startActivity(intent);
    
    
            } catch (Exception e) {
                Log.e("UpdateAPP", "Update error! " + e.getMessage());
            }
            return null;
        }
    }   
    

    To use it, in your main activity call by this way:

    atualizaApp = new UpdateApp();
    atualizaApp.setContext(getApplicationContext());
    atualizaApp.execute("http://serverurl/appfile.apk");
    

    How to select and change value of table cell with jQuery?

    I wanted to change the column value in a specific row. Thanks to above answers and after some serching able to come up with below,

    var dataTable = $("#yourtableid");
    var rowNumber = 0;  
    var columnNumber= 2;   
    dataTable[0].rows[rowNumber].cells[columnNumber].innerHTML = 'New Content';
    

    How to add Google Maps Autocomplete search box?

    Follow the below code.

    Add this to your TS file.

    declare this, top of your class.

    declare var google;
    

    declare the view child for Map and the input.

    @ViewChild('mapElement', {static: true}) mapNativeElement: ElementRef;
    @ViewChild('autoCompleteInput', {static: true}) inputNativeElement: any;
    

    this method is run on ngOnInit() event or ngAfterViewInit() event.

    autoComplete() {
        const map = new google.maps.Map(this.mapNativeElement.nativeElement, {
          center: {lat: -33.8688, lng: 151.2093},
          zoom: 7
        });
    
        const infowindow = new google.maps.InfoWindow();
        const infowindowContent = document.getElementById('infowindow-content');
    
        infowindow.setContent(infowindowContent);
    
        const marker = new google.maps.Marker({
          map: map,
          anchorPoint: new google.maps.Point(0, -29)
        });
        const autocomplete = new google.maps.places.Autocomplete(this.inputNativeElement.nativeElement as HTMLInputElement);
        autocomplete.addListener('place_changed', () => {
          infowindow.close();
          marker.setVisible(false);
          const place = autocomplete.getPlace();
    
          let cus_location = {
            lat: place.geometry.location.lat(),
            long: place.geometry.location.lng()
          }
    
          console.log('place data :................', cus_location); 
          localStorage.setItem('LOC_DATA', this.helper.encryptData(cus_location));
    
          if (!place.geometry) {
            // User entered the name of a Place that was not suggested and
            // pressed the Enter key, or the Place Details request failed.
            window.alert('No details available for input: ' + place.name );
            return;
          }
    
          if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
          } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);  // Why 17? Because it looks good.
          }
    
          marker.setPosition(place.geometry.location);
          marker.setVisible(true);
          let address = '';
          if (place.address_components) {
            address = [
              (place.address_components[0] && place.address_components[0].short_name || ''),
              (place.address_components[1] && place.address_components[1].short_name || ''),
              (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
          }
    
          if(infowindowContent){
            infowindowContent.children['place-icon'].src = place.icon;
            infowindowContent.children['place-name'].textContent = place.name;
            infowindowContent.children['place-address'].textContent = address;
          } 
    
          infowindow.open(map, marker);
        });
    
      }
    

    calling the method on ngAfterViewInit.

    ngAfterViewInit(): void {
        this.autoComplete();
      }
    

    And this is the HTML code. please modify as per your need.

    <ion-content fullscreen>
        <div class="location-col">
    
    
            <div class="google-map">
                <!-- <img src="../../assets/images/google-map.jpg" alt=""> -->
                <div #mapElement id="map"></div>
            </div>
    
    
            <div class="location-info">
                <h2>Where is your car located?</h2>
                <p>Enter address manually or click location detector icon to use current address.</p>
                <div class="form-group">
    
                    <div class="location-row">
                        <input type="text" #autoCompleteInput class="location-input" [(ngModel)]="search_location" placeholder="Search location">
                        <span class="location-icon" (click)="getCurrentLocation()">
                            <img src="../../assets/images/location-icon.svg" alt="">
                        </span>
                    </div>
    
                    <button type="button" class="location-search-btn" (click)="goToVendorSearch()">
                        <i class="fa fa-angle-right"></i>
                    </button>
    
                </div>
            </div>
        </div>
    </ion-content>
    

    What is the difference between IQueryable<T> and IEnumerable<T>?

    First of all, IQueryable<T> extends the IEnumerable<T> interface, so anything you can do with a "plain" IEnumerable<T>, you can also do with an IQueryable<T>.

    IEnumerable<T> just has a GetEnumerator() method that returns an Enumerator<T> for which you can call its MoveNext() method to iterate through a sequence of T.

    What IQueryable<T> has that IEnumerable<T> doesn't are two properties in particular—one that points to a query provider (e.g., a LINQ to SQL provider) and another one pointing to a query expression representing the IQueryable<T> object as a runtime-traversable abstract syntax tree that can be understood by the given query provider (for the most part, you can't give a LINQ to SQL expression to a LINQ to Entities provider without an exception being thrown).

    The expression can simply be a constant expression of the object itself or a more complex tree of a composed set of query operators and operands. The query provider's IQueryProvider.Execute() or IQueryProvider.CreateQuery() methods are called with an Expression passed to it, and then either a query result or another IQueryable is returned, respectively.

    WhatsApp API (java/python)

    After trying everything, Yowsup library worked for me. The bug that I was facing was recently fixed. Anyone trying to do something with Whatsapp should try it.

    Getting a browser's name client-side

    Based on is.js you can write a helper file for getting browser name like this-

    const Browser = {};
    const vendor = (navigator && navigator.vendor || '').toLowerCase();
    const userAgent = (navigator && navigator.userAgent || '').toLowerCase();
    
    Browser.getBrowserName = () => {
      if(isOpera()) return 'opera'; // Opera
      else if(isChrome()) return 'chrome'; // Chrome
      else if(isFirefox()) return 'firefox'; // Firefox
      else if(isSafari()) return 'safari'; // Safari
      else if(isInternetExplorer()) return 'ie'; // Internet Explorer
    }
    
    
    // Start Detecting browser helpers functions
    function isOpera() {
      const isOpera = userAgent.match(/(?:^opera.+?version|opr)\/(\d+)/);
      return isOpera !== null;
    }
    
    function isChrome() {
      const isChrome = /google inc/.test(vendor) ? userAgent.match(/(?:chrome|crios)\/(\d+)/) : null;
      return isChrome !== null;
    }
    
    function isFirefox() {
      const isFirefox = userAgent.match(/(?:firefox|fxios)\/(\d+)/);
      return isFirefox !== null;
    }
    
    function isSafari() {
      const isSafari = userAgent.match(/version\/(\d+).+?safari/);
      return isSafari !== null;
    }
    
    function isInternetExplorer() {
      const isInternetExplorer = userAgent.match(/(?:msie |trident.+?; rv:)(\d+)/);
      return isInternetExplorer !== null;
    }
    // End Detecting browser helpers functions
    
    export default Browser;
    

    And just import this file where you need.

    import Browser from './Browser.js';
    
    const userBrowserName = Browser.getBrowserName() // return your browser name
                                                     // opera | chrome | firefox | safari | ie
    

    React.js: Wrapping one component into another

    In addition to Sophie's answer, I also have found a use in sending in child component types, doing something like this:

    var ListView = React.createClass({
        render: function() {
            var items = this.props.data.map(function(item) {
                return this.props.delegate({data:item});
            }.bind(this));
            return <ul>{items}</ul>;
        }
    });
    
    var ItemDelegate = React.createClass({
        render: function() {
            return <li>{this.props.data}</li>
        }
    });
    
    var Wrapper = React.createClass({    
        render: function() {
            return <ListView delegate={ItemDelegate} data={someListOfData} />
        }
    });
    

    Regular expression to match characters at beginning of line only

    Beginning of line or beginning of string?

    Start and end of string

    /^CTR.*$/
    

    / = delimiter
    ^ = start of string
    CTR = literal CTR
    $ = end of string
    .* = zero or more of any character except newline

    Start and end of line

    /^CTR.*$/m
    

    / = delimiter
    ^ = start of line
    CTR = literal CTR
    $ = end of line
    .* = zero or more of any character except newline
    m = enables multi-line mode, this sets regex to treat every line as a string, so ^ and $ will match start and end of line

    While in multi-line mode you can still match the start and end of the string with \A\Z permanent anchors

    /\ACTR.*\Z/m
    

    \A = means start of string
    CTR = literal CTR
    .* = zero or more of any character except newline
    \Z = end of string
    m = enables multi-line mode

    As such, another way to match the start of the line would be like this:

    /(\A|\r|\n|\r\n)CTR.*/
    

    or

    /(^|\r|\n|\r\n)CTR.*/
    

    \r = carriage return / old Mac OS newline
    \n = line-feed / Unix/Mac OS X newline
    \r\n = windows newline

    Note, if you are going to use the backslash \ in some program string that supports escaping, like the php double quotation marks "" then you need to escape them first

    so to run \r\nCTR.* you would use it as "\\r\\nCTR.*"

    Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

    Add a reference to 'Microsoft.VisualStudio.QualityTools.UnitTestFramework" NuGet packet and it should successfully build it.

    How to drop a PostgreSQL database if there are active connections to it?

    Depending on your version of postgresql you might run into a bug, that makes pg_stat_activity to omit active connections from dropped users. These connections are also not shown inside pgAdminIII.

    If you are doing automatic testing (in which you also create users) this might be a probable scenario.

    In this case you need to revert to queries like:

     SELECT pg_terminate_backend(procpid) 
     FROM pg_stat_get_activity(NULL::integer) 
     WHERE datid=(SELECT oid from pg_database where datname = 'your_database');
    

    NOTE: In 9.2+ you'll have change procpid to pid.

    PHP case-insensitive in_array function

    $user_agent = 'yandeX';
    $bots = ['Google','Yahoo','Yandex'];        
            
    foreach($bots as $b){
         if( stripos( $user_agent, $b ) !== false ) return $b;
    }
    

    how I can show the sum of in a datagridview column?

    int sum = 0;
    for (int i = 0; i < dataGridView1.Rows.Count; ++i)
    {
        sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
    }
    label1.Text = sum.ToString();
    

    Remote Linux server to remote linux server dir copy. How?

    Log in to one machine

    $ scp -r /path/to/top/directory user@server:/path/to/copy

    Generating a drop down list of timezones with PHP

    See this example also

    <?php
         function get_timezones() 
         {
            $o = array();
            $t_zones = timezone_identifiers_list();
            foreach($t_zones as $a)
            {
                $t = '';
    
                try
                {
                    //this throws exception for 'US/Pacific-New'
                    $zone = new DateTimeZone($a);
    
                    $seconds = $zone->getOffset( new DateTime("now" , $zone) );
                    $hours = sprintf( "%+02d" , intval($seconds/3600));
                    $minutes = sprintf( "%02d" , ($seconds%3600)/60 );
    
                    $t = $a ."  [ $hours:$minutes ]" ;
    
                    $o[$a] = $t;
                }
    
                //exceptions must be catched, else a blank page
                catch(Exception $e)
                {
                    //die("Exception : " . $e->getMessage() . '<br />');
                    //what to do in catch ? , nothing just relax
                }
            }
    
            ksort($o);
    
            return $o;
        } 
    
        $o = get_timezones();
        ?>
    
        <html>
        <body>
        <select name="time_zone">
        <?php
            foreach($o as $tz => $label)
            {
                echo "<option value="$tz">$label</option>";
            }
        ?>
        </select>
        </body>
        </html>
    

    How to convert an entire MySQL database characterset and collation to UTF-8?

    Before proceeding, ensure that you: Have completed a full database backup!

    Step 1: Database Level Changes

    • Identifying the Collation and Character set of your database

      SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME FROM 
      information_schema.SCHEMATA S
      WHERE schema_name = 'your_database_name'
      AND
      (DEFAULT_CHARACTER_SET_NAME != 'utf8'
          OR
       DEFAULT_COLLATION_NAME not like 'utf8%');
      
    • Fixing the collation for the database

      ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
      

    Step 2: Table Level Changes

    • Identifying Database Tables with the incorrect character set or collation

      SELECT CONCAT(
      'ALTER TABLE ',  table_name, ' CHARACTER SET utf8 COLLATE utf8_general_ci;  ', 
      'ALTER TABLE ',  table_name, ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  ')
      FROM information_schema.TABLES AS T, information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` AS C
      WHERE C.collation_name = T.table_collation
      AND T.table_schema = 'your_database_name'
      AND
      (C.CHARACTER_SET_NAME != 'utf8'
          OR
       C.COLLATION_NAME not like 'utf8%')
      
    • Adjusting table columns' collation and character set

    Capture upper sql output and run it. (like following)

    ALTER TABLE rma CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
    ALTER TABLE rma_history CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_history CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
    ALTER TABLE rma_products CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_products CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
    ALTER TABLE rma_report_period CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_report_period CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
    ALTER TABLE rma_reservation CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_reservation CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
    ALTER TABLE rma_supplier_return CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_supplier_return CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
    ALTER TABLE rma_supplier_return_history CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_supplier_return_history CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;  
    ALTER TABLE rma_supplier_return_product CHARACTER SET utf8 COLLATE utf8_general_ci;ALTER TABLE rma_supplier_return_product CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; 
    

    refer to: https://confluence.atlassian.com/display/CONFKB/How+to+Fix+the+Collation+and+Character+Set+of+a+MySQL+Database

    jQuery and AJAX response header

    UPDATE 2018 FOR JQUERY 3 AND LATER

    I know this is an old question but none of the above solutions worked for me. Here is the solution that worked:

    //I only created this function as I am making many ajax calls with different urls and appending the result to different divs
    function makeAjaxCall(requestType, urlTo, resultAreaId){
            var jqxhr = $.ajax({
                type: requestType,
                url: urlTo
            });
            //this section is executed when the server responds with no error 
            jqxhr.done(function(){
    
            });
            //this section is executed when the server responds with error
            jqxhr.fail(function(){
    
            })
            //this section is always executed
            jqxhr.always(function(){
                console.log("getting header " + jqxhr.getResponseHeader('testHeader'));
            });
        }
    

    How to handle anchor hash linking in AngularJS

    Here is kind of dirty workaround by creating custom directive that will scrolls to specified element (with hardcoded "faq")

    app.directive('h3', function($routeParams) {
      return {
        restrict: 'E',
        link: function(scope, element, attrs){        
            if ('faq'+$routeParams.v == attrs.id) {
              setTimeout(function() {
                 window.scrollTo(0, element[0].offsetTop);
              },1);        
            }
        }
      };
    });
    

    http://plnkr.co/edit/Po37JFeP5IsNoz5ZycFs?p=preview

    How can prepared statements protect from SQL injection attacks?

    Here is SQL for setting up an example:

    CREATE TABLE employee(name varchar, paymentType varchar, amount bigint);
    
    INSERT INTO employee VALUES('Aaron', 'salary', 100);
    INSERT INTO employee VALUES('Aaron', 'bonus', 50);
    INSERT INTO employee VALUES('Bob', 'salary', 50);
    INSERT INTO employee VALUES('Bob', 'bonus', 0);
    

    The Inject class is vulnerable to SQL injection. The query is dynamically pasted together with user input. The intent of the query was to show information about Bob. Either salary or bonus, based on user input. But the malicious user manipulates the input corrupting the query by tacking on the equivalent of an 'or true' to the where clause so that everything is returned, including the information about Aaron which was supposed to be hidden.

    import java.sql.*;
    
    public class Inject {
    
        public static void main(String[] args) throws SQLException {
    
            String url = "jdbc:postgresql://localhost/postgres?user=user&password=pwd";
            Connection conn = DriverManager.getConnection(url);
    
            Statement stmt = conn.createStatement();
            String sql = "SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='" + args[0] + "'";
            System.out.println(sql);
            ResultSet rs = stmt.executeQuery(sql);
    
            while (rs.next()) {
                System.out.println(rs.getString("paymentType") + " " + rs.getLong("amount"));
            }
        }
    }
    

    Running this, the first case is with normal usage, and the second with the malicious injection:

    c:\temp>java Inject salary
    SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='salary'
    salary 50
    
    c:\temp>java Inject "salary' OR 'a'!='b"
    SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType='salary' OR 'a'!='b'
    salary 100
    bonus 50
    salary 50
    bonus 0
    

    You should not build your SQL statements with string concatenation of user input. Not only is it vulnerable to injection, but it has caching implications on the server as well (the statement changes, so less likely to get a SQL statement cache hit whereas the bind example is always running the same statement).

    Here is an example of Binding to avoid this kind of injection:

    import java.sql.*;
    
    public class Bind {
    
        public static void main(String[] args) throws SQLException {
    
            String url = "jdbc:postgresql://localhost/postgres?user=postgres&password=postgres";
            Connection conn = DriverManager.getConnection(url);
    
            String sql = "SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?";
            System.out.println(sql);
    
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, args[0]);
    
            ResultSet rs = stmt.executeQuery();
    
            while (rs.next()) {
                System.out.println(rs.getString("paymentType") + " " + rs.getLong("amount"));
            }
        }
    }
    

    Running this with the same input as the previous example shows the malicious code does not work because there is no paymentType matching that string:

    c:\temp>java Bind salary
    SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?
    salary 50
    
    c:\temp>java Bind "salary' OR 'a'!='b"
    SELECT paymentType, amount FROM employee WHERE name = 'bob' AND paymentType=?
    

    Is it possible to install iOS 6 SDK on Xcode 5?

    Just to add, you can actually download old versions of the simulator with Xcode 5 itself - just go to preferences and you'll find them under Downloads:

    enter image description here

    Creating an empty bitmap and drawing though canvas in Android

    This is probably simpler than you're thinking:

    int w = WIDTH_PX, h = HEIGHT_PX;
    
    Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
    Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
    Canvas canvas = new Canvas(bmp);
    
    // ready to draw on that bitmap through that canvas
    

    Here's a series of tutorials I've found on the topic: Drawing with Canvas Series

    Pass arguments to Constructor in VBA

    Another approach

    Say you create a class clsBitcoinPublicKey

    In the class module create an ADDITIONAL subroutine, that acts as you would want the real constructor to behave. Below I have named it ConstructorAdjunct.

    Public Sub ConstructorAdjunct(ByVal ...)
    
     ...
    
    End Sub
    
    From the calling module, you use an additional statement
    
    Dim loPublicKey AS clsBitcoinPublicKey
    
    Set loPublicKey = New clsBitcoinPublicKey
    
    Call loPublicKey.ConstructorAdjunct(...)
    

    The only penalty is the extra call, but the advantage is that you can keep everything in the class module, and debugging becomes easier.

    How to make HTML Text unselectable

    You can't do this with plain vanilla HTML, so JSF can't do much for you here as well.

    If you're targeting decent browsers only, then just make use of CSS3:

    .unselectable {
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
    }
    
    <label class="unselectable">Unselectable label</label>
    

    If you'd like to cover older browsers as well, then consider this JavaScript fallback:

    <!doctype html>
    <html lang="en">
        <head>
            <title>SO question 2310734</title>
            <script>
                window.onload = function() {
                    var labels = document.getElementsByTagName('label');
                    for (var i = 0; i < labels.length; i++) {
                        disableSelection(labels[i]);
                    }
                };
                function disableSelection(element) {
                    if (typeof element.onselectstart != 'undefined') {
                        element.onselectstart = function() { return false; };
                    } else if (typeof element.style.MozUserSelect != 'undefined') {
                        element.style.MozUserSelect = 'none';
                    } else {
                        element.onmousedown = function() { return false; };
                    }
                }
            </script>
        </head>
        <body>
            <label>Try to select this</label>
        </body>
    </html>
    

    If you're already using jQuery, then here's another example which adds a new function disableSelection() to jQuery so that you can use it anywhere in your jQuery code:

    <!doctype html>
    <html lang="en">
        <head>
            <title>SO question 2310734 with jQuery</title>
            <script src="http://code.jquery.com/jquery-latest.min.js"></script>
            <script>
                $.fn.extend({ 
                    disableSelection: function() { 
                        this.each(function() { 
                            if (typeof this.onselectstart != 'undefined') {
                                this.onselectstart = function() { return false; };
                            } else if (typeof this.style.MozUserSelect != 'undefined') {
                                this.style.MozUserSelect = 'none';
                            } else {
                                this.onmousedown = function() { return false; };
                            }
                        }); 
                    } 
                });
    
                $(document).ready(function() {
                    $('label').disableSelection();            
                });
            </script>
        </head>
        <body>
            <label>Try to select this</label>
        </body>
    </html>
    

    Quotation marks inside a string

    String name = "\"john\"";
    

    You have to escape the second pair of quotation marks using the \ character in front. It might be worth looking at this link, which explains in some detail.

    Other scenario where you set variable:

    String name2 = "\""+name+"\"";
    

    Sequence in console:

    > String name = "\"john\"";
    > name
    ""john""
    > String name2 = "\""+name+"\"";
    > name2
    """john"""
    

    Match exact string

    It depends. You could

    string.match(/^abc$/)
    

    But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'

    I think you would want to use \b (word boundaries):

    _x000D_
    _x000D_
    var str = 'the first 3 letters of the alphabet are abc. not abc123';_x000D_
    var pat = /\b(abc)\b/g;_x000D_
    console.log(str.match(pat));
    _x000D_
    _x000D_
    _x000D_

    Live example: http://jsfiddle.net/uu5VJ/

    If the former solution works for you, I would advise against using it.

    That means you may have something like the following:

    var strs = ['abc', 'abc1', 'abc2']
    for (var i = 0; i < strs.length; i++) {
        if (strs[i] == 'abc') {
            //do something 
        }
        else {
            //do something else
        }
    }
    

    While you could use

    if (str[i].match(/^abc$/g)) {
        //do something 
    }
    

    It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.

    More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

    Fitting empirical distribution to theoretical ones with Scipy (Python)?

    It sounds like probability density estimation problem to me.

    from scipy.stats import gaussian_kde
    occurences = [0,0,0,0,..,1,1,1,1,...,2,2,2,2,...,47]
    values = range(0,48)
    kde = gaussian_kde(map(float, occurences))
    p = kde(values)
    p = p/sum(p)
    print "P(x>=1) = %f" % sum(p[1:])
    

    Also see http://jpktd.blogspot.com/2009/03/using-gaussian-kernel-density.html.

    Easy way to write contents of a Java InputStream to an OutputStream

    A IMHO more minimal snippet (that also more narrowly scopes the length variable):

    byte[] buffer = new byte[2048];
    for (int n = in.read(buffer); n >= 0; n = in.read(buffer))
        out.write(buffer, 0, n);
    

    As a side note, I don't understand why more people don't use a for loop, instead opting for a while with an assign-and-test expression that is regarded by some as "poor" style.

    GitHub: How to make a fork of public repository private?

    The answers are correct but don't mention how to sync code between the public repo and the fork.

    Here is the full workflow (we've done this before open sourcing React Native):


    First, duplicate the repo as others said (details here):

    Create a new repo (let's call it private-repo) via the Github UI. Then:

    git clone --bare https://github.com/exampleuser/public-repo.git
    cd public-repo.git
    git push --mirror https://github.com/yourname/private-repo.git
    cd ..
    rm -rf public-repo.git
    

    Clone the private repo so you can work on it:

    git clone https://github.com/yourname/private-repo.git
    cd private-repo
    make some changes
    git commit
    git push origin master
    

    To pull new hotness from the public repo:

    cd private-repo
    git remote add public https://github.com/exampleuser/public-repo.git
    git pull public master # Creates a merge commit
    git push origin master
    

    Awesome, your private repo now has the latest code from the public repo plus your changes.


    Finally, to create a pull request private repo -> public repo:

    Use the GitHub UI to create a fork of the public repo (the small "Fork" button at the top right of the public repo page). Then:

    git clone https://github.com/yourname/the-fork.git
    cd the-fork
    git remote add private_repo_yourname https://github.com/yourname/private-repo.git
    git checkout -b pull_request_yourname
    git pull private_repo_yourname master
    git push origin pull_request_yourname
    

    Now you can create a pull request via the Github UI for public-repo, as described here.

    Once project owners review your pull request, they can merge it.

    Of course the whole process can be repeated (just leave out the steps where you add remotes).

    SVN check out linux

    You can use checkout or co

    $ svn co http://example.com/svn/app-name directory-name
    

    Some short codes:-

    1. checkout (co)
    2. commit (ci)
    3. copy (cp)
    4. delete (del, remove,rm)
    5. diff (di)

    Change value of input onchange?

    for jQuery we can use below:

    by input name:

    $('input[name="textboxname"]').val('some value');
    

    by input class:

    $('input[type=text].textboxclass').val('some value');
    

    by input id:

    $('#textboxid').val('some value');
    

    Get the week start date and week end date from week number

    Week Start & End Date From Date For Power BI Dax Formula

    WeekStartDate = [DateColumn] - (WEEKDAY([DateColumn])-1)
    WeekEndDate = [DateColumn] + (7-WEEKDAY([DateColumn]))
    

    How do I convert certain columns of a data frame to become factors?

    Here's an example:

    #Create a data frame
    > d<- data.frame(a=1:3, b=2:4)
    > d
      a b
    1 1 2
    2 2 3
    3 3 4
    
    #currently, there are no levels in the `a` column, since it's numeric as you point out.
    > levels(d$a)
    NULL
    
    #Convert that column to a factor
    > d$a <- factor(d$a)
    > d
      a b
    1 1 2
    2 2 3
    3 3 4
    
    #Now it has levels.
    > levels(d$a)
    [1] "1" "2" "3"
    

    You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

    Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

    Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

    Is a DIV inside a TD a bad idea?

    I have faced the problem by placing a <div> inside <td>.

    I was unable to identify the div using document.getElementById() if i place that inside td. But outside, it was working fine.

    How exactly does <script defer="defer"> work?

    This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. Never call document.write() from a defer script (since Gecko 1.9.2, this will blow away the document). The defer attribute shouldn't be used on scripts that don't have the src attribute. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.

    defer works with chrome , firefox , ie > 7 and Safari

    ref: https://developer.mozilla.org/en-US/docs/HTML/Element/script

    Add back button to action bar

    Add this line in onCreate() method

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    

    then Override this method

     @Override
        public boolean onSupportNavigateUp(){
            finish();
            return true;
        }
    

    href image link download on click

    <a download="custom-filename.jpg" href="/path/to/image" title="ImageName">
        <img alt="ImageName" src="/path/to/image">
    </a>
    

    It's not yet fully supported caniuse, but you can use with modernizr (under Non-core detects) to check the support of the browser.

    server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

    TLDR:

    hostname=XXX
    port=443
    trust_cert_file_location=`curl-config --ca`
    
    sudo bash -c "echo -n | openssl s_client -showcerts -connect $hostname:$port -servername $hostname \
        2>/dev/null  | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'  \
        >> $trust_cert_file_location"
    

    Long answer

    The basic reason is that your computer doesn't trust the certificate authority that signed the certificate used on the Gitlab server. This doesn't mean the certificate is suspicious, but it could be self-signed or signed by an institution/company that isn't in the list of your OS's list of CAs. What you have to do to circumvent the problem on your computer is telling it to trust that certificate - if you don't have any reason to be suspicious about it.

    You need to check the web certificate used for your gitLab server, and add it to your </git_installation_folder>/bin/curl-ca-bundle.crt.

    To check if at least the clone works without checking said certificate, you can set:

    export GIT_SSL_NO_VERIFY=1
    #or
    git config --global http.sslverify false
    

    But that would be for testing only, as illustrated in "SSL works with browser, wget, and curl, but fails with git", or in this blog post.

    Check your GitLab settings, a in issue 4272.


    To get that certificate (that you would need to add to your curl-ca-bundle.crt file), type a:

    echo -n | openssl s_client -showcerts -connect yourserver.com:YourHttpsGitlabPort \
      2>/dev/null  | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
    

    (with 'yourserver.com' being your GitLab server name, and YourHttpsGitlabPort is the https port, usually 443)

    To check the CA (Certificate Authority issuer), type a:

    echo -n | openssl s_client -showcerts -connect yourserver.com:YourHttpsGilabPort \
      2>/dev/null  | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' \
      | openssl x509 -noout -text | grep "CA Issuers" | head -1
    

    Note: Valeriy Katkov suggests in the comments to add -servername option to the openssl command, otherwise the command isn't showed certificate for www.github.com in Valeriy's case.

    openssl s_client -showcerts -servername www.github.com -connect www.github.com:443
    

    Findekano adds in the comments:

    to identify the location of curl-ca-bundle.crt, you could use the command

    curl-config --ca
    

    Also, see my more recent answer "github: server certificate verification failed": you might have to renistall those certificates:

    sudo apt-get install --reinstall ca-certificates
    sudo mkdir /usr/local/share/ca-certificates/cacert.org
    sudo wget -P /usr/local/share/ca-certificates/cacert.org http://www.cacert.org/certs/root.crt http://www.cacert.org/certs/class3.crt
    sudo update-ca-certificates
    git config --global http.sslCAinfo /etc/ssl/certs/ca-certificates.crt
    

    How to get the number of columns from a JDBC ResultSet?

    PreparedStatement ps=con.prepareStatement("select * from stud");
    
    ResultSet rs=ps.executeQuery();
    
    ResultSetMetaData rsmd=rs.getMetaData();
    
    System.out.println("columns: "+rsmd.getColumnCount());  
    System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));  
    System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)); 
    

    Zoom to fit all markers in Mapbox or Leaflet

    To fit to the visible markers only, I've this method.

    fitMapBounds() {
        // Get all visible Markers
        const visibleMarkers = [];
        this.map.eachLayer(function (layer) {
            if (layer instanceof L.Marker) {
                visibleMarkers.push(layer);
            }
        });
    
        // Ensure there's at least one visible Marker
        if (visibleMarkers.length > 0) {
    
            // Create bounds from first Marker then extend it with the rest
            const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
            visibleMarkers.forEach((marker) => {
                markersBounds.extend(marker.getLatLng());
            });
    
            // Fit the map with the visible markers bounds
            this.map.flyToBounds(markersBounds, {
                padding: L.point(36, 36), animate: true,
            });
        }
    }
    

    What is a Data Transfer Object (DTO)?

    A Data Transfer Object is an object that is used to encapsulate data, and send it from one subsystem of an application to another.

    DTOs are most commonly used by the Services layer in an N-Tier application to transfer data between itself and the UI layer. The main benefit here is that it reduces the amount of data that needs to be sent across the wire in distributed applications. They also make great models in the MVC pattern.

    Another use for DTOs can be to encapsulate parameters for method calls. This can be useful if a method takes more than 4 or 5 parameters.

    When using the DTO pattern, you would also make use of DTO assemblers. The assemblers are used to create DTOs from Domain Objects, and vice versa.

    The conversion from Domain Object to DTO and back again can be a costly process. If you're not creating a distributed application, you probably won't see any great benefits from the pattern, as Martin Fowler explains here

    Sort Pandas Dataframe by Date

    @JAB's answer is fast and concise. But it changes the DataFrame you are trying to sort, which you may or may not want.

    (Note: You almost certainly will want it, because your date columns should be dates, not strings!)

    In the unlikely event that you don't want to change the dates into dates, you can also do it a different way.

    First, get the index from your sorted Date column:

    In [25]: pd.to_datetime(df.Date).order().index
    Out[25]: Int64Index([0, 2, 1], dtype='int64')
    

    Then use it to index your original DataFrame, leaving it untouched:

    In [26]: df.ix[pd.to_datetime(df.Date).order().index]
    Out[26]: 
            Date Symbol
    0 2015-02-20      A
    2 2015-08-21      A
    1 2016-01-15      A
    

    Magic!

    Note: for Pandas versions 0.20.0 and later, use loc instead of ix, which is now deprecated.

    How to set a variable to current date and date-1 in linux?

    simple:

    today="$(date '+%Y-%m-%d')"
    yesterday="$(date -d yesterday '+%Y-%m-%d')"
    

    adding .css file to ejs

    In order to serve up a static CSS file in express app (i.e. use a css style file to style ejs "templates" files in express app). Here are the simple 3 steps that need to happen:

    1. Place your css file called "styles.css" in a folder called "assets" and the assets folder in a folder called "public". Thus the relative path to the css file should be "/public/assets/styles.css"

    2. In the head of each of your ejs files you would simply call the css file (like you do in a regular html file) with a <link href=… /> as shown in the code below. Make sure you copy and paste the code below directly into your ejs file <head> section

      <link href= "/public/assets/styles.css" rel="stylesheet" type="text/css" />
      
    3. In your server.js file, you need to use the app.use() middleware. Note that a middleware is nothing but a term that refers to those operations or code that is run between the request and the response operations. By putting a method in middleware, that method will automatically be called everytime between the request and response methods. To serve up static files (such as a css file) in the app.use() middleware there is already a function/method provided by express called express.static(). Lastly, you also need to specify a request route that the program will respond to and serve up the files from the static folder everytime the middleware is called. Since you will be placing the css files in your public folder. In the server.js file, make sure you have the following code:

      // using app.use to serve up static CSS files in public/assets/ folder when /public link is called in ejs files
      // app.use("/route", express.static("foldername"));
      app.use('/public', express.static('public'));
      

    After following these simple 3 steps, every time you res.render('ejsfile') in your app.get() methods you will automatically see the css styling being called. You can test by accessing your routes in the browser.

    CHECK constraint in MySQL is not working

    The CHECK constraint doesn't seem to be implemented in MySQL.

    See this bug report: https://bugs.mysql.com/bug.php?id=3464

    Default password of mysql in ubuntu server 16.04

    I think another place to look is /var/lib. If you go there you can see three mysql folders with 'interesting' permissions:

    user   group 
    mysql  mysql
    

    Here is what I did to solve my problem with root password:

    after running

    sudo apt-get purge mysql*
    sudo rm -rf /etc/mysql
    

    I also ran the following (instead of my_username put yours):

    cd /var/lib
    sudo chown --from=mysql <my_username> mysql* -R
    sudo rm -rf mysql*
    

    And then:

    sudo apt-get install mysql-server
    

    which prompted me to select a new root password. I hope it helps

    invalid_client in google oauth2

    Set/change your product name, I had this issue until I created a product name as same as project name.

    The product name can be set in the Consent screen section of the Google Developers Console for your project. Look under APIs & auth in the left navigation and select Consent screen. You need also to set your email address in the box above the product name.

    Find duplicates and delete all in notepad++

    If it is possible to change the sequence of the lines you could do:

    1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
    2. do a Find / Replace:
      • Find What: ^(.*\r?\n)\1+
      • Replace with: (Nothing, leave empty)
      • Check Regular Expression in the lower left
      • Click Replace All

    How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

    The \r?\n should deal nicely with Windows and Unix lineendings.

    What's wrong with nullable columns in composite primary keys?

    A primary key defines a unique identifier for every row in a table: when a table has a primary key, you have a guranteed way to select any row from it.

    A unique constraint does not necessarily identify every row; it just specifies that if a row has values in its columns, then they must be unique. This is not sufficient to uniquely identify every row, which is what a primary key must do.

    How to initialize a nested struct?

    Well, any specific reason to not make Proxy its own struct?

    Anyway you have 2 options:

    The proper way, simply move proxy to its own struct, for example:

    type Configuration struct {
        Val string
        Proxy Proxy
    }
    
    type Proxy struct {
        Address string
        Port    string
    }
    
    func main() {
    
        c := &Configuration{
            Val: "test",
            Proxy: Proxy{
                Address: "addr",
                Port:    "port",
            },
        }
        fmt.Println(c)
        fmt.Println(c.Proxy.Address)
    }
    

    The less proper and ugly way but still works:

    c := &Configuration{
        Val: "test",
        Proxy: struct {
            Address string
            Port    string
        }{
            Address: "addr",
            Port:    "80",
        },
    }
    

    Python threading. How do I lock a thread?

    import threading 
    
    # global variable x 
    x = 0
    
    def increment(): 
        """ 
        function to increment global variable x 
        """
        global x 
        x += 1
    
    def thread_task(): 
        """ 
        task for thread 
        calls increment function 100000 times. 
        """
        for _ in range(100000): 
            increment() 
    
    def main_task(): 
        global x 
        # setting global variable x as 0 
        x = 0
    
        # creating threads 
        t1 = threading.Thread(target=thread_task) 
        t2 = threading.Thread(target=thread_task) 
    
        # start threads 
        t1.start() 
        t2.start() 
    
        # wait until threads finish their job 
        t1.join() 
        t2.join() 
    
    if __name__ == "__main__": 
        for i in range(10): 
            main_task() 
            print("Iteration {0}: x = {1}".format(i,x))
    

    C# how to create a Guid value?

    Alternately, if you are using SQL Server as your database you can get your GUID from the server instead. In TSQL:

    //Retrive your key ID on the bases of GUID 
    
    declare @ID as uniqueidentifier
    
    SET @ID=NEWID()
    insert into Sector(Sector,CID)
    
    Values ('Diry7',@ID)
    
    
    select SECTORID from sector where CID=@ID
    

    Want to download a Git repository, what do I need (windows machine)?

    Install mysysgit. (Same as Greg Hewgill's answer.)

    Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.)

    After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.

    This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)

    How to set the maximum memory usage for JVM?

    The answer above is kind of correct, you can't gracefully control how much native memory a java process allocates. It depends on what your application is doing.

    That said, depending on platform, you may be able to do use some mechanism, ulimit for example, to limit the size of a java or any other process.

    Just don't expect it to fail gracefully if it hits that limit. Native memory allocation failures are much harder to handle than allocation failures on the java heap. There's a fairly good chance the application will crash but depending on how critical it is to the system to keep the process size down that might still suit you.

    How can I change the text inside my <span> with jQuery?

    Try this

    $("#abc").html('<span class = "xyz"> SAMPLE TEXT</span>');

    Handle all the css relevant to that span within xyz

    Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

    I think that error from Nginx is indicating that the connection was closed by your nodejs server (i.e., "upstream"). How is nodejs configured?

    Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

    same thing JUST happened to me with NUGET.

    the following tag helped

    <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages.Razor" PublicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
    

    Also if this is happening on the server, I had to make sure I was running the application pool on a more "privileged account" to the file system, but I don think that's your issue here

    How to get enum value by string or int

    From SQL database get enum like:

    SqlDataReader dr = selectCmd.ExecuteReader();
    while (dr.Read()) {
       EnumType et = (EnumType)Enum.Parse(typeof(EnumType), dr.GetString(0));
       ....         
    }
    

    How can I disable ReSharper in Visual Studio and enable it again?

    Now Resharper supports Suspend & Resume argument at devenv.exe

    (ReSharper 2019.2.3)

    Run VS & Suspend R#:

    devenv.exe /ReSharper.Suspend
    

    Run VS & Resume R#:

    devenv.exe /ReSharper.Resume
    

    Here's an example usage:

    enter image description here

    error: RPC failed; curl transfer closed with outstanding read data remaining

    Simple Solution: Rather then cloning via https, clone it via ssh.

    For example:

    git clone https://github.com/vaibhavjain2/xxx.git - Avoid
    git clone [email protected]:vaibhavjain2/xxx.git - Correct
    

    Command line: search and replace in all filenames matched by grep

    I like and used the above solution or a system wide search and replace among thousands of files:

    find -name '*.htm?' -print -exec sed -i.bak 's/foo/bar/g' {} \;
    

    I assume with the '*.htm?' instead of .html it searches and finds .htm and .html files alike.

    I replace the .bak with the more system wide used tilde (~) to make clean up of backup files easier.

    Resolving ORA-4031 "unable to allocate x bytes of shared memory"

    Don't forget about fragmentation. If you have a lot of traffic, your pools can be fragmented and even if you have several MB free, there could be no block larger than 4KB. Check size of largest free block with a query like:

     select
      '0 (<140)' BUCKET, KSMCHCLS, KSMCHIDX,
      10*trunc(KSMCHSIZ/10) "From",
      count(*) "Count" ,
      max(KSMCHSIZ) "Biggest",
      trunc(avg(KSMCHSIZ)) "AvgSize",
      trunc(sum(KSMCHSIZ)) "Total"
    from
      x$ksmsp
    where
      KSMCHSIZ<140
    and
      KSMCHCLS='free'
    group by
      KSMCHCLS, KSMCHIDX, 10*trunc(KSMCHSIZ/10)
    UNION ALL
    select
      '1 (140-267)' BUCKET,
      KSMCHCLS,
      KSMCHIDX,
      20*trunc(KSMCHSIZ/20) ,
      count(*) ,
      max(KSMCHSIZ) ,
      trunc(avg(KSMCHSIZ)) "AvgSize",
      trunc(sum(KSMCHSIZ)) "Total"
    from
      x$ksmsp
    where
      KSMCHSIZ between 140 and 267
    and
      KSMCHCLS='free'
    group by
      KSMCHCLS, KSMCHIDX, 20*trunc(KSMCHSIZ/20)
    UNION ALL
    select
      '2 (268-523)' BUCKET,
      KSMCHCLS,
      KSMCHIDX,
      50*trunc(KSMCHSIZ/50) ,
      count(*) ,
      max(KSMCHSIZ) ,
      trunc(avg(KSMCHSIZ)) "AvgSize",
      trunc(sum(KSMCHSIZ)) "Total"
    from
      x$ksmsp
    where
      KSMCHSIZ between 268 and 523
    and
      KSMCHCLS='free'
    group by
      KSMCHCLS, KSMCHIDX, 50*trunc(KSMCHSIZ/50)
    UNION ALL
    select
      '3-5 (524-4107)' BUCKET,
      KSMCHCLS,
      KSMCHIDX,
      500*trunc(KSMCHSIZ/500) ,
      count(*) ,
      max(KSMCHSIZ) ,
      trunc(avg(KSMCHSIZ)) "AvgSize",
      trunc(sum(KSMCHSIZ)) "Total"
    from
      x$ksmsp
    where
      KSMCHSIZ between 524 and 4107
    and
      KSMCHCLS='free'
    group by
      KSMCHCLS, KSMCHIDX, 500*trunc(KSMCHSIZ/500)
    UNION ALL
    select
      '6+ (4108+)' BUCKET,
      KSMCHCLS,
      KSMCHIDX,
      1000*trunc(KSMCHSIZ/1000) ,
      count(*) ,
      max(KSMCHSIZ) ,
      trunc(avg(KSMCHSIZ)) "AvgSize",
      trunc(sum(KSMCHSIZ)) "Total"
    from
      x$ksmsp
    where
      KSMCHSIZ >= 4108
    and
      KSMCHCLS='free'
    group by
      KSMCHCLS, KSMCHIDX, 1000*trunc(KSMCHSIZ/1000);
    

    Code from

    Options for HTML scraping?

    In the .NET world, I recommend the HTML Agility Pack. Not near as simple as some of the above options (like HTMLSQL), but it's very flexible. It lets you maniuplate poorly formed HTML as if it were well formed XML, so you can use XPATH or just itereate over nodes.

    http://www.codeplex.com/htmlagilitypack

    Select multiple columns using Entity Framework

    It's correct way to get data in specified type:

    var dataset = entities.processlists
             .Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
             .Select(x => new { x.ServerName, x.ProcessID, x.Username })
             .ToList() /// To get data from database
             .Select(x => new PInfo()
                  { 
                       ServerName = x.ServerName, 
                       ProcessID = x.ProcessID, 
                       Username = x.Username 
                  });
    

    For more information see: The entity cannot be constructed in a LINQ to Entities query

    Limit String Length

    From php 4.0.6 , there is a function for the exact same thing

    function mb_strimwidth can be used for your requirement

    <?php
    echo mb_strimwidth("Hello World", 0, 10, "...");
    //Hello W...
    ?>
    

    It does have more options though,here is the documentation for this mb_strimwidth

    join list of lists in python

    There's always reduce (being deprecated to functools):

    >>> x = [ [ 'a', 'b'], ['c'] ]
    >>> for el in reduce(lambda a,b: a+b, x, []):
    ...  print el
    ...
    __main__:1: DeprecationWarning: reduce() not supported in 3.x; use functools.reduce()
    a
    b
    c
    >>> import functools
    >>> for el in functools.reduce(lambda a,b: a+b, x, []):
    ...   print el
    ...
    a
    b
    c
    >>>
    

    Unfortunately the plus operator for list concatenation can't be used as a function -- or fortunate, if you prefer lambdas to be ugly for improved visibility.

    Check if string is in a pandas dataframe

    Pandas seem to be recommending df.to_numpy since the other methods still raise a FutureWarning: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html#pandas.DataFrame.to_numpy

    So, an alternative that would work int this case is:

    b=a['Names']
    c = b.to_numpy().tolist()
    if 'Mel' in c:
         print("Mel is in the dataframe column Names")
    

    AJAX Mailchimp signup form integration

    You should use the server-side code in order to secure your MailChimp account.

    The following is an updated version of this answer which uses PHP:

    The PHP files are "secured" on the server where the user never sees them yet the jQuery can still access & use.

    1) Download the PHP 5 jQuery example here...

    http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip

    If you only have PHP 4, simply download version 1.2 of the MCAPI and replace the corresponding MCAPI.class.php file above.

    http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip

    2) Follow the directions in the Readme file by adding your API key and List ID to the store-address.php file at the proper locations.

    3) You may also want to gather your users' name and/or other information. You have to add an array to the store-address.php file using the corresponding Merge Variables.

    Here is what my store-address.php file looks like where I also gather the first name, last name, and email type:

    <?php
    
    function storeAddress(){
    
        require_once('MCAPI.class.php');  // same directory as store-address.php
    
        // grab an API Key from http://admin.mailchimp.com/account/api/
        $api = new MCAPI('123456789-us2');
    
        $merge_vars = Array( 
            'EMAIL' => $_GET['email'],
            'FNAME' => $_GET['fname'], 
            'LNAME' => $_GET['lname']
        );
    
        // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
        // Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
        $list_id = "123456a";
    
        if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
            // It worked!   
            return 'Success!&nbsp; Check your inbox or spam folder for a message containing a confirmation link.';
        }else{
            // An error ocurred, return error message   
            return '<b>Error:</b>&nbsp; ' . $api->errorMessage;
        }
    
    }
    
    // If being called via ajax, autorun the function
    if($_GET['ajax']){ echo storeAddress(); }
    ?>
    

    4) Create your HTML/CSS/jQuery form. It is not required to be on a PHP page.

    Here is something like what my index.html file looks like:

    <form id="signup" action="index.html" method="get">
        <input type="hidden" name="ajax" value="true" />
        First Name: <input type="text" name="fname" id="fname" />
        Last Name: <input type="text" name="lname" id="lname" />
        email Address (required): <input type="email" name="email" id="email" />
        HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
        Text: <input type="radio" name="emailtype" value="text" />
        <input type="submit" id="SendButton" name="submit" value="Submit" />
    </form>
    <div id="message"></div>
    
    <script src="jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript"> 
    $(document).ready(function() {
        $('#signup').submit(function() {
            $("#message").html("<span class='error'>Adding your email address...</span>");
            $.ajax({
                url: 'inc/store-address.php', // proper url to your "store-address.php" file
                data: $('#signup').serialize(),
                success: function(msg) {
                    $('#message').html(msg);
                }
            });
            return false;
        });
    });
    </script>
    

    Required pieces...

    • index.html constructed as above or similar. With jQuery, the appearance and options are endless.

    • store-address.php file downloaded as part of PHP examples on Mailchimp site and modified with your API KEY and LIST ID. You need to add your other optional fields to the array.

    • MCAPI.class.php file downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4). Place it in the same directory as your store-address.php or you must update the url path within store-address.php so it can find it.

    Python pandas Filtering out nan from a data selection of a column of strings

    df = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],'rating': [3., 4., 5., np.nan, np.nan, np.nan],'name': ['John','James', np.nan, np.nan, np.nan,np.nan]})
    
    for col in df.columns:
        df = df[~pd.isnull(df[col])]
    

    pros and cons between os.path.exists vs os.path.isdir

    Just like it sounds like: if the path exists, but is a file and not a directory, isdir will return False. Meanwhile, exists will return True in both cases.

    jQuery javascript regex Replace <br> with \n

    myString.replace(/<br ?\/?>/g, "\n")

    HTML how to clear input using javascript?

    you can use attribute placeholder

    <input type="text" name="email" placeholder="[email protected]" size="30" />
    

    or try this for older browsers

    <input type="text" name="email" value="[email protected]" size="30" onblur="if(this.value==''){this.value='[email protected]';}" onfocus="if(this.value=='[email protected]'){this.value='';}">
    

    How do I check for a network connection?

    You can check for a network connection in .NET 2.0 using GetIsNetworkAvailable():

    System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
    

    To monitor changes in IP address or changes in network availability use the events from the NetworkChange class:

    System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
    System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
    

    MySQL how to join tables on two fields

    JOIN t2 ON (t2.id = t1.id AND t2.date = t1.date)
    

    PowerShell Connect to FTP server and get files

    The AlexFTPS library used in the question seems to be dead (was not updated since 2011).


    With no external libraries

    You can try to implement this without any external library. But unfortunately, neither the .NET Framework nor PowerShell have any explicit support for downloading all files in a directory (let only recursive file downloads).

    You have to implement that yourself:

    • List the remote directory
    • Iterate the entries, downloading files (and optionally recursing into subdirectories - listing them again, etc.)

    Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the .NET framework (FtpWebRequest or WebClient). The .NET framework unfortunately does not support the MLSD command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.

    Your options are:

    • If you know that the directory does not contain any subdirectories, use the ListDirectory method (NLST FTP command) and simply download all the "names" as files.
    • Do an operation on a file name that is certain to fail for file and succeeds for directories (or vice versa). I.e. you can try to download the "name".
    • You may be lucky and in your specific case, you can tell a file from a directory by a file name (i.e. all your files have an extension, while subdirectories do not)
    • You use a long directory listing (LIST command = ListDirectoryDetails method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)
    function DownloadFtpDirectory($url, $credentials, $localPath)
    {
        $listRequest = [Net.WebRequest]::Create($url)
        $listRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
        $listRequest.Credentials = $credentials
    
        $lines = New-Object System.Collections.ArrayList
    
        $listResponse = $listRequest.GetResponse()
        $listStream = $listResponse.GetResponseStream()
        $listReader = New-Object System.IO.StreamReader($listStream)
        while (!$listReader.EndOfStream)
        {
            $line = $listReader.ReadLine()
            $lines.Add($line) | Out-Null
        }
        $listReader.Dispose()
        $listStream.Dispose()
        $listResponse.Dispose()
    
        foreach ($line in $lines)
        {
            $tokens = $line.Split(" ", 9, [StringSplitOptions]::RemoveEmptyEntries)
            $name = $tokens[8]
            $permissions = $tokens[0]
    
            $localFilePath = Join-Path $localPath $name
            $fileUrl = ($url + $name)
    
            if ($permissions[0] -eq 'd')
            {
                if (!(Test-Path $localFilePath -PathType container))
                {
                    Write-Host "Creating directory $localFilePath"
                    New-Item $localFilePath -Type directory | Out-Null
                }
    
                DownloadFtpDirectory ($fileUrl + "/") $credentials $localFilePath
            }
            else
            {
                Write-Host "Downloading $fileUrl to $localFilePath"
    
                $downloadRequest = [Net.WebRequest]::Create($fileUrl)
                $downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
                $downloadRequest.Credentials = $credentials
    
                $downloadResponse = $downloadRequest.GetResponse()
                $sourceStream = $downloadResponse.GetResponseStream()
                $targetStream = [System.IO.File]::Create($localFilePath)
                $buffer = New-Object byte[] 10240
                while (($read = $sourceStream.Read($buffer, 0, $buffer.Length)) -gt 0)
                {
                    $targetStream.Write($buffer, 0, $read);
                }
                $targetStream.Dispose()
                $sourceStream.Dispose()
                $downloadResponse.Dispose()
            }
        }
    }
    

    Use the function like:

    $credentials = New-Object System.Net.NetworkCredential("user", "mypassword") 
    $url = "ftp://ftp.example.com/directory/to/download/"
    DownloadFtpDirectory $url $credentials "C:\target\directory"
    

    The code is translated from my C# example in C# Download all files and subdirectories through FTP.


    Using 3rd party library

    If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD command and/or parsing various LIST listing formats. And ideally with a support for downloading all files from a directory or even recursive downloads.

    For example with WinSCP .NET assembly you can download whole directory with a single call to Session.GetFiles:

    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
    
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Ftp
        HostName = "ftp.example.com"
        UserName = "user"
        Password = "mypassword"
    }
    
    $session = New-Object WinSCP.Session
    
    try
    {
        # Connect
        $session.Open($sessionOptions)
    
        # Download files
        $session.GetFiles("/directory/to/download/*", "C:\target\directory\*").Check()
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }    
    

    Internally, WinSCP uses the MLSD command, if supported by the server. If not, it uses the LIST command and supports dozens of different listing formats.

    The Session.GetFiles method is recursive by default.

    (I'm the author of WinSCP)

    Why use multiple columns as primary keys (composite primary key)

    We create composite primary keys to guarantee the uniqueness column values which compose a single record. It is a constraint which helps prevent insertion of data which should not be duplicated.

    i.e: If all student Ids and birth certificate numbers are uniquely assigned to a single person. Then it would be a good idea to make the primary key for a person a composition of student id and birth certificate number because it would prevent you from accidentally inserting two people who have different student ids and the same birth certificate.

    How to add multiple values to a dictionary key in python?

    Make the value a list, e.g.

    a["abc"] = [1, 2, "bob"]
    

    UPDATE:

    There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

    key = "somekey"
    a.setdefault(key, [])
    a[key].append(1)
    

    Results:

    >>> a
    {'somekey': [1]}
    

    Next, try:

    key = "somekey"
    a.setdefault(key, [])
    a[key].append(2)
    

    Results:

    >>> a
    {'somekey': [1, 2]}
    

    The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

    a.setdefault("somekey",[]).append("bob")
    

    Results:

    >>> a
    {'somekey': [1, 2, 'bob']}
    

    You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.

    "Could not find or load main class" Error while running java program using cmd prompt

    For a lot of us, at least for me, I think the class path hierarchy is not intuitive since I'm working inside a directory structure and it feels like that ought to be it.

    Java is looking at the name of the class based on it's package path, not just the file path.

    It doesn't matter if: i'm in the local directory ./packagefoo/MainClass, or a directory up ./packagefoo/, or one down ./packagefoo/MainClass/foo.

    The command "java packagefoo.MainClass" is running off the root %CLASSPATH% which means something significant to Java. Then from there it traverses package names, not path names like us lay coders would expect.

    So if my CLASSPATH is set to %CWD%/, then "java packagefoo.MainClass" will work. If I set the CLASSPATH to %CWD%/packagefoo/ then packagefoo.MainClass can't be found. Always "java MainClass" means nothing, if it is a member of "package", until I rip out the java code "package packagefoo;" and move the Class File up a directory.

    In fact if I change "package packagefoo;" to "package foopackage;" I have to create a subfolder under CLASSPATH/foopackage or foopackage.MainClass stops working again.

    To make matters worse, Between PATH, CLASSPATH, JAVAHOME, for Windows, JDeveloper, Oracle Database, and every user name it was installed under, I think a coder trying to just get something up fast ends up brute forcing path variables and structure until something works without understanding what it means.

    at least i did.

    click or change event on radio using jquery

    This code worked for me:

    $(function(){
    
        $('input:radio').change(function(){
            alert('changed');   
        });          
    
    });
    

    http://jsfiddle.net/3q29L/

    HTML: How to make a submit button with text + image in it?

    Here is an other example:

    <button type="submit" name="submit" style="border: none; background-color: white">
    

    node.js require all files in a folder?

    Can use : https://www.npmjs.com/package/require-file-directory

    • Require selected files with name only or all files.
    • No need of absoulute path.
    • Easy to understand and use.

    How do I set the maximum line length in PyCharm?

    Here is screenshot of my Pycharm. Required settings is in following path: File -> Settings -> Editor -> Code Style -> General: Right margin (columns)

    Pycharm 4 Settings Screenshot

    SQL: How do I SELECT only the rows with a unique value on certain column?

    Assuming your table of data is called ProjectInfo:

    SELECT DISTINCT Contract, Activity
        FROM ProjectInfo
        WHERE Contract = (SELECT Contract
                              FROM (SELECT DISTINCT Contract, Activity
                                        FROM ProjectInfo) AS ContractActivities
                              GROUP BY Contract
                              HAVING COUNT(*) = 1);
    

    The innermost query identifies the contracts and the activities. The next level of the query (the middle one) identifies the contracts where there is just one activity. The outermost query then pulls the contract and activity from the ProjectInfo table for the contracts that have a single activity.

    Tested using IBM Informix Dynamic Server 11.50 - should work elsewhere too.

    How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

    You can use a ComboBox with its ComboBoxStyle (appears as DropDownStyle in later versions) set to DropDownList. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx

    C++ - Hold the console window open?

    A more appropriate method is to use std::cin.ignore:

    #include <iostream>
    
    void Pause()
    {
       std::cout << "Press Enter to continue...";
       std::cout.flush();
       std::cin.ignore(10000, '\n');
       return;
    }
    

    How to get first/top row of the table in Sqlite via Sql Query

    Use the following query:

    SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1
    

    Note: Sqlite's row id references are detailed here.

    How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

    Here is my attempt:

    Function RegParse(ByVal pattern As String, ByVal html As String)
        Dim regex   As RegExp
        Set regex = New RegExp
    
        With regex
            .IgnoreCase = True  'ignoring cases while regex engine performs the search.
            .pattern = pattern  'declaring regex pattern.
            .Global = False     'restricting regex to find only first match.
    
            If .Test(html) Then         'Testing if the pattern matches or not
                mStr = .Execute(html)(0)        '.Execute(html)(0) will provide the String which matches with Regex
                RegParse = .Replace(mStr, "$1") '.Replace function will replace the String with whatever is in the first set of braces - $1.
            Else
                RegParse = "#N/A"
            End If
    
        End With
    End Function
    

    If hasClass then addClass to parent

    Alternatively you could use:

    if ($('#navigation a').is(".active")) {
        $(this).parent().addClass("active");
    }
    

    Can I have onScrollListener for a ScrollView?

    you can define a custom ScrollView class, & add an interface be called when scrolling like this:

    public class ScrollChangeListenerScrollView extends HorizontalScrollView {
    
    
    private MyScrollListener mMyScrollListener;
    
    public ScrollChangeListenerScrollView(Context context) {
        super(context);
    }
    
    public ScrollChangeListenerScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    public ScrollChangeListenerScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    
    
    public void setOnMyScrollListener(MyScrollListener myScrollListener){
        this.mMyScrollListener = myScrollListener;
    }
    
    
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if(mMyScrollListener!=null){
            mMyScrollListener.onScrollChange(this,l,t,oldl,oldt);
        }
    
    }
    
    public interface MyScrollListener {
        void onScrollChange(View view,int scrollX,int scrollY,int oldScrollX, int oldScrollY);
    }
    
    }
    

    To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

    It helped my case to install the right curl version

    sudo apt-get install php5-curl
    

    How to find out whether a file is at its `eof`?

    The Python read functions will return an empty string if they reach EOF

    Count characters in textarea

    Seems like the most reusable and elegant solution combines the abive to take MaxLength from the Input attribute and then reference the Span element with a predictable id....

    Then to use, all you need to do is add '.countit' to the Input class and 'counter_' + [input-ID] to your span

    HTML

    <textarea class="countit" name="name" maxlength='6' id="post"></textarea>
    <span>characters remaining: <span id="counter_name"></span></span>
    <br>
    <textarea class="countit" name="post" maxlength='20' id="post"></textarea>
    <span>characters remaining: <span id="counter_post"></span></span>
    <br>
    <textarea class="countit" name="desc" maxlength='10' id="desc"></textarea>
    <span>characters remaining: <span id="counter_desc"></span></span>
    

    Jquery

    $(".countit").keyup(function () {
      var maxlength = $(this).attr("maxlength");
      var currentLength = $(this).val().length;
    
      if( currentLength >= maxlength ){
        $("#counter_" + $(this).attr("id")).html(currentLength + ' / ' + maxlength);
        }else{
        $("#counter_" + $(this).attr("id")).html(maxlength - currentLength + " chars left");
      }
    });
    

    How to add bootstrap to an angular-cli project

    I guess the above methods have changed after the release, check this link out

    https://github.com/valor-software/ng2-bootstrap/blob/development/docs/getting-started/ng-cli.md

    initiate project

    npm i -g angular-cli
    ng new my-app
    cd my-app
    ng serve
    npm install --save @ng-bootstrap/ng-bootstrap
    

    install ng-bootstrap and bootstrap

    npm install ng2-bootstrap bootstrap --save
    

    open src/app/app.module.ts and add

    import { AlertModule } from 'ng2-bootstrap/ng2-bootstrap';
    ...
    
    @NgModule({
       ...
       imports: [AlertModule, ... ],
        ... 
    })
    

    open angular-cli.json and insert a new entry into the styles array

    "styles": [
            "styles.css",
            "../node_modules/bootstrap/dist/css/bootstrap.min.css"
          ],
    

    open src/app/app.component.html and test all works by adding

    <alert type="success">hello</alert>
    

    How to make div's percentage width relative to parent div and not viewport

    Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

    See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

    We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

    _x000D_
    _x000D_
    #outer {_x000D_
      min-width: 2000px; _x000D_
      min-height: 1000px; _x000D_
      background: #3e3e3e; _x000D_
      position:relative_x000D_
    }_x000D_
    _x000D_
    #inner {_x000D_
      left: 1%; _x000D_
      top: 45px; _x000D_
      width: 50%; _x000D_
      height: auto; _x000D_
      position: absolute; _x000D_
      z-index: 1;_x000D_
    }_x000D_
    _x000D_
    #inner-inner {_x000D_
      background: #efffef;_x000D_
      position: absolute; _x000D_
      height: 400px; _x000D_
      right: 0px; _x000D_
      left: 0px;_x000D_
    }
    _x000D_
    <div id="outer">_x000D_
      <div id="inner">_x000D_
        <div id="inner-inner"></div>_x000D_
      </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

    You need to set AutoPostBack to true for the Country DropDownList.

    protected override void OnLoad(EventArgs e)
    {
        // base stuff
    
        ddlCountries.AutoPostBack = true;
    
        // other stuff
    }
    

    Edit

    I missed that you had done this. In that case you need to check that ViewState is enabled.

    Windows 8.1 gets Error 720 on connect VPN

    Based on the Microsoft support KBs, this can occur if TCP/IP is damaged or is not bound to your dial-up adapter.You can try reinstalling or resetting TCP/IP as follows:

    • Reset TCP/IP to Original Configuration- Using the NetShell utility, type this command (in CommandLine): netsh int ip reset [file_name.txt], [file_name.txt] is the name of the file where the actions taken by NetShell are record, for example netsh hint ip reset fixtcpip.txt.

    • Remove and re-install NIC – Open Controller and select System. Click Hardware tab and select devices. Double-click on Network Adapter and right-click on the NIC, select Uninstall. Restart the computer and the Windows should auto detect the NIC and re-install it.

    • Upgrade the NIC driver – You may download the latest NIC driver and upgrade the driver.

    Hope it could help.

    Gather multiple sets of columns

    This could be done using reshape. It is possible with dplyr though.

      colnames(df) <- gsub("\\.(.{2})$", "_\\1", colnames(df))
      colnames(df)[2] <- "Date"
      res <- reshape(df, idvar=c("id", "Date"), varying=3:8, direction="long", sep="_")
      row.names(res) <- 1:nrow(res)
      
       head(res)
      #  id       Date time       Q3.2       Q3.3
      #1  1 2009-01-01    1  1.3709584  0.4554501
      #2  2 2009-01-02    1 -0.5646982  0.7048373
      #3  3 2009-01-03    1  0.3631284  1.0351035
      #4  4 2009-01-04    1  0.6328626 -0.6089264
      #5  5 2009-01-05    1  0.4042683  0.5049551
      #6  6 2009-01-06    1 -0.1061245 -1.7170087
    

    Or using dplyr

      library(tidyr)
      library(dplyr)
      colnames(df) <- gsub("\\.(.{2})$", "_\\1", colnames(df))
    
      df %>%
         gather(loop_number, "Q3", starts_with("Q3")) %>% 
         separate(loop_number,c("L1", "L2"), sep="_") %>% 
         spread(L1, Q3) %>%
         select(-L2) %>%
         head()
      #  id       time       Q3.2       Q3.3
      #1  1 2009-01-01  1.3709584  0.4554501
      #2  1 2009-01-01  1.3048697  0.2059986
      #3  1 2009-01-01 -0.3066386  0.3219253
      #4  2 2009-01-02 -0.5646982  0.7048373
      #5  2 2009-01-02  2.2866454 -0.3610573
      #6  2 2009-01-02 -1.7813084 -0.7838389
    

    Update

    With new version of tidyr, we can use pivot_longer to reshape multiple columns. (Using the changed column names from gsub above)

    library(dplyr)
    library(tidyr)
    df %>% 
        pivot_longer(cols = starts_with("Q3"), 
              names_to = c(".value", "Q3"), names_sep = "_") %>% 
        select(-Q3)
    # A tibble: 30 x 4
    #      id time         Q3.2    Q3.3
    #   <int> <date>      <dbl>   <dbl>
    # 1     1 2009-01-01  0.974  1.47  
    # 2     1 2009-01-01 -0.849 -0.513 
    # 3     1 2009-01-01  0.894  0.0442
    # 4     2 2009-01-02  2.04  -0.553 
    # 5     2 2009-01-02  0.694  0.0972
    # 6     2 2009-01-02 -1.11   1.85  
    # 7     3 2009-01-03  0.413  0.733 
    # 8     3 2009-01-03 -0.896 -0.271 
    #9     3 2009-01-03  0.509 -0.0512
    #10     4 2009-01-04  1.81   0.668 
    # … with 20 more rows
    

    NOTE: Values are different because there was no set seed in creating the input dataset

    Changing color of Twitter bootstrap Nav-Pills

    Bootstrap 4.x Solution

    .nav-pills .nav-link.active {
        background-color: #ff0000 !important;
    }
    

    Best way to store time (hh:mm) in a database

    DATETIME start DATETIME end

    I implore you to use two DATETIME values instead, labelled something like event_start and event_end.

    Time is a complex business

    Most of the world has now adopted the denery based metric system for most measurements, rightly or wrongly. This is good overall, because at least we can all agree that a g, is a ml, is a cubic cm. At least approximately so. The metric system has many flaws, but at least it's internationally consistently flawed.

    With time however, we have; 1000 milliseconds in a second, 60 seconds to a minute, 60 minutes to an hour, 12 hours for each half a day, approximately 30 days per month which vary by the month and even year in question, each country has its time offset from others, the way time is formatted in each country vary.

    It's a lot to digest, but the long and short of it is impossible for such a complex scenario to have a simple solution.

    Some corners can be cut, but there are those where it is wiser not to

    Although the top answer here suggests that you store an integer of minutes past midnight might seem perfectly reasonable, I have learned to avoid doing so the hard way.

    The reasons to implement two DATETIME values are for an increase in accuracy, resolution and feedback.

    These are all very handy for when the design produces undesirable results.

    Am I storing more data than required?

    It might initially appear like more information is being stored than I require, but there is a good reason to take this hit.

    Storing this extra information almost always ends up saving me time and effort in the long-run, because I inevitably find that when somebody is told how long something took, they'll additionally want to know when and where the event took place too.

    It's a huge planet

    In the past, I have been guilty of ignoring that there are other countries on this planet aside from my own. It seemed like a good idea at the time, but this has ALWAYS resulted in problems, headaches and wasted time later on down the line. ALWAYS consider all time zones.

    C#

    A DateTime renders nicely to a string in C#. The ToString(string Format) method is compact and easy to read.

    E.g.

    new TimeSpan(EventStart.Ticks - EventEnd.Ticks).ToString("h'h 'm'm 's's'")
    

    SQL server

    Also if you're reading your database seperate to your application interface, then dateTimes are pleasnat to read at a glance and performing calculations on them are straightforward.

    E.g.

    SELECT DATEDIFF(MINUTE, event_start, event_end)
    

    ISO8601 date standard

    If using SQLite then you don't have this, so instead use a Text field and store it in ISO8601 format eg.

    "2013-01-27T12:30:00+0000"

    Notes:

    • This uses 24 hour clock*

    • The time offset (or +0000) part of the ISO8601 maps directly to longitude value of a GPS coordiate (not taking into account daylight saving or countrywide).

    E.g.

    TimeOffset=(±Longitude.24)/360 
    

    ...where ± refers to east or west direction.

    It is therefore worth considering if it would be worth storing longitude, latitude and altitude along with the data. This will vary in application.

    • ISO8601 is an international format.

    • The wiki is very good for further details at http://en.wikipedia.org/wiki/ISO_8601.

    • The date and time is stored in international time and the offset is recorded depending on where in the world the time was stored.

    In my experience there is always a need to store the full date and time, regardless of whether I think there is when I begin the project. ISO8601 is a very good, futureproof way of doing it.

    Additional advice for free

    It is also worth grouping events together like a chain. E.g. if recording a race, the whole event could be grouped by racer, race_circuit, circuit_checkpoints and circuit_laps.

    In my experience, it is also wise to identify who stored the record. Either as a seperate table populated via trigger or as an additional column within the original table.

    The more you put in, the more you get out

    I completely understand the desire to be as economical with space as possible, but I would rarely do so at the expense of losing information.

    A rule of thumb with databases is as the title says, a database can only tell you as much as it has data for, and it can be very costly to go back through historical data, filling in gaps.

    The solution is to get it correct first time. This is certainly easier said than done, but you should now have a deeper insight of effective database design and subsequently stand a much improved chance of getting it right the first time.

    The better your initial design, the less costly the repairs will be later on.

    I only say all this, because if I could go back in time then it is what I'd tell myself when I got there.

    Why do I get a warning icon when I add a reference to an MEF plugin project?

    One of the reasons to get this annoying yellow triangle is that you are adding a reference to a project twice, meaning:

    • Reference one: MyProjectOne (which contains already a reference to MyProjectTwo)
    • Reference two: MyProjectTwo

    By deleting the Reference two, the yellow triangle will disappear.

    How to remove the arrow from a select element in Firefox

    Update: this was fixed in Firefox v35. See the full gist for details.


    Just figured out how to remove the select arrow from Firefox. The trick is to use a mix of -prefix-appearance, text-indent and text-overflow. It is pure CSS and requires no extra markup.

    select {
        -moz-appearance: none;
        text-indent: 0.01px;
        text-overflow: '';
    }
    

    Tested on Windows 8, Ubuntu and Mac, latest versions of Firefox.

    Live example: http://jsfiddle.net/joaocunha/RUEbp/1/

    More on the subject: https://gist.github.com/joaocunha/6273016

    SQL Server remove milliseconds from datetime

    select * from table
         where DATEADD(ms, DATEDIFF(ms, '20000101', date), '20000101') > '2010-07-20 03:21:52'
    

    You'll have to trim milliseconds before comparison, which will be slow over many rows

    Do one of these to fix this:

    • created a computed column with the expressions above to compare against
    • remove milliseconds on insert/update to avoid the read overhead
    • If SQL Server 2008, use datetime2(0)

    Can Android do peer-to-peer ad-hoc networking?

    You can use Alljoyn framework for Peer-to-Peer connectivity in Android. Its based on Ad-hoc networking and also Open source.

    MySQL DROP all tables, ignoring foreign keys

    From http://www.devdaily.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys:

    SET FOREIGN_KEY_CHECKS = 0;
    drop table if exists customers;
    drop table if exists orders;
    drop table if exists order_details;
    SET FOREIGN_KEY_CHECKS = 1;
    

    (Note that this answers how to disable foreign key checks in order to be able to drop the tables in arbitrary order. It does not answer how to automatically generate drop-table statements for all existing tables and execute them in a single script. Jean's answer does.)

    Difference between Statement and PreparedStatement

    Statement will be used for executing static SQL statements and it can't accept input parameters.

    PreparedStatement will be used for executing SQL statements many times dynamically. It will accept input parameters.

    Increase bootstrap dropdown menu width

    Add the following css class

    .dropdown-menu {
        width: 300px !important;
        height: 400px !important;
    }
    

    Of course you can use what matches your need.

    System.Net.WebException HTTP status code

    You can try this code to get HTTP status code from WebException. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

    HttpStatusCode GetHttpStatusCode(WebException we)
    {
        if (we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            return response.StatusCode;
        }
        return null;
    }
    

    Jquery ajax call click event submit button

    You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

    See documentation: http://api.jquery.com/category/selectors/
    its your friend.

    Try this:

    It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

    <input type="hidden" name="id" value="" id="id">
    

    you need to change this line:

    id: $("#Shareitem").val()
    

    by

    id: $("#id").val()
    

    All together:

     <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
        <script>
        $(document).ready(function(){
          $("#Shareitem").click(function(e){
              e.preventDefault();
            $.ajax({type: "POST",
                    url: "/imball-reagens/public/shareitem",
                    data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                    success:function(result){
              $("#sharelink").html(result);
            }});
          });
        });
        </script>
    

    How to set .net Framework 4.5 version in IIS 7 application pool

    There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:

    appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5
    

    Appcmd is located in %windir%\System32\inetsrv. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.

    MS article on setting .Net version for App Pool

    Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

    Timestamp in saving workbook path, the ":" needs to be changed. I used ":" -> "." which implies that I need to add the extension back "xlsx".

    wb(x).SaveAs ThisWorkbook.Path & "\" & unique(x) & " - " & Format(Now(), "mm-dd-yy, hh.mm.ss") & ".xlsx"
    

    Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

    After installing OpenSSL I was required to create a new environment variable:

    • Name: OPENSSL_CONF
    • Value: C:\Program Files\OpenSSL\openssl.cnf

    In powershell:

    $env:OPENSSL_CONF = "${env:ProgramFiles}\OpenSSL\openssl.cnf"
    

    This value differs from previous installation versions (as seen in a previous edit of this post). Also, don't forget to add the openssl binary folder ${env:ProgramFiles}\OpenSSL to your Path.

    Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

    1. delete C:\Users\Administrator.gradle\caches\xxx (xxx gradle version)
    2. rebuild

    Is there a math nCr function in python?

    Do you want iteration? itertools.combinations. Common usage:

    >>> import itertools
    >>> itertools.combinations('abcd',2)
    <itertools.combinations object at 0x01348F30>
    >>> list(itertools.combinations('abcd',2))
    [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
    >>> [''.join(x) for x in itertools.combinations('abcd',2)]
    ['ab', 'ac', 'ad', 'bc', 'bd', 'cd']
    

    If you just need to compute the formula, use math.factorial:

    import math
    
    def nCr(n,r):
        f = math.factorial
        return f(n) / f(r) / f(n-r)
    
    if __name__ == '__main__':
        print nCr(4,2)
    

    In Python 3, use the integer division // instead of / to avoid overflows:

    return f(n) // f(r) // f(n-r)

    Output

    6
    

    Why does foo = filter(...) return a <filter object>, not a list?

    From the documentation

    Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)]

    In python3, rather than returning a list; filter, map return an iterable. Your attempt should work on python2 but not in python3

    Clearly, you are getting a filter object, make it a list.

    shesaid = list(filter(greetings(), ["hello", "goodbye"]))
    

    How to initialize an array in one step using Ruby?

    Oneliner:

    array = [] << 1 << 2 << 3   #this is for fixnums.
    

    or

     a = %w| 1 2 3 4 5 |
    

    or

     a = [*'1'..'3']
    

    or

     a = Array.new(3, '1')
    

    or

     a = Array[*'1'..'3']
    

    Serializing with Jackson (JSON) - getting "No serializer found"?

    in spring boot 2.2.5

    after adding getter and setter

    i added @JsonIgnore on top of the field.

    JavaScript Array Push key value

    You have to use bracket notation:

    var obj = {};
    obj[a[i]] = 0;
    x.push(obj);
    

    The result will be:

    x = [{left: 0}, {top: 0}];
    

    Maybe instead of an array of objects, you just want one object with two properties:

    var x = {};
    

    and

    x[a[i]] = 0;
    

    This will result in x = {left: 0, top: 0}.

    Volley - POST/GET parameters

    Dealing with GET parameters I iterated on Andrea Motto' solution. The problem was that Volley called GetUrl several times and his solution, using an Iterator, destroyed original Map object. The subsequent Volley internal calls had an empty params object.

    I added also the encode of parameters.

    This is an inline usage (no subclass).

    public void GET(String url, Map<String, String> params, Response.Listener<String> response_listener, Response.ErrorListener error_listener, String API_KEY, String stringRequestTag) {
        final Map<String, String> mParams = params;
        final String mAPI_KEY = API_KEY;
        final String mUrl = url;
    
        StringRequest stringRequest = new StringRequest(
                Request.Method.GET,
                mUrl,
                response_listener,
                error_listener
        ) {
            @Override
            protected Map<String, String> getParams() {
                return mParams;
            }
    
            @Override
            public String getUrl() {
                StringBuilder stringBuilder = new StringBuilder(mUrl);
                int i = 1;
                for (Map.Entry<String,String> entry: mParams.entrySet()) {
                    String key;
                    String value;
                    try {
                        key = URLEncoder.encode(entry.getKey(), "UTF-8");
                        value = URLEncoder.encode(entry.getValue(), "UTF-8");
                        if(i == 1) {
                            stringBuilder.append("?" + key + "=" + value);
                        } else {
                            stringBuilder.append("&" + key + "=" + value);
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    i++;
    
                }
                String url = stringBuilder.toString();
    
                return url;
            }
    
            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> headers = new HashMap<>();
                if (!(mAPI_KEY.equals(""))) {
                    headers.put("X-API-KEY", mAPI_KEY);
                }
                return headers;
            }
        };
    
        if (stringRequestTag != null) {
            stringRequest.setTag(stringRequestTag);
        }
    
        mRequestQueue.add(stringRequest);
    }
    

    This function uses headers to pass an APIKEY and sets a TAG to the request useful to cancel it before its completion.

    Hope this helps.

    what is the use of fflush(stdin) in c programming

    It's an unportable way to remove all data from the input buffer till the next newline. I've seen it used in cases like that:

    char c;
    char s[32];
    puts("Type a char");
    c=getchar();
    fflush(stdin);
    puts("Type a string");
    fgets(s,32,stdin);
    

    Without the fflush(), if you type a character, say "a", and the hit enter, the input buffer contains "a\n", the getchar() peeks the "a", but the "\n" remains in the buffer, so the next fgets() will find it and return an empty string without even waiting for user input.

    However, note that this use of fflush() is unportable. I've tested right now on a Linux machine, and it does not work, for example.

    How to Inspect Element using Safari Browser

    in menu bar click on Edit->preference->advance at bottom click the check box true that is for Show develop menu in menu bar now a develop menu is display at menu bar where you can see all develop option and inspect.

    Best way to check if MySQL results returned in PHP?

    Of all the options above I would use

    if (mysql_num_rows($result)==0) { PERFORM ACTION }

    checking against the result like below

    if (!$result) { PERFORM ACTION }
    

    This will be true if a mysql_error occurs so effectively if an error occurred you could then enter a duplicate user-name...

    .Net System.Mail.Message adding multiple "To" addresses

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net.Mail;
    using System.Web;
    
    namespace HMS.HtmlHelper
    {
        public class SendmailHelper
        {
            //Created SendEMail method for sendiing mails to users 
            public bool SendEMail(string FromName, string ToAddress, string Subject, string Message)
            {
                bool valid =false;
                try
                {
                    string smtpUserName = System.Configuration.ConfigurationManager.AppSettings["smtpusername"].ToString();
                    string smtpPassword = System.Configuration.ConfigurationManager.AppSettings["smtppassword"].ToString();
                    MailMessage mail = new MailMessage();``
                    mail.From = new MailAddress(smtpUserName, FromName);
                    mail.Subject = Subject;
                    mail.To.Add(FormatMultipleEmailAddresses(ToAddress));
                    //mail.To.Add(ToAddress);
                    mail.Body = Message.ToString();
                    mail.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["smtpserverport"]);
                    smtp.Host = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"]; /
                    smtp.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword);
                    smtp.EnableSsl = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["ssl"]); ;
                    smtp.Send(mail);
                    valid = true;
    
                }
                catch (Exception ex)
                {
                    valid =false ;
                }
    
                return valid;
            }
    
    
    
            public string FormatMultipleEmailAddresses(string emailAddresses)
            {
                var delimiters = new[] { ',', ';' };
    
                var addresses = emailAddresses.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
    
                return string.Join(",", addresses);
            }
    
        }
    }``
    

    What is the difference between class and instance methods?

    I think the best way to understand this is to look at alloc and init. It was this explanation that allowed me to understand the differences.

    Class Method

    A class method is applied to the class as a whole. If you check the alloc method, that's a class method denoted by the + before the method declaration. It's a class method because it is applied to the class to make a specific instance of that class.

    Instance Method

    You use an instance method to modify a specific instance of a class that is unique to that instance, rather than to the class as a whole. init for example (denoted with a - before the method declaration), is an instance method because you are normally modifying the properties of that class after it has been created with alloc.

    Example

    NSString *myString = [NSString alloc];
    

    You are calling the class method alloc in order to generate an instance of that class. Notice how the receiver of the message is a class.

    [myString initWithFormat:@"Hope this answer helps someone"];
    

    You are modifying the instance of NSString called myString by setting some properties on that instance. Notice how the receiver of the message is an instance (object of class NSString).

    Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

    There is boolean data type in SQL Server. Its values can be TRUE, FALSE or UNKNOWN. However, the boolean data type is only the result of a boolean expression containing some combination of comparison operators (e.g. =, <>, <, >=) or logical operators (e.g. AND, OR, IN, EXISTS). Boolean expressions are only allowed in a handful of places including the WHERE clause, HAVING clause, the WHEN clause of a CASE expression or the predicate of an IF or WHILE flow control statement.

    For all other usages, including the data type of a column in a table, boolean is not allowed. For those other usages, the BIT data type is preferred. It behaves like a narrowed-down INTEGER which allows only the values 0, 1 and NULL, unless further restricted with a NOT NULL column constraint or a CHECK constraint.

    To use a BIT column in a boolean expression it needs to be compared using a comparison operator such as =, <> or IS NULL. e.g.

    SELECT
        a.answer_body
    FROM answers AS a
    WHERE a.is_accepted = 0;
    

    From a formatting perspective, a bit value is typically displayed as 0 or 1 in client software. When a more user-friendly format is required, and it can't be handled at an application tier in front of the database, it can be converted "just-in-time" using a CASE expression e.g.

    SELECT
        a.answer_body,
        CASE a.is_accepted WHEN 1 THEN 'TRUE' ELSE 'FALSE' END AS is_accepted
    FROM answers AS a;
    

    Storing boolean values as a character data type like char(1) or varchar(5) is also possible, but that is much less clear, has more storage/network overhead, and requires CHECK constraints on each column to restrict illegal values.

    For reference, the schema of answers table would be similar to:

    CREATE TABLE answers (
        ...,
        answer_body nvarchar(MAX) NOT NULL,
        is_accepted bit NOT NULL DEFAULT (0)
    );
    

    Select all columns except one in MySQL?

    If the column that you didn't want to select had a massive amount of data in it, and you didn't want to include it due to speed issues and you select the other columns often, I would suggest that you create a new table with the one field that you don't usually select with a key to the original table and remove the field from the original table. Join the tables when that extra field is actually required.

    Convert String (UTF-16) to UTF-8 in C#

    Check the Jon Skeet answer to this other question: UTF-16 to UTF-8 conversion (for scripting in Windows)

    It contains the source code that you need.

    Hope it helps.

    Converting from longitude\latitude to Cartesian coordinates

    I have recently done something similar to this using the "Haversine Formula" on WGS-84 data, which is a derivative of the "Law of Haversines" with very satisfying results.

    Yes, WGS-84 assumes the Earth is an ellipsoid, but I believe you only get about a 0.5% average error using an approach like the "Haversine Formula", which may be an acceptable amount of error in your case. You will always have some amount of error unless you're talking about a distance of a few feet and even then there is theoretically curvature of the Earth... If you require a more rigidly WGS-84 compatible approach checkout the "Vincenty Formula."

    I understand where starblue is coming from, but good software engineering is often about trade-offs, so it all depends on the accuracy you require for what you are doing. For example, the result calculated from "Manhattan Distance Formula" versus the result from the "Distance Formula" can be better for certain situations as it is computationally less expensive. Think "which point is closest?" scenarios where you don't need a precise distance measurement.

    Regarding, the "Haversine Formula" it is easy to implement and is nice because it is using "Spherical Trigonometry" instead of a "Law of Cosines" based approach which is based on two-dimensional trigonometry, therefore you get a nice balance of accuracy over complexity.

    A gentleman by the name of Chris Veness has a great website that explains some of the concepts you are interested in and demonstrates various programmatic implementations; this should answer your x/y conversion question as well.

    How to determine the version of the C++ standard used by the compiler?

    __cplusplus

    In C++0x the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.

    C++0x FAQ by BS

    Ansible: Store command's stdout in new variable?

    There's no need to set a fact.

        - shell: cat "hello"
          register: cat_contents
    
        - shell: echo "I cat hello"
          when: cat_contents.stdout == "hello"
    

    sass :first-child not working

    I think that it is better (for my expirience) to use: :first-of-type, :nth-of-type(), :last-of-type. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type, than *-child selectors.

    How to set max width of an image in CSS

    The problem is that img tag is inline element and you can't restrict width of inline element.

    So to restrict img tag width first you need to convert it into a inline-block element

    img.Image{
        display: inline-block;
    }
    

    How do I create a table based on another table

    select * into newtable from oldtable
    

    Looping through the content of a file in Bash

    cat peptides.txt | while read line 
    do
       # do something with $line here
    done
    

    and the one-liner variant:

    cat peptides.txt | while read line; do something_with_$line_here; done
    

    These options will skip the last line of the file if there is no trailing line feed.

    You can avoid this by the following:

    cat peptides.txt | while read line || [[ -n $line ]];
    do
       # do something with $line here
    done
    

    Hive: Filtering Data between Specified Dates when Date is a String

    Try this:

    select * from your_table
    where date >= '2020-10-01'  
    

    How to set Oracle's Java as the default Java in Ubuntu?

    If you want to change it globally and at system level;

    In

    /etc/environment
    

    add this line:

    JAVA_HOME=/usr/lib/jvm/java-7-oracle
    

    How do I encode/decode HTML entities in Ruby?

    If you don't want to add a new dependency just to do this (like HTMLEntities) and you're already using Hpricot, it can both escape and unescape for you. It handles much more than CGI:

    Hpricot.uxs "foo&nbsp;b&auml;r"
    => "foo bär"