Programs & Examples On #Networking

For most programming questions use [network-programming] tag. Non-programming networking questions are off topic and should be asked on Network Engineering, Super User or Server Fault instead. This tag is only appropriate for questions concerning unique networking needs in support of software development.

Can Android do peer-to-peer ad-hoc networking?

In addition to Telmo Marques answer: I use Virtual Router for this.

Like connectify it creates an accesspoint on your Windows 8, Windows 7 or 2008 R2 machine, but it's open-source.

Simulating Slow Internet Connection

I was using http://www.netlimiter.com/ and it works very well. Not only limit speed for single processes but also shows actual transfer rates.

Forward host port to docker container

You could also create an ssh tunnel.

docker-compose.yml:

---

version: '2'

services:
  kibana:
    image: "kibana:4.5.1"
    links:
      - elasticsearch
    volumes:
      - ./config/kibana:/opt/kibana/config:ro

  elasticsearch:
    build:
      context: .
      dockerfile: ./docker/Dockerfile.tunnel
    entrypoint: ssh
    command: "-N elasticsearch -L 0.0.0.0:9200:localhost:9200"

docker/Dockerfile.tunnel:

FROM buildpack-deps:jessie

RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive \
    apt-get -y install ssh && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

COPY ./config/ssh/id_rsa /root/.ssh/id_rsa
COPY ./config/ssh/config /root/.ssh/config
COPY ./config/ssh/known_hosts /root/.ssh/known_hosts
RUN chmod 600 /root/.ssh/id_rsa && \
    chmod 600 /root/.ssh/config && \
    chown $USER:$USER -R /root/.ssh

config/ssh/config:

# Elasticsearch Server
Host elasticsearch
    HostName jump.host.czerasz.com
    User czerasz
    ForwardAgent yes
    IdentityFile ~/.ssh/id_rsa

This way the elasticsearch has a tunnel to the server with the running service (Elasticsearch, MongoDB, PostgreSQL) and exposes port 9200 with that service.

How do I find out which computer is the domain controller in Windows programmatically?

With the most simple programming language: DOS batch

echo %LOGONSERVER%

Get the IP Address of local computer

Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.

Java socket API: How to tell if a connection has been closed?

I faced similar problem. In my case client must send data periodically. I hope you have same requirement. Then I set SO_TIMEOUT socket.setSoTimeout(1000 * 60 * 5); which is throw java.net.SocketTimeoutException when specified time is expired. Then I can detect dead client easily.

Setting network adapter metric priority in Windows 7

I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.

Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.

After this, Windows started prioritize Ethernet adapter.

Communication between multiple docker-compose projects

Since Compose 1.18 (spec 3.5), you can just override the default network using your own custom name for all Compose YAML files you need. It is as simple as appending the following to them:

networks:
  default:
    name: my-app

The above assumes you have version set to 3.5 (or above if they don't deprecate it in 4+).

Other answers have pointed the same; this is a simplified summary.

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.

What port is a given program using?

You may already have Process Explorer (from Sysinternals, now part of Microsoft) installed. If not, go ahead and install it now -- it's just that cool.

In Process Explorer: locate the process in question, right-click and select the TCP/IP tab. It will even show you, for each socket, a stack trace representing the code that opened that socket.

How do I delete virtual interface in Linux?

You can use sudo ip link delete to remove the interface.

Export data from Chrome developer tool

if you right click on any of the rows you can export the item or the entire data set as HAR which appears to be a JSON format.

It shouldn't be terribly difficult to script up something to transform that to a csv if you really need it in excel, but if you're already scripting you might as well just use the script to ask your questions of the data.

If anyone knows how to drive the "load page, export data" part of the process from the command line I'd be quite interested in hearing how

Apache and IIS side by side (both listening to port 80) on windows2003

You will need to use different IP addresses. The server, whether Apache or IIS, grabs the traffic based on the IP and Port, which ever they are bound to listen to. Once it starts listening, then it uses the headers, such as the server name to filter and determine what site is being accessed. You can't do it will simply changing the server name in the request

How to check internet access on Android? InetAddress never times out

This code will help you find the internet is on or not.

public final boolean isInternetOn() {
        ConnectivityManager conMgr = (ConnectivityManager) this.con
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conMgr.getActiveNetworkInfo();
        return (info != null && info.isConnected());
}

Also, you should provide the following permissions

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Artificially create a connection timeout error

For me easiest way was adding static route on office router based on destination network. Just route traffic to some unresponsive host (e.g. your computer) and you will get request timeout.

Best thing for me was that static route can be managed over web interface and enabled/disabled easily.

How to make sure that a certain Port is not occupied by any other process

It's netstat -ano|findstr port no

Result would show process id in last column

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

NITZ is a form of NTP and is sent to the mobile device over Layer 3 or NAS layers. Commonly this message is seen as GMM Info and contains the following informaiton:

Certain carriers dont support this and some support it and have it setup incorrectly.

LAYER 3 SIGNALING MESSAGE

Time: 9:38:49.800

GMM INFORMATION 3GPP TS 24.008 ver 12.12.0 Rel 12 (9.4.19)

M Protocol Discriminator (hex data: 8)

(0x8) Mobility Management message for GPRS services

M Skip Indicator (hex data: 0) Value: 0 M Message Type (hex data: 21) Message number: 33

O Network time zone (hex data: 4680) Time Zone value: GMT+2:00 O Universal time and time zone (hex data: 47716070 70831580) Year: 17 Month: 06 Day: 07 Hour: 07 Minute :38 Second: 51 Time zone value: GMT+2:00 O Network Daylight Saving Time (hex data: 490100) Daylight Saving Time value: No adjustment

Layer 3 data: 08 21 46 80 47 71 60 70 70 83 15 80 49 01 00

java.net.SocketException: Connection reset

In my experience, I often encounter the following situations;

  1. If you work in a corporate company, contact the network and security team. Because in requests made to external services, it may be necessary to give permission for the relevant endpoint.

  2. Another issue is that the SSL certificate may have expired on the server where your application is running.

How to ping ubuntu guest on VirtualBox

Using NAT (the default) this is not possible. Bridged Networking should allow it. If bridged does not work for you (this may be the case when your network adminstration does not allow multiple IP addresses on one physical interface), you could try 'Host-only networking' instead.

For configuration of Host-only here is a quote from the vbox manual(which is pretty good). http://www.virtualbox.org/manual/ch06.html:

For host-only networking, like with internal networking, you may find the DHCP server useful that is built into VirtualBox. This can be enabled to then manage the IP addresses in the host-only network since otherwise you would need to configure all IP addresses statically.

In the VirtualBox graphical user interface, you can configure all these items in the global settings via "File" -> "Settings" -> "Network", which lists all host-only networks which are presently in use. Click on the network name and then on the "Edit" button to the right, and you can modify the adapter and DHCP settings.

Getting MAC Address

For Linux you can retrieve the MAC address using a SIOCGIFHWADDR ioctl.

struct ifreq    ifr;
uint8_t         macaddr[6];

if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0)
    return -1;

strcpy(ifr.ifr_name, "eth0");

if (ioctl(s, SIOCGIFHWADDR, (void *)&ifr) == 0) {
    if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
        memcpy(macaddr, ifr.ifr_hwaddr.sa_data, 6);
        return 0;
... etc ...

You've tagged the question "python". I don't know of an existing Python module to get this information. You could use ctypes to call the ioctl directly.

What causes a TCP/IP reset (RST) flag to be sent?

One thing to be aware of is that many Linux netfilter firewalls are misconfigured.

If you have something like:

-A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT

-A FORWARD -p tcp -j REJECT --reject-with tcp-reset

then packet reordering can result in the firewall considering the packets invalid and thus generating resets which will then break otherwise healthy connections.

Reordering is particularly likely with a wireless network.

This should instead be:

-A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT

-A FORWARD -m state --state INVALID -j DROP

-A FORWARD -p tcp -j REJECT --reject-with tcp-reset

Basically anytime you have:

... -m state --state RELATED,ESTABLISHED -j ACCEPT

it should immediately be followed by:

... -m state --state INVALID -j DROP

It's better to drop a packet then to generate a potentially protocol disrupting tcp reset. Resets are better when they're provably the correct thing to send... since this eliminates timeouts. But if there's any chance they're invalid then they can cause this sort of pain.

Wireshark localhost traffic capture

On Windows platform, it is also possible to capture localhost traffic using Wireshark. What you need to do is to install the Microsoft loopback adapter, and then sniff on it.

TCP vs UDP on video stream

There are some use cases suitable to UDP transport and others suitable to TCP transport.

The use case also dictates encoding settings for the video. When broadcasting soccer match focus is on quality and for video conference focus is on latency.

When using multicast to deliver video to your customers then UDP is used.

Requirement for multicast is expensive networking hardware between broadcasting server and customer. In practice this means if your company owns network infrastructure you can use UDP and multicast for live video streaming. Even then quality-of-service is also implemented to mark video packets and prioritize them so no packet loss happens.

Multicast will simplify broadcasting software because network hardware will handle distributing packets to customers. Customers subscribe to multicast channels and network will reconfigure to route packets to new subscriber. By default all channels are available to all customers and can be optimally routed.

This workflow places dificulty on authorization process. Network hardware does not differentiate subscribed users from other users. Solution to authorization is in encrypting video content and enabling decryption in player software when subscription is valid.

Unicast (TCP) workflow allows server to check client's credentials and only allow valid subscriptions. Even allow only certain number of simultaneous connections.

Multicast is not enabled over internet.

For delivering video over internet TCP must be used. When UDP is used developers end up re-implementing packet re-transmission, for eg. Bittorrent p2p live protocol.

"If you use TCP, the OS must buffer the unacknowledged segments for every client. This is undesirable, particularly in the case of live events".

This buffer must exist in some form. Same is true for jitter buffer on player side. It is called "socket buffer" and server software can know when this buffer is full and discard proper video frames for live streams. It is better to use unicast/TCP method because server software can implement proper frame dropping logic. Random missing packets in UDP case will just create bad user experience. like in this video: http://tinypic.com/r/2qn89xz/9

"IP multicast significantly reduces video bandwidth requirements for large audiences"

This is true for private networks, Multicast is not enabled over internet.

"Note that if TCP loses too many packets, the connection dies; thus, UDP gives you much more control for this application since UDP doesn't care about network transport layer drops."

UDP also doesn't care about dropping entire frames or group-of-frames so it does not give any more control over user experience.

"Usually a video stream is somewhat fault tolerant"

Encoded video is not fault tolerant. When transmitted over unreliable transport then forward error correction is added to video container. Good example is MPEG-TS container used in satellite video broadcast that carry several audio, video, EPG, etc. streams. This is necessary as satellite link is not duplex communication, meaning receiver can't request re-transmission of lost packets.

When you have duplex communication available it is always better to re-transmit data only to clients having packet loss then to include overhead of forward-error-correction in stream sent to all clients.

In any case lost packets are unacceptable. Dropped frames are ok in exceptional cases when bandwidth is hindered.

The result of missing packets are artifacts like this one: artifacts

Some decoders can break on streams missing packets in critical places.

Propagation Delay vs Transmission delay

The transmission delay is the amount of time required for the router to push out the packet, it has nothing to do with the distance between the two routers. The propagation delay is the time taken by a bit to to propagate form one router to the next

How to close TCP and UDP ports via windows command line

CurrPorts did not work for us and we could only access the server through ssh, so no TCPView either. We could not kill the process either, as to not drop other connections. What we ended up doing and was not suggested yet was to block the connection on Windows' Firewall. Yes, this will block all connections that fit the rule, but in our case there was a single connection (the one we were interested in):

netsh advfirewall firewall add rule name="Conn hotfix" dir=out action=block protocol=T
CP remoteip=192.168.38.13

Replace the IP by the one you need and add other rules if needed.

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

When is it appropriate to use UDP instead of TCP?

This is one of my favorite questions. UDP is so misunderstood.

In situations where you really want to get a simple answer to another server quickly, UDP works best. In general, you want the answer to be in one response packet, and you are prepared to implement your own protocol for reliability or to resend. DNS is the perfect description of this use case. The costs of connection setups are way too high (yet, DNS does support a TCP mode as well).

Another case is when you are delivering data that can be lost because newer data coming in will replace that previous data/state. Weather data, video streaming, a stock quotation service (not used for actual trading), or gaming data comes to mind.

Another case is when you are managing a tremendous amount of state and you want to avoid using TCP because the OS cannot handle that many sessions. This is a rare case today. In fact, there are now user-land TCP stacks that can be used so that the application writer may have finer grained control over the resources needed for that TCP state. Prior to 2003, UDP was really the only game in town.

One other case is for multicast traffic. UDP can be multicasted to multiple hosts whereas TCP cannot do this at all.

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

Adding to the accepted answer and what LOG_TAG said....for Volley to parse your data in a background thread you must subclass Request<YourClassName> as the onResponse method is called on the main thread and parsing on the main thread may cause the UI to lag if your response is big. Read here on how to do that.

What is the difference between active and passive FTP?

Active mode: -server initiates the connection.

Passive mode: -client initiates the connection.

Get local IP address

I think using LINQ is easier:

Dns.GetHostEntry(Dns.GetHostName())
   .AddressList
   .First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
   .ToString()

Increasing the maximum number of TCP/IP connections in Linux

Maximum number of connections are impacted by certain limits on both client & server sides, albeit a little differently.

On the client side: Increase the ephermal port range, and decrease the tcp_fin_timeout

To find out the default values:

sysctl net.ipv4.ip_local_port_range
sysctl net.ipv4.tcp_fin_timeout

The ephermal port range defines the maximum number of outbound sockets a host can create from a particular I.P. address. The fin_timeout defines the minimum time these sockets will stay in TIME_WAIT state (unusable after being used once). Usual system defaults are:

  • net.ipv4.ip_local_port_range = 32768 61000
  • net.ipv4.tcp_fin_timeout = 60

This basically means your system cannot consistently guarantee more than (61000 - 32768) / 60 = 470 sockets per second. If you are not happy with that, you could begin with increasing the port_range. Setting the range to 15000 61000 is pretty common these days. You could further increase the availability by decreasing the fin_timeout. Suppose you do both, you should see over 1500 outbound connections per second, more readily.

To change the values:

sysctl net.ipv4.ip_local_port_range="15000 61000"
sysctl net.ipv4.tcp_fin_timeout=30

The above should not be interpreted as the factors impacting system capability for making outbound connections per second. But rather these factors affect system's ability to handle concurrent connections in a sustainable manner for large periods of "activity."

Default Sysctl values on a typical Linux box for tcp_tw_recycle & tcp_tw_reuse would be

net.ipv4.tcp_tw_recycle=0
net.ipv4.tcp_tw_reuse=0

These do not allow a connection from a "used" socket (in wait state) and force the sockets to last the complete time_wait cycle. I recommend setting:

sysctl net.ipv4.tcp_tw_recycle=1
sysctl net.ipv4.tcp_tw_reuse=1 

This allows fast cycling of sockets in time_wait state and re-using them. But before you do this change make sure that this does not conflict with the protocols that you would use for the application that needs these sockets. Make sure to read post "Coping with the TCP TIME-WAIT" from Vincent Bernat to understand the implications. The net.ipv4.tcp_tw_recycle option is quite problematic for public-facing servers as it won’t handle connections from two different computers behind the same NAT device, which is a problem hard to detect and waiting to bite you. Note that net.ipv4.tcp_tw_recycle has been removed from Linux 4.12.

On the Server Side: The net.core.somaxconn value has an important role. It limits the maximum number of requests queued to a listen socket. If you are sure of your server application's capability, bump it up from default 128 to something like 128 to 1024. Now you can take advantage of this increase by modifying the listen backlog variable in your application's listen call, to an equal or higher integer.

sysctl net.core.somaxconn=1024

txqueuelen parameter of your ethernet cards also have a role to play. Default values are 1000, so bump them up to 5000 or even more if your system can handle it.

ifconfig eth0 txqueuelen 5000
echo "/sbin/ifconfig eth0 txqueuelen 5000" >> /etc/rc.local

Similarly bump up the values for net.core.netdev_max_backlog and net.ipv4.tcp_max_syn_backlog. Their default values are 1000 and 1024 respectively.

sysctl net.core.netdev_max_backlog=2000
sysctl net.ipv4.tcp_max_syn_backlog=2048

Now remember to start both your client and server side applications by increasing the FD ulimts, in the shell.

Besides the above one more popular technique used by programmers is to reduce the number of tcp write calls. My own preference is to use a buffer wherein I push the data I wish to send to the client, and then at appropriate points I write out the buffered data into the actual socket. This technique allows me to use large data packets, reduce fragmentation, reduces my CPU utilization both in the user land and at kernel-level.

Network tools that simulate slow network connection

In case you need to simulate network connection quality when developing for Windows Phone, you might give a try to a Visual Studio built-in tool called Simulation Dashboard (more details here http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206952(v=vs.105).aspx):

You can use the Simulation Dashboard in Visual Studio to test your app for these connection problems, and to help prevent users from encountering scenarios like the following:

  • High-resolution music or videos stutter or freeze while streaming, or take a long time to download over a low-bandwidth connection.
  • Calls to a web service fail with a timeout.
  • The app crashes when no network is available.
  • Data transfer does not resume when the network connection is lost and then restored.
  • The user’s battery is drained by a streaming app that uses the network inefficiently.
  • Mapping the user’s route is interrupted in a navigation app.

...

In Visual Studio, on the Tools menu, open Simulation Dashboard. Find the network simulation section of the dashboard and check the Enable Network Simulation check box.

trace a particular IP and port

Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.

You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

first,i used "localhost:port" format met this error.then I changed the address to "ip:port" format and the problem solved.

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

I found a solution to this. It's bloody witchcraft, but it works.

When you install the client, open Control Panel > Network Connections.

You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).

Right Click it, click Enable.

The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.

How to detect a remote side socket close?

The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.

List of IP addresses/hostnames from local network in Python

If you know the names of your computers you can use:

import socket
IP1 = socket.gethostbyname(socket.gethostname()) # local IP adress of your computer
IP2 = socket.gethostbyname('name_of_your_computer') # IP adress of remote computer

Otherwise you will have to scan for all the IP addresses that follow the same mask as your local computer (IP1), as stated in another answer.

Find UNC path of a network drive?

If you have Microsoft Office:

  1. RIGHT-drag the drive, folder or file from Windows Explorer into the body of a Word document or Outlook email
  2. Select 'Create Hyperlink Here'

The inserted text will be the full UNC of the dragged item.

Which Protocols are used for PING?

Internet Control Message Protocol

http://en.wikipedia.org/wiki/Internet_Control_Message_Protocol

ICMP is built on top of a bunch of other protocols, so in that sense your TA is correct. However, ping itself is ICMP.

An URL to a Windows shared folder

If you are allowed to go further then javascript/html facilities - I would use the apache web server to represent your directory listing via http.

If this solution is appropriate. these are the steps:

  1. download apache hhtp server from one of the mirrors http://httpd.apache.org/download.cgi

  2. unzip/install (if msi) it to the directory e.g C:\opt\Apache (the instruction is for windows)

  3. map the network forlder as a local drive on windows (\server\folder to let's say drive H:)

  4. open conf/httpd.conf file

  5. make sure the next line is present and not commented

    LoadModule autoindex_module modules/mod_autoindex.so

  6. Add directory configuration

<Directory "H:/path">

Options +Indexes

AllowOverride None

Order allow,deny

Allow from all

</Directory> 7. Start the web server and make sure the directory listingof the remote folder is available by http. hit localhost/path 8. use a frame inside your web page to access the listing

What is missed: 1. you mignt need more fancy configuration for the host name, refer to Apache Web Server docs. Register the host name in DNS server

  1. the mapping to the network drive might not work, i did not check. As a posible resolution - host your web server on the same machine as smb server.

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.

How to detect the physical connected state of a network cable/connector?

I was using my OpenWRT enhanced device as a repeater (which adds virtual ethernet and wireless lan capabilities) and found that the /sys/class/net/eth0 carrier and opstate values were unreliable. I played around with /sys/class/net/eth0.1 and /sys/class/net/eth0.2 as well with (at least to my finding) no reliable way to detect that something was physically plugged in and talking on any of the ethernet ports. I figured out a bit crude but seemingly reliable way to detect if anything had been plugged in since the last reboot/poweron state at least (which worked exactly as I needed it to in my case).

ifconfig eth0 | grep -o 'RX packets:[0-9]*' | grep -o '[0-9]*'

You'll get a 0 if nothing has been plugged in and something > 0 if anything has been plugged in (even if it was plugged in and since removed) since the last power on or reboot cycle.

Hope this helps somebody out at least!

UDP vs TCP, how much faster is it?

UDP is slightly quicker in my experience, but not by much. The choice shouldn't be made on performance but on the message content and compression techniques.

If it's a protocol with message exchange, I'd suggest that the very slight performance hit you take with TCP is more than worth it. You're given a connection between two end points that will give you everything you need. Don't try and manufacture your own reliable two-way protocol on top of UDP unless you're really, really confident in what you're undertaking.

Virtual network interface in Mac OS X

Replying in particular to:

You can create a new interface in the networking panel, based on an existing interface, but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive).

This can be achieved using a Tun/Tap device as suggested by psv141, and manipulating the /Library/Preferences/SystemConfiguration/preferences.plist file to add a NetworkService based on either a tun or tap interface. Mac OS X will not allow the creation of a NetworkService based on a virtual network interface, but one can directly manipulate the preferences.plist file to add the NetworkService by hand. Basically you would open the preferences.plist file in Xcode (or edit the XML directly, but Xcode is likely to be more fool-proof), and copy the configuration from an existing Ethernet interface. The place to create the new NetworkService is under "NetworkServices", and if your Mac has an Ethernet device the NetworkService profile will also be under this property entry. The Ethernet entry can be copied pretty much verbatim, the only fields you would actually be changing are:

  • UUID
  • UserDefinedName
  • IPv4 configuration and set the interface to your tun or tap device (i.e. tun0 or tap0).
  • DNS server if needed.

Then you would also manipulate the particular Location you want this NetworkService for (remember Mac OS X can configure all network interfaces dependent on your "Location"). The default location UUID can be obtained in the root of the PropertyList as the key "CurrentSet". After figuring out which location (or set) you want, expand the Set property, and add entries under Global/IPv4/ServiceOrder with the UUID of the new NetworkService. Also under the Set property you need to expand the Service property and add the UUID here as a dictionary with one String entry with key __LINK__ and value as the UUID (use the other interfaces as an example).

After you have modified your preferences.plist file, just reboot, and the NetworkService will be available under SystemPreferences->Network. Note that we have mimicked an Ethernet device so Mac OS X layer of networking will note that "a cable is unplugged" and will not let you activate the interface through the GUI. However, since the underlying device is a tun/tap device and it has an IP address, the interface will become active and the proper routing will be added at the BSD level.

As a reference this is used to do special routing magic.

In case you got this far and are having trouble, you have to create the tun/tap device by opening one of the devices under /dev/. You can use any program to do this, but I'm a fan of good-old-fashioned C myself:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
   int fd = open("/dev/tun0", O_RDONLY);
   if (fd < 0)
   {
      printf("Failed to open tun/tap device. Are you root? Are the drivers installed?\n");
      return -1;
   }
   while (1)
   {
      sleep(100000);
   }
   return 0;
}

The network path was not found

At The Beginning, I faced the same error but with a different scenario. I was having two connection strings, one for ado.net, and the other was for the EntityFramework, Both connections where correct. The problem specifically was within the edmx file of the EF, where I changed the ProviderManifestToken="2012" to ProviderManifestToken="2008" therefore, the application worked fine after that.

How can I get the current network interface throughput statistics on Linux/UNIX?

Got sar? Likely yes if youre using RHEL/CentOS.

No need for priv, dorky binaries, hacky scripts, libpcap, etc. Win.

$ sar -n DEV 1 3
Linux 2.6.18-194.el5 (localhost.localdomain)    10/27/2010

02:40:56 PM     IFACE   rxpck/s   txpck/s   rxbyt/s   txbyt/s   rxcmp/s   txcmp/s  rxmcst/s
02:40:57 PM        lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00
02:40:57 PM      eth0  10700.00   1705.05 15860765.66 124250.51      0.00      0.00      0.00
02:40:57 PM      eth1      0.00      0.00      0.00      0.00      0.00      0.00      0.00

02:40:57 PM     IFACE   rxpck/s   txpck/s   rxbyt/s   txbyt/s   rxcmp/s   txcmp/s  rxmcst/s
02:40:58 PM        lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00
02:40:58 PM      eth0   8051.00   1438.00 11849206.00 105356.00      0.00      0.00      0.00
02:40:58 PM      eth1      0.00      0.00      0.00      0.00      0.00      0.00      0.00

02:40:58 PM     IFACE   rxpck/s   txpck/s   rxbyt/s   txbyt/s   rxcmp/s   txcmp/s  rxmcst/s
02:40:59 PM        lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00
02:40:59 PM      eth0   6093.00   1135.00 8970988.00  82942.00      0.00      0.00      0.00
02:40:59 PM      eth1      0.00      0.00      0.00      0.00      0.00      0.00      0.00

Average:        IFACE   rxpck/s   txpck/s   rxbyt/s   txbyt/s   rxcmp/s   txcmp/s  rxmcst/s
Average:           lo      0.00      0.00      0.00      0.00      0.00      0.00      0.00
Average:         eth0   8273.24   1425.08 12214833.44 104115.72      0.00      0.00      0.00
Average:         eth1      0.00      0.00      0.00      0.00      0.00      0.00      0.00

Using Python, how can I access a shared folder on windows network?

Use forward slashes to specify the UNC Path:

open('//HOST/share/path/to/file')

(if your Python client code is also running under Windows)

Accessing a local website from another computer inside the local network in IIS 7

Add two bindings to your website, one for local access and another for LAN access like so:

Open IIS and select your local website (that you want to access from your local network) from the left panel:

Connections > server (user-pc) > sites > local site

Open Bindings on the right panel under Actions tab add these bindings:

  1. Local:

    Type: http
    Ip Address: All Unassigned
    Port: 80
    Host name: samplesite.local
    
  2. LAN:

    Type: http
    Ip Address: <Network address of the hosting machine ex. 192.168.0.10>
    Port: 80
    Host name: <Leave it blank>
    

Voila, you should be able to access the website from any machine on your local network by using the host's LAN IP address (192.168.0.10 in the above example) as the site url.

NOTE:

if you want to access the website from LAN using a host name (like samplesite.local) instead of an ip address, add the host name to the hosts file on the local network machine (The hosts file can be found in "C:\Windows\System32\drivers\etc\hosts" in windows, or "/etc/hosts" in ubuntu):

192.168.0.10 samplesite.local

Send a ping to each IP on a subnet

The command line utility nmap can do this too:

nmap -sP 192.168.1.*

Android check internet connection

in manifest

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

in code,

public static boolean isOnline(Context ctx) {
    if (ctx == null)
        return false;

    ConnectivityManager cm =
            (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

An existing connection was forcibly closed by the remote host

I had this issue when i tried to connect to postgresql while i'm using microsoft sutdio for mssql :)

Valid characters of a hostname?

It depends on whether you process IDNs before or after the IDN toASCII algorithm (that is, do you see the domain name pa??de??µa.d???µ? in Greek or as xn--hxajbheg2az3al.xn--jxalpdlp?).

In the latter case—where you are handling IDNs through the punycode—the old RFC 1123 rules apply:

U+0041 through U+005A (A-Z), U+0061 through U+007A (a-z) case folded as each other, U+0030 through U+0039 (0-9) and U+002D (-).

and U+002E (.) of course; the rules for labels allow the others, with dots between labels.

If you are seeing it in IDN form, the allowed characters are much varied, see http://unicode.org/reports/tr36/idn-chars.html for a handy chart of all valid characters.

Chances are your network code will deal with the punycode, but your display code (or even just passing strings to and from other layers) with the more human-readable form as nobody running a server on the ????????. domain wants to see their server listed as being on .xn--mgberp4a5d4ar.

Copy files to network computers on windows command line

Why for? What do you want to iterate? Try this.

call :cpy pc-name-1
call :cpy pc-name-2
...

:cpy
net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF

How to communicate between Docker containers via "hostname"

EDIT : It is not bleeding edge anymore : http://blog.docker.com/2016/02/docker-1-10/

Original Answer
I battled with it the whole night. If you're not afraid of bleeding edge, the latest version of Docker engine and Docker compose both implement libnetwork.

With the right config file (that need to be put in version 2), you will create services that will all see each other. And, bonus, you can scale them with docker-compose as well (you can scale any service you want that doesn't bind port on the host)

Here is an example file

version: "2"
services:
  router:
    build: services/router/
    ports:
      - "8080:8080"
  auth:
    build: services/auth/
  todo:
    build: services/todo/
  data:
    build: services/data/

And the reference for this new version of compose file: https://github.com/docker/compose/blob/1.6.0-rc1/docs/networking.md

Best C/C++ Network Library

Aggregated List of Libraries

OpenCV with Network Cameras

I just do it like this:

CvCapture *capture = cvCreateFileCapture("rtsp://camera-address");

Also make sure this dll is available at runtime else cvCreateFileCapture will return NULL

opencv_ffmpeg200d.dll

The camera needs to allow unauthenticated access too, usually set via its web interface. MJPEG format worked via rtsp but MPEG4 didn't.

hth

Si

Can't access 127.0.0.1

In windows first check under services if world wide web publishing services is running. If not start it.

If you cannot find it switch on IIS features of windows: In 7,8,10 it is under control panel , "turn windows features on or off". Internet Information Services World Wide web services and Internet information Services Hostable Core are required. Not sure if there is another way to get it going on windows, but this worked for me for all browsers. You might need to add localhost or http:/127.0.0.1 to the trusted websites also under IE settings.

Where to find the complete definition of off_t type?

Since this answer still gets voted up, I want to point out that you should almost never need to look in the header files. If you want to write reliable code, you're much better served by looking in the standard. A better question than "how is off_t defined on my machine" is "how is off_t defined by the standard?". Following the standard means that your code will work today and tomorrow, on any machine.

In this case, off_t isn't defined by the C standard. It's part of the POSIX standard, which you can browse here.

Unfortunately, off_t isn't very rigorously defined. All I could find to define it is on the page on sys/types.h:

blkcnt_t and off_t shall be signed integer types.

This means that you can't be sure how big it is. If you're using GNU C, you can use the instructions in the answer below to ensure that it's 64 bits. Or better, you can convert to a standards defined size before putting it on the wire. This is how projects like Google's Protocol Buffers work (although that is a C++ project).


So, I think "where do I find the definition in my header files" isn't the best question. But, for completeness here's the answer:

On my machine (and most machines using glibc) you'll find the definition in bits/types.h (as a comment says at the top, never directly include this file), but it's obscured a bit in a bunch of macros. An alternative to trying to unravel them is to look at the preprocessor output:

#include <stdio.h>
#include <sys/types.h>

int main(void) {
  off_t blah;

  return 0;
}

And then:

$ gcc -E sizes.c  | grep __off_t
typedef long int __off_t;
....

However, if you want to know the size of something, you can always use the sizeof() operator.

Edit: Just saw the part of your question about the __. This answer has a good discussion. The key point is that names starting with __ are reserved for the implementation (so you shouldn't start your own definitions with __).

Detect network connection type on Android

I use this simple code:

fun getConnectionInfo(): ConnectionInfo {
    val cm = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    return if (cm.activeNetwork == null) {
        ConnectionInfo.NO_CONNECTION
    } else {
        if (cm.isActiveNetworkMetered) {
            ConnectionInfo.MOBILE
        } else {
            ConnectionInfo.WI_FI
        }
    }
}

Freeing up a TCP/IP port?

The "netstat --programs" command will give you the process information, assuming you're the root user. Then you will have to kill the "offending" process which may well start up again just to annoy you.

Depending on what you're actually trying to achieve, solutions to that problem will vary based on the processes holding those ports. For example, you may need to disable services (assuming they're unneeded) or configure them to use a different port (if you do need them but you need that port more).

Viewing my IIS hosted site on other machines on my network

As others said your Firewall needs to be configured to accept incoming calls on TCP Port 80.

in win 7+ (easy wizardry way)

  1. go to windows firewall with advance security
  2. Inbound Rules -> Action -> New Rule
  3. select Predefined radio button and then select the last item - World Wide Web Services(HTTP)
  4. click next and leave the next steps as they are (allow the connection)

  • Because outbound traffic(from server to outside world) is allowed by default .it means for example http responses that web server is sending back to outside users and requests

  • But inbound traffic (originating from outside world to the server) is blocked by default like the user web requests originating from their browser which cannot reach the web server by default and you must open it.

You can also take a closer look at inbound and outbound rules at this page

ping response "Request timed out." vs "Destination Host unreachable"

Put very simply, request timeout means there was no response whereas destination unreachable may mean the address specified does not exist i.e. you typed in the wrong IP address.

How to redirect DNS to different ports

Use SRV record. If you are using freenom go to cloudflare.com and connect your freenom server to cloudflare (freenom doesn't support srv records) use _minecraft as service tcp as protocol and your ip as target (you need "a" record to use your ip. I recommend not using your "Arboristal.com" domain as "a" record. If you use "Arboristal.com" as your "a" record hackers can go in your router settings and hack your network) priority - 0, weight - 0 and port - the port you want to use.(i know this because i was in the same situation) Do the same for any domain provider. (sorry if i made spell mistakes)

Getting the 'external' IP address in Java

If you are using JAVA based webapp and if you want to grab the client's (One who makes the request via a browser) external ip try deploying the app in a public domain and use request.getRemoteAddr() to read the external IP address.

How can I get the IP address from NIC in Python?

Two methods:

Method #1 (use external package)

You need to ask for the IP address that is bound to your eth0 interface. This is available from the netifaces package

import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
print ip  # should print "192.168.100.37"

You can also get a list of all available interfaces via

ni.interfaces()

Method #2 (no external package)

Here's a way to get the IP address without using a python package:

import socket
import fcntl
import struct

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

get_ip_address('eth0')  # '192.168.0.110'

Note: detecting the IP address to determine what environment you are using is quite a hack. Almost all frameworks provide a very simple way to set/modify an environment variable to indicate the current environment. Try and take a look at your documentation for this. It should be as simple as doing

if app.config['ENV'] == 'production':
  #send production email
else:
  #send development email

How to connect wireless network adapter to VMWare workstation?

Here is a simple way to connect with your WIFI -

  1. Click on Edit from the menu section
  2. Virtual Network Editor
  3. Change Settings
  4. Add Network
  5. Select a network name
  6. Select Bridged option in VMnet Information -> Bridge to : Automatic
  7. Apply

That's it. You might be asked password to connect. Add it and you would be able to connect to the network.

Kind Regards,

Rahul Tilloo

Why doesn't wireshark detect my interface?

As described in other answer, it's usually caused by incorrectly setting up permissions related to running Wireshark correctly.

Windows machines:

Run Wireshark as administrator.

Wireshark in Administrator privileges.

How can you find out which process is listening on a TCP or UDP port on Windows?

I recommend CurrPorts from NirSoft.

CurrPorts can filter the displayed results. TCPView doesn't have this feature.

Note: You can right click a process's socket connection and select "Close Selected TCP Connections" (You can also do this in TCPView). This often fixes connectivity issues I have with Outlook and Lync after I switch VPNs. With CurrPorts, you can also close connections from the command line with the "/close" parameter.

close vs shutdown socket?

None of the existing answers tell people how shutdown and close works at the TCP protocol level, so it is worth to add this.

A standard TCP connection gets terminated by 4-way finalization:

  1. Once a participant has no more data to send, it sends a FIN packet to the other
  2. The other party returns an ACK for the FIN.
  3. When the other party also finished data transfer, it sends another FIN packet
  4. The initial participant returns an ACK and finalizes transfer.

However, there is another "emergent" way to close a TCP connection:

  1. A participant sends an RST packet and abandons the connection
  2. The other side receives an RST and then abandon the connection as well

In my test with Wireshark, with default socket options, shutdown sends a FIN packet to the other end but it is all it does. Until the other party send you the FIN packet you are still able to receive data. Once this happened, your Receive will get an 0 size result. So if you are the first one to shut down "send", you should close the socket once you finished receiving data.

On the other hand, if you call close whilst the connection is still active (the other side is still active and you may have unsent data in the system buffer as well), an RST packet will be sent to the other side. This is good for errors. For example, if you think the other party provided wrong data or it refused to provide data (DOS attack?), you can close the socket straight away.

My opinion of rules would be:

  1. Consider shutdown before close when possible
  2. If you finished receiving (0 size data received) before you decided to shutdown, close the connection after the last send (if any) finished.
  3. If you want to close the connection normally, shutdown the connection (with SHUT_WR, and if you don't care about receiving data after this point, with SHUT_RD as well), and wait until you receive a 0 size data, and then close the socket.
  4. In any case, if any other error occurred (timeout for example), simply close the socket.

Ideal implementations for SHUT_RD and SHUT_WR

The following haven't been tested, trust at your own risk. However, I believe this is a reasonable and practical way of doing things.

If the TCP stack receives a shutdown with SHUT_RD only, it shall mark this connection as no more data expected. Any pending and subsequent read requests (regardless whichever thread they are in) will then returned with zero sized result. However, the connection is still active and usable -- you can still receive OOB data, for example. Also, the OS will drop any data it receives for this connection. But that is all, no packages will be sent to the other side.

If the TCP stack receives a shutdown with SHUT_WR only, it shall mark this connection as no more data can be sent. All pending write requests will be finished, but subsequent write requests will fail. Furthermore, a FIN packet will be sent to another side to inform them we don't have more data to send.

Network usage top/htop on Linux

Check bmon. It's cli, simple and has charts.

Not exactly what question asked - it doesn't split by processes, only by network interfaces.

How can I kill whatever process is using port 8080 so that I can vagrant up?

Run: nmap -p 8080 localhost (Install nmap with MacPorts or Homebrew if you don't have it on your system yet)

Nmap scan report for localhost (127.0.0.1)

Host is up (0.00034s latency).

Other addresses for localhost (not scanned): ::1

PORT STATE SERVICE

8080/tcp open http-proxy

Run: ps -ef | grep http-proxy

UID PID PPID C STIME TTY TIME CMD

640 99335 88310 0 12:26pm ttys002 0:00.01 grep http-proxy"

Run: ps -ef 640 (replace 501 with your UID)

/System/Library/PrivateFrameworks/PerformanceAnalysis.framework/Versions/A/XPCServices/com.apple.PerformanceAnalysis.animationperfd.xpc/Contents/MacOS/com.apple.PerformanceAnalysis.animationperfd

Port 8080 on mac osx is used by something installed with XCode SDK

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from somewhere.com. Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

When is TCP option SO_LINGER (0) required?

I like Maxim's observation that DOS attacks can exhaust server resources. It also happens without an actually malicious adversary.

Some servers have to deal with the 'unintentional DOS attack' which occurs when the client app has a bug with connection leak, where they keep creating a new connection for every new command they send to your server. And then perhaps eventually closing their connections if they hit GC pressure, or perhaps the connections eventually time out.

Another scenario is when 'all clients have the same TCP address' scenario. Then client connections are distinguishable only by port numbers (if they connect to a single server). And if clients start rapidly cycling opening/closing connections for any reason they can exhaust the (client addr+port, server IP+port) tuple-space.

So I think servers may be best advised to switch to the Linger-Zero strategy when they see a high number of sockets in the TIME_WAIT state - although it doesn't fix the client behavior, it might reduce the impact.

How to get a list of all valid IP addresses in a local network?

Install nmap,

sudo apt-get install nmap

then

nmap -sP 192.168.1.*

or more commonly

nmap -sn 192.168.1.0/24

will scan the entire .1 to .254 range

This does a simple ping scan in the entire subnet to see which hosts are online.

Default SQL Server Port

The default port for SQL Server Database Engine is 1433.

And as a best practice it should always be changed after the installation. 1433 is widely known which makes it vulnerable to attacks.

What do pty and tty mean?

tty: teletype. Usually refers to the serial ports of a computer, to which terminals were attached.

pty: pseudoteletype. Kernel provided pseudoserial port connected to programs emulating terminals, such as xterm, or screen.

Good tool for testing socket connections?

Try Wireshark or WebScarab second is better for interpolating data into the exchange (not sure Wireshark even can). Anyway, one of them should be able to help you out.

How to find an available port?

According to Wikipedia, you should use ports 49152 to 65535 if you don't need a 'well known' port.

AFAIK the only way to determine wheter a port is in use is to try to open it.

How to provide user name and password when connecting to a network share

Today 7 years later I'm facing the same issue and I'd like to share my version of the solution.

It is copy & paste ready :-) Here it is:

Step 1

In your code (whenever you need to do something with permissions)

ImpersonationHelper.Impersonate(domain, userName, userPassword, delegate
                            {
                                //Your code here 
                                //Let's say file copy:
                                if (!File.Exists(to))
                                {
                                    File.Copy(from, to);
                                }
                            });

Step 2

The Helper file which does a magic

using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;    
using Microsoft.Win32.SafeHandles;


namespace BlaBla
{
    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true)
        {
        }

        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }

    public class ImpersonationHelper
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private extern static bool CloseHandle(IntPtr handle);

        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static void Impersonate(string domainName, string userName, string userPassword, Action actionToExecute)
        {
            SafeTokenHandle safeTokenHandle;
            try
            {

                const int LOGON32_PROVIDER_DEFAULT = 0;
                //This parameter causes LogonUser to create a primary token.
                const int LOGON32_LOGON_INTERACTIVE = 2;

                // Call LogonUser to obtain a handle to an access token.
                bool returnValue = LogonUser(userName, domainName, userPassword,
                    LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                    out safeTokenHandle);
                //Facade.Instance.Trace("LogonUser called.");

                if (returnValue == false)
                {
                    int ret = Marshal.GetLastWin32Error();
                    //Facade.Instance.Trace($"LogonUser failed with error code : {ret}");

                    throw new System.ComponentModel.Win32Exception(ret);
                }

                using (safeTokenHandle)
                {
                    //Facade.Instance.Trace($"Value of Windows NT token: {safeTokenHandle}");
                    //Facade.Instance.Trace($"Before impersonation: {WindowsIdentity.GetCurrent().Name}");

                    // Use the token handle returned by LogonUser.
                    using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                    {
                        using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                        {
                            //Facade.Instance.Trace($"After impersonation: {WindowsIdentity.GetCurrent().Name}");
                            //Facade.Instance.Trace("Start executing an action");

                            actionToExecute();

                            //Facade.Instance.Trace("Finished executing an action");
                        }
                    }
                    //Facade.Instance.Trace($"After closing the context: {WindowsIdentity.GetCurrent().Name}");
                }

            }
            catch (Exception ex)
            {
                //Facade.Instance.Trace("Oh no! Impersonate method failed.");
                //ex.HandleException();
                //On purpose: we want to notify a caller about the issue /Pavel Kovalev 9/16/2016 2:15:23 PM)/
                throw;
            }
        }
    }
}

java.net.ConnectException: Connection refused

I had the same problem with Mqtt broker called vernemq.but solved it by adding the following.

  1. $ sudo vmq-admin listener show

to show the list o allowed ips and ports for vernemq

  1. $ sudo vmq-admin listener start port=1885 -a 0.0.0.0 --mountpoint /appname --nr_of_acceptors=10 --max_connections=20000

to add any ip and your new port. now u should be able to connect without any problem.

Hope it solves your problem. enter image description here

Checking network connection

Perhaps you could use something like this:

import urllib2

def internet_on():
    try:
        urllib2.urlopen('http://216.58.192.142', timeout=1)
        return True
    except urllib2.URLError as err: 
        return False

Currently, 216.58.192.142 is one of the IP addresses for google.com. Change http://216.58.192.142 to whatever site can be expected to respond quickly.

This fixed IP will not map to google.com forever. So this code is not robust -- it will need constant maintenance to keep it working.

The reason why the code above uses a fixed IP address instead of fully qualified domain name (FQDN) is because a FQDN would require a DNS lookup. When the machine does not have a working internet connection, the DNS lookup itself may block the call to urllib_request.urlopen for more than a second. Thanks to @rzetterberg for pointing this out.


If the fixed IP address above is not working, you can find a current IP address for google.com (on unix) by running

% dig google.com  +trace 
...
google.com.     300 IN  A   216.58.192.142

How can I use iptables on centos 7?

If you do so, and you're using fail2ban, you will need to enable the proper filters/actions:

Put the following lines in /etc/fail2ban/jail.d/sshd.local

[ssh-iptables]
enabled  = true
filter   = sshd
action   = iptables[name=SSH, port=ssh, protocol=tcp]
logpath  = /var/log/secure
maxretry = 5
bantime = 86400

Enable and start fail2ban:

systemctl enable fail2ban
systemctl start fail2ban

Reference: http://blog.iopsl.com/fail2ban-on-centos-7-to-protect-ssh-part-ii/

Is it possible to disable the network in iOS Simulator?

With Xcode 8.3 and iOS 10.3:

XCUIDevice.shared().siriService.activate(voiceRecognitionText: "Turn off wifi")
XCUIDevice.shared().press(XCUIDeviceButton.home)

Be sure to include @available(iOS 10.3, *) at the top of your test suite file.

You could alternatively "Turn on Airplane Mode" if you prefer.

Once Siri turns off wifi or turns on Airplane Mode, you will need to dismiss the Siri dialogue that says that Siri requires internet. This is accomplished by pressing the home button, which dismisses the dialogue and returns to your app.

Python socket receive - incoming packets always have a different size

The answer by Larry Hastings has some great general advice about sockets, but there are a couple of mistakes as it pertains to how the recv(bufsize) method works in the Python socket module.

So, to clarify, since this may be confusing to others looking to this for help:

  1. The bufsize param for the recv(bufsize) method is not optional. You'll get an error if you call recv() (without the param).
  2. The bufferlen in recv(bufsize) is a maximum size. The recv will happily return fewer bytes if there are fewer available.

See the documentation for details.

Now, if you're receiving data from a client and want to know when you've received all of the data, you're probably going to have to add it to your protocol -- as Larry suggests. See this recipe for strategies for determining end of message.

As that recipe points out, for some protocols, the client will simply disconnect when it's done sending data. In those cases, your while True loop should work fine. If the client does not disconnect, you'll need to figure out some way to signal your content length, delimit your messages, or implement a timeout.

I'd be happy to try to help further if you could post your exact client code and a description of your test protocol.

How can I check if an ip is in a network in Python?

I don't know of anything in the standard library, but PySubnetTree is a Python library that will do subnet matching.

How can one check to see if a remote file exists using PHP?

This works for me to check if a remote file exist in PHP:

$url = 'https://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico';
    $header_response = get_headers($url, 1);

    if ( strpos( $header_response[0], "404" ) !== false ) {
        echo 'File does NOT exist';
        } else {
        echo 'File exists';
        }

How to set the timeout for a TcpClient?

Here is a code improvement based on mcandal solution. Added exception catching for any exception generated from the client.ConnectAsync task (e.g: SocketException when server is unreachable)

var timeOut = TimeSpan.FromSeconds(5);     
var cancellationCompletionSource = new TaskCompletionSource<bool>();

try
{
    using (var cts = new CancellationTokenSource(timeOut))
    {
        using (var client = new TcpClient())
        {
            var task = client.ConnectAsync(hostUri, portNumber);

            using (cts.Token.Register(() => cancellationCompletionSource.TrySetResult(true)))
            {
                if (task != await Task.WhenAny(task, cancellationCompletionSource.Task))
                {
                    throw new OperationCanceledException(cts.Token);
                }

                // throw exception inside 'task' (if any)
                if (task.Exception?.InnerException != null)
                {
                    throw task.Exception.InnerException;
                }
            }

            ...

        }
    }
}
catch (OperationCanceledException operationCanceledEx)
{
    // connection timeout
    ...
}
catch (SocketException socketEx)
{
    ...
}
catch (Exception ex)
{
    ...
}

How to validate IP address in Python?

Don't parse it. Just ask.

import socket

try:
    socket.inet_aton(addr)
    # legal
except socket.error:
    # Not legal

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

In Ubuntu/Unix we can resolve this problem in 2 steps as described below.

  1. Type netstat -plten |grep java

    This will give an output similar to:

    tcp   0   0 0.0.0.0:8080   0.0.0.0:*  LISTEN   1001  76084  9488/java       
    

    Here 8080 is the port number at which the java process is listening and 9488 is its process id (pid).

  2. In order to free the occupied port, we have to kill this process using the kill command.

    kill -9 9488
    

    9488 is the process id from earlier. We use -9 to force stop the process.

Your port should now be free and you can restart the server.

How to overcome root domain CNAME restrictions?

CNAME'ing a root record is technically not against RFC, but does have limitations meaning it is a practice that is not recommended.

Normally your root record will have multiple entries. Say, 3 for your name servers and then one for an IP address.

Per RFC:

If a CNAME RR is present at a node, no other data should be present;

And Per IETF 'Common DNS Operational and Configuration Errors' Document:

This is often attempted by inexperienced administrators as an obvious way to allow your domain name to also be a host. However, DNS servers like BIND will see the CNAME and refuse to add any other resources for that name. Since no other records are allowed to coexist with a CNAME, the NS entries are ignored. Therefore all the hosts in the podunk.xx domain are ignored as well!

References:

Fastest way to ping a network range and return responsive hosts?

You should use NMAP:

nmap -T5 -sP 192.168.0.0-255

How to monitor network calls made from iOS Simulator

Personally, I use Charles for that kind of stuff.
When enabled, it will monitor every network request, displaying extended request details, including support for SSL and various request/reponse format, like JSON, etc...

You can also configure it to sniff only requests to specific servers, not the whole traffic.

It's commercial software, but there is a trial, and IMHO it's definitively a great tool.

Sending string via socket (python)

import socket
from threading import *

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.3"
port = 8000
print (host)
print (port)
serversocket.bind((host, port))

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()

    def run(self):
        while 1:
            print('Client sent:', self.sock.recv(1024).decode())
            self.sock.send(b'Oi you sent something to me')

serversocket.listen(5)
print ('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

This is a very VERY simple design for how you could solve it. First of all, you need to either accept the client (server side) before going into your while 1 loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.

How can I connect to Android with ADB over TCP?

I've found a convenient method that i would like to share.

For Windows

Having USB Access Once

No root required

Connect your phone and pc to a hotspot or run portable hotspot from your phone and connect your pc to it.

Get the ip of your phone as prescribed by brian (Wont need if you're making hotspot from your phone)

adb shell ip -f inet addr show wlan0

Open Notepad

Write these

@echo off
cd C:\android\android-sdk\platform-tools
adb tcpip 5555
adb connect 192.168.43.1:5555

Change the location given above to where your pc contains the abd.exe file

Change the ip to your phone ip.

Note : The IP given above is the basic IP of an android device when it makes a hotspot. If you are connecting to a wifi network and if your device's IP keeps on changing while connecting to a hotspot every time, you can make it static by configuring within the wifi settings. Google it.

Now save the file as ABD_Connect.bat (MS-DOS batch file).

Save it somewhere and refer a shortcut to Desktop or Start button.

Connect through USB once, and try running some application. After that whenever you want to connect wirelessly, double click the shortcut.

Note : Sometimes you need to open the shortcut each time you debug the application. So making a shortcut key for the shortcut in desktop will be more convenient. I've made a shortcut key like Ctrl+Alt+S. So whenever i wish to debug, i'll press Shift+F9 and Ctrl+Alt+S

Note : If you find device=null error on cmd window, check your IP, it might have changed.

Capturing mobile phone traffic on Wireshark

Similarly to making your PC a wireless access point, but can be much easier, is using reverse tethering. If you happen to have an HTC phone they have a nice reverse-tethering option called "Internet pass-through", under the network/mobile network sharing settings. It routes all your traffic through your PC and you can just run Wireshark there.

How to check if internet connection is present in Java?

This code:

"127.0.0.1".equals(InetAddress.getLocalHost().getHostAddress().toString());

Returns - to me - true if offline, and false, otherwise. (well, I don't know if this true to all computers).

This works much faster than the other approaches, up here.


EDIT: I found this only working, if the "flip switch" (on a laptop), or some other system-defined option, for the internet connection, is off. That's, the system itself knows not to look for any IP addresses.

Maximum packet size for a TCP connection

One solution can be to set socket option TCP_MAXSEG (http://linux.die.net/man/7/tcp) to a value that is "safe" with underlying network (e.g. set to 1400 to be safe on ethernet) and then use a large buffer in send system call. This way there can be less system calls which are expensive. Kernel will split the data to match MSS.

This way you can avoid truncated data and your application doesn't have to worry about small buffers.

What is the difference between a port and a socket?

A socket represents a single connection between two network applications. These two applications nominally run on different computers, but sockets can also be used for interprocess communication on a single computer. Applications can create multiple sockets for communicating with each other. Sockets are bidirectional, meaning that either side of the connection is capable of both sending and receiving data. Therefore a socket can be created theoretically at any level of the OSI model from 2 upwards. Programmers often use sockets in network programming, albeit indirectly. Programming libraries like Winsock hide many of the low-level details of socket programming. Sockets have been in widespread use since the early 1980s.

A port represents an endpoint or "channel" for network communications. Port numbers allow different applications on the same computer to utilize network resources without interfering with each other. Port numbers most commonly appear in network programming, particularly socket programming. Sometimes, though, port numbers are made visible to the casual user. For example, some Web sites a person visits on the Internet use a URL like the following:

http://www.mairie-metz.fr:8080/ In this example, the number 8080 refers to the port number used by the Web browser to connect to the Web server. Normally, a Web site uses port number 80 and this number need not be included with the URL (although it can be).

In IP networking, port numbers can theoretically range from 0 to 65535. Most popular network applications, though, use port numbers at the low end of the range (such as 80 for HTTP).

Note: The term port also refers to several other aspects of network technology. A port can refer to a physical connection point for peripheral devices such as serial, parallel, and USB ports. The term port also refers to certain Ethernet connection points, such as those on a hub, switch, or router.

ref http://compnetworking.about.com/od/basicnetworkingconcepts/l/bldef_port.htm

ref http://compnetworking.about.com/od/itinformationtechnology/l/bldef_socket.htm

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

You may get your answer here: Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

UPDATE

It might be due to various issues.I cant say which one is there in your case. It may be because:

  • DCOM is not enabled in host pc or target pc or on both
  • your firewall or even your antivirus is preventing the access
  • any WMI related service is disabled

Some WMI related services are:

  • Remote Access Auto Connection Manager
  • Remote Access Connection Manager
  • Remote Procedure Call (RPC)
  • Remote Procedure Call (RPC) Locator
  • Remote Registry

For DCOM settings refer to registry key HKLM\Software\Microsoft\OLE, value EnableDCOM. The value should be set to 'Y'.

Can an Option in a Select tag carry multiple values?

Duplicate tag parameters are not allowed in HTML. What you could do, is VALUE="1,2010". But you would have to parse the value on the server.

Image UriSource and Data Binding

You can also simply set the Source attribute rather than using the child elements. To do this your class needs to return the image as a Bitmap Image. Here is an example of one way I've done it

<Image Width="90" Height="90" 
       Source="{Binding Path=ImageSource}"
       Margin="0,0,0,5" />

And the class property is simply this

public object ImageSource {
    get {
        BitmapImage image = new BitmapImage();

        try {
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            image.UriSource = new Uri( FullPath, UriKind.Absolute );
            image.EndInit();
        }
        catch{
            return DependencyProperty.UnsetValue;
        }

        return image;
    }
}

I suppose it may be a little more work than the value converter, but it is another option.

Extracting numbers from vectors of strings

Using the package unglue we can do :

# install.packages("unglue")
library(unglue)

years<-c("20 years old", "1 years old")
unglue_vec(years, "{x} years old", convert = TRUE)
#> [1] 20  1

Created on 2019-11-06 by the reprex package (v0.3.0)

More info: https://github.com/moodymudskipper/unglue/blob/master/README.md

jQuery using append with effects

Something like:

$('#test').append('<div id="newdiv">Hello</div>').hide().show('slow');

should do it?

Edit: sorry, mistake in code and took Matt's suggestion on board too.

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

Load arrayList data into JTable

You probably need to use a TableModel (Oracle's tutorial here)

How implements your own TableModel

public class FootballClubTableModel extends AbstractTableModel {
  private List<FootballClub> clubs ;
  private String[] columns ; 

  public FootBallClubTableModel(List<FootballClub> aClubList){
    super();
    clubs = aClubList ;
    columns = new String[]{"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
  }

  // Number of column of your table
  public int getColumnCount() {
    return columns.length ;
  }

  // Number of row of your table
  public int getRowsCount() {
    return clubs.size();
  }

  // The object to render in a cell
  public Object getValueAt(int row, int col) {
    FootballClub club = clubs.get(row);
    switch(col) {
      case 0: return club.getPosition();
      // to complete here...
      default: return null;
    }
  }

  // Optional, the name of your column
  public String getColumnName(int col) {
    return columns[col] ;
  }

}

You maybe need to override anothers methods of TableModel, depends on what you want to do, but here is the essential methods to understand and implements :)
Use it like this

List<FootballClub> clubs = getFootballClub();
TableModel model = new FootballClubTableModel(clubs);
JTable table = new JTable(model);

Hope it help !

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

If you are using Less or Sass with your project, you can define the link-hover-decoration variable (which is underline by default) and you're all set.

Remote debugging Tomcat with Eclipse

Let me share the simple way to enable the remote debugging mode in tomcat7 with eclipse (Windows).

Step 1: open bin/startup.bat file
Step 2: add the below lines for debugging with JDPA option (it should starting line of the file )

    set JPDA_ADDRESS=8000  
    set JPDA_TRANSPORT=dt_socket  

Step 3: in the same file .. go to end of the file modify this line -

    call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%  
    instead of line  
    call "%EXECUTABLE%" start %CMD_LINE_ARGS%  

step 4: then just run bin>startup.bat (so now your tomcat server ran in remote mode with port 8000).

step 5: after that lets connect your source project by eclipse IDE with remote client.

step6: In the Eclipse IDE go to "debug Configuration"

step7:click "remote java application" and on that click "New"

step8. in the "connect" tab set the parameter value

   project= your source project  
   connection Type: standard (socket attached)   
   host: localhost  
   port:8000  

step9: click apply and debug.

so finally your eclipse remote client is connected with the running tomcat server (debug mode).

Hope this approach might be help you.

Regards..

Procedure expects parameter which was not supplied

If Template is not set (i.e. ==null), this error will be raised, too.

More comments:

If you know the parameter value by the time you add parameters, you can also use AddWithValue

The EXEC is not required. You can reference the @template parameter in the SELECT directly.

Ruby: How to post a file via HTTP as multipart/form-data?

restclient did not work for me until I overrode create_file_field in RestClient::Payload::Multipart.

It was creating a 'Content-Disposition: multipart/form-data' in each part where it should be ‘Content-Disposition: form-data’.

http://www.ietf.org/rfc/rfc2388.txt

My fork is here if you need it: [email protected]:kcrawford/rest-client.git

How do I change the font-size of an <option> element within <select>?

One solution could be to wrap the options inside optgroup:

_x000D_
_x000D_
optgroup { font-size:40px; }
_x000D_
<select>
  <optgroup>
    <option selected="selected" class="service-small">Service area?</option>
    <option class="service-small">Volunteering</option>
    <option class="service-small">Partnership &amp; Support</option>
    <option class="service-small">Business Services</option>
  </optgroup>
</select>
_x000D_
_x000D_
_x000D_

Send form data using ajax

In your function form is a DOM object, In order to use attr() you need to convert it to jQuery object.

function f(form, fname, lname) {
    action = $(form).attr("action");
    $.post(att, {fname : fname , lname :lname}).done(function (data) {
        alert(data);
    });
    return true;
}

With .serialize()

function f(form, fname, lname) {
    action = $(form).attr("action");
    $.post(att, $(form).serialize() ).done(function (data) {
        alert(data);
    });
    return true;
}

Additionally, You can use .serialize()

Sleep function in C++

Just use it...

Firstly include the unistd.h header file, #include<unistd.h>, and use this function for pausing your program execution for desired number of seconds:

sleep(x);

x can take any value in seconds.

If you want to pause the program for 5 seconds it is like this:

sleep(5);

It is correct and I use it frequently.

It is valid for C and C++.

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

This message means that for some reason the garbage collector is taking an excessive amount of time (by default 98% of all CPU time of the process) and recovers very little memory in each run (by default 2% of the heap).

This effectively means that your program stops doing any progress and is busy running only the garbage collection at all time.

To prevent your application from soaking up CPU time without getting anything done, the JVM throws this Error so that you have a chance of diagnosing the problem.

The rare cases where I've seen this happen is where some code was creating tons of temporary objects and tons of weakly-referenced objects in an already very memory-constrained environment.

Check out the Java GC tuning guide, which is available for various Java versions and contains sections about this specific problem:

How to fix the "508 Resource Limit is reached" error in WordPress?

On my blog, the reason of this error is a plugin named Broken Link checker. This plugin has high resource usage from hosting, resulting in this error.

Check if a plugin on your installation is behaving similarly like this.

What is process.env.PORT in Node.js?

When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT variable for you; after all, your script runs in their environment.

Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000 instead of process.env.PORT || 3000 where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.

This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;

app.listen(port);

Is there a WebSocket client implemented for Python?

web2py has comet_messaging.py, which uses Tornado for websockets look at an example here: http://vimeo.com/18399381 and here vimeo . com / 18232653

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

I just implemented this utility class that creates UUIDs as String with or without dashes. Fell free to use and share. I hope that it helps!

package your.package.name;

import java.security.SecureRandom;
import java.util.Random;

/**
 * Utility class that creates random-based UUIDs.
 * 
 */
public abstract class RandomUuidStringCreator {

    private static final int RANDOM_VERSION = 4;

    /**
     * Returns a random-based UUID as String.
     * 
     * It uses a thread local {@link SecureRandom}.
     * 
     * @return a random-based UUID string
     */
    public static String getRandomUuid() {
        return getRandomUuid(SecureRandomLazyHolder.SECURE_RANDOM);
    }

    /**
     * Returns a random-based UUID as String WITH dashes.
     * 
     * It uses a thread local {@link SecureRandom}.
     * 
     * @return a random-based UUID string
     */
    public static String getRandomUuidWithDashes() {
        return format(getRandomUuid());
    }

    /**
     * Returns a random-based UUID String.
     * 
     * It uses any instance of {@link Random}.
     * 
     * @return a random-based UUID string
     */
    public static String getRandomUuid(Random random) {

        long msb = 0;
        long lsb = 0;

        // (3) set all bit randomly
        if (random instanceof SecureRandom) {
            // Faster for instances of SecureRandom
            final byte[] bytes = new byte[16];
            random.nextBytes(bytes);
            msb = toNumber(bytes, 0, 8); // first 8 bytes for MSB
            lsb = toNumber(bytes, 8, 16); // last 8 bytes for LSB
        } else {
            msb = random.nextLong(); // first 8 bytes for MSB
            lsb = random.nextLong(); // last 8 bytes for LSB
        }

        // Apply version and variant bits (required for RFC-4122 compliance)
        msb = (msb & 0xffffffffffff0fffL) | (RANDOM_VERSION & 0x0f) << 12; // apply version bits
        lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L; // apply variant bits

        // Convert MSB and LSB to hexadecimal
        String msbHex = zerofill(Long.toHexString(msb), 16);
        String lsbHex = zerofill(Long.toHexString(lsb), 16);

        // Return the UUID
        return msbHex + lsbHex;
    }

    /**
     * Returns a random-based UUID as String WITH dashes.
     * 
     * It uses a thread local {@link SecureRandom}.
     * 
     * @return a random-based UUID string
     */
    public static String getRandomUuidWithDashes(Random random) {
        return format(getRandomUuid(random));
    }

    private static long toNumber(final byte[] bytes, final int start, final int length) {
        long result = 0;
        for (int i = start; i < length; i++) {
            result = (result << 8) | (bytes[i] & 0xff);
        }
        return result;
    }

    private static String zerofill(String string, int length) {
        return new String(lpad(string.toCharArray(), length, '0'));
    }

    private static char[] lpad(char[] chars, int length, char fill) {

        int delta = 0;
        int limit = 0;

        if (length > chars.length) {
            delta = length - chars.length;
            limit = length;
        } else {
            delta = 0;
            limit = chars.length;
        }

        char[] output = new char[chars.length + delta];
        for (int i = 0; i < limit; i++) {
            if (i < delta) {
                output[i] = fill;
            } else {
                output[i] = chars[i - delta];
            }
        }
        return output;
    }

    private static String format(String string) {
        char[] input = string.toCharArray();
        char[] output = new char[36];

        System.arraycopy(input, 0, output, 0, 8);
        System.arraycopy(input, 8, output, 9, 4);
        System.arraycopy(input, 12, output, 14, 4);
        System.arraycopy(input, 16, output, 19, 4);
        System.arraycopy(input, 20, output, 24, 12);

        output[8] = '-';
        output[13] = '-';
        output[18] = '-';
        output[23] = '-';

        return new String(output);
    }

    // Holds lazy secure random
    private static class SecureRandomLazyHolder {
        static final Random SECURE_RANDOM = new SecureRandom();
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        System.out.println("// Using `java.security.SecureRandom` (DEFAULT)");
        System.out.println("RandomUuidCreator.getRandomUuid()");
        System.out.println();
        for (int i = 0; i < 5; i++) {
            System.out.println(RandomUuidStringCreator.getRandomUuid());
        }

        System.out.println();
        System.out.println("// Using `java.util.Random` (FASTER)");
        System.out.println("RandomUuidCreator.getRandomUuid(new Random())");
        System.out.println();
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            System.out.println(RandomUuidStringCreator.getRandomUuid(random));
        }
    }
}

This is the output:

// Using `java.security.SecureRandom` (DEFAULT)
RandomUuidStringCreator.getRandomUuid()

'f553ca75657b4b5d85bedf1082785a0b'
'525ecc389e934f209b97d0f0db09d9c6'
'93ec6425bb04499ab47b790fd013ab0d'
'c2d438c620ea4cd5baafd448f9fe945b'
'fb4bc5734931415e94e78da62cb5fe0d'

// Using `java.util.Random` (FASTER)
RandomUuidStringCreator.getRandomUuid(new Random())

'051360b5c92d40fbbb89b40842adbacc'
'a993896538aa43faacbcfd83f913f38b'
'720684d22c584d5299cb03cdbc1912d2'
'82cf94ea296a4a138a92825a0068d4a1'
'a7eda46a215c4e55be3aa957ba74ca9c'

There's a codec in uuid-creator that can do it more efficiently: Base16Codec. Example:

// Returns a base-16 string
// It is much faster than doing `uuid.toString().replaceAll("-", "")`.
UuidCodec<String> codec = new Base16Codec();
String string = codec.encode(UUID.randomUUID());

How do I edit an incorrect commit message in git ( that I've pushed )?

The message from Linus Torvalds may answer your question:

Modify/edit old commit messages

Short answer: you can not (if pushed).


extract (Linus refers to BitKeeper as BK):

Side note, just out of historical interest: in BK you could.

And if you're used to it (like I was) it was really quite practical. I would apply a patch-bomb from Andrew, notice something was wrong, and just edit it before pushing it out.

I could have done the same with git. It would have been easy enough to make just the commit message not be part of the name, and still guarantee that the history was untouched, and allow the "fix up comments later" thing.

But I didn't.

Part of it is purely "internal consistency". Git is simply a cleaner system thanks to everything being SHA1-protected, and all objects being treated the same, regardless of object type. Yeah, there are four different kinds of objects, and they are all really different, and they can't be used in the same way, but at the same time, even if their encoding might be different on disk, conceptually they all work exactly the same.

But internal consistency isn't really an excuse for being inflexible, and clearly it would be very flexible if we could just fix up mistakes after they happen. So that's not a really strong argument.

The real reason git doesn't allow you to change the commit message ends up being very simple: that way, you can trust the messages. If you allowed people to change them afterwards, the messages are inherently not very trustworthy.


To be complete, you could rewrite your local commit history in order to reflect what you want, as suggested by sykora (with some rebase and reset --hard, gasp!)

However, once you publish your revised history again (with a git push origin +master:master, the + sign forcing the push to occur, even if it doesn't result in a "fast-forward" commit)... you might get into some trouble.

Extract from this other SO question:

I actually once pushed with --force to git.git repository and got scolded by Linus BIG TIME. It will create a lot of problems for other people. A simple answer is "don't do it".

How to add a list item to an existing unordered list?

This would do it:

$("#header ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

Two things:

  • You can just append the <li> to the <ul> itself.
  • You need to use the opposite type of quotes than what you're using in your HTML. So since you're using double quotes in your attributes, surround the code with single quotes.

Open Popup window using javascript

First point is- showing multiple popups is not desirable in terms of usability.

But you can achieve it by using multiple popup names

var newwindow;
function createPop(url, name)
{    
   newwindow=window.open(url,name,'width=560,height=340,toolbar=0,menubar=0,location=0');  
   if (window.focus) {newwindow.focus()}
}

Better approach will be showing both in a single page in two different iFrames or Divs.

Update:

So I will suggest to create a new tab in the test.aspx page to show the report, instead of replacing the image content and placing the pdf.

#1071 - Specified key was too long; max key length is 1000 bytes

I had this issue, and solved by following:

Cause

There is a known bug with MySQL related to MyISAM, the UTF8 character set and indexes that you can check here.

Resolution

  • Make sure MySQL is configured with the InnoDB storage engine.

  • Change the storage engine used by default so that new tables will always be created appropriately:

    set GLOBAL storage_engine='InnoDb';

  • For MySQL 5.6 and later, use the following:

    SET GLOBAL default_storage_engine = 'InnoDB';

  • And finally make sure that you're following the instructions provided in Migrating to MySQL.

Reference

Determining the current foreground application from a background task or service

Taking into account that getRunningTasks() is deprecated and getRunningAppProcesses() is not reliable, I came to decision to combine 2 approaches mentioned in StackOverflow:

   private boolean isAppInForeground(Context context)
    {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        {
            ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
            String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();

            return foregroundTaskPackageName.toLowerCase().equals(context.getPackageName().toLowerCase());
        }
        else
        {
            ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
            ActivityManager.getMyMemoryState(appProcessInfo);
            if (appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE)
            {
                return true;
            }

            KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            // App is foreground, but screen is locked, so show notification
            return km.inKeyguardRestrictedInputMode();
        }
    }

Why and how to fix? IIS Express "The specified port is in use"

In Visual Studio 2017, select Project/Properties and then select the Web option. In the IIS section next to the default project URL click Create Virtual Directory. This solved the problem for me. I think in my case the default project Virtual Directory had been corrupted in some way following a debugging session.

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

I was getting the error A client error (403) occurred when calling the HeadObject operation: Forbidden for my aws cli copy command aws s3 cp s3://bucket/file file. I was using a IAM role which had full S3 access using an Inline Policy.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "*"
    }
  ]
}

If I give it the full S3 access from the Managed Policies instead, then the command works. I think this must be a bug from Amazon, because the policies in both cases were exactly the same.

jQuery scroll to ID from different page

Combining answers by Petr and Sarfraz, I arrive at the following.

On page1.html:

<a href="page2.html#elementID">Jump</a>

On page2.html:

<script type="text/javascript">
    $(document).ready(function() {
        $('html, body').hide();

        if (window.location.hash) {
            setTimeout(function() {
                $('html, body').scrollTop(0).show();
                $('html, body').animate({
                    scrollTop: $(window.location.hash).offset().top
                    }, 1000)
            }, 0);
        }
        else {
            $('html, body').show();
        }
    });
</script>

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

If you're using the EntityDataSource in your project, the solution is in Fix: 'Unable to load one or more of the requested types' Errors. You should set the ContextTypeName="ProjectNameNameSpace.EntityContainerName" '

This solved my problems...

How to determine the IP address of a Solaris system

hostname and uname will give you the name of the host. Then use nslookup to translate that to an IP address.

Iterating through a variable length array

You've specifically mentioned a "variable-length array" in your question, so neither of the existing two answers (as I write this) are quite right.

Java doesn't have any concept of a "variable-length array", but it does have Collections, which serve in this capacity. Any collection (technically any "Iterable", a supertype of Collections) can be looped over as simply as this:

Collection<Thing> things = ...;
for (Thing t : things) {
  System.out.println(t);
}

EDIT: it's possible I misunderstood what he meant by 'variable-length'. He might have just meant it's a fixed length but not every instance is the same fixed length. In which case the existing answers would be fine. I'm not sure what was meant.

How can I modify the size of column in a MySQL table?

Have you tried this?

ALTER TABLE <table_name> MODIFY <col_name> VARCHAR(65353);

This will change the col_name's type to VARCHAR(65353)

make image( not background img) in div repeat?

You have use to repeat-y as style="background-repeat:repeat-y;width: 200px;" instead of style="repeat-y".

Try this inside the image tag or you can use the below css for the div

.div_backgrndimg
{
    background-repeat: repeat-y;
    background-image: url("/image/layout/lotus-dreapta.png");
    width:200px;
}

How to return the current timestamp with Moment.js?

Get by Location:

moment.locale('pt-br')
return moment().format('DD/MM/YYYY HH:mm:ss')

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

Use These two lines to your EditText

android:imeActionLabel="Done"
android:singleLine="true"

or you can achieve it Programmatically by this line.

editText.setImeOptions(EditorInfo.IME_ACTION_DONE);

How to get file creation date/time in Bash/Debian?

Unfortunately your quest won't be possible in general, as there are only 3 distinct time values stored for each of your files as defined by the POSIX standard (see Base Definitions section 4.8 File Times Update)

Each file has three distinct associated timestamps: the time of last data access, the time of last data modification, and the time the file status last changed. These values are returned in the file characteristics structure struct stat, as described in <sys/stat.h>.

EDIT: As mentioned in the comments below, depending on the filesystem used metadata may contain file creation date. Note however storage of information like that is non standard. Depending on it may lead to portability problems moving to another filesystem, in case the one actually used somehow stores it anyways.

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I solved this converting the JSP from XHTML to HTML, doing this in the begining:

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
...

Clear text input on click with AngularJS

Try this,

 this.searchAll = element(by.xpath('path here'));
 this.searchAll.sendKeys('');

How to generate range of numbers from 0 to n in ES2015 only?

With Delta/Step

smallest and one-liner
[...Array(N)].map((_, i) => from + i * step);

Examples and other alternatives

[...Array(10)].map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array.from(Array(10)).map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array.from(Array(10).keys()).map(i => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

[...Array(10).keys()].map(i => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]

Array(10).fill(0).map((_, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Array(10).fill().map((_, i) => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]
Range Function
const range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

range(0, 9, 2);
//=> [0, 2, 4, 6, 8]

// can also assign range function as static method in Array class (but not recommended )
Array.range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

Array.range(2, 10, 2);
//=> [2, 4, 6, 8, 10]

Array.range(0, 10, 1);
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array.range(2, 10, -1);
//=> []

Array.range(3, 0, -1);
//=> [3, 2, 1, 0]
As Iterators
class Range {
  constructor(total = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      for (let i = 0; i < total; yield from + i++ * step) {}
    };
  }
}

[...new Range(5)]; // Five Elements
//=> [0, 1, 2, 3, 4]
[...new Range(5, 2)]; // Five Elements With Step 2
//=> [0, 2, 4, 6, 8]
[...new Range(5, -2, 10)]; // Five Elements With Step -2 From 10
//=>[10, 8, 6, 4, 2]
[...new Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of new Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2
As Generators Only
const Range = function* (total = 0, step = 1, from = 0) {
  for (let i = 0; i < total; yield from + i++ * step) {}
};

Array.from(Range(5, -2, -10));
//=> [-10, -12, -14, -16, -18]

[...Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]

// Also works with for..of loop
for (i of Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2

// Lazy loaded way
const number0toInf = Range(Infinity);
number0toInf.next().value;
//=> 0
number0toInf.next().value;
//=> 1
// ...

From-To with steps/delta

using iterators
class Range2 {
  constructor(to = 0, step = 1, from = 0) {
    this[Symbol.iterator] = function* () {
      let i = 0,
        length = Math.floor((to - from) / step) + 1;
      while (i < length) yield from + i++ * step;
    };
  }
}
[...new Range2(5)]; // First 5 Whole Numbers
//=> [0, 1, 2, 3, 4, 5]

[...new Range2(5, 2)]; // From 0 to 5 with step 2
//=> [0, 2, 4]

[...new Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]
using Generators
const Range2 = function* (to = 0, step = 1, from = 0) {
  let i = 0,
    length = Math.floor((to - from) / step) + 1;
  while (i < length) yield from + i++ * step;
};

[...Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]

let even4to10 = Range2(10, 2, 4);
even4to10.next().value;
//=> 4
even4to10.next().value;
//=> 6
even4to10.next().value;
//=> 8
even4to10.next().value;
//=> 10
even4to10.next().value;
//=> undefined

For Typescript

interface _Iterable extends Iterable<{}> {
  length: number;
}

class _Array<T> extends Array<T> {
  static range(from: number, to: number, step: number): number[] {
    return Array.from(
      <_Iterable>{ length: Math.floor((to - from) / step) + 1 },
      (v, k) => from + k * step
    );
  }
}
_Array.range(0, 9, 1);
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

Update

class _Array<T> extends Array<T> {
  static range(from: number, to: number, step: number): number[] {
    return [...Array(Math.floor((to - from) / step) + 1)].map(
      (v, k) => from + k * step
    );
  }
}
_Array.range(0, 9, 1);

Edit

class _Array<T> extends Array<T> {
  static range(from: number, to: number, step: number): number[] {
    return Array.from(Array(Math.floor((to - from) / step) + 1)).map(
      (v, k) => from + k * step
    );
  }
}
_Array.range(0, 9, 1);

Spark : how to run spark file from spark shell

You can use either sbt or maven to compile spark programs. Simply add the spark as dependency to maven

<repository>
      <id>Spark repository</id>
      <url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
</repository>

And then the dependency:

<dependency>
      <groupId>spark</groupId>
      <artifactId>spark</artifactId>
      <version>1.2.0</version>
</dependency>

In terms of running a file with spark commands: you can simply do this:

echo"
   import org.apache.spark.sql.*
   ssc = new SQLContext(sc)
   ssc.sql("select * from mytable").collect
" > spark.input

Now run the commands script:

cat spark.input | spark-shell

PSEXEC, access denied errors

I couldn't get access to remote machines unless I had UAC disabled.

That has to be done locally, either from control panel or running the following through cmd:

reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f

While UAC is enabled, make sure you run cmd as administrator.

Start HTML5 video at a particular position when loading?

On Safari Mac for an HLS source, I needed to use the loadeddata event instead of the metadata event.

How can I round down a number in Javascript?

You need to put -1 to round half down and after that multiply by -1 like the example down bellow.

<script type="text/javascript">

  function roundNumber(number, precision, isDown) {
    var factor = Math.pow(10, precision);
    var tempNumber = number * factor;
    var roundedTempNumber = 0;
    if (isDown) {
      tempNumber = -tempNumber;
      roundedTempNumber = Math.round(tempNumber) * -1;
    } else {
      roundedTempNumber = Math.round(tempNumber);
    }
    return roundedTempNumber / factor;
  }
</script>

<div class="col-sm-12">
  <p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
  </p>
  <p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
</div>

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

TL;DR

For JDK 11 try this:

To handle this problem in a clean way, I suggest to use brew and jenv.

For Java 11 follow this 2 steps, first :

JAVA_VERSION=11
brew reinstall jenv 
brew reinstall openjdk@${JAVA_VERSION}
jenv add /usr/local/opt/openjdk@${JAVA_VERSION}/
jenv global ${JAVA_VERSION}

And add this at end of your shell config scripts
~/.bashrc or ~/.zshrc

export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"
export JAVA_HOME="$HOME/.jenv/versions/`jenv version-name`"

Problem solved!

Then restart your shell and try to execute java -version

Note: If you have this problem, your current JDK version is not existent or misconfigured (or may be you have only JRE).

Default values for Vue component props & how to check if a user did not set the prop?

This is an old question, but regarding the second part of the question - how can you check if the user set/didn't set a prop?

Inspecting this within the component, we have this.$options.propsData. If the prop is present here, the user has explicitly set it; default values aren't shown.

This is useful in cases where you can't really compare your value to its default, e.g. if the prop is a function.

NoSql vs Relational database

The biggest advantage of NoSQL over RDBMS is Scalability.
NoSQL databases can easily scale-out to many nodes, but for RDBMS it is very hard.
Scalability not only gives you more storage space but also much higher performance since many hosts work at the same time.

How do I time a method's execution in Java?

Really good code.

http://www.rgagnon.com/javadetails/java-0585.html

import java.util.concurrent.TimeUnit;

long startTime = System.currentTimeMillis();
........
........
........
long finishTime = System.currentTimeMillis();

String diff = millisToShortDHMS(finishTime - startTime);


  /**
   * converts time (in milliseconds) to human-readable format
   *  "<dd:>hh:mm:ss"
   */
  public static String millisToShortDHMS(long duration) {
    String res = "";
    long days  = TimeUnit.MILLISECONDS.toDays(duration);
    long hours = TimeUnit.MILLISECONDS.toHours(duration)
                   - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(duration));
    long minutes = TimeUnit.MILLISECONDS.toMinutes(duration)
                     - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(duration));
    long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
                   - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration));
    if (days == 0) {
      res = String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
    else {
      res = String.format("%dd%02d:%02d:%02d", days, hours, minutes, seconds);
    }
    return res;
  }

Pandas: ValueError: cannot convert float NaN to integer

if you have null value then in doing mathematical operation you will get this error to resolve it use df[~df['x'].isnull()]df[['x']].astype(int) if you want your dataset to be unchangeable.

How to use foreach with a hash reference?

So, with Perl 5.20, the new answer is:

foreach my $key (keys $ad_grp_ref->%*) {

(which has the advantage of transparently working with more complicated expressions:

foreach my $key (keys $ad_grp_obj[3]->get_ref()->%*) {

etc.)

See perlref for the full documentation.

Note: in Perl version 5.20 and 5.22, this syntax is considered experimental, so you need

use feature 'postderef';
no warnings 'experimental::postderef';

at the top of any file that uses it. Perl 5.24 and later don't require any pragmas for this feature.

Play infinitely looping video on-load in HTML5

As of April 2018, Chrome (along with several other major browsers) now require the muted attribute too.

Therefore, you should use

<video width="320" height="240" autoplay loop muted>
  <source src="movie.mp4" type="video/mp4" />
</video>

Min and max value of input in angular4 application

Actually when you use type="number" your input control populate with up/down arrow to increment/decrement numeric value, so when you update textbox value with those button it will not pass limit of 100, but when you manually give input like 120/130 and so on, it will not validate for max limit, so you have to validate it by code.

You can disable manual input OR you have to write some code on valueChange/textChange/key* event.

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

I am using windows 8. I had the same problem. I added the path "C:\MinGW\bin" to system environment variable named 'path' then it worked. May be, you can try the same. Hope it'll help!

npm install error from the terminal

npm install -d --save worked for me. -d flag command force npm to install your dependencies and --save will save the all updated dependencies in your package.json

What's the difference between the atomic and nonatomic attributes?

The last two are identical; "atomic" is the default behavior (note that it is not actually a keyword; it is specified only by the absence of nonatomic -- atomic was added as a keyword in recent versions of llvm/clang).

Assuming that you are @synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory. (Note: @synthesize is now the default behavior in recent versions of LLVM. There is also no need to declare instance variables; they will be synthesized automatically, too, and will have an _ prepended to their name to prevent accidental direct access).

With "atomic", the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.

In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than "atomic".

What "atomic" does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.

Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.

Adding to this:

atomicity of a single property also cannot guarantee thread safety when multiple dependent properties are in play.

Consider:

 @property(atomic, copy) NSString *firstName;
 @property(atomic, copy) NSString *lastName;
 @property(readonly, atomic, copy) NSString *fullName;

In this case, thread A could be renaming the object by calling setFirstName: and then calling setLastName:. In the meantime, thread B may call fullName in between thread A's two calls and will receive the new first name coupled with the old last name.

To address this, you need a transactional model. I.e. some other kind of synchronization and/or exclusion that allows one to exclude access to fullName while the dependent properties are being updated.

Postgres manually alter sequence

Use select setval('payments_id_seq', 21, true);

setval contains 3 parameters:

  • 1st parameter is sequence_name
  • 2nd parameter is Next nextval
  • 3rd parameter is optional.

The use of true or false in 3rd parameter of setval is as follows:

SELECT setval('payments_id_seq', 21);           // Next nextval will return 22
SELECT setval('payments_id_seq', 21, true);     // Same as above 
SELECT setval('payments_id_seq', 21, false);    // Next nextval will return 21

The better way to avoid hard-coding of sequence name, next sequence value and to handle empty column table correctly, you can use the below way:

SELECT setval(pg_get_serial_sequence('table_name', 'id'), coalesce(max(id), 0)+1 , false) FROM table_name;

where table_name is the name of the table, id is the primary key of the table

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

How do I make JavaScript beep?

function beep(wavFile){
    wavFile = wavFile || "beep.wav"
    if (navigator.appName == 'Microsoft Internet Explorer'){
        var e = document.createElement('BGSOUND');
        e.src = wavFile;
        e.loop =1;
        document.body.appendChild(e);
        document.body.removeChild(e);
    }else{
        var e = document.createElement('AUDIO');
        var src1 = document.createElement('SOURCE');
        src1.type= 'audio/wav';
        src1.src= wavFile;
        e.appendChild(src1);
        e.play();
    }
}

Works on Chrome,IE,Mozilla using Win7 OS. Requires a beep.wav file on the server.

SQL Server : Arithmetic overflow error converting expression to data type int

Is the problem with SUM(billableDuration)? To find out, try commenting out that line and see if it works.

It could be that the sum is exceeding the maximum int. If so, try replacing it with SUM(CAST(billableDuration AS BIGINT)).

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

As you can see by reading the other answers, there are a lot of options available. If you are just doing < 10k rows you should go with the second option.

In short, for approx > 10k all the way to say a <100k. It is kind of a gray area. A lot of old geezers will bark at big rollback segments. But honestly hardware and software have made amazing progress to where you may be able to get away with option 2 for a lot of records if you only run the code a few times. Otherwise you should probably commit every 1k-10k or so rows. Here is a snippet that I use. I like it because it is short and I don't have to declare a cursor. Plus it has the benefits of bulk collect and forall.

begin
    for r in (select rownum rn, t.* from foo t) loop
        insert into bar (A,B,C) values (r.A,r.B,r.C);
        if mod(rn,1000)=0 then
            commit;
        end if;
    end;
    commit;
end;

I found this link from the oracle site that illustrates the options in more detail.

How to send a message to a particular client with socket.io

In a project of our company we are using "rooms" approach and it's name is a combination of user ids of all users in a conversation as a unique identifier (our implementation is more like facebook messenger), example:

|id | name |1 | Scott |2 | Susan

"room" name will be "1-2" (ids are ordered Asc.) and on disconnect socket.io automatically cleans up the room

this way you send messages just to that room and only to online (connected) users (less packages sent throughout the server).

Enum Naming Convention - Plural

Coming in a bit late...

There's an important difference between your question and the one you mention (which I asked ;-):

You put the enum definition out of the class, which allows you to have the same name for the enum and the property:

public enum EntityType { 
  Type1, Type2 
} 

public class SomeClass { 
  public EntityType EntityType {get; set;} // This is legal

}

In this case, I'd follow the MS guidelins and use a singular name for the enum (plural for flags). It's probaby the easiest solution.

My problem (in the other question) is when the enum is defined in the scope of the class, preventing the use of a property named exactly after the enum.

Firebase onMessageReceived not called when app in background

according to the solution from t3h Exi i would like to post the clean code here. Just put it into MyFirebaseMessagingService and everything works fine if the app is in background mode. You need at least to compile com.google.firebase:firebase-messaging:10.2.1

 @Override
public void handleIntent(Intent intent)
{
    try
    {
        if (intent.getExtras() != null)
        {
            RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");

            for (String key : intent.getExtras().keySet())
            {
                builder.addData(key, intent.getExtras().get(key).toString());
            }



           onMessageReceived(builder.build());
        }
        else
        {
            super.handleIntent(intent);
        }
    }
    catch (Exception e)
    {
        super.handleIntent(intent);
    }
}

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

After a lot of trial and error I found this solved my problems. This is used to display photos on TVs via a browser.

  • It Keeps the photos aspect ratio
  • Scales in vertical and horizontal
  • Centers vertically and horizontal
  • The only thing to watch for are really wide images. They do stretch to fill, but not by much, standard camera photos are not altered.

    Give it a try :)

*only tested in chrome so far

HTML:

<div class="frame">
  <img src="image.jpg"/>
</div>

CSS:

.frame {
  border: 1px solid red;

  min-height: 98%;
  max-height: 98%;
  min-width: 99%;
  max-width: 99%;

  text-align: center;
  margin: auto;
  position: absolute;
}
img {
  border: 1px solid blue;

  min-height: 98%;
  max-width: 99%;
  max-height: 98%;

  width: auto;
  height: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

Why are my PHP files showing as plain text?

You should install the PHP 5 library for Apache.

For Debian and Ubuntu:

apt-get install libapache2-mod-php5

And restart the Apache:

service apache2 restart

What does enctype='multipart/form-data' mean?

  • enctype(ENCode TYPE) attribute specifies how the form-data should be encoded when submitting it to the server.
  • multipart/form-data is one of the value of enctype attribute, which is used in form element that have a file upload. multi-part means form data divides into multiple parts and send to server.

How do I generate a random integer between min and max in Java?

As the solutions above do not consider the possible overflow of doing max-min when min is negative, here another solution (similar to the one of kerouac)

public static int getRandom(int min, int max) {
    if (min > max) {
        throw new IllegalArgumentException("Min " + min + " greater than max " + max);
    }      
    return (int) ( (long) min + Math.random() * ((long)max - min + 1));
}

this works even if you call it with:

getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE) 

How to get the range of occupied cells in excel sheet

See the Range.SpecialCells method. For example, to get cells with constant values or formulas use:

_xlWorksheet.UsedRange.SpecialCells(
        Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeConstants |
        Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeFormulas)

How does setTimeout work in Node.JS?

setTimeout is a kind of Thread, it holds a operation for a given time and execute.

setTimeout(function,time_in_mills);

in here the first argument should be a function type; as an example if you want to print your name after 3 seconds, your code should be something like below.

setTimeout(function(){console.log('your name')},3000);

Key point to remember is, what ever you want to do by using the setTimeout method, do it inside a function. If you want to call some other method by parsing some parameters, your code should look like below:

setTimeout(function(){yourOtherMethod(parameter);},3000);

How to open a WPF Popup when another control is clicked, using XAML markup only?

I did something simple, but it works.

I used a typical ToggleButton, which I restyled as a textblock by changing its control template. Then I just bound the IsChecked property on the ToggleButton to the IsOpen property on the popup. Popup has some properties like StaysOpen that let you modify the closing behavior.

The following works in XamlPad.

 <StackPanel>
  <ToggleButton Name="button"> 
    <ToggleButton.Template>
      <ControlTemplate TargetType="ToggleButton">
        <TextBlock>Click Me Here!!</TextBlock>
      </ControlTemplate>      
    </ToggleButton.Template>
  </ToggleButton>
  <Popup IsOpen="{Binding IsChecked, ElementName=button}" StaysOpen="False">
    <Border Background="LightYellow">
      <TextBlock>I'm the popup</TextBlock>
    </Border>
  </Popup> 
 </StackPanel>

Select Last Row in the Table

Try this :

Model::latest()->get();

Can I override and overload static methods in Java?

Static methods can not be overridden in the exact sense of the word, but they can hide parent static methods

In practice it means that the compiler will decide which method to execute at the compile time, and not at the runtime, as it does with overridden instance methods.

For a neat example have a look here.

And this is java documentation explaining the difference between overriding instance methods and hiding class (static) methods.

Overriding: Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods)

Hiding: Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.

Bootstrap 3 Glyphicons CDN

An alternative would be to use Font-Awesome for icons:

Including Font-Awesome

Open Font-Awesome on CDNJS and copy the CSS url of the latest version:

<link rel="stylesheet" href="<url>">

Or in CSS

@import url("<url>");

For example (note, the version will change):

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

Usage:

<i class="fa fa-bed"></i>

It contains a lot of icons!

How to list all the roles existing in Oracle database?

Got the answer :

SELECT * FROM DBA_ROLES;

permission denied - php unlink

You (as in the process that runs b.php, either you through CLI or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.

Note that if you use the PHP chmod() function to set the mode of a file or folder to 777 you should use 0777 to make sure the number is correctly interpreted as an octal number.

Handling null values in Freemarker

If you have a lot of variables to convert in optional, you can use SubimeText with this:

Find: \${([A-Za-z_0-9]*)}
Replace: \$\{${1}!\}

Be sure regex and case-sensitive options are enabled:

Sublime regex replace

An error occurred while executing the command definition. See the inner exception for details

Usually this means that your schema and mapping files are not in synch and there is a renamed or missing column someplace.

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the + operator fails for strings in EL (which is correct), then just do:

<c:out value="abc${test}" />

Or if abc is to obtained from another scoped variable named ${resp}, then do:

<c:out value="${resp}${test}" />

Adb install failure: INSTALL_CANCELED_BY_USER

In MIUI 8 go to Developer Settings and toggle "Install over USB" to enable it.

How to get a parent element to appear above child

style:

.parent{
  overflow:hidden;
  width:100px;
}

.child{
  width:200px;
}

body:

<div class="parent">
   <div class="child"></div>
</div>

Just get column names from hive table

Best way to do this is setting the below property:

set hive.cli.print.header=true;
set hive.resultset.use.unique.column.names=false;

Reset Excel to default borders

I had this issue, grid lines appeared to be missing on some cells.

Took me awhile to figure out that the color of those cells were white. I clicked format cell, pattern and then selected "no color" (instead of white) The the grid lines were visible again.

I hope this helps others as it took me a while to figure out why.

XmlSerializer giving FileNotFoundException at constructor

There is a workaround for that. If you use

XmlSerializer lizer = XmlSerializer.FromTypes(new[] { typeof(MyType) })[0];

it should avoid that exception. This worked for me.

WARNING: Do not use multiple times, or you will have a memory leak

You will leak memory like crazy if you use this method to create instances of XmlSerializer for the same type more than once!

This is because this method bypasses the built-in caching provided the XmlSerializer(type) and XmlSerializer(type, defaultNameSpace) constructors (all other constructors also bypass the cache).

If you use any method to create an XmlSerializer that is not via these two constructors, you must implement your own caching or you'll hemorrhage memory.

What is the use of the @ symbol in PHP?

Suppose we haven't used the "@" operator then our code would look like this:

$fileHandle = fopen($fileName, $writeAttributes);

And what if the file we are trying to open is not found? It will show an error message.

To suppress the error message we are using the "@" operator like:

$fileHandle = @fopen($fileName, $writeAttributes);

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

The error for me was:

Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.2) from [com.android.support:percent:26.0.2] AndroidManifest.xml:25:13-35
    is also present at [com.android.support:support-v4:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:23:9-25:38 to override.

The solution for me was in my project Gradle file I needed to bump my com.google.gms:google-services version.

I was using version 3.1.1:

classpath 'com.google.gms:google-services:3.1.1

And the error resolved after I bumped it to version 3.2.1:

classpath 'com.google.gms:google-services:3.2.1

I had just upgraded all my libraries to the latest including v27.1.1 of all the support libraries and v15.0.0 of all the Firebase libraries when I saw the error.

jQuery & CSS - Remove/Add display:none

If you have a lot of elements you would like to .hide() or .show(), you are going to waste a lot of resources to do what you want - even if use .hide(0) or .show(0) - the 0 parameter is the duration of the animation.

As opposed to Prototype.js .hide() and .show() methods which only used to manipulate the display attribute of the element, jQuery's implementation is more complex and not recommended for a large number of elements.

In this cases you should probably try .css('display','none') to hide and .css('display','') to show

.css('display','block') should be avoided, especially if you're working with inline elements, table rows (actually any table elements) etc.

Relationship between hashCode and equals method in Java

Yes, it should be overridden. If you think you need to override equals(), then you need to override hashCode() and vice versa. The general contract of hashCode() is:

  1. Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  3. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Could not find method android() for arguments

guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:

Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.

So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.

I solved my problem just follow this steps:

? Copy .aar package in app/libs.

? Add this in app/build.gradle file:

repositories {
    flatDir {
        dirs 'libs' //this way we can find the .aar file in libs folder
    }
}

? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):

dependencies {
    compile(name:'package_name', ext:'aar')
}

So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.

Adding text to ImageView in Android

Use drawalbeLeft/Right/Bottom/Top in TextView to render image at respective position.

        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/image"    
        android:text="@strings/text" 
        />

Activity has leaked window that was originally added

You're trying to show a Dialog after you've exited an Activity.

[EDIT]

This question is one of the top search on google for android developer, therefore Adding few important points from comments, which might be more helpful for future investigator without going in depth of comment conversation.

Answer 1 :

You're trying to show a Dialog after you've exited an Activity.

Answer 2

This error can be a little misleading in some circumstances (although the answer is still completely accurate) - i.e. in my case an unhandled Exception was thrown in an AsyncTask, which caused the Activity to shutdown, then an open progressdialog caused this Exception.. so the 'real' exception was a little earlier in the log

Answer 3

Call dismiss() on the Dialog instance you created before exiting your Activity, e.g. in onPause() or onDestroy()

PHP Fatal error when trying to access phpmyadmin mb_detect_encoding

First error is caused by php because the extension mbstring is either not installed or not active.

The second error is output of phpMyAdmin/your site asking you to install / enable the mysqli extension.

To enable mbstring and mysqli edit your php.ini and add/uncomment the two lines with mbstring.so and mysqli.so on unix or mbstring.dll and mysqli.dll on windows

Unix /etc/(phpX/)php.ini

extension=mysqli.so
extension=mbstring.so

Windows PHP installation folder\etc\php.ini

extension=mysqli.dll
extension=mbstring.dll

Don't forget to restart your webserver after this.

EDIT: User added he was using redhat in the comments so here's how you install extensions on all CentOS/Fedora/RedHat/Yum based linux distros

sudo yum install php-mysqli
sudo yum install php-mbstring

restart your werbserver
sudo /etc/init.d/httpd restart

you can verify your installation with a little php script in your document root. This lists all settings, versions and active extensions you've installed for php

test.php

<?php
phpinfo();

Adding Google Translate to a web site

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Graphviz's executables are not found (Python 3.4)

I encountered the same problem in Jupyter Notebook. Add this, and you are good to go.

import os

os.environ['PATH'] = os.environ['PATH']+';'+os.environ['CONDA_PREFIX']+r"\Library\bin\graphviz"

Shrink a YouTube video to responsive width

With credits to previous answer https://stackoverflow.com/a/36549068/7149454

Boostrap compatible, adust your container width (300px in this example) and you're good to go:

<div class="embed-responsive embed-responsive-16by9" style="height: 100 %; width: 300px; ">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/LbLB0K-mXMU?start=1841" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0"></iframe>
</div>

How to get first two characters of a string in oracle query?

take a look here

SELECT SUBSTR('Take the first four characters', 1, 4) FIRST_FOUR FROM DUAL;

input file appears to be a text format dump. Please use psql

For me, It's working like this one.

C:\Program Files\PostgreSQL\12\bin> psql -U postgres -p 5432  -d dummy -f C:\Users\Downloads\d2cm_test.sql

How to use a class object in C++ as a function parameter

class is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class itself.

e.g.

class ANewType
{
    // ... details
};

This defines a new type called ANewType which is a class type.

You can then use this in function declarations:

void function(ANewType object);

You can then pass objects of type ANewType into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.

If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.

void function(ANewType& object); // object passed by reference

This syntax means that any use of object in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.

[* The class keyword is also used in template definitions, but that's a different subject.]

Set font-weight using Bootstrap classes

On Bootstrap 4 you can use:

<p class="font-weight-bold">Bold text.</p>
<p class="font-weight-normal">Normal weight text.</p>
<p class="font-weight-light">Light weight text.</p>

Simple 'if' or logic statement in Python

If key isn't an int or float but a string, you need to convert it to an int first by doing

key = int(key)

or to a float by doing

key = float(key)

Otherwise, what you have in your question should work, but

if (key < 1) or (key > 34):

or

if not (1 <= key <= 34):

would be a bit clearer.

Convert CString to const char*

I used this conversion:

CString cs = "TEST";
char* c = cs.GetBuffer(m_ncs me.GetLength())

I hope this is useful.

Partition Function COUNT() OVER possible using DISTINCT

I think the only way of doing this in SQL-Server 2008R2 is to use a correlated subquery, or an outer apply:

SELECT  datekey,
        COALESCE(RunningTotal, 0) AS RunningTotal,
        COALESCE(RunningCount, 0) AS RunningCount,
        COALESCE(RunningDistinctCount, 0) AS RunningDistinctCount
FROM    document
        OUTER APPLY
        (   SELECT  SUM(Amount) AS RunningTotal,
                    COUNT(1) AS RunningCount,
                    COUNT(DISTINCT d2.dateKey) AS RunningDistinctCount
            FROM    Document d2
            WHERE   d2.DateKey <= document.DateKey
        ) rt;

This can be done in SQL-Server 2012 using the syntax you have suggested:

SELECT  datekey,
        SUM(Amount) OVER(ORDER BY DateKey) AS RunningTotal
FROM    document

However, use of DISTINCT is still not allowed, so if DISTINCT is required and/or if upgrading isn't an option then I think OUTER APPLY is your best option

C# Creating and using Functions

static void Main(string[] args)
    {
        Console.WriteLine("geef een leeftijd");
        int a = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("geef een leeftijd");
        int b = Convert.ToInt32(Console.ReadLine());

        int einde = Sum(a, b);
        Console.WriteLine(einde);
    }
    static int Sum(int x, int y)
    {
        int result = x + y;
        return result;
    }

Android custom dropdown/popup menu

The Kotlin Way

fun showPopupMenu(view: View) {
    PopupMenu(view.context, view).apply {
                menuInflater.inflate(R.menu.popup_men, menu)
                setOnMenuItemClickListener { item ->
                    Toast.makeText(view.context, "You Clicked : " + item.title, Toast.LENGTH_SHORT).show()
                    true
                }
            }.show()
}

UPDATE: In the above code, the apply function returns this which is not required, so we can use run which don't return anything and to make it even simpler we can also remove the curly braces of showPopupMenu method.

Even Simpler:

fun showPopupMenu(view: View) = PopupMenu(view.context, view).run {
            menuInflater.inflate(R.menu.popup_men, menu)
            setOnMenuItemClickListener { item ->
                Toast.makeText(view.context, "You Clicked : ${item.title}", Toast.LENGTH_SHORT).show()
                true
            }
            show()
        }

Easiest way to use SVG in Android?

Android Studio supports SVG from 1.4 onwards

Here is a video on how to import.

Why does git status show branch is up-to-date when changes exist upstream?

What the status is telling you is that you're behind the ref called origin/master which is a local ref in your local repo. In this case that ref happens to track a branch in some remote, called origin, but the status is not telling you anything about the branch on the remote. It's telling you about the ref, which is just a commit ID stored on your local filesystem (in this case, it's typically in a file called .git/refs/remotes/origin/master in your local repo).

git pull does two operations; first it does a git fetch to get up to date with the commits in the remote repo (which updates the origin/master ref in your local repo), then it does a git merge to merge those commits into the current branch.

Until you do the fetch step (either on its own or via git pull) your local repo has no way to know that there are additional commits upstream, and git status only looks at your local origin/master ref.

When git status says up-to-date, it means "up-to-date with the branch that the current branch tracks", which in this case means "up-to-date with the local ref called origin/master". That only equates to "up-to-date with the upstream status that was retrieved last time we did a fetch" which is not the same as "up-to-date with the latest live status of the upstream".

Why does it work this way? Well the fetch step is a potentially slow and expensive network operation. The design of Git (and other distributed version control systems) is to avoid network operations when unnecessary, and is a completely different model to the typical client-server system many people are used to (although as pointed out in the comments below, Git's concept of a "remote tracking branch" that causes confusion here is not shared by all DVCSs). It's entirely possible to use Git offline, with no connection to a centralized server, and the output of git status reflects this.

Creating and switching branches (and checking their status) in Git is supposed to be lightweight, not something that performs a slow network operation to a centralized system. The assumption when designing Git, and the git status output, was that users understand this (too many Git features only make sense if you already know how Git works). With the adoption of Git by lots and lots of users who are not familiar with DVCS this assumption is not always valid.

jQuery trigger event when click outside the element

$(document).click((e) => {
  if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
  } else {
    this.onClose();
  }
}); 

Path.Combine absolute with relative path strings

For windows universal apps Path.GetFullPath() is not available, you can use the System.Uri class instead:

 Uri uri = new Uri(Path.Combine(@"C:\blah\",@"..\bling"));
 Console.WriteLine(uri.LocalPath);

CSS performance relative to translateZ(0)

If you want implications, in some scenarios Google Chrome performance is horrible with hardware acceleration enabled. Oddly enough, changing the "trick" to -webkit-transform: rotateZ(360deg); worked just fine.

I don't believe we ever figured out why.

Read file line by line using ifstream in C++

Use ifstream to read data from a file:

std::ifstream input( "filename.ext" );

If you really need to read line by line, then do this:

for( std::string line; getline( input, line ); )
{
    ...for each line in input...
}

But you probably just need to extract coordinate pairs:

int x, y;
input >> x >> y;

Update:

In your code you use ofstream myfile;, however the o in ofstream stands for output. If you want to read from the file (input) use ifstream. If you want to both read and write use fstream.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

The problem is that value is ignored when ng-model is present.

Firefox, which doesn't currently support type="date", will convert all the values to string. Since you (rightly) want date to be a real Date object and not a string, I think the best choice is to create another variable, for instance dateString, and then link the two variables:

<input type="date" ng-model="dateString" />
function MainCtrl($scope, dateFilter) {
    $scope.date = new Date();

    $scope.$watch('date', function (date)
    {
        $scope.dateString = dateFilter(date, 'yyyy-MM-dd');
    });

    $scope.$watch('dateString', function (dateString)
    {
        $scope.date = new Date(dateString);
    });
}

Fiddle

The actual structure is for demonstration purposes only. You'd be better off creating your own directive, especially in order to:

Please notice that I've used yyyy-MM-dd, because it's a format directly supported by the JavaScript Date object. In case you want to use another one, you must make the conversion yourself.


EDIT

Here is a way to make a clean directive:

myModule.directive(
    'dateInput',
    function(dateFilter) {
        return {
            require: 'ngModel',
            template: '<input type="date"></input>',
            replace: true,
            link: function(scope, elm, attrs, ngModelCtrl) {
                ngModelCtrl.$formatters.unshift(function (modelValue) {
                    return dateFilter(modelValue, 'yyyy-MM-dd');
                });

                ngModelCtrl.$parsers.unshift(function(viewValue) {
                    return new Date(viewValue);
                });
            },
        };
});

Fiddle

That's a basic directive, there's still a lot of room for improvement, for example:

  • allow the use of a custom format instead of yyyy-MM-dd,
  • check that the date typed by the user is correct.

CSS3 100vh not constant in mobile browser

Hopefully, this will be a UA-defined CSS environment variable as suggested here: https://github.com/w3c/csswg-drafts/issues/2630#issuecomment-397536046

How, in general, does Node.js handle 10,000 concurrent requests?

Adding to slebetman answer: When you say Node.JS can handle 10,000 concurrent requests they are essentially non-blocking requests i.e. these requests are majorly pertaining to database query.

Internally, event loop of Node.JS is handling a thread pool, where each thread handles a non-blocking request and event loop continues to listen to more request after delegating work to one of the thread of the thread pool. When one of the thread completes the work, it send a signal to the event loop that it has finished aka callback. Event loop then process this callback and send the response back.

As you are new to NodeJS, do read more about nextTick to understand how event loop works internally. Read blogs on http://javascriptissexy.com, they were really helpful for me when I started with JavaScript/NodeJS.

Tomcat request timeout

You can set the default time out in the server.xml

<Connector URIEncoding="UTF-8" 
    acceptCount="100" 
    connectionTimeout="20000" 
    disableUploadTimeout="true" 
    enableLookups="false" 
    maxHttpHeaderSize="8192" 
    maxSpareThreads="75" 
    maxThreads="150" 
    minSpareThreads="25" 
    port="7777" 
    redirectPort="8443"/>

Load a WPF BitmapImage from a System.Drawing.Bitmap

I work at an imaging vendor and wrote an adapter for WPF to our image format which is similar to a System.Drawing.Bitmap.

I wrote this KB to explain it to our customers:

http://www.atalasoft.com/kb/article.aspx?id=10156

And there is code there that does it. You need to replace AtalaImage with Bitmap and do the equivalent thing that we are doing -- it should be pretty straightforward.

how to import csv data into django models

For django 1.8 that im using,

I made a command that you can create objects dynamically in the future, so you can just put the file path of the csv, the model name and the app name of the relevant django application, and it will populate the relevant model without specified the field names. so if we take for example the next csv:

field1,field2,field3
value1,value2,value3
value11,value22,value33

it will create the objects [{field1:value1,field2:value2,field3:value3}, {field1:value11,field2:value22,field3:value33}] for the model name you will enter to the command.

the command code:

from django.core.management.base import BaseCommand
from django.db.models.loading import get_model
import csv


class Command(BaseCommand):
    help = 'Creating model objects according the file path specified'

    def add_arguments(self, parser):
        parser.add_argument('--path', type=str, help="file path")
        parser.add_argument('--model_name', type=str, help="model name")
        parser.add_argument('--app_name', type=str, help="django app name that the model is connected to")

    def handle(self, *args, **options):
        file_path = options['path']
        _model = get_model(options['app_name'], options['model_name'])
        with open(file_path, 'rb') as csv_file:
            reader = csv.reader(csv_file, delimiter=',', quotechar='|')
            header = reader.next()
            for row in reader:
                _object_dict = {key: value for key, value in zip(header, row)}
                _model.objects.create(**_object_dict)

note that maybe in later versions

from django.db.models.loading import get_model

is deprecated and need to be change to

from django.apps.apps import get_model

In Powershell what is the idiomatic way of converting a string to an int?

$source = "number35"

$number=$null

$result = foreach ($_ in $source.ToCharArray()){$digit="0123456789".IndexOf($\_,0);if($digit -ne -1){$number +=$\_}}[int32]$number

Just feed it digits and it wil convert to an Int32

How to install MySQLi on MacOS

Since you are using a Mac, open a terminal, and

  • cd /etc

Find the php.ini, and sudo open it, for example, using the nano editor

  • nano php.ini

Find use control+w to search for "mysqli.default_socket", and change the line to

  • mysqli.default_socket = /tmp/mysql.sock

Use control+x and then hit "y" and "return" to save the file. Restart Aapche if necessary.

Now you should be able to run mysqli.

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

All of the other contributors gave great answers, which work when you have a single dimension (leveled) list, however of the methods mentioned so far, only copy.deepcopy() works to clone/copy a list and not have it point to the nested list objects when you are working with multidimensional, nested lists (list of lists). While Felix Kling refers to it in his answer, there is a little bit more to the issue and possibly a workaround using built-ins that might prove a faster alternative to deepcopy.

While new_list = old_list[:], copy.copy(old_list)' and for Py3k old_list.copy() work for single-leveled lists, they revert to pointing at the list objects nested within the old_list and the new_list, and changes to one of the list objects are perpetuated in the other.

Edit: New information brought to light

As was pointed out by both Aaron Hall and PM 2Ring using eval() is not only a bad idea, it is also much slower than copy.deepcopy().

This means that for multidimensional lists, the only option is copy.deepcopy(). With that being said, it really isn't an option as the performance goes way south when you try to use it on a moderately sized multidimensional array. I tried to timeit using a 42x42 array, not unheard of or even that large for bioinformatics applications, and I gave up on waiting for a response and just started typing my edit to this post.

It would seem that the only real option then is to initialize multiple lists and work on them independently. If anyone has any other suggestions, for how to handle multidimensional list copying, it would be appreciated.

As others have stated, there are significant performance issues using the copy module and copy.deepcopy for multidimensional lists.

Find the most popular element in int[] array

You can count the occurrences of the different numbers, then look for the highest one. This is an example that uses a Map, but could relatively easily be adapted to native arrays.

Second largest element: Let us take example : [1,5,4,2,3] in this case, Second largest element will be 4.

  1. Sort the Array in descending order, once the sort done output will be A = [5,4,3,2,1]

  2. Get the Second Largest Element from the sorted array Using Index 1. A[1] -> Which will give the Second largest element 4.

private static int getMostOccuringElement(int[] A) { Map occuringMap = new HashMap();

    //count occurences
    for (int i = 0; i < A.length; i++) { 
        if (occuringMap.get(A[i]) != null) {
            int val = occuringMap.get(A[i]) + 1;
            occuringMap.put(A[i], val);
        } else {
            occuringMap.put(A[i], 1);
        }
    }

    //find maximum occurence
    int max = Integer.MIN_VALUE; 
    int element = -1;
    for (Map.Entry<Integer, Integer> entry : occuringMap.entrySet()) {
        if (entry.getValue() > max) {
            max = entry.getValue();
            element = entry.getKey();
        }
    }
    return element;
}

How to auto-scroll to end of div when data is added?

var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Great answers! One thing that I would like to clarify deeper is nonatomic/atomic. The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents. I.e. atomic will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute. For example:

@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...

In this case it is guaranteed that the pointer to the dict will be read/set in the atomic manner by different threads. BUT the dict itself (the dictionary dict pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.

If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".

Get week day name from a given month, day and year individually in SQL Server

I used

select
case
when (extract (weekday from DATE)=0) then 'Sunday'

and so on...

0 Sunday, 1 Monday...

error: the details of the application error from being viewed remotely

Dear olga is clear what the message says. Turn off the custom errors to see the details about this error for fix it, and then you close them back. So add mode="off" as:

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Relative answer: Deploying website: 500 - Internal server error

By the way: The error message declare that the web.config is not the one you type it here. Maybe you have forget to upload your web.config ? And remember to close the debug flag on the web.config that you use for online pages.

How can I check whether a radio button is selected with JavaScript?

The scripts in this page helped me come up with the script below, which I think is more complete and universal. Basically it will validate any number of radio buttons in a form, meaning that it will make sure that a radio option has been selected for each one of the different radio groups within the form. e.g in the test form below:

   <form id="FormID">

    Yes <input type="radio" name="test1" value="Yes">
    No <input type="radio" name="test1" value="No">

    <br><br>

    Yes <input type="radio" name="test2" value="Yes">
    No <input type="radio" name="test2" value="No">

   <input type="submit" onclick="return RadioValidator();">

The RadioValidator script will make sure that an answer has been given for both 'test1' and 'test2' before it submits. You can have as many radio groups in the form, and it will ignore any other form elements. All missing radio answers will show inside a single alert popup. Here it goes, I hope it helps people. Any bug fixings or helpful modifications welcome :)

<SCRIPT LANGUAGE="JAVASCRIPT">
function RadioValidator()
{
    var ShowAlert = '';
    var AllFormElements = window.document.getElementById("FormID").elements;
    for (i = 0; i < AllFormElements.length; i++) 
    {
        if (AllFormElements[i].type == 'radio') 
        {
            var ThisRadio = AllFormElements[i].name;
            var ThisChecked = 'No';
            var AllRadioOptions = document.getElementsByName(ThisRadio);
            for (x = 0; x < AllRadioOptions.length; x++)
            {
                 if (AllRadioOptions[x].checked && ThisChecked == 'No')
                 {
                     ThisChecked = 'Yes';
                     break;
                 } 
            }   
            var AlreadySearched = ShowAlert.indexOf(ThisRadio);
            if (ThisChecked == 'No' && AlreadySearched == -1)
            {
            ShowAlert = ShowAlert + ThisRadio + ' radio button must be answered\n';
            }     
        }
    }
    if (ShowAlert != '')
    {
    alert(ShowAlert);
    return false;
    }
    else
    {
    return true;
    }
}
</SCRIPT>

How to refresh a Page using react-route Link

Try like this.

You must give a function as value to onClick()

You button:

<button type="button" onClick={ refreshPage }> <span>Reload</span> </button> 

refreshPage function:

function refreshPage(){ 
    window.location.reload(); 
}

How can I enable MySQL's slow query log without restarting MySQL?

This should work on mysql > 5.5

SHOW VARIABLES LIKE '%long%';

SET GLOBAL long_query_time = 1;

Nullable property to entity field, Entity Framework through Code First

The other option is to tell EF to allow the column to be null:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();            
        base.OnModelCreating(modelBuilder);
}

This code should be in the object that inherits from DbContext.

What is "String args[]"? parameter in main method Java

in public static void main(String args[]) args is an array of console line argument whose data type is String. in this array, you can store various string arguments by invoking them at the command line as shown below: java myProgram Shaan Royal then Shaan and Royal will be stored in the array as arg[0]="Shaan"; arg[1]="Royal"; you can do this manually also inside the program, when you don't call them at the command line.

turn typescript object into json string

You can use the standard JSON object, available in Javascript:

var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);

How to apply color in Markdown?

Seems that kramdown supports colors in some form.

Kramdown allows inline html:

This is <span style="color: red">written in red</span>.

Also it has another syntax for including css classes inline:

This is *red*{: style="color: red"}.

This page further explains how GitLab utilizes more compact way to apply css classes in Kramdown:

Applying blue class to text:

This is a paragraph that for some reason we want blue.
{: .blue}

Applying blue class to headings:

#### A blue heading
{: .blue}

Applying two classes:

A blue and bold paragraph.
{: .blue .bold}

Applying ids:

#### A blue heading
{: .blue #blue-h}

This produces:

<h4 class="blue" id="blue-h">A blue heading</h4>

There is a lot of other stuff explained at above link. You may need to check.

Also, as other answer said, Kramdown is also the default markdown renderer behind Jekyll. So if you are authoring anything on github pages, above functionality might be available out of the box.

How can I create a correlation matrix in R?

Have a look at qtlcharts. It allows you to create interactive correlation matrices:

library(qtlcharts)
data(iris)
iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)

enter image description here

It's more impressive when you correlate more variables, like in the package's vignette: enter image description here

How to see remote tags?

Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote:

git ls-remote --tags /url/to/upstream/repo

(as illustrated in "When listing git-ls-remote why there's “^{}” after the tag name?")

xbmono illustrates in the comments that quotes are needed:

git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"

Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):

git push --follow-tags

See Push git commits & tags simultaneously.


Regarding Atlassian SourceTree specifically:

Note that, from this thread, SourceTree ONLY shows local tags.

There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015 since Dec. 2015.

A simple workaround:

see a list of only unpushed tags?

git push --tags

or check the "Push all tags" box on the "Push" dialog box, all tags will be pushed to your remote.

https://community.atlassian.com/tnckb94959/attachments/tnckb94959/sourcetree-questions/10923/1/Screen%20Shot%202015-12-15%20at%208.49.48%20AM.png

That way, you will be "sure that they are present in remote so that other developers can pull them".

Does C# have an equivalent to JavaScript's encodeURIComponent()?

Try Server.UrlEncode(), or System.Web.HttpUtility.UrlEncode() for instances when you don't have access to the Server object. You can also use System.Uri.EscapeUriString() to avoid adding a reference to the System.Web assembly.

Execute jar file with multiple classpath libraries from command prompt

This will not work java -cp lib\*.jar -jar myproject.jar. You have to put it jar by jar.

So in case of commons-codec-1.3.jar.

java -cp lib/commons-codec-1.3.jar;lib/next_jar.jar and so on.

The other solution might be putting all your jars to ext directory of your JRE. This is ok if you are using a standalone JRE. If you are using the same JRE for running more than one application I do not recommend doing it.

How to force a line break on a Javascript concatenated string?

Using Backtick

Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string

_x000D_
_x000D_
let title = 'John';_x000D_
let address = 'address';_x000D_
let address2 = 'address2222';_x000D_
let address3 = 'address33333';_x000D_
let address4 = 'address44444';_x000D_
document.getElementById("address_box").innerText = `${title} _x000D_
${address}_x000D_
${address2}_x000D_
${address3} _x000D_
${address4}`;
_x000D_
<div id="address_box">_x000D_
</div>
_x000D_
_x000D_
_x000D_

What's the difference setting Embed Interop Types true and false in Visual Studio?

I noticed that when it's set to false, I'm able to see the value of an item using the debugger. When it was set to true, I was getting an error - item.FullName.GetValue The embedded interop type 'FullName' does not contain a definition for 'QBFC11Lib.IItemInventoryRet' since it was not used in the compiled assembly. Consider casting to object or changing the 'Embed Interop Types' property to true.

JavaScript string newline character?

printAccountSummary: function()
        {return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // method

Prints:

Welcome!
Your balance is currently $1000 and your interest rate is 1%.

How to extract base URL from a string in JavaScript?

There is no reason to do splits to get the path, hostname, etc from a string that is a link. You just need to use a link

//create a new element link with your link
var a = document.createElement("a");
a.href="http://www.sitename.com/article/2009/09/14/this-is-an-article/";

//hide it from view when it is added
a.style.display="none";

//add it
document.body.appendChild(a);

//read the links "features"
alert(a.protocol);
alert(a.hostname)
alert(a.pathname)
alert(a.port);
alert(a.hash);

//remove it
document.body.removeChild(a);

You can easily do it with jQuery appending the element and reading its attr.

Update: There is now new URL() which simplifies it

_x000D_
_x000D_
const myUrl = new URL("https://www.example.com:3000/article/2009/09/14/this-is-an-article/#m123")

const parts = ['protocol', 'hostname', 'pathname', 'port', 'hash'];

parts.forEach(key => console.log(key, myUrl[key]))
_x000D_
_x000D_
_x000D_

Get the last non-empty cell in a column in Google Sheets

If A2:A contains dates contiguously then INDEX(A2:A,COUNT(A2:A)) will return the last date. The final formula is

=DAYS360(A2,INDEX(A2:A,COUNT(A2:A)))

How to execute .sql script file using JDBC

I had the same problem trying to execute an SQL script that creates an SQL database. Googling here and there I found a Java class initially written by Clinton Begin which supports comments (see http://pastebin.com/P14HsYAG). I modified slightly the file to cater for triggers where one has to change the default DELIMITER to something different. I've used that version ScriptRunner (see http://pastebin.com/sb4bMbVv). Since an (open source and free) SQLScriptRunner class is an absolutely necessary utility, it would be good to have some more input from developers and hopefully we'll have soon a more stable version of it.

Using Jquery Ajax to retrieve data from Mysql


You can't return ajax return value. You stored global variable store your return values after return.
Or Change ur code like this one.

AjaxGet = function (url) {
    var result = $.ajax({
        type: "POST",
        url: url,
       param: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
       async: false,
        success: function (data) {
            // nothing needed here
      }
    }) .responseText ;
    return  result;
}

How to change checkbox's border style in CSS?

I'm outdated I know.. But a little workaround would be to put your checkbox inside a label tag, then style the label with a border:

<label class='hasborder'><input type='checkbox' /></label>

then style the label:

.hasborder { border:1px solid #F00; }

Is it .yaml or .yml?

EDIT:

So which am I supposed to use? The proper 4 letter extension suggested by the creator, or the 3 letter extension found in the wild west of the internet?

This question could be:

  1. A request for advice; or

  2. A natural expression of that particular emotion which is experienced, while one is observing that some official recommendation is being disregarded—prominently, or even predominantly.

People differ in their predilection for following:

  1. Official advice; or

  2. The preponderance of practice.

Of course, I am unlikely to influence you, regarding which of these two paths you prefer to take!

In what follows (and, in the spirit of science), I merely make an hypothesis, about what (merely as a matter of fact) led the majority of people to use the 3-letter extension. And, I focus on efficient causes.

By this, I do not intend moral exhortation. As you may recall, the fact that something is, does not imply that it should be.

Whatever your personal inclination, be it to follow one path or the other, I do not object.

(End of edit.)

The suggestion, that this preference (in real life usage) was caused by a 8.3 character DOS-ish limitation, IMO is a red herring (erroneous and misleading).

As of August, 2016, the Google search counts for YML and YAML were approximately 6,000,000 and 4,100,000 (to two digits of precision). Furthermore, the "YAML" count was unfairly high because it included mention of the language by name, beyond its use as an extension.

As of July, 2018, the Google's search counts for YML and YAML were approximately 8,100,000 and 4,100,000 (again, to two digits of precision). So, in the last two years, YML has essentially doubled in popularity, but YAML has stayed the same.

Another cultural measure is websites which attempt to explain file extensions. For example, on the FilExt website (as of July, 2018), the page for YAML results in: "Ooops! The FILEXT.com database does not have any information on file extension .YAML."

Whereas, it has an entry for YML, which gives: "YAML...uses a text file and organizes it into a format which is Human-readable. 'database.yml' is a typical example when YAML is used by Ruby on Rails to connect to a database."

As of November, 2014, Wikipedia's article on extension YML still stated that ".yml" is "the file extension for the YAML file format" (emphasis added). Its YAML article lists both extensions, without expressing a preference.

The extension ".yml" is sufficiently clear, is more brief (thus easier to type and recognize), and is much more common.

Of course, both of these extensions could be viewed as abbreviations of a long, possible extension, ".yamlaintmarkuplanguage". But programmers (and users) don't want to type all of that!

Instead, we programmers (and users) want to type as little as possible, and still yet be unambiguous and clear. And we want to see what kind of file it is, as quickly as possible, without reading a longer word. Typing just how many characters accomplishes both of these goals? Isn't the answer three (3)? In other words, YML?

Wikipedia's Category:Filename_extensions page lists entries for .a, .o and .Z. Somehow, it missed .c and .h (used by the C language). These example single-letter extensions help us to see that extensions should be as long as necessary, but no longer (to half-quote Albert Einstein).

Instead, notice that, in general, few extensions start with "Y". Commonly, on the other hand, the letter X is used for a great variety of meanings including "cross," "extensible," "extreme," "variable," etc. (e.g. in XML). So starting with "Y" already conveys much information (in terms of information theory), whereas starting with "X" does not.

Linguistically speaking, therefore, the acronym "XML" has (in a way) only two informative letters ("M" and "L"). "YML", instead, has three informative letters ("M", "L" and "Y"). Indeed, the existing set of acronyms beginning with Y seems extremely small. By implication, this is why a four letter YAML file extension feels greatly overspecified.

Perhaps this is why we see in practice that the "linguistic" pressure (in natural use) to lengthen the abbreviation in question to four (4) characters is weak, and the "linguistic" pressure to shorten this abbreviation to three (3) characters is strong.

Purely as a result, probably, of these factors (and not as an official endorsement), I would note that the YAML.org website's latest news item (from November, 2011) is all about a project written in JavaScript, JS-YAML, which, itself, internally prefers to use the extension ".yml".

The above-mentioned factors may have been the main ones; nevertheless, all the factors (known or unknown) have resulted in the abbreviated, three (3) character extension becoming the one in predominant use for YAML—despite the inventors' preference.

".YML" seems to be the de facto standard. Yet the same inventors were perceptive and correct, about the world's need for a human-readable data language. And we should thank them for providing it.

Adding a slide effect to bootstrap dropdown

$('.navbar .dropdown').hover(function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
}, function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideUp();
});

This code works if you want to reveal dropdowns on hover.

I just changed the .slideToggle to .slideDown & .slideUp, and removed the (400) timing

Getting permission denied (public key) on gitlab

I had the same problems, It has been fixed after I re-generate the ssh key inside .ssh folder without naming it (keep it as id_rsa.pub). Then add it again to gitlab ssh key. Everything working fine now.

Should I use <i> tag for icons instead of <span>?

I take a totally different approach to everyone else's answers here altogether. Let me prefix my solution and argue by stating that sometimes standards and conventions are meant to be broken, especially in the context of the standard HTML lexical tag definitions.

There's nothing to stop you from creating custom elements that are self-descriptive to it's very purpose.

Both modern browsers and even IE 6+ (w/ shim) can support things like:

<icon class="plus">

or

<icon-add>

Just make sure to normalize the tag:

 icon { display:block; margin:0; padding:0; border:0; ... }

and use a shim if you need to support IE9 or earlier (see post below).

Check out this StackOverflow Post:

Is there a way to create your own html tag in HTML5

To further my argument, both Google's Angular Directives and the new Polymer projects utilize the concept of custom HTML tags.

C++ where to initialize static const

In a translation unit within the same namespace, usually at the top:

// foo.h
struct foo
{
    static const std::string s;
};

// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives

// bar.h
namespace baz
{
    struct bar
    {
        static const float f;
    };
}

// bar.cpp
namespace baz
{
    const float bar::f = 3.1415926535;
}

Passing parameters to JavaScript files

No, you cant really do this by adding variables to the querystring portion of the JS file URL. If its writing the portion of code to parse the string that bothers you, perhaps another way would be to json encode your variables and put them in something like the rel attribute of the tag? I don't know how valid this is in terms of HTML validation, if thats something you're very worried about. Then you just need to find the rel attribute of the script and then json_decode that.

eg

<script type='text/javascript' src='file.js' rel='{"myvar":"somevalue","anothervar":"anothervalue"}'></script>

How to save username and password in Git?

Turn on the credential helper so that Git will save your password in memory for some time:

In Terminal, enter the following:

# Set git to use the credential memory cache
git config --global credential.helper cache

By default, Git will cache your password for 15 minutes.

To change the default password cache timeout, enter the following:

# Set the cache to timeout after 1 hour (setting is in seconds)
git config --global credential.helper 'cache --timeout=3600'

From GitHub Help

Under which circumstances textAlign property works in Flutter?

textAlign property only works when there is a more space left for the Text's content. Below are 2 examples which shows when textAlign has impact and when not.


No impact

For instance, in this example, it won't have any impact because there is no extra space for the content of the Text.

Text(
  "Hello",
  textAlign: TextAlign.end, // no impact
),

enter image description here


Has impact

If you wrap it in a Container and provide extra width such that it has more extra space.

Container(
  width: 200,
  color: Colors.orange,
  child: Text(
    "Hello",
    textAlign: TextAlign.end, // has impact
  ),
)

enter image description here

Visual Studio Code open tab in new window

This is a very highly upvoted issue request in Github for Floating Windows.

Until they support it, you can try the following workarounds:

1. Duplicate Workspace in New Window [1]

The Duplicate Workspace in new Window Command was added in v1.24 (May 2018) to sort of address this.

  1. Open up Keyboard Shortcuts Ctrl + K, Ctrl + S
  2. Map workbench.action.duplicateWorkspaceInNewWindow to Ctrl + Shift + N or whatever you'd like

Duplicate Workspace in New Window

2. Open Active File in New Window [2]

Rather than manually open a new window and dragging the file, you can do it all with a single command.

  1. Open Active File in New Window Ctrl + K, O

Open Active File in New Window

3. New Window with Same File [3]

As AllenBooTung also pointed out, you can open/drag any file in a separate blank instance.

  1. Open New Window Ctrl + Shift + N
  2. Drag tab into new window

4. Open Workspace and Folder Simultaneously [4]

VS Code will not allow you to open the same folder in two different instances, but you can use Workspaces to open the same directory of files in a side by side instance.

  1. Open Folder Ctrl + K,Ctrl + O
  2. Save Current Project As a Workspace
  3. Open Folder Ctrl + K,Ctrl + O

For any workaround, also consider setting setting up auto save so the documents are kept in sync by updating the files.autoSave setting to afterDelay, onFocusChange, or onWindowChange

AutoSave

How can I get the name of an object in Python?

Variable names can be found in the globals() and locals() dicts. But they won't give you what you're looking for above. "bla" will contain the value of each item of my_list, not the variable.

Encode String to UTF-8

In a moment I went through this problem and managed to solve it in the following way

first i need to import

import java.nio.charset.Charset;

Then i had to declare a constant to use UTF-8 and ISO-8859-1

private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final Charset ISO = Charset.forName("ISO-8859-1");

Then I could use it in the following way:

String textwithaccent="Thís ís a text with accent";
String textwithletter="Ñandú";

text1 = new String(textwithaccent.getBytes(ISO), UTF_8);
text2 = new String(textwithletter.getBytes(ISO),UTF_8);

How to remove leading whitespace from each line in a file

For this specific problem, something like this would work:

$ sed 's/^ *//g' < input.txt > output.txt

It says to replace all spaces at the start of a line with nothing. If you also want to remove tabs, change it to this:

$ sed 's/^[ \t]+//g' < input.txt > output.txt

The leading "s" before the / means "substitute". The /'s are the delimiters for the patterns. The data between the first two /'s are the pattern to match, and the data between the second and third / is the data to replace it with. In this case you're replacing it with nothing. The "g" after the final slash means to do it "globally", ie: over the entire file rather than on only the first match it finds.

Finally, instead of < input.txt > output.txt you can use the -i option which means to edit the file "in place". Meaning, you don't need to create a second file to contain your result. If you use this option you will lose your original file.

First Heroku deploy failed `error code=H10`

I got the same above error as "app crashed" and H10 error and the heroku app logs is not showing much info related to the error msg reasons. Then I restarted the dynos in heroku and then it showed the error saying additional curly brace in one of the index.js files in my setup. The issue got fixed once it is removed and redeployed the app on heroku.

How to convert a date String to a Date or Calendar object?

The DateFormat class has a parse method.

See DateFormat for more information.

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

I did not want to install visual studio and development environment, so I have installed AspNetMVC4Setup.exe in Windows server 2016 machine and it solved the problem. The installer was downloaded from Microsoft website.

File properties of the installer

Test if object implements interface

Using the is or as operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is Type.IsAssignableFrom:

if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}

I think this is much neater than looking through the array returned by GetInterfaces and has the advantage of working for classes as well.

How to sort a Ruby Hash by number value?

Since value is the last entry, you can do:

metrics.sort_by(&:last)

"document.getElementByClass is not a function"

As others have said, you're not using the right function name and it doesn't exist univerally in all browsers.

If you need to do cross-browser fetching of anything other than an element with an id with document.getElementById(), then I would strongly suggest you get a library that supports CSS3 selectors across all browsers. It will save you a massive amount of development time, testing and bug fixing. The easiest thing to do is to just use jQuery because it's so widely available, has excellent documentation, has free CDN access and has an excellent community of people behind it to answer questions. If that seems like more than you need, then you can get Sizzle which is just a selector library (it's actually the selector engine inside of jQuery and others). I've used it by itself in other projects and it's easy, productive and small.

If you want to select multiple nodes at once, you can do that many different ways. If you give them all the same class, you can do that with:

var list = document.getElementsByClassName("myButton");
for (var i = 0; i < list.length; i++) {
    // list[i] is a node with the desired class name
}

and it will return a list of nodes that have that class name.

In Sizzle, it would be this:

var list = Sizzle(".myButton");
for (var i = 0; i < list.length; i++) {
    // list[i] is a node with the desired class name
}

In jQuery, it would be this:

$(".myButton").each(function(index, element) {
    // element is a node with the desired class name
});

In both Sizzle and jQuery, you can put multiple class names into the selector like this and use much more complicated and powerful selectors:

$(".myButton, .myInput, .homepage.gallery, #submitButton").each(function(index, element) {
    // element is a node that matches the selector
});

load and execute order of scripts

The browser will execute the scripts in the order it finds them. If you call an external script, it will block the page until the script has been loaded and executed.

To test this fact:

// file: test.php
sleep(10);
die("alert('Done!');");

// HTML file:
<script type="text/javascript" src="test.php"></script>

Dynamically added scripts are executed as soon as they are appended to the document.

To test this fact:

<!DOCTYPE HTML>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <script type="text/javascript">
        var s = document.createElement('script');
        s.type = "text/javascript";
        s.src = "link.js"; // file contains alert("hello!");
        document.body.appendChild(s);
        alert("appended");
    </script>
    <script type="text/javascript">
        alert("final");
    </script>
</body>
</html>

Order of alerts is "appended" -> "hello!" -> "final"

If in a script you attempt to access an element that hasn't been reached yet (example: <script>do something with #blah</script><div id="blah"></div>) then you will get an error.

Overall, yes you can include external scripts and then access their functions and variables, but only if you exit the current <script> tag and start a new one.

Vertical Align text in a Label

Vertical alignment only works with inline or inline-block elements, and it's only relative to other inline[-block] elements. Because you float the label, it becomes a block element.

The simplest solution in your case is to set the label to display: inline-block and add vertical-align: middle to the labels and the inputs. (You might find that the height of the text is such that vertical align won't make any difference anyway.)

Convert HTML string to image

       <!--ForExport data in iamge -->
        <script type="text/javascript">
            function ConvertToImage(btnExport) {
                html2canvas($("#dvTable")[0]).then(function (canvas) {
                    var base64 = canvas.toDataURL();
                    $("[id*=hfImageData]").val(base64);
                    __doPostBack(btnExport.name, "");
                });
                return false;
            }
        </script>

        <!--ForExport data in iamge -->

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="../js/html2canvas.min.js"></script> 





<table>
                <tr>
                    <td valign="top">
                        <asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
                            OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
                        <div id="dvTable" class="divsection2" style="width: 350px">
                            <asp:HiddenField ID="hfImageData" runat="server" />
                            <table width="100%">
                                <tr>
                                    <td>
                                        <br />

                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
                                    </td>
                                </tr>

                            </table>
                        </div>
                    </td>
                </tr>
            </table>


         protected void ExportToImage(object sender, EventArgs e)
                {
                    string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
                    byte[] bytes = Convert.FromBase64String(base64);
                    Response.Clear();
                    Response.ContentType = "image/png";
                    Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
                    Response.Buffer = true;
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(bytes);
                    Response.End();

                }

Clang vs GCC for my Linux Development project

EDIT:

The gcc guys really improved the diagnosis experience in gcc (ah competition). They created a wiki page to showcase it here. gcc 4.8 now has quite good diagnostics as well (gcc 4.9x added color support). Clang is still in the lead, but the gap is closing.


Original:

For students, I would unconditionally recommend Clang.

The performance in terms of generated code between gcc and Clang is now unclear (though I think that gcc 4.7 still has the lead, I haven't seen conclusive benchmarks yet), but for students to learn it does not really matter anyway.

On the other hand, Clang's extremely clear diagnostics are definitely easier for beginners to interpret.

Consider this simple snippet:

#include <string>
#include <iostream>

struct Student {
std::string surname;
std::string givenname;
}

std::ostream& operator<<(std::ostream& out, Student const& s) {
  return out << "{" << s.surname << ", " << s.givenname << "}";
}

int main() {
  Student me = { "Doe", "John" };
  std::cout << me << "\n";
}

You'll notice right away that the semi-colon is missing after the definition of the Student class, right :) ?

Well, gcc notices it too, after a fashion:

prog.cpp:9: error: expected initializer before ‘&’ token
prog.cpp: In function ‘int main()’:
prog.cpp:15: error: no match for ‘operator<<’ in ‘std::cout << me’
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:112: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:121: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ios<_CharT, _Traits>& (*)(std::basic_ios<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:131: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:169: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:173: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:177: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(bool) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:97: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:184: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:111: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:195: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:204: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:208: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:213: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:217: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(float) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:225: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:229: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(const void*) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:125: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_streambuf<_CharT, _Traits>*) [with _CharT = char, _Traits = std::char_traits<char>]

And Clang is not exactly starring here either, but still:

/tmp/webcompile/_25327_1.cc:9:6: error: redefinition of 'ostream' as different kind of symbol
std::ostream& operator<<(std::ostream& out, Student const& s) {
     ^
In file included from /tmp/webcompile/_25327_1.cc:1:
In file included from /usr/include/c++/4.3/string:49:
In file included from /usr/include/c++/4.3/bits/localefwd.h:47:
/usr/include/c++/4.3/iosfwd:134:33: note: previous definition is here
  typedef basic_ostream<char>           ostream;        ///< @isiosfwd
                                        ^
/tmp/webcompile/_25327_1.cc:9:13: error: expected ';' after top level declarator
std::ostream& operator<<(std::ostream& out, Student const& s) {
            ^
            ;
2 errors generated.

I purposefully choose an example which triggers an unclear error message (coming from an ambiguity in the grammar) rather than the typical "Oh my god Clang read my mind" examples. Still, we notice that Clang avoids the flood of errors. No need to scare students away.

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

I was having same issue, way i have resolved is:

opened the MySQL installer. i was having a Reconfigure link on MYSQL Server row. MYSQL Server having Reconfigure Link

Clicked on it, it does reinstalled MySQL Server. after that opened MySQL Workbench, and it was working fine.

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

I had a similar problem.

Setting width to "auto" worked fine for me but when the dialog contained a lot of text it made it span the full width of the page, ignoring the maxWidth setting.

Setting maxWidth on create works fine though:

$( ".selector" ).dialog({
  width: "auto",
  // maxWidth: 660, // This won't work
  create: function( event, ui ) {
    // Set maxWidth
    $(this).css("maxWidth", "660px");
  }
});

How to select all checkboxes with jQuery?

 $(document).ready(function(){
    $("#select_all").click(function(){
      var checked_status = this.checked;
      $("input[name='select[]']").each(function(){
        this.checked = checked_status;
      });
    });
  });

Bootstrap radio button "checked" flag

Use active class with label to make it auto select and use checked="" .

   <label class="btn btn-primary  active" value="regular"  style="width:47%">
   <input  type="radio" name="service" checked=""  > Regular </label>
   <label class="btn btn-primary " value="express" style="width:46%">
   <input type="radio" name="service"> Express </label>

How to run a Maven project from Eclipse?

(Alt + Shift + X) , then M to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

Undo git stash pop that results in merge conflict

As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:

  1. To unstage the merge conflicts: git reset HEAD . (note the trailing dot)
  2. To save the conflicted merge (just in case): git stash
  3. To return to master: git checkout master
  4. To pull latest changes: git fetch upstream; git merge upstream/master
  5. To correct my new branch: git checkout new-branch; git rebase master
  6. To apply the correct stashed changes (now 2nd on the stack): git stash apply stash@{1}

How to cast an Object to an int

Scenario 1: simple case

If it's guaranteed that your object is an Integer, this is the simple way:

int x = (Integer)yourObject;

Scenario 2: any numerical object

In Java Integer, Long, BigInteger etc. all implement the Number interface which has a method named intValue. Any other custom types with a numerical aspect should also implement Number (for example: Age implements Number). So you can:

int x = ((Number)yourObject).intValue();

Scenario 3: parse numerical text

When you accept user input from command line (or text field etc.) you get it as a String. In this case you can use Integer.parseInt(String string):

String input = someBuffer.readLine();
int x = Integer.parseInt(input);

If you get input as Object, you can use (String)input, or, if it can have an other textual type, input.toString():

int x = Integer.parseInt(input.toString());

Scenario 4: identity hash

In Java there are no pointers. However Object has a pointer-like default implementation for hashCode(), which is directly available via System.identityHashCode(Object o). So you can:

int x = System.identityHashCode(yourObject);

Note that this is not a real pointer value. Objects' memory address can be changed by the JVM while their identity hashes are keeping. Also, two living objects can have the same identity hash.

You can also use object.hashCode(), but it can be type specific.

Scenario 5: unique index

In same cases you need a unique index for each object, like to auto incremented ID values in a database table (and unlike to identity hash which is not unique). A simple sample implementation for this:

class ObjectIndexer {

    private int index = 0;

    private Map<Object, Integer> map = new WeakHashMap<>();

    public int indexFor(Object object) {
        if (map.containsKey(object)) {
            return map.get(object);
        } else {
            index++;
            map.put(object, index);
            return index;
        }
    }

}

Usage:

ObjectIndexer indexer = new ObjectIndexer();
int x = indexer.indexFor(yourObject);    // 1
int y = indexer.indexFor(new Object());  // 2
int z = indexer.indexFor(yourObject);    // 1

Scenario 6: enum member

In Java enum members aren't integers but full featured objects (unlike C/C++, for example). Probably there is never a need to convert an enum object to int, however Java automatically associates an index number to each enum member. This index can be accessed via Enum.ordinal(), for example:

enum Foo { BAR, BAZ, QUX }

// ...

Object baz = Foo.BAZ;
int index = ((Enum)baz).ordinal(); // 1

enter image description here

ffprobe or avprobe not found. Please install one

This is so simple if on windows...

In the folder where you have youtube-dl.exe

goto https://www.gyan.dev/ffmpeg/builds/

download the ffmpeg-git-full.7z file the download link is https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-full.7z

Open that zip file and move the ffmpeg.exe file to the same folder where youtube-dl.exe is

Example "blahblah.7z / whatevertherootfolderis / bin / ffmpeg.exe"

youtube-dl.exe -x --audio-format mp3 -o %(title)s.%(ext)s https://www.youtube.com/watch?v=wyPKRcBTsFQ

What is the difference between getText() and getAttribute() in Selenium WebDriver?

  <input attr1='a' attr2='b' attr3='c'>foo</input>

getAttribute(attr1) you get 'a'

getAttribute(attr2) you get 'b'

getAttribute(attr3) you get 'c'

getText() with no parameter you can only get 'foo'

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

The current spec of the CSS 3 Lists module does specify the ::marker pseudo-element which would do exactly what you want; FF has been tested to not support ::marker and I doubt that either Safari or Opera has it. IE, of course, does not support it.

So right now, the only way to do this is to use an image with list-style-image.

I guess you could wrap the contents of an li with a span and then you could set the color of each, but that seems a little hackish to me.

Is it possible to break a long line to multiple lines in Python?

When trying to enter continuous text (say, a query) do not put commas at the end of the line or you will get a list of strings instead of one long string:

queryText= "SELECT * FROM TABLE1 AS T1"\
"JOIN TABLE2 AS T2 ON T1.SOMETHING = T2.SOMETHING"\
"JOIN TABLE3 AS T3 ON T3.SOMETHING = T2.SOMETHING"\
"WHERE SOMETHING BETWEEN <WHATEVER> AND <WHATEVER ELSE>"\
"ORDER BY WHATEVERS DESC"

kinda like that.

There is a comment like this from acgtyrant, sorry, didn't see that. :/

Why the switch statement cannot be applied on strings?

In c++ strings are not first class citizens. The string operations are done through standard library. I think, that is the reason. Also, C++ uses branch table optimization to optimize the switch case statements. Have a look at the link.

http://en.wikipedia.org/wiki/Switch_statement

alternative to "!is.null()" in R

If it's just a matter of easy reading, you could always define your own function :

is.not.null <- function(x) !is.null(x)

So you can use it all along your program.

is.not.null(3)
is.not.null(NULL)

Java ElasticSearch None of the configured nodes are available

This means we are not able to instantiate ES transportClient and throw this exception. There are couple of possibilities that cause this issue.

  • Cluster name is incorrect. So open ES_HOME_DIR/config/elasticserach.yml file and check the cluster name value OR use this command: curl -XGET 'http://localhost:9200/_nodes'
  • Verify port 9200 is http port but elasticsearch service is using tcp port 9300 [by default]. So verify that the port is not blocked.
  • Authentication issue: set the header in transportClient's context for authentication:

    client.threadPool().getThreadContext()
      .putHeader("Authorization", "Basic " + encodeBase64String(basicHeader.getBytes()));
    

If you are still facing this issue then add the following property:

put("client.transport.ignore_cluster_name", true)

The below basic code is working fine for me:

Settings settings = Settings.builder()
            .put("cluster.name", "my-application").put("client.transport.sniff", true).put("client.transport.ignore_cluster_name", false).build();
    TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

Sorry for digging, but I met the same problem and found the simplier solution.

In Java compiler options you need to uncheck "Preserve unused (never read) local variables" so there is no need to change back target JVM version.

It seems to be a bug in an older Eclipe versions.

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

Strip all non-numeric characters from string in JavaScript

If you need this to leave the dot for float numbers, use this

var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"

Apache won't follow symlinks (403 Forbidden)

There is another way that symbolic links may fail you, as I discovered in my situation. If you have an SELinux system as the server and the symbolic links point to an NFS-mounted folder (other file systems may yield similar symptoms), httpd may see the wrong contexts and refuse to serve the contents of the target folders.

In my case the SELinux context of /var/www/html (which you can obtain with ls -Z) is unconfined_u:object_r:httpd_sys_content_t:s0. The symbolic links in /var/www/html will have the same context, but their target's context, being an NFS-mounted folder, are system_u:object_r:nfs_t:s0.

The solution is to add fscontext=unconfined_u:object_r:httpd_sys_content_t:s0 to the mount options (e.g. # mount -t nfs -o v3,fscontext=unconfined_u:object_r:httpd_sys_content_t:s0 <IP address>:/<server path> /<mount point>). rootcontext is irrelevant and defcontext is rejected by NFS. I did not try context by itself.

How can I upgrade NumPy?

All the same.

   sudo easy_install numpy

My Traceback

Searching for numpy

Best match: numpy 1.13.0

Adding numpy 1.13.0 to easy-install.pth file

Using /Library/Python/2.7/site-packages

Processing dependencies for numpy

How do I POST an array of objects with $.ajax (jQuery or Zepto)

I was having same issue when I was receiving array of objects in django sent by ajax. JSONStringyfy worked for me. You can have a look for this.

First I stringify the data as

var myData = [];
   allData.forEach((x, index) => {
         // console.log(index);
         myData.push(JSON.stringify({
         "product_id" : x.product_id,
         "product" : x.product,
         "url" : x.url,
         "image_url" : x.image_url,
         "price" : x.price,
         "source": x.source
      }))
   })

Then I sent it like

$.ajax({
        url: '{% url "url_name" %}',
        method: "POST",
        data: {
           'csrfmiddlewaretoken': '{{ csrf_token }}',
           'queryset[]': myData
        },
        success: (res) => {
        // success post work here.
    }
})

And received as :

list_of_json = request.POST.getlist("queryset[]", [])
list_of_json = [ json.loads(item) for item in list_of_json ]

Replace only some groups with Regex

Here is another nice clean option that does not require changing your pattern.

        var text = "example-123-example";
        var pattern = @"-(\d+)-";

        var replaced = Regex.Replace(text, pattern, (_match) =>
        {
            Group group = _match.Groups[1];
            string replace = "AA";
            return String.Format("{0}{1}{2}", _match.Value.Substring(0, group.Index - _match.Index), replace, _match.Value.Substring(group.Index - _match.Index + group.Length));
        });

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

In app store connect now if we are using ads in our app then we will answer as yes to Does this app use the Advertising Identifier (IDFA)?

further 3 questions will be asked as

enter image description here

if your using just admob then check the first one and leave other two unchecked. Other two options (2nd , 3rd ) will be checked if your using app flyer to show ads. all options are explained with detail here

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

It can happen because of native method calling in your application. For example, in Qtjambi if you use QApplication.quit() instead of QApplication.closeAllWindows() for closing a Java application it generates an error log.

In this case, you can get a stack trace right to your method that called the native code and caused the crash. Just look in the log file it tells you about:

# An error report file with more information is saved as hs_err_pid24139.log.

The stack trace looks quite unusual, since it has native code mixed with VM code and your code, but each line is prefixed so you can tell which lines are your own code. There's a key at the top of the stack trace to explain the prefixes:

Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)

ECMAScript 6 class destructor

"A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered."

Not so. The purpose of a destructor is to allow the item that registered the listeners to unregister them. Once an object has no other references to it, it will be garbage collected.

For instance, in AngularJS, when a controller is destroyed, it can listen for a destroy event and respond to it. This isn't the same as having a destructor automatically called, but it's close, and gives us the opportunity to remove listeners that were set when the controller was initialized.

// Set event listeners, hanging onto the returned listener removal functions
function initialize() {
    $scope.listenerCleanup = [];
    $scope.listenerCleanup.push( $scope.$on( EVENTS.DESTROY, instance.onDestroy) );
    $scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.SUCCESS, instance.onCreateUserResponse ) );
    $scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.FAILURE, instance.onCreateUserResponse ) );
}

// Remove event listeners when the controller is destroyed
function onDestroy(){
    $scope.listenerCleanup.forEach( remove => remove() );
}


Mapping US zip code to time zone

There's actually a great Google API for this. It takes in a location and returns the timezone for that location. Should be simple enough to create a bash or python script to get the results for each address in a CSV file or database then save the timezone information.

https://developers.google.com/maps/documentation/timezone/start

Request Endpoint:

https://maps.googleapis.com/maps/api/timezone/json?location=38.908133,-77.047119&timestamp=1458000000&key=YOUR_API_KEY

Response:

{
   "dstOffset" : 3600,
   "rawOffset" : -18000,
   "status" : "OK",
   "timeZoneId" : "America/New_York",
   "timeZoneName" : "Eastern Daylight Time"
}

Is there an API to get bank transaction and bank balance?

Also check out the open financial exchange (ofx) http://www.ofx.net/

This is what apps like quicken, ms money etc use.

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

In my side, it is because POSTMAN setting issue, but I don't know why, maybe I copy a query from other. I simply create a new request in POSTMAN and run it, it works.

Javascript "Not a Constructor" Exception while creating objects

To add the solution I found to this problem when I had it, I was including a class from another file and the file I tried to instantiate it in gave the "not a constructor" error. Ultimately the issue was a couple unused requires in the other file before the class was defined. I'm not sure why they broke it, but removing them fixed it. Always be sure to check if something might be hiding in between the steps you're thinking about.

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Easy done:

(?<=\[)(.*?)(?=\])

Technically that's using lookaheads and lookbehinds. See Lookahead and Lookbehind Zero-Width Assertions. The pattern consists of:

  • is preceded by a [ that is not captured (lookbehind);
  • a non-greedy captured group. It's non-greedy to stop at the first ]; and
  • is followed by a ] that is not captured (lookahead).

Alternatively you can just capture what's between the square brackets:

\[(.*?)\]

and return the first captured group instead of the entire match.

How to enter in a Docker container already running with a new TTY

Update

As of docker 0.9, for the steps below to now work, one now has to update the /etc/default/docker file with the '-e lxc' to the docker daemon startup option before restarting the daemon (I did this by rebooting the host).

update to the /etc/default/docker file

This is all because...

...it [docker 0.9] contains a new "engine driver" abstraction to make possible the use of other API than LXC to start containers. It also provide a new engine driver based on a new API library (libcontainer) which is able to handle Control Groups without using LXC tools. The main issue is that if you are relying on lxc-attach to perform actions on your container, like starting a shell inside the container, which is insanely useful for developpment environment...

source

Please note that this will prevent the new host only networking optional feature of docker 0.11 from "working" and you will only see the loopback interface. bug report


It turns out that the solution to a different question was also the solution to this one:

...you can use docker ps -notrunc to get the full lxc container ID and then use lxc-attach -n <container_id> run bash in that container as root.

Update: You will soon need to use ps --no-trunc instead of ps -notrunc which is being deprecated.

enter image description here Find the full container ID

enter image description here Enter the lxc attach command.

enter image description here Top shows my apache process running that docker started.

Converting binary to decimal integer output

There is actually a much faster alternative to convert binary numbers to decimal, based on artificial intelligence (linear regression) model:

  1. Train an AI algorithm to convert 32-binary number to decimal based.
  2. Predict a decimal representation from 32-binary.

See example and time comparison below:

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np

y = np.random.randint(0, 2**32, size=10_000)

def gen_x(y):
    _x = bin(y)[2:]
    n = 32 - len(_x)
    return [int(sym) for sym in '0'*n + _x]

X = np.array([gen_x(x) for x in y])

model = LinearRegression()
model.fit(X, y)

def convert_bin_to_dec_ai(array):
    return model.predict(array)

y_pred = convert_bin_to_dec_ai(X)

Time comparison:

enter image description here

This AI solution converts numbers almost x10 times faster than conventional way!

How to add include path in Qt Creator?

For anyone completely new to Qt Creator like me, you can modify your project's .pro file from within Qt Creator:

enter image description here

Just double-click on "your project name".pro in the Projects window and add the include path at the bottom of the .pro file like I've done.

Using module 'subprocess' with timeout

I added the solution with threading from jcollado to my Python module easyprocess.

Install:

pip install easyprocess

Example:

from easyprocess import Proc

# shell is not supported!
stdout=Proc('ping localhost').call(timeout=1.5).stdout
print stdout