Programs & Examples On #Blogengine.net

BlogEngine.NET is an Open Source blog based on ASP.NET.

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

Some firewalls do that if a connection is idle for x number of minutes. Some ISPs set their routers to do that for various reasons as well.

In this day and age, you'll need to gracefully handle (re-establish as needed) that condition.

How to target the href to div

Put for div same name as in href target.

ex: <div name="link"> and <a href="#link">

if condition in sql server update query

DECLARE @JCnt int=null
SEt @JCnt=(SELECT COUNT( ISNUll(EmpCode,0)) FROM tbl_Employees WHERE EmpCode=1  )

UPDATE #TempCode
SET janCA= CASE WHEN @JCnt>0 THEN (SELECT SUM (ISNUll(Amount,0)) FROM tbl_Salary WHERE Code=1 )ELSE 0 END
WHERE code=1

What is the best IDE for C Development / Why use Emacs over an IDE?

Use Code::Blocks. It has everything you need and a very clean GUI.

What does "hard coded" mean?

The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.

  • Hard-coding: feature is coded to the system not allowing for configuration;
  • Parametric: feature is configurable via table driven, or properties files with limited parametric values ;
  • Soft-coding: feature uses “engines” that derive results based on any number of parametric values (e.g. business rules in BRE); rules are coded but exist as parameters in system, written in script form

Examples:

// firstName has a hard-coded value of "hello world"
string firstName = "hello world";

// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();

A hard-coded constant[1]:

float areaOfCircle(int radius)
{
    float area = 0;
    area = 3.14*radius*radius;  //  3.14 is a hard-coded value
    return area;
}

Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.

  1. Hard CodingHard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.

    The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.

  2. Soft Coding
    If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.

    In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.

    In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.

Sources and Citations:

1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid

Further Reading:

Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

Auto highlight text in a textbox control

If your intention is to get the text in the textbox highlighted on a mouse click you can make it simple by adding:

this.textBox1.Click += new System.EventHandler(textBox1_Click);

in:

partial class Form1
{
    private void InitializeComponent()
    {

    }
}

where textBox1 is the name of the relevant textbox located in Form1

And then create the method definition:

void textBox1_Click(object sender, System.EventArgs e)
{
    textBox1.SelectAll();
}

in:

public partial class Form1 : Form
{

}

Binding Button click to a method

Click is an event. In your code behind, you need to have a corresponding event handler to whatever you have in the XAML. In this case, you would need to have the following:

private void Command(object sender, RoutedEventArgs e)
{

}

Commands are different. If you need to wire up a command, you'd use the Commmand property of the button and you would either use some pre-built Commands or wire up your own via the CommandManager class (I think).

How to clear a data grid view

IF you want to clear not only Data, but also ComboBoxes, Checkboxes, try

dataGridView.Columns.Clear();

Empty ArrayList equals null

Just as zero is a number - just a number that represents none - an empty list is still a list, just a list with nothing in it. null is no list at all; it's therefore different from an empty list.

Similarly, a list that contains null items is a list, and is not an empty list. Because it has items in it; it doesn't matter that those items are themselves null. As an example, a list with three null values in it, and nothing else: what is its length? Its length is 3. The empty list's length is zero. And, of course, null doesn't have a length.

FAIL - Application at context path /Hello could not be started

1st Reason could be the ending tag of your application's web.xml file which could not have been closed properly.

web.xml might be ending with <web-app>, but must end with </web-app>

2nd Reason which worked in my case could be the lib folder of your tomcat must contain the supporting jar file of your database.

ojdbc on case of Oracle or sqljdbc in case of SqlServer

Unsupported Media Type in postman

Thanks for all Contributions;

that is happening with me in XML; I just Change application/XML to be text/XML which solve my Problem

Python 3 string.join() equivalent?

str.join() works fine in Python 3, you just need to get the order of the arguments correct

>>> str.join('.', ('a', 'b', 'c'))
'a.b.c'

Number of occurrences of a character in a string

Why use regex for that. String implements IEnumerable<char>, so you can just use LINQ.

test.Count(c => c == '&')

Why is processing a sorted array faster than processing an unsorted array?

That's for sure!...

Branch prediction makes the logic run slower, because of the switching which happens in your code! It's like you are going a straight street or a street with a lot of turnings, for sure the straight one is going to be done quicker!...

If the array is sorted, your condition is false at the first step: data[c] >= 128, then becomes a true value for the whole way to the end of the street. That's how you get to the end of the logic faster. On the other hand, using an unsorted array, you need a lot of turning and processing which make your code run slower for sure...

Look at the image I created for you below. Which street is going to be finished faster?

Branch Prediction

So programmatically, branch prediction causes the process to be slower...

Also at the end, it's good to know we have two kinds of branch predictions that each is going to affect your code differently:

1. Static

2. Dynamic

Branch Prediction

Static branch prediction is used by the microprocessor the first time a conditional branch is encountered, and dynamic branch prediction is used for succeeding executions of the conditional branch code.

In order to effectively write your code to take advantage of these rules, when writing if-else or switch statements, check the most common cases first and work progressively down to the least common. Loops do not necessarily require any special ordering of code for static branch prediction, as only the condition of the loop iterator is normally used.

Batch Script to Run as Administrator

You have a couple options.

  1. If you need to do it using only a batch file and native commands, check out How can I auto-elevate my batch file, so that it requests from UAC admin rights if required?.

  2. If 3rd-party utilities are an option, you can use a tool like Elevate. It is an executable that you call with the program you want to run elevated as a parameter.
    Like this: elevate net share ....

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

How to wait for a JavaScript Promise to resolve before resuming function?

If using ES2016 you can use async and await and do something like:

(async () => {
  const data = await fetch(url)
  myFunc(data)
}())

If using ES2015 you can use Generators. If you don't like the syntax you can abstract it away using an async utility function as explained here.

If using ES5 you'll probably want a library like Bluebird to give you more control.

Finally, if your runtime supports ES2015 already execution order may be preserved with parallelism using Fetch Injection.

MySQL Job failed to start

My problem was running out of memory. Digital ocean has great instruction for adding swap memory for Ubuntu: https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04

This solved the issue and enabled me to restart the Mysql that otherwise would not start.

Maven: The packaging for this project did not assign a file to the build artifact

This reply is on a very old question to help others facing this issue.

I face this failed error while I were working on my Java project using IntelliJ IDEA IDE.

Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-cli) on project getpassword: The packaging for this project did not assign a file to the build artifact

this failed happens, when I choose install:install under Plugins - install, as pointed with red arrow in below image.

Choose Wrong Selection

Once I run the selected install under Lifecycle as illustrated above, the issue gone, and my maven install compile build successfully.

How to run cron job every 2 hours

Just do:

0 */2 * * *  /home/username/test.sh 

The 0 at the beginning means to run at the 0th minute. (If it were an *, the script would run every minute during every second hour.)

Don't forget, you can check syslog to see if it ever actually ran!

C# : Passing a Generic Object

It doesn't compile because T could be anything, and not everything will have the myvar field.

You could make myvar a property on ITest:

public ITest
{
    string myvar{get;}
}

and implement it on the classes as a property:

public class MyClass1 : ITest
{
    public string myvar{ get { return "hello 1"; } }
}

and then put a generic constraint on your method:

public void PrintGeneric<T>(T test) where T : ITest
{
    Console.WriteLine("Generic : " + test.myvar);
}

but in that case to be honest you are better off just passing in an ITest:

public void PrintGeneric(ITest test)
{
    Console.WriteLine("Generic : " + test.myvar);
}

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

You can get the raw data by calling ReadAsStringAsAsync on the Request.Content property.

string result = await Request.Content.ReadAsStringAsync();

There are various overloads if you want it in a byte or in a stream. Since these are async-methods you need to make sure your controller is async:

public async Task<IHttpActionResult> GetSomething()
{
    var rawMessage = await Request.Content.ReadAsStringAsync();
    // ...
    return Ok();
}

EDIT: if you're receiving an empty string from this method, it means something else has already read it. When it does that, it leaves the pointer at the end. An alternative method of doing this is as follows:

public IHttpActionResult GetSomething()
{
    var reader = new StreamReader(Request.Body);
    reader.BaseStream.Seek(0, SeekOrigin.Begin); 
    var rawMessage = reader.ReadToEnd();

    return Ok();
}

In this case, your endpoint doesn't need to be async (unless you have other async-methods)

input() error - NameError: name '...' is not defined

For anyone else that may run into this issue, turns out that even if you include #!/usr/bin/env python3 at the beginning of your script, the shebang is ignored if the file isn't executable.

To determine whether or not your file is executable:

  • run ./filename.py from the command line
  • if you get -bash: ./filename.py: Permission denied, run chmod a+x filename.py
  • run ./filename.py again

If you've included import sys; print(sys.version) as Kevin suggested, you'll now see that the script is being interpreted by python3

Multiple Java versions running concurrently under Windows

If you use Java Web Start (you can start applications from any URL, even the local file system) it will take care of finding the right version for your application.

C# How to determine if a number is a multiple of another?

Use the modulus (%) operator:

6 % 3 == 0
7 % 3 == 1

How to deal with certificates using Selenium?

Just an update regarding this issue.

Require Drivers:

Linux: Centos 7 64bit, Window 7 64bit

Firefox: 52.0.3

Selenium Webdriver: 3.4.0 (Windows), 3.8.1 (Linux Centos)

GeckoDriver: v0.16.0 (Windows), v0.17.0 (Linux Centos)

Code

System.setProperty("webdriver.gecko.driver", "/home/seleniumproject/geckodrivers/linux/v0.17/geckodriver");

ProfilesIni ini = new ProfilesIni();


// Change the profile name to your own. The profile name can 
// be found under .mozilla folder ~/.mozilla/firefox/profile. 
// See you profile.ini for the default profile name

FirefoxProfile profile = ini.getProfile("default"); 

DesiredCapabilities cap = new DesiredCapabilities();
cap.setAcceptInsecureCerts(true);

FirefoxBinary firefoxBinary = new FirefoxBinary();

GeckoDriverService service =new GeckoDriverService.Builder(firefoxBinary)
    .usingDriverExecutable(new 
File("/home/seleniumproject/geckodrivers/linux/v0.17/geckodriver"))
    .usingAnyFreePort()
    .usingAnyFreePort()
    .build();
try {
    service.start();
} catch (IOException e) {
    e.printStackTrace();
}

FirefoxOptions options = new FirefoxOptions().setBinary(firefoxBinary).setProfile(profile).addCapabilities(cap);

driver = new FirefoxDriver(options);
driver.get("https://www.google.com");

System.out.println("Life Title -> " + driver.getTitle());
driver.close();

Switching users inside Docker image to a non-root user

You should not use su in a dockerfile, however you should use the USER instruction in the Dockerfile.

At each stage of the Dockerfile build, a new container is created so any change you make to the user will not persist on the next build stage.

For example:

RUN whoami
RUN su test
RUN whoami

This would never say the user would be test as a new container is spawned on the 2nd whoami. The output would be root on both (unless of course you run USER beforehand).

If however you do:

RUN whoami
USER test
RUN whoami

You should see root then test.

Alternatively you can run a command as a different user with sudo with something like

sudo -u test whoami

But it seems better to use the official supported instruction.

XAMPP Apache won't start

I gave all users full access on the xampp folder, inclusive subdirectories. Afterwards it worked.

How to get a user's time zone?

edit/update:

Xcode 8 or later • Swift 3 or later

var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() }
secondsFromGMT  // -7200

if you need the abbreviation:

var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" }
localTimeZoneAbbreviation   // "GMT-2"

if you need the timezone identifier:

var localTimeZoneIdentifier: String { return TimeZone.current.identifier }

localTimeZoneIdentifier // "America/Sao_Paulo"

To know all timezones abbreviations available:

var timeZoneAbbreviations: [String:String] { return TimeZone.abbreviationDictionary }
timeZoneAbbreviations   // ["CEST": "Europe/Paris", "WEST": "Europe/Lisbon", "CDT": "America/Chicago", "EET": "Europe/Istanbul", "BRST": "America/Sao_Paulo", "EEST": "Europe/Istanbul", "CET": "Europe/Paris", "MSD": "Europe/Moscow", "MST": "America/Denver", "KST": "Asia/Seoul", "PET": "America/Lima", "NZDT": "Pacific/Auckland", "CLT": "America/Santiago", "HST": "Pacific/Honolulu", "MDT": "America/Denver", "NZST": "Pacific/Auckland", "COT": "America/Bogota", "CST": "America/Chicago", "SGT": "Asia/Singapore", "CAT": "Africa/Harare", "BRT": "America/Sao_Paulo", "WET": "Europe/Lisbon", "IST": "Asia/Calcutta", "HKT": "Asia/Hong_Kong", "GST": "Asia/Dubai", "EDT": "America/New_York", "WIT": "Asia/Jakarta", "UTC": "UTC", "JST": "Asia/Tokyo", "IRST": "Asia/Tehran", "PHT": "Asia/Manila", "AKDT": "America/Juneau", "BST": "Europe/London", "PST": "America/Los_Angeles", "ART": "America/Argentina/Buenos_Aires", "PDT": "America/Los_Angeles", "WAT": "Africa/Lagos", "EST": "America/New_York", "BDT": "Asia/Dhaka", "CLST": "America/Santiago", "AKST": "America/Juneau", "ADT": "America/Halifax", "AST": "America/Halifax", "PKT": "Asia/Karachi", "GMT": "GMT", "ICT": "Asia/Bangkok", "MSK": "Europe/Moscow", "EAT": "Africa/Addis_Ababa"]

To know all timezones names (identifiers) available:

var timeZoneIdentifiers: [String] { return TimeZone.knownTimeZoneIdentifiers }
timeZoneIdentifiers           // ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Juba", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Anguilla", "America/Antigua", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Argentina/Catamarca", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/La_Rioja", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Salta", "America/Argentina/San_Juan", "America/Argentina/San_Luis", "America/Argentina/Tucuman", "America/Argentina/Ushuaia", "America/Aruba", "America/Asuncion", "America/Atikokan", "America/Bahia", "America/Bahia_Banderas", "America/Barbados", "America/Belem", "America/Belize", "America/Blanc-Sablon", "America/Boa_Vista", "America/Bogota", …, "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Pohnpei", "Pacific/Ponape", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Truk", "Pacific/Wake", "Pacific/Wallis"]

There is a few other info you may need:

var isDaylightSavingTime: Bool { return TimeZone.current.isDaylightSavingTime(for: Date()) }
print(isDaylightSavingTime) // true (in effect)

var daylightSavingTimeOffset: TimeInterval { return TimeZone.current.daylightSavingTimeOffset() }
print(daylightSavingTimeOffset)  // 3600 seconds (1 hour - daylight savings time)


var nextDaylightSavingTimeTransition: Date? { return TimeZone.current.nextDaylightSavingTimeTransition }    //  "Feb 18, 2017, 11:00 PM"
 print(nextDaylightSavingTimeTransition?.description(with: .current) ?? "none")
nextDaylightSavingTimeTransition   // "Saturday, February 18, 2017 at 11:00:00 PM Brasilia Standard Time\n"

var nextDaylightSavingTimeTransitionAfterNext: Date? {
    guard
        let nextDaylightSavingTimeTransition = nextDaylightSavingTimeTransition
        else { return nil }
    return TimeZone.current.nextDaylightSavingTimeTransition(after: nextDaylightSavingTimeTransition)
}

nextDaylightSavingTimeTransitionAfterNext  //   "Oct 15, 2017, 1:00 AM"

TimeZone - Apple Developer Swift Documentation

Multiple lines of input in <input type="text" />

You need to use a textarea to get multiline handling.

_x000D_
_x000D_
<textarea name="Text1" cols="40" rows="5"></textarea>
_x000D_
_x000D_
_x000D_

Correct way to pass multiple values for same parameter name in GET request

Solutions above didn't work. It simply displayed the last key/value pairs, but this did:

http://localhost/?key[]=1&key[]=2

Returns:

Array
(
[key] => Array
    (
        [0] => 1
        [1] => 2
    )

Activity has leaked window that was originally added

I was also facing this problem for some time but I realized it's not because of dialog in my case it's because of ActionMode. So if you are trying to finish activity when an ActionMode is open it will cause this problem. In your activity's onPause finish the action mode.

 private ActionMode actionMode;

 @Override
 public void onActionModeStarted(ActionMode mode) {
    super.onActionModeStarted(mode);
    actionMode = mode;
 }

 @Override
 protected void onPause() {
    super.onPause();
    if (actionMode != null) actionMode.finish();
 }

Couldn't load memtrack module Logcat Error

I had this issue too, also running on an emulator.. The same message was showing up on Logcat, but it wasn't affecting the functionality of the app. But it was annoying, and I don't like seeing errors on the log that I don't understand.

Anyway, I got rid of the message by increasing the RAM on the emulator.

How to configure logging to syslog in Python?

You should always use the local host for logging, whether to /dev/log or localhost through the TCP stack. This allows the fully RFC compliant and featureful system logging daemon to handle syslog. This eliminates the need for the remote daemon to be functional and provides the enhanced capabilities of syslog daemon's such as rsyslog and syslog-ng for instance. The same philosophy goes for SMTP. Just hand it to the local SMTP software. In this case use 'program mode' not the daemon, but it's the same idea. Let the more capable software handle it. Retrying, queuing, local spooling, using TCP instead of UDP for syslog and so forth become possible. You can also [re-]configure those daemons separately from your code as it should be.

Save your coding for your application, let other software do it's job in concert.

Check if Python Package is installed

I would like to comment to @ice.nicer reply but I cannot, so ... My observations is that packages with dashes are saved with underscores, not only with dots as pointed out by @dwich comment

For example, you do pip3 install sphinx-rtd-theme, but:

  • importlib.util.find_spec(sphinx_rtd_theme) returns an Object
  • importlib.util.find_spec(sphinx-rtd-theme) returns None
  • importlib.util.find_spec(sphinx.rtd.theme) raises ModuleNotFoundError

Moreover, some names are totally changed. For example, you do pip3 install pyyaml but it is saved simply as yaml

I am using python3.8

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

What is a good Hash Function?

A good hash function has the following properties:

  1. Given a hash of a message it is computationally infeasible for an attacker to find another message such that their hashes are identical.

  2. Given a pair of message, m' and m, it is computationally infeasible to find two such that that h(m) = h(m')

The two cases are not the same. In the first case, there is a pre-existing hash that you're trying to find a collision for. In the second case, you're trying to find any two messages that collide. The second task is significantly easier due to the birthday "paradox."

Where performance is not that great an issue, you should always use a secure hash function. There are very clever attacks that can be performed by forcing collisions in a hash. If you use something strong from the outset, you'll secure yourself against these.

Don't use MD5 or SHA-1 in new designs. Most cryptographers, me included, would consider them broken. The principle source of weakness in both of these designs is that the second property, which I outlined above, does not hold for these constructions. If an attacker can generate two messages, m and m', that both hash to the same value they can use these messages against you. SHA-1 and MD5 also suffer from message extension attacks, which can fatally weaken your application if you're not careful.

A more modern hash such as Whirpool is a better choice. It does not suffer from these message extension attacks and uses the same mathematics as AES uses to prove security against a variety of attacks.

Hope that helps!

How to use terminal commands with Github?

git add myfile.h
git commit -m "your commit message"
git push -u origin master

if you don't remember all the files you need to update, use

git status

How to insert text in a td with id, using JavaScript

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

I don't use Retrofit and for OkHttp here is the only solution for self-signed certificate that worked for me:

  1. Get a certificate from our site like in Gowtham's question and put it into res/raw dir of the project:

    echo -n | openssl s_client -connect elkews.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ./res/raw/elkews_cert.crt
    
  2. Use Paulo answer to set ssl factory (nowadays using OkHttpClient.Builder()) but without RestAdapter creation.

  3. Then add the following solution to fix: SSLPeerUnverifiedException: Hostname not verified

So the end of Paulo's code (after sslContext initialization) that is working for me looks like the following:

...
OkHttpClient.Builder builder = new OkHttpClient.Builder().sslSocketFactory(sslContext.getSocketFactory());
builder.hostnameVerifier(new HostnameVerifier() {
  @Override
  public boolean verify(String hostname, SSLSession session) {
    return "secure.elkews.com".equalsIgnoreCase(hostname);
});
OkHttpClient okHttpClient = builder.build();

Is there more to an interface than having the correct methods

Interfaces where a fetature added to java to allow multiple inheritance. The developers of Java though/realized that having multiple inheritance was a "dangerous" feature, that is why the came up with the idea of an interface.

multiple inheritance is dangerous because you might have a class like the following:


class Box{
    public int getSize(){
       return 0;
    }
    public int getArea(){
       return 1;
    }

}

class Triangle{
    public int getSize(){
       return 1;
    }
    public int getArea(){
       return 0;
    }

}

class FunckyFigure extends Box, Triable{
   // we do not implement the methods we will used the inherited ones
}

Which would be the method that should be called when we use


   FunckyFigure.GetArea(); 

All the problems are solved with interfaces, because you do know you can extend the interfaces and that they wont have classing methods... ofcourse the compiler is nice and tells you if you did not implemented a methods, but I like to think that is a side effect of a more interesting idea.

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

I took Earmon Nerbonne's answer and edited it to work with tables that fill the whole width.

http://jsfiddle.net/DYgD6/6/

<!DOCTYPE html>
<html><head><title>testdoc</title>
<style type="text/css">
            body {
        font:16px Calibri;
    }
    table {
        border-collapse:separate;
        border-top: 3px solid grey;
    }
    td {
        margin:0;
        border:3px solid grey;
        border-top-width:0px;
        white-space:nowrap;
    }
    #outerdiv {
        position: absolute;
        top: 0;
        left: 0;
        right: 5em;
    }
    #innerdiv {
        width: 100%;
        overflow-x:scroll;
        margin-left: 5em;
        overflow-y:visible;
        padding-bottom:1px;
    }
    .headcol {
        position:absolute;
        width:5em;
        left:0;
        top:auto;
        border-right: 0px none black;
        border-top-width:3px;
        /*only relevant for first row*/
        margin-top:-3px;
        /*compensate for top border*/
    }
    .headcol:before {
        content:'Row ';
    }
    .long {
        background:yellow;
        letter-spacing:1em;
    }
</style></head><body>
  <div id="outerdiv">
   <div id="innerdiv">
    <table>
        <tr>
            <td class="headcol">1</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">2</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">3</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">4</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">5</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">6</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">7</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">8</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
        <tr>
            <td class="headcol">9</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
            <td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td>
        </tr>
    </table>
</div></div>
</body></html>

The width of the fixed column still needs to be a set value though.

Check if an array contains any element of another array in JavaScript

With underscorejs

var a1 = [1,2,3];
var a2 = [1,2];

_.every(a1, function(e){ return _.include(a2, e); } ); //=> false
_.every(a2, function(e){ return _.include(a1, e); } ); //=> true

How to change environment's font size?

Try playing around with a combination of the following user settings:

{
  "editor.fontSize": 18,
  "window.zoomLevel": 1.5,
}

git-diff to ignore ^M

Why do you get these ^M in your git diff?

In my case I was working on a project which was developed in Windows and I used OS X. When I changed some code, I saw ^M at the end of the lines I added in git diff. I think the ^M were showing up because they were different line endings than the rest of the file. Because the rest of the file was developed in Windows it used CR line endings, and in OS X it uses LF line endings.

Apparently, the Windows developer didn't use the option "Checkout Windows-style, commit Unix-style line endings" during the installation of Git.

So what should we do about this?

You can have the Windows users reinstall git and use the "Checkout Windows-style, commit Unix-style line endings" option. This is what I would prefer, because I see Windows as an exception in its line ending characters and Windows fixes its own issue this way.

If you go for this option, you should however fix the current files (because they're still using the CR line endings). I did this by following these steps:

  1. Remove all files from the repository, but not from your filesystem.

    git rm --cached -r .
    
  2. Add a .gitattributes file that enforces certain files to use a LF as line endings. Put this in the file:

    *.ext text eol=crlf
    

    Replace .ext with the file extensions you want to match.

  3. Add all the files again.

    git add .
    

    This will show messages like this:

    warning: CRLF will be replaced by LF in <filename>.
    The file will have its original line endings in your working directory.
    
  4. You could remove the .gitattributes file unless you have stubborn Windows users that don't want to use the "Checkout Windows-style, commit Unix-style line endings" option.

  5. Commit and push it all.

  6. Remove and checkout the applicable files on all the systems where they're used. On the Windows systems, make sure they now use the "Checkout Windows-style, commit Unix-style line endings" option. You should also do this on the system where you executed these tasks because when you added the files git said:

    The file will have its original line endings in your working directory.
    

    You can do something like this to remove the files:

    git ls | grep ".ext$" | xargs rm -f
    

    And then this to get them back with the correct line endings:

    git ls | grep ".ext$" | xargs git checkout
    

    Of course replacing .ext with the extension you want.

Now your project only uses LF characters for the line endings, and the nasty CR characters won't ever come back :).

The other option is to enforce windows style line endings. You can also use the .gitattributes file for this.

More info: https://help.github.com/articles/dealing-with-line-endings/#platform-all

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

htdocs is your default document-root directory, so you have to use localhost/index.html to see that html file. In other words, localhost is mapped to xampp/htdocs, so index.html is at localhost itself. You can change the location of document root by modifying httpd.conf and restarting the server.

Where does Hive store files in HDFS?

Summarize few points posted earlier, in hive-site.xml, property hive.metastore.warehouse.dir specifies where the files located under hadoop HDFS

<property>
   <name>hive.metastore.warehouse.dir</name>
   <value>/user/hive/warehouse</value>
</property>

To view files, use this command:

hadoop fs -ls /user/hive/warehouse

or

http://localhost:50070
Utilities > Browse the file system
or
http://localhost:50070/explorer.html#/

tested under hadoop-2.7.3, hive-2.1.1

How can I get browser to prompt to save password?

I spent a lot of time reading the various answers on this thread, and for me, it was actually something slightly different (related, but different). On Mobile Safari (iOS devices), if the login form is HIDDEN when the page loads, the prompt will not appear (after you show the form then submit it). You can test with the following code, which displays the form 5 seconds after the page load. Remove the JS and the display: none and it works. I am yet to find a solution to this, just posted in case anyone else has the same issue and can not figure out the cause.

JS:

$(function() {
  setTimeout(function() {
    $('form').fadeIn();
  }, 5000);
});

HTML:

<form method="POST" style="display: none;">
  <input name='email' id='email' type='email' placeholder='email' />
  <input name='password' id='password' type='password' placeholder='password' />
  <button type="submit">LOGIN</button>
</form>

how to cancel/abort ajax request in axios

Axios does not support canceling requests at the moment. Please see this issue for details.

UPDATE: Cancellation support was added in axios v0.15.

EDIT: The axios cancel token API is based on the withdrawn cancelable promises proposal.

Example:

const cancelTokenSource = axios.CancelToken.source();

axios.get('/user/12345', {
  cancelToken: cancelTokenSource.token
});

// Cancel request
cancelTokenSource.cancel();

using OR and NOT in solr query

Solr currently checks for a "pure negative" query and inserts *:* (which matches all documents) so that it works correctly.

-foo is transformed by solr into (*:* -foo)

The big caveat is that Solr only checks to see if the top level query is a pure negative query! So this means that a query like bar OR (-foo) is not changed since the pure negative query is in a sub-clause of the top level query. You need to transform this query yourself into bar OR (*:* -foo)

You may check the solr query explanation to verify the query transformation:

?q=-title:foo&debug=query

is transformed to

(+(-title:foo +MatchAllDocsQuery(*:*))

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.

Find an object in SQL Server (cross-database)

Easiest way is to hit up the information_schemas...

SELECT *
FROM information_schema.Tables
WHERE [Table_Name]='????'

SELECT *
FROM information_schema.Views
WHERE [Table_Name]='????'

SELECT *
FROM information_schema.Routines
WHERE [Routine_Name]='????'

Angular ngClass and click event for toggling class

If you're looking for an HTML only way of doing this in angular...

<div #myDiv class="my_class" (click)="myDiv.classList.toggle('active')">
  Some content
</div>

The important bit is the #myDiv part.

It's a HTML Node reference, so you can use that variable as if it was assigned to document.querySelector('.my_class')

NOTE: this variable is scope specific, so you can use it in *ngFor statements

How to getElementByClass instead of GetElementById with JavaScript?

adding to CMS's answer, this is a more generic approach of toggle_visibility I've just used myself:

function toggle_visibility(className,display) {
   var elements = getElementsByClassName(document, className),
       n = elements.length;
   for (var i = 0; i < n; i++) {
     var e = elements[i];

     if(display.length > 0) {
       e.style.display = display;
     } else {
       if(e.style.display == 'block') {
         e.style.display = 'none';
       } else {
         e.style.display = 'block';
       }
     }
  }
}

Python list / sublist selection -1 weirdness

-1 isn't special in the sense that the sequence is read backwards, it rather wraps around the ends. Such that minus one means zero minus one, exclusive (and, for a positive step value, the sequence is read "from left to right".

so for i = [1, 2, 3, 4], i[2:-1] means from item two to the beginning minus one (or, 'around to the end'), which results in [3]. The -1th element, or element 0 backwards 1 is the last 4, but since it's exclusive, we get 3.

I hope this is somewhat understandable.

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

Gmail: OAuth

  • Goto the link
  • Login with your gmail username password
  • Click on the google menu at the top left
  • Click API Manager
  • Click on Credentials
  • Click Create Credentials and select OAuth Client
  • Select Web Application as Application type and Enter the Name-> Enter Authorised Redirect URL (Eg: http://localhost:53922/signin-google) ->Click on Create button. This will create the credentials. Pls make a note of Client ID and Secret ID. Finally click OK to close the credentials pop up.
  • Next important step is to enable the Google API. Click on Overview in the left pane.
  • Click on the Google API under Social APIs section.
  • Click Enable.

That’s all from the Google part.

Come back to your application, open App_start/Startup.Auth.cs and uncomment the following snippet

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "",
            ClientSecret = ""
        });

Update the ClientId and ClientSecret with the values from Google API credentials which you have created already.

  • Run your application
  • Click Login
  • You will see the Google button under ‘Use Another Section to log in’ section
  • Click on the Google button
  • Application will prompt you to enter the username and password
  • Enter the gmail username and password and click Sign In
  • This will perform the OAuth and come back to your application and prompting you to register with the Gmail id.
  • Click register to register the Gmail id into your application database.
  • You will see the Identity details appear in the top as normal registration
  • Try logout and login again thru Gmail. This will automatically logs you into the app.

Build Maven Project Without Running Unit Tests

Run following command:

mvn clean install -DskipTests=true

How do I group Windows Form radio buttons?

All radio buttons inside of a share container are in the same group by default. Means, if you check one of them - others will be unchecked. If you want to create independent groups of radio buttons, you must situate them into different containers such as Group Box, or control their Checked state through code behind.

Bind class toggle to window scroll event

Thanks to Flek for answering my question in his comment:

http://jsfiddle.net/eTTZj/30/

<div ng-app="myApp" scroll id="page" ng-class="{min:boolChangeClass}">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 scope.boolChangeClass = true;
             } else {
                 scope.boolChangeClass = false;
             }
            scope.$apply();
        });
    };
});

Best way to check if a character array is empty

if (!*text) {}  

The above dereferences the pointer 'text' and checks to see if it's zero. alternatively:

if (*text == 0) {} 

What is the Regular Expression For "Not Whitespace and Not a hyphen"

It can be done much easier:

\S which equals [^ \t\r\n\v\f]

How do I style (css) radio buttons and labels?

This will get your buttons and labels next to each other, at least. I believe the second part can't be done in css alone, and will need javascript. I found a page that might help you with that part as well, but I don't have time right now to try it out: http://www.webmasterworld.com/forum83/6942.htm

<style type="text/css">
.input input {
  float: left;
}
.input label {
  margin: 5px;
}
</style>
<div class="input radio">
    <fieldset>
        <legend>What color is the sky?</legend>
        <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1"  />
        <label for="SubmitQuestion1">A strange radient green.</label>

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2"  />
        <label for="SubmitQuestion2">A dark gloomy orange</label>
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3"  />
        <label for="SubmitQuestion3">A perfect glittering blue</label>
    </fieldset>
</div>

What is event bubbling and capturing?

Bubbling

  Event propagate to the upto root element is **BUBBLING**.

Capturing

  Event propagate from body(root) element to eventTriggered Element is **CAPTURING**.

Iterating Over Dictionary Key Values Corresponding to List in Python

Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from __future__ you can do simplify things a bit.

Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.

from __future__ import division

def Pythag(league):
    def win_percentages():
        for team, (runs_scored, runs_allowed) in league.iteritems():
            win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
            yield win_percentage

    for win_percentage in win_percentages():
        print win_percentage

Getting a list of all subdirectories in the current directory

This will list all subdirectories right down the file tree.

import pathlib


def list_dir(dir):
    path = pathlib.Path(dir)
    dir = []
    try:
        for item in path.iterdir():
            if item.is_dir():
                dir.append(item)
                dir = dir + list_dir(item)
        return dir
    except FileNotFoundError:
        print('Invalid directory')

pathlib is new in version 3.4

PHP preg_replace special characters

If you by writing "non letters and numbers" exclude more than [A-Za-z0-9] (ie. considering letters like åäö to be letters to) and want to be able to accurately handle UTF-8 strings \p{L} and \p{N} will be of aid.

  1. \p{N} will match any "Number"
  2. \p{L} will match any "Letter Character", which includes
    • Lower case letter
    • Modifier letter
    • Other letter
    • Title case letter
    • Upper case letter

Documentation PHP: Unicode Character Properties


$data = "Thäre!wouldn't%bé#äny";

$new_data = str_replace  ("'", "", $data);
$new_data = preg_replace ('/[^\p{L}\p{N}]/u', '_', $new_data);

var_dump (
  $new_data
);

output

string(23) "Thäre_wouldnt_bé_äny"

How to Navigate from one View Controller to another using Swift

SWIFT 3.01

let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)

How do I remove time part from JavaScript date?

This is probably the easiest way:

new Date(<your-date-object>.toDateString());

Example: To get the Current Date without time component:

new Date(new Date().toDateString());

gives: Thu Jul 11 2019 00:00:00 GMT-0400 (Eastern Daylight Time)

Note this works universally, because toDateString() produces date string with your browser's localization (without the time component), and the new Date() uses the same localization to parse that date string.

Selenium Webdriver move mouse to Point

Got it working with

Actions builder = new Actions(driver);
WebElement el = some element;
builder.keyDown(Keys.CONTROL)
.moveByOffset( 10, 25 )
.clickAndHold(el)
.build().perform();

In Chart.js set chart title, name of x axis and y axis?

In Chart.js version 2.0, it is possible to set labels for axes:

options = {
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: 'probability'
      }
    }]
  }     
}

See Labelling documentation for more details.

How to set data attributes in HTML elements

[jQuery] .data() vs .attr() vs .extend()

The jQuery method .data() updates an internal object managed by jQuery through the use of the method, if I'm correct.

If you'd like to update your data-attributes with some spread, use --

$('body').attr({ 'data-test': 'text' });

-- otherwise, $('body').attr('data-test', 'text'); will work just fine.

Another way you could accomplish this is using --

$.extend( $('body')[0].dataset, { datum: true } );

-- which restricts any attribute change to HTMLElement.prototype.dataset, not any additional HTMLElement.prototype.attributes.

How can I implement custom Action Bar with custom buttons in Android?

Please write following code in menu.xml file:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:my_menu_tutorial_app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.example.mymenus.menu_app.MainActivity">
<item android:id="@+id/item_one"
      android:icon="@drawable/menu_icon"
      android:orderInCategory="l01"
      android:title="Item One"
      my_menu_tutorial_app:showAsAction="always">
      <!--sub-menu-->
      <menu>
          <item android:id="@+id/sub_one"
                android:title="Sub-menu item one" />
          <item android:id="@+id/sub_two"
                android:title="Sub-menu item two" />
      </menu>

Also write this java code in activity class file:

public boolean onOptionsItemSelected(MenuItem item)
{
    super.onOptionsItemSelected(item);
    Toast.makeText(this, "Menus item selected: " +
        item.getTitle(), Toast.LENGTH_SHORT).show();
    switch (item.getItemId())
    {
        case R.id.sub_one:
            isItemOneSelected = true;
            supportInvalidateOptionsMenu();
            return true;
        case MENU_ITEM + 1:
            isRemoveItem = true;
            supportInvalidateOptionsMenu();
            return true;
        default:
            return false;
    }
}

This is the easiest way to display menus in action bar.

"&" meaning after variable type

The & means that the function accepts the address (or reference) to a variable, instead of the value of the variable.

For example, note the difference between this:

void af(int& g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

And this (without the &):

void af(int g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

Shorthand for if-else statement

?: Operator

If you want to shorten If/Else you can use ?: operator as:

condition ? action-on-true : action-on-false(else)

For instance:

let gender = isMale ? 'Male' : 'Female';

In this case else part is mandatory.

&& Operator

In another case, if you have only if condition you can use && operator as:

condition && action;

For instance:

!this.settings && (this.settings = new TableSettings());

FYI: You have to try to avoid using if-else or at least decrease using it and try to replace it with Polymorphism or Inheritance. Go for being Anti-If guy.

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

My issue resolve via following Steps

  1. File->Import (android-sdk\extras\android\support\v7\appcompat)

  2. Right Click Project-> properties->Android. In the section library "Add" and choose library appcompat that's include in step 1

  3. Delete all files from project's libs directory

  4. add following file to project's libs directory <SDK-PATH>\extras\android\support\v13android-support-v13.jar

    Restart Eclipse if required. That's it. Your problem should be disappeared.

Convert varchar to float IF ISNUMERIC

..extending Mikaels' answers

SELECT
  CASE WHEN ISNUMERIC(QTY + 'e0') = 1 THEN CAST(QTY AS float) ELSE null END AS MyFloat
  CASE WHEN ISNUMERIC(QTY + 'e0') = 0 THEN QTY ELSE null END AS MyVarchar
FROM
  ...
  • Two data types requires two columns
  • Adding e0 fixes some ISNUMERIC issues (such as + - . and empty string being accepted)

Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes

Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so

import pandas
df = pandas.DataFrame(columns=['to','fr','ans'])
df.to = [pandas.Timestamp('2014-01-24 13:03:12.050000'), pandas.Timestamp('2014-01-27 11:57:18.240000'), pandas.Timestamp('2014-01-23 10:07:47.660000')]
df.fr = [pandas.Timestamp('2014-01-26 23:41:21.870000'), pandas.Timestamp('2014-01-27 15:38:22.540000'), pandas.Timestamp('2014-01-23 18:50:41.420000')]
(df.fr-df.to).astype('timedelta64[h]')

to yield,

0    58
1     3
2     8
dtype: float64

Is it possible to use jQuery to read meta tags

Would this parser help you?

https://github.com/fiann/jquery.ogp

It parses meta OG data to JSON, so you can just use the data directly. If you prefer, you can read/write them directly using JQuery, of course. For example:

$("meta[property='og:title']").attr("content", document.title);
$("meta[property='og:url']").attr("content", location.toString());

Note the single-quotes around the attribute values; this prevents parse errors in jQuery.

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

Update:

The plugin previously mentioned has been abandoned, but it apparently has an up-to-date fork here.

Old Answer:

I use the Android Studio plugin named Android Drawable Importer:

enter image description here

To use it after installed, right click your res/drawable folder and select New > Batch Drawable Import:

Then select your image via the + button and set the Resolution to be xxhdpi (or whatever the resolution of your source image is).

Installing Oracle Instant Client

If you want to use SQL Server Management Studio, you want to install the full Oracle client, not the Instant Client. The full Oracle client is on the same download page as the Oracle database. Assuming that you are installing on a 64-bit version of Windows, I expect you want the "Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64)" download. This is several hundred MB rather than a couple of MB for the Instant Client.

How to create a property for a List<T>

Either specify the type of T, or if you want to make it generic, you'll need to make the parent class generic.

public class MyClass<T>
{
  etc

How to return value from function which has Observable subscription inside?

For example this is my html template:

<select class="custom-select d-block w-100" id="genre" name="genre"
                  [(ngModel)]="film.genre"
                  #genreInput="ngModel"
                  required>
            <option value="">Choose...</option>
            <option *ngFor="let genre of genres;" [value]="genre.value">{{genre.name}}</option>
          </select>

This is the field that binded with template from my Component:

  // Genres of films like action or drama that will populate dropdown list.
  genres: Genre[];

I fetch genres of films from server dynamically. In order do communicate with server I have created FilmService

This is the method which communicate server:

 fetchGenres(): Observable<Genre[]> {
    return this.client.get(WebUtils.RESOURCE_HOST_API + 'film' + '/genre') as Observable<Genre[]>;
  }

Why this method returns Observable<Genre[]> not something like Genre[]?

JavaScript is async and it does not wait for a method to return value after an expensive process. With expensive I mean a process that take a time to return value. Like fetching data from server. So you have to return reference of Observable and subscribe it.

For example in my Component :

ngOnInit() {
    this.filmService.fetchGenres().subscribe(
      val => this.genres = val
    );
  }

An error occurred while collecting items to be installed (Access is denied)

I got this error on my ubuntu box until I ran eclipse as root and installed from there:

$ gksudo eclipse

Eclipse was trying to download the packages to /usr/lib/* where I don't have write permissions

Double array initialization in Java

double m[][] declares an array of arrays, so called multidimensional array.

m[0] points to an array in the size of four, containing 0*0,1*0,2*0,3*0. Simple math shows the values are actually 0,0,0,0.

Second line is also array in the size of four, containing 0,1,2,3.

And so on...

I guess this mutiple format in you book was to show that 0*0 is row 0 column 0, 0*1 is row 0 column 1, and so on.

disable textbox using jquery?

I'm not sure why some of these solutions use .each() - it's not necessary.

Here's some working code that disables if the 3rd checkbox is clicked, otherwise is removes the disabled attribute.

Note: I added an id to the checkbox. Also, remember that ids must be unique in your document, so either remove the ids on the radiobuttons, or make them unique

$("input:radio[name='userradiobtn']").click(function() {
    var isDisabled = $(this).is(":checked") && $(this).val() == "3";
    $("#chkbox").attr("disabled", isDisabled);
    $("#usertxtbox").attr("disabled", isDisabled);
});

in angularjs how to access the element that triggered the event?

The general Angular way to get access to an element that triggered an event is to write a directive and bind() to the desired event:

app.directive('myChange', function() {
  return function(scope, element) {
    element.bind('change', function() {
      alert('change on ' + element);
    });
  };
});

or with DDO (as per @tpartee's comment below):

app.directive('myChange', function() {
  return { 
    link:  function link(scope, element) {
      element.bind('change', function() {
        alert('change on ' + element);
      });
    }
  }
});

The above directive can be used as follows:

<input id="searchText" ng-model="searchText" type="text" my-change>

Plunker.

Type into the text field, then leave/blur. The change callback function will fire. Inside that callback function, you have access to element.

Some built-in directives support passing an $event object. E.g., ng-*click, ng-Mouse*. Note that ng-change does not support this event.

Although you can get the element via the $event object:

<button ng-click="clickit($event)">Hello</button>

$scope.clickit = function(e) {
    var elem = angular.element(e.srcElement);
    ...

this goes "deep against the Angular way" -- Misko.

JavaScript OR (||) variable assignment explanation

There isn't any magic to it. Boolean expressions like a || b || c || d are lazily evaluated. Interpeter looks for the value of a, it's undefined so it's false so it moves on, then it sees b which is null, which still gives false result so it moves on, then it sees c - same story. Finally it sees d and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.

This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).

Getting full URL of action in ASP.NET MVC

There is an overload of Url.Action that takes your desired protocol (e.g. http, https) as an argument - if you specify this, you get a fully qualified URL.

Here's an example that uses the protocol of the current request in an action method:

var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);

HtmlHelper (@Html) also has an overload of the ActionLink method that you can use in razor to create an anchor element, but it also requires the hostName and fragment parameters. So I'd just opt to use @Url.Action again:

<span>
  Copy
  <a href='@Url.Action("About", "Home", null, Request.Url.Scheme)'>this link</a> 
  and post it anywhere on the internet!
</span>

How to make the main content div fill height of screen with css

Although this might sounds like an easy issue, but it's actually not!

I've tried many things to achieve what you're trying to do with pure CSS, and all my tries were failure. But.. there's a possible solution if you use javascript or jquery!

Assuming you have this CSS:

#myheader {
    width: 100%;
}
#mybody {
    width: 100%;
}
#myfooter {
    width: 100%;
}

Assuming you have this HTML:

<div id="myheader">HEADER</div>
<div id="mybody">BODY</div>
<div id="myfooter">FOOTER</div>

Try this with jquery:

<script>
    $(document).ready(function() {
        var windowHeight = $(window).height();/* get the browser visible height on screen */
        var headerHeight = $('#myheader').height();/* get the header visible height on screen */
        var bodyHeight = $('#mybody').height();/* get the body visible height on screen */
        var footerHeight = $('#myfooter').height();/* get the footer visible height on screen */
        var newBodyHeight = windowHeight - headerHeight - footerHeight;
        if(newBodyHeight > 0 && newBodyHeight > bodyHeight) {
            $('#mybody').height(newBodyHeight);
        }
    });
</script>

Note: I'm not using absolute positioning in this solution, as it might look ugly in mobile browsers

Django auto_now and auto_now_add

As for your Admin display, see this answer.

Note: auto_now and auto_now_add are set to editable=False by default, which is why this applies.

How to set background color of an Activity to white programmatically?

To get the root view defined in your xml file, without action bar, you can use this:

View root = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);

So, to change color to white:

root.setBackgroundResource(Color.WHITE);

current/duration time of html5 video?

This page might help you out. Everything you need to know about HTML5 video and audio

var video = document.createElement('video');
var curtime = video.currentTime;

If you already have the video element, .currentTime should work. If you need more details, that webpage should be able to help.

Including .cpp files

Using ".h" method is better But if you really want to include the .cpp file then make foo(int) static in foo.cpp

Accessing member of base class

You are incorrectly using the super and this keyword. Here is an example of how they work:

class Animal {
    public name: string;
    constructor(name: string) { 
        this.name = name;
    }
    move(meters: number) {
        console.log(this.name + " moved " + meters + "m.");
    }
}

class Horse extends Animal {
    move() {
        console.log(super.name + " is Galloping...");
        console.log(this.name + " is Galloping...");
        super.move(45);
    }
}

var tom: Animal = new Horse("Tommy the Palomino");

Animal.prototype.name = 'horseee'; 

tom.move(34);
// Outputs:

// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.

Explanation:

  1. The first log outputs super.name, this refers to the prototype chain of the object tom, not the object tom self. Because we have added a name property on the Animal.prototype, horseee will be outputted.
  2. The second log outputs this.name, the this keyword refers to the the tom object itself.
  3. The third log is logged using the move method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);. Using the super keyword in this context will look for a move method on the prototype chain which is found on the Animal prototype.

Remember TS still uses prototypes under the hood and the class and extends keywords are just syntactic sugar over prototypical inheritance.

IE Driver download location Link for Selenium

Use the below link to download IE Driver latest version

IE Driver

How to use glob() to find files recursively?

pathlib.Path.rglob

Use pathlib.Path.rglob from the the pathlib module, which was introduced in Python 3.5.

from pathlib import Path

for path in Path('src').rglob('*.c'):
    print(path.name)

If you don't want to use pathlib, use can use glob.glob('**/*.c'), but don't forget to pass in the recursive keyword parameter and it will use inordinate amount of time on large directories.

For cases where matching files beginning with a dot (.); like files in the current directory or hidden files on Unix based system, use the os.walk solution below.

os.walk

For older Python versions, use os.walk to recursively walk a directory and fnmatch.filter to match against a simple expression:

import fnmatch
import os

matches = []
for root, dirnames, filenames in os.walk('src'):
    for filename in fnmatch.filter(filenames, '*.c'):
        matches.append(os.path.join(root, filename))

Unable to load script from assets index.android.bundle on windows

I think you don't have yarn installed try installing it with chocolatey or something. It should be installed before creating your project (react-native init command).

No need of creating assets directory.

Reply if it doesn't work.

Edit: In the recent version of react-native they have fixed it. If you want complete freedom from this just uninstall node (For complete uninstallation Completely remove node refer this link) and reinstall node, react-native-cli then create your new project.

Validate select box

you want to make sure that the user selects anything but "Choose an option" (which is the default one). So that it won't validate if you choose the first option. How can this be done?

You can do this by simple adding attribute required = "required" in the select tag. you can see it in below code

<select id="select" required="required">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>

It worked fine for me at chorme, firefox and internet explorer. Thanks

How to add external JS scripts to VueJS Components

Are you using one of the Webpack starter templates for vue (https://github.com/vuejs-templates/webpack)? It already comes set up with vue-loader (https://github.com/vuejs/vue-loader). If you're not using a starter template, you have to set up webpack and vue-loader.

You can then import your scripts to the relevant (single file) components. Before that, you have toexport from your scripts what you want to import to your components.

ES6 import:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
- http://exploringjs.com/es6/ch_modules.html

~Edit~
You can import from these wrappers:
- https://github.com/matfish2/vue-stripe
- https://github.com/khoanguyen96/vue-paypal-checkout

How to paste text to end of every line? Sublime 2

You can use the Search & Replace feature with this regex ^([\w\d\_\.\s\-]*)$ to find text and the replaced text is "$1".

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

use this filter:

(dns.flags.response == 0) and (ip.src == 159.25.78.7)

what this query does is it only gives dns queries originated from your ip

How to print jquery object/array

_x000D_
_x000D_
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];_x000D_
var data = arrofobject.map(arrofobject => arrofobject);_x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

for more details please look at jQuery.map()

How to change onClick handler dynamically?

The YUI example above should really be:

<script>
  YAHOO.util.Event.onDOMReady(function() {   
     Dom.get("foo").onclick =  function (){alert('foo');};
  });
</script>

What is the maximum length of a valid email address?

The other answers muddy the water a bit. Simple answer: 254 total chars in our control for email 256 are for the ENTIRE email address, which includes implied "<" at the beginning, and ">" at the end. Therefore, 254 are left over for our use.

How to parse JSON in Kotlin?

i am using my custom implementation in kotlin:

/**
 * Created by Anton Kogan on 10/9/2020
 */
object JsonParser {

    val TAG = "JsonParser"
    /**
 * parse json object
 * @param objJson
 * @param include - all  keys, that you want to display
 * @return  Map<String, String>
 * @throws JSONException
 */
    @Throws(JSONException::class)
    fun parseJson(objJson: Any?, map :HashMap<String, String>, include : Array<String>?): Map<String, String> {
        // If obj is a json array
        if (objJson is JSONArray) {
            for (i in 0 until objJson.length()) {
                parseJson(objJson[i], map, include)
            }
        } else if (objJson is JSONObject) {
            val it: Iterator<*> = objJson.keys()
            while (it.hasNext()) {
                val key = it.next().toString()
                // If you get an array
                when (val jobject = objJson[key]) {
                    is JSONArray -> {
                        Log.e(TAG, " JSONArray: $jobject")
                        parseJson(
                            jobject, map, include
                        )
                    }
                    is JSONObject -> {
                        Log.e(TAG, " JSONObject: $jobject")
                        parseJson(
                            jobject, map, include
                        )
                    }
                    else -> {
//
                        if(include == null || include.contains(key)) // here is check for include param
                        {
                            map[key] = jobject.toString()
                            Log.e(TAG, " adding to map: $key $jobject")
                        }
                    }
                }
            }
        }
        return map
    }

    /**
     * parse json object
     * @param objJson
     * @param include - all  keys, that you want to display
     * @return  Map<String, String>
     * @throws JSONException
     */
    @Throws(JSONException::class)
    fun parseJson(objJson: Any?, map :HashMap<String, String>): Map<String, String> {
        return parseJson(objJson, map, null)
    }
}

You can use it like:

    val include= arrayOf(
        "atHome",//JSONArray
        "cat",
        "dog",
        "persons",//JSONArray
        "man",
        "woman"
    )
    JsonParser.parseJson(jsonObject, map, include)
    val linearContent: LinearLayout = taskInfoFragmentBinding.infoContainer

here is some useful links:

json parsing :

plugin: https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-

create POJOs from json: https://codebeautify.org/jsonviewer

Retrofit: https://square.github.io/retrofit/

Gson: https://github.com/google/gson

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

Packing and byte alignment, as described in the C FAQ here:

It's for alignment. Many processors can't access 2- and 4-byte quantities (e.g. ints and long ints) if they're crammed in every-which-way.

Suppose you have this structure:

struct {
    char a[3];
    short int b;
    long int c;
    char d[3];
};

Now, you might think that it ought to be possible to pack this structure into memory like this:

+-------+-------+-------+-------+
|           a           |   b   |
+-------+-------+-------+-------+
|   b   |           c           |
+-------+-------+-------+-------+
|   c   |           d           |
+-------+-------+-------+-------+

But it's much, much easier on the processor if the compiler arranges it like this:

+-------+-------+-------+
|           a           |
+-------+-------+-------+
|       b       |
+-------+-------+-------+-------+
|               c               |
+-------+-------+-------+-------+
|           d           |
+-------+-------+-------+

In the packed version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers will pad the structure (as if with extra, invisible fields) like this:

+-------+-------+-------+-------+
|           a           | pad1  |
+-------+-------+-------+-------+
|       b       |     pad2      |
+-------+-------+-------+-------+
|               c               |
+-------+-------+-------+-------+
|           d           | pad3  |
+-------+-------+-------+-------+

List comprehension vs map

Here is one possible case:

map(lambda op1,op2: op1*op2, list1, list2)

versus:

[op1*op2 for op1,op2 in zip(list1,list2)]

I am guessing the zip() is an unfortunate and unnecessary overhead you need to indulge in if you insist on using list comprehensions instead of the map. Would be great if someone clarifies this whether affirmatively or negatively.

Using .NET, how can you find the mime type of a file based on the file signature not the extension

If you're using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note that this uses the file extension, not data in the file itself.

Documentation is at http://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping

Creating a constant Dictionary in C#

Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.

There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:

switch (myString)
{
   case "cat": return 0;
   case "dog": return 1;
   case "elephant": return 3;
}

This is exactly what you want. And yes, I know, it's ugly.

load Js file in HTML

If this is your detail.html I don't see where do you load detail.js? Maybe this

<script src="js/index.js"></script>

should be this

<script src="js/detail.js"></script>

?

javascript push multidimensional array

Use []:

cookie_value_add.push([productID,itemColorTitle, itemColorPath]);

or

arrayToPush.push([value1, value2, ..., valueN]);

How should I copy Strings in Java?

Second case is also inefficient in terms of String pool, you have to explicitly call intern() on return reference to make it intern.

How to determine the version of Gradle?

You can also add the following line to your build script:

println "Running gradle version: $gradle.gradleVersion"

or (it won't be printed with -q switch)

logger.lifecycle "Running gradle version: $gradle.gradleVersion"

m2e lifecycle-mapping not found

Try using the build/pluginManagement section, e.g. :

<pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.eclipse.m2e</groupId>
            <artifactId>lifecycle-mapping</artifactId>
            <version>1.0.0</version>
            <configuration>
                <lifecycleMappingMetadata>
                    <pluginExecutions>
                        <pluginExecution>
                            <pluginExecutionFilter>
                                <groupId>org.bsc.maven</groupId>
                                <artifactId>maven-processor-plugin</artifactId>
                                <versionRange>[2.0.2,)</versionRange>
                                <goals>
                                    <goal>process</goal>
                                </goals>
                            </pluginExecutionFilter>
                            <action>
                                <execute />
                            </action>
                        </pluginExecution>
                    </pluginExecutions>                         
                </lifecycleMappingMetadata>
            </configuration>
        </plugin>
    </plugins>
</pluginManagement>

Here's an example to generate bundle manifest during incremental compilation inside Eclipse :

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.felix</groupId>
                                    <artifactId>maven-bundle-plugin</artifactId>
                                    <versionRange>[1.0.0,)</versionRange>
                                    <goals>
                                        <goal>manifest</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <execute />
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <version>2.3.7</version>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                </instructions>
            </configuration>
            <executions>
                <execution>
                    <id>manifest</id>
                    <phase>process-classes</phase>
                    <goals>
                        <goal>manifest</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

versionRange is required, if omitted m2e (as of 1.1.0) will throw NullPointerException.

How to Use UTF-8 Collation in SQL Server database?

No! It's not a joke.

Take a look here: http://msdn.microsoft.com/en-us/library/ms186939.aspx

Character data types that are either fixed-length, nchar, or variable-length, nvarchar, Unicode data and use the UNICODE UCS-2 character set.

And also here: http://en.wikipedia.org/wiki/UTF-16

The older UCS-2 (2-byte Universal Character Set) is a similar character encoding that was superseded by UTF-16 in version 2.0 of the Unicode standard in July 1996.

"pip install json" fails on Ubuntu

While it's true that json is a built-in module, I also found that on an Ubuntu system with python-minimal installed, you DO have python but you can't do import json. And then I understand that you would try to install the module using pip!

If you have python-minimal you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json module. The solution is to install an additional package, called libpython2.7-stdlib, to install all 'default' python libraries.

sudo apt install libpython2.7-stdlib

And then you can do import json in python and it would work!

How to remove all .svn directories from my application directories

What you wrote sends a list of newline separated file names (and paths) to rm, but rm doesn't know what to do with that input. It's only expecting command line parameters.

xargs takes input, usually separated by newlines, and places them on the command line, so adding xargs makes what you had work:

find . -name .svn | xargs rm -fr

xargs is intelligent enough that it will only pass as many arguments to rm as it can accept. Thus, if you had a million files, it might run rm 1,000,000/65,000 times (if your shell could accept 65,002 arguments on the command line {65k files + 1 for rm + 1 for -fr}).

As persons have adeptly pointed out, the following also work:

find . -name .svn -exec rm -rf {} \;
find . -depth -name .svn -exec rm -fr {} \;
find . -type d -name .svn -print0|xargs -0 rm -rf

The first two -exec forms both call rm for each folder being deleted, so if you had 1,000,000 folders, rm would be invoked 1,000,000 times. This is certainly less than ideal. Newer implementations of rm allow you to conclude the command with a + indicating that rm will accept as many arguments as possible:

find . -name .svn -exec rm -rf {} +

The last find/xargs version uses print0, which makes find generate output that uses \0 as a terminator rather than a newline. Since POSIX systems allow any character but \0 in the filename, this is truly the safest way to make sure that the arguments are correctly passed to rm or the application being executed.

In addition, there's a -execdir that will execute rm from the directory in which the file was found, rather than at the base directory and a -depth that will start depth first.

No module named _sqlite3

my python is build from source, the cause is missing options when exec configure python version:3.7.4

./configure --enable-loadable-sqlite-extensions --enable-optimizations
make
make install

fixed

Char array in a struct - incompatible assignment?

use strncpy to make sure you have no buffer overflow.

char name[]= "whatever_you_want";
strncpy( sara.first, name, sizeof(sara.first)-1 );
sara.first[sizeof(sara.first)-1] = 0;

Disabling Log4J Output in Java

If you want to turn off logging programmatically then use

List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for ( Logger logger : loggers ) {
    logger.setLevel(Level.OFF);
}

Return multiple values from a function, sub or type?

A function returns one value, but it can "output" any number of values. A sample code:

Function Test (ByVal Input1 As Integer, ByVal Input2 As Integer, _
ByRef Output1 As Integer, ByRef Output2 As Integer) As Integer

  Output1 = Input1 + Input2
  Output2 = Input1 - Input2
  Test = Output1 + Output2

End Function

Sub Test2()

  Dim Ret As Integer, Input1 As Integer, Input2 As Integer, _
  Output1 As integer, Output2 As Integer
  Input1 = 1
  Input2 = 2
  Ret = Test(Input1, Input2, Output1, Output2)
  Sheet1.Range("A1") = Ret     ' 2
  Sheet1.Range("A2") = Output1 ' 3
  Sheet1.Range("A3") = Output2 '-1

End Sub

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

Tell Ruby Program to Wait some amount of time

I find until very useful with sleep. example:

> time = Time.now
> sleep 2.seconds until Time.now > time + 10.seconds # breaks when true
# or something like
> sleep 1.seconds until !req.loading # suggested by ohsully

Unsetting array values in a foreach loop

foreach($images as $key => $image)
{
    if(in_array($image, array(
       'http://i27.tinypic.com/29ykt1f.gif',
       'http://img3.abload.de/img/10nxjl0fhco.gif',
       'http://i42.tinypic.com/9pp2tx.gif',
    ))
    {
        unset($images[$key]);
    }
}

Android dependency has different version for the compile and runtime

I resolved it by following what Eddi mentioned above,

 resolutionStrategy.eachDependency { details ->
            if (details.requested.group == 'com.android.support'
                    && !details.requested.name.contains('multidex') ) {
                details.useVersion "26.1.0"
            }
        }

Get driving directions using Google Maps API v2

This is what I am using,

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );     
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);

How to detect the character encoding of a text file?

I use Ude that is a C# port of Mozilla Universal Charset Detector. It is easy to use and gives some really good results.

How to catch segmentation fault in Linux?

C++ solution found here (http://www.cplusplus.com/forum/unices/16430/)

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void ouch(int sig)
{
    printf("OUCH! - I got signal %d\n", sig);
}
int main()
{
    struct sigaction act;
    act.sa_handler = ouch;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGINT, &act, 0);
    while(1) {
        printf("Hello World!\n");
        sleep(1);
    }
}

Programmatically navigate using React router

Those who are facing issues in implementing this on react-router v4.

Here is a working solution for navigating through the react app from redux actions.

history.js

import createHistory from 'history/createBrowserHistory'

export default createHistory()

App.js/Route.jsx

import { Router, Route } from 'react-router-dom'
import history from './history'
...
<Router history={history}>
 <Route path="/test" component={Test}/>
</Router>

another_file.js OR redux file

import history from './history' 

history.push('/test') // this should change the url and re-render Test component

All thanks to this comment: ReactTraining issues comment

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

I got the solution for onunload in all browsers except Opera by changing the Ajax asynchronous request into synchronous request.

xmlhttp.open("POST","LogoutAction",false);

It works well for all browsers except Opera.

how to parse json using groovy

Have you tried using JsonSlurper?

Example usage:

def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

What do you mean timestamp? If you mean milliseconds since the Unix epoch:

GregorianCalendar cal = new GregorianCalendar(2007, 9 - 1, 23);
long millis = cal.getTimeInMillis();

If you want an actual java.sql.Timestamp object:

Timestamp ts = new Timestamp(millis);

An "and" operator for an "if" statement in Bash

Quote:

The "-a" operator also doesn't work:

if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]

For a more elaborate explanation: [ and ] are not Bash reserved words. The if keyword introduces a conditional to be evaluated by a job (the conditional is true if the job's return value is 0 or false otherwise).

For trivial tests, there is the test program (man test).

As some find lines like if test -f filename; then foo bar; fi, etc. annoying, on most systems you find a program called [ which is in fact only a symlink to the test program. When test is called as [, you have to add ] as the last positional argument.

So if test -f filename is basically the same (in terms of processes spawned) as if [ -f filename ]. In both cases the test program will be started, and both processes should behave identically.

Here's your mistake: if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]] will parse to if + some job, the job being everything except the if itself. The job is only a simple command (Bash speak for something which results in a single process), which means the first word ([) is the command and the rest its positional arguments. There are remaining arguments after the first ].

Also not, [[ is indeed a Bash keyword, but in this case it's only parsed as a normal command argument, because it's not at the front of the command.

How to check edittext's text is email address or not?

I wrote a library that extends EditText which supports natively some validation methods and is actually very flexible.

Current, as I write, natively supported (through xml attributes) validation methods are:

  1. regexp: for custom regexp
  2. numeric: for an only numeric field
  3. alpha: for an alpha only field
  4. alphaNumeric: guess what?
  5. email: checks that the field is a valid email
  6. creditCard: checks that the field contains a valid credit card using Luhn Algorithm
  7. phone: checks that the field contains a valid phone number
  8. domainName: checks that field contains a valid domain name ( always passes the test in API Level < 8 )
  9. ipAddress: checks that the field contains a valid ip address webUrl: checks that the field contains a valid url ( always passes the test in API Level < 8 )
  10. nocheck: It does not check anything. (Default)

You can check it out here: https://github.com/vekexasia/android-form-edittext

Hope you enjoy it :)

In the page I linked you'll be able to find also an example for email validation. I'll copy the relative snippet here:

<com.andreabaccega.widget.FormEditText
       style="@android:style/Widget.EditText"
       whatever:test="email"
       android:id="@+id/et_email"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="@string/hint_email"
       android:inputType="textEmailAddress"
       />  

There is also a test app showcasing the library possibilities.

This is a screenshot of the app validating the email field.

email validation done thorugh xml+library

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

To view your iOS device's console in Safari on your Mac (Mac only apparently):

  1. On your iOS device, go to Settings > Safari > Advanced and switch on Web Inspector
  2. On your iOS device, load your web page in Safari
  3. Connect your device directly to your Mac
  4. On your Mac, if you've not already got Safari's Developer menu activated, go to Preferences > Advanced, and select "Show Develop menu in menu bar"
  5. On your Mac, go to Develop > [your iOS device name] > [your web page]

Safari's Inspector will appear showing a console for your iOS device.

Where to download visual studio express 2005?

For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html

EDIT: In case that blog dies, here are the links from the blog.

All the bellow files are more them 400MB.

Visual Web Developer 2005 Express Edition
449,848 KB
.IMG File | .ISO File

Visual Basic 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C# 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C++ 2005 Express Edition
474,686 KB
.IMG File | .ISO File

Visual J# 2005 Express Edition
448,702 KB
.IMG File | .ISO File

How to access model hasMany Relation with where condition?

Just in case anyone else encounters the same problems.

Note, that relations are required to be camelcase. So in my case available_videos() should have been availableVideos().

You can easily find out investigating the Laravel source:

// Illuminate\Database\Eloquent\Model.php
...
/**
 * Get an attribute from the model.
 *
 * @param  string  $key
 * @return mixed
 */
public function getAttribute($key)
{
    $inAttributes = array_key_exists($key, $this->attributes);

    // If the key references an attribute, we can just go ahead and return the
    // plain attribute value from the model. This allows every attribute to
    // be dynamically accessed through the _get method without accessors.
    if ($inAttributes || $this->hasGetMutator($key))
    {
        return $this->getAttributeValue($key);
    }

    // If the key already exists in the relationships array, it just means the
    // relationship has already been loaded, so we'll just return it out of
    // here because there is no need to query within the relations twice.
    if (array_key_exists($key, $this->relations))
    {
        return $this->relations[$key];
    }

    // If the "attribute" exists as a method on the model, we will just assume
    // it is a relationship and will load and return results from the query
    // and hydrate the relationship's value on the "relationships" array.
    $camelKey = camel_case($key);

    if (method_exists($this, $camelKey))
    {
        return $this->getRelationshipFromMethod($key, $camelKey);
    }
}

This also explains why my code worked, whenever I loaded the data using the load() method before.

Anyway, my example works perfectly okay now, and $model->availableVideos always returns a Collection.

How to catch a specific SqlException error?

If you are looking for a better way to handle SQLException, there are a couple things you could do. First, Spring.NET does something similar to what you are looking for (I think). Here is a link to what they are doing:

http://springframework.net/docs/1.2.0/reference/html/dao.html

Also, instead of looking at the message, you could check the error code (sqlEx.Number). That would seem to be a better way of identifying which error occurred. The only problem is that the error number returned might be different for each database provider. If you plan to switch providers, you will be back to handling it the way you are or creating an abstraction layer that translates this information for you.

Here is an example of a guy who used the error code and a config file to translate and localize user-friendly error messages:

https://web.archive.org/web/20130731181042/http://weblogs.asp.net/guys/archive/2005/05/20/408142.aspx

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

It might be a wrong path. Ensure in your main app file you have:

app.use(express.static(path.join(__dirname,"public")));

Example link to your css as:

<link href="/css/clean-blog.min.css" rel="stylesheet">

similar for link to js files:

<script src="/js/clean-blog.min.js"></script>

Arrays.asList() of an array

As far as I understand it, the sort function in the collection class can only be used to sort collections implementing the comparable interface.

You are supplying it a array of integers. You should probably wrap this around one of the know Wrapper classes such as Integer. Integer implements comparable.

Its been a long time since I have worked on some serious Java, however reading some matter on the sort function will help.

How do I test for an empty JavaScript object?

If jQuery and the web browser is not available, there is also an isEmpty function in underscore.js.

_.isEmpty({}) // returns true

Additionally, it does not assume the input parameter to be an object. For a list or string or undefined, it will also turn the correct answer.

Bind TextBox on Enter-key press

I personally think having a Markup Extension is a cleaner approach.

public class UpdatePropertySourceWhenEnterPressedExtension : MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return new DelegateCommand<TextBox>(textbox => textbox.GetBindingExpression(TextBox.TextProperty).UpdateSource());
    }
}


<TextBox x:Name="TextBox"
             Text="{Binding Text}">
        <TextBox.InputBindings>
            <KeyBinding Key="Enter"
                        Command="{markupExtensions:UpdatePropertySourceWhenEnterPressed}" 
                        CommandParameter="{Binding ElementName=TextBox}"/>
        </TextBox.InputBindings>
</TextBox>

Like Operator in Entity Framework?

I don't know anything about EF really, but in LINQ to SQL you usually express a LIKE clause using String.Contains:

where entity.Name.Contains("xyz")

translates to

WHERE Name LIKE '%xyz%'

(Use StartsWith and EndsWith for other behaviour.)

I'm not entirely sure whether that's helpful, because I don't understand what you mean when you say you're trying to implement LIKE. If I've misunderstood completely, let me know and I'll delete this answer :)

MySQL integer field is returned as string in PHP

My solution is to pass the query result $rs and get a assoc array of the casted data as the return:

function cast_query_results($rs) {
    $fields = mysqli_fetch_fields($rs);
    $data = array();
    $types = array();
    foreach($fields as $field) {
        switch($field->type) {
            case 3:
                $types[$field->name] = 'int';
                break;
            case 4:
                $types[$field->name] = 'float';
                break;
            default:
                $types[$field->name] = 'string';
                break;
        }
    }
    while($row=mysqli_fetch_assoc($rs)) array_push($data,$row);
    for($i=0;$i<count($data);$i++) {
        foreach($types as $name => $type) {
            settype($data[$i][$name], $type);
        }
    }
    return $data;
}

Example usage:

$dbconn = mysqli_connect('localhost','user','passwd','tablename');
$rs = mysqli_query($dbconn, "SELECT * FROM Matches");
$matches = cast_query_results($rs);
// $matches is now a assoc array of rows properly casted to ints/floats/strings

overlay two images in android to set an imageview

ok just so you know there is a program out there that's called DroidDraw. It can help you draw objects and try them one on top of the other. I tried your solution but I had animation under the smaller image so that didn't work. But then I tried to place one image in a relative layout that's suppose to be under first and then on top of that I drew the other image that is suppose to overlay and everything worked great. So RelativeLayout, DroidDraw and you are good to go :) Simple, no any kind of jiggery pockery :) and here is a bit of code for ya:

The logo is going to be on top of shazam background image.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="@+id/widget39"
android:layout_width="219px"
android:layout_height="225px"
android:src="@drawable/shazam_bkgd"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
<ImageView
android:id="@+id/widget37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/shazam_logo"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
</ImageView>
</RelativeLayout>

Form onSubmit determine which submit button was pressed

OP stated he didn't want to modify the code for the buttons. This is the least-intrusive answer I could come up with using the other answers as a guide. It doesn't require additional hidden fields, allows you to leave the button code intact (sometimes you don't have access to what generates it), and gives you the info you were looking for from anywhere in your code...which button was used to submit the form. I haven't evaluated what happens if the user uses the Enter key to submit the form, rather than clicking.

<script language="javascript" type="text/javascript">

    var initiator = '';
    $(document).ready(function() {
        $(":submit").click(function() { initiator = this.name });
    });

</script>

Then you have access to the 'initiator' variable anywhere that might need to do the checking. Hope this helps.

~Spanky

How to write both h1 and h2 in the same line?

Put the h1 and h2 in a container with an id of container then:

#container {
    display: flex;
    justify-content: space-beteen;
}

Count all occurrences of a string in lots of files with grep

Another oneliner using basic command line functions handling multiple occurences per line.

 cat * |sed s/string/\\\nstring\ /g |grep string |wc -l

I'm getting Key error in python

Let us make it simple if you're using Python 3

mydict = {'a':'apple','b':'boy','c':'cat'}
check = 'c' in mydict
if check:
    print('c key is present')

If you need else condition

mydict = {'a':'apple','b':'boy','c':'cat'}
if 'c' in mydict:
    print('key present')
else:
    print('key not found')

For the dynamic key value, you can also handle through try-exception block

mydict = {'a':'apple','b':'boy','c':'cat'}
try:
    print(mydict['c'])
except KeyError:
    print('key value not found')mydict = {'a':'apple','b':'boy','c':'cat'}

2 column div layout: right column with fixed width, left fluid

Simplest and most flexible solution so far it to use table display:

HTML, left div comes first, right div comes second ... we read and write left to right, so it won't make any sense to place the divs right to left

<div class="container">
    <div class="left">
        left content flexible width
    </div>
    <div class="right">
        right content fixed width
    </div>
</div>

CSS:

.container {
  display: table;
  width: 100%;
}

.left {
  display: table-cell;
  width: (whatever you want: 100%, 150px, auto)
}??

.right {
  display: table-cell;
  width: (whatever you want: 100%, 150px, auto)
}

Cases examples:

// One div is 150px fixed width ; the other takes the rest of the width
.left {width: 150px} .right {width: 100%}

// One div is auto to its inner width ; the other takes the rest of the width
.left {width: 100%} .right {width: auto}

Fragment pressing back button

What I do in this cases is I implement the onBackPressed() function from the Activity:

@Override
public void onBackPressed() {
   super.onBackPressed();
   FragmentManager fm = getSupportFragmentManager();
   MyFragment myFragment = (MyFragment) fm.findFragmentById(R.id.my_fragment);

   if((myFragmen.isVisible()){
      //Do what you want to do
   }
}

How this works for you too.

Load HTML page dynamically into div with jQuery

I think you are looking for the Jquery Load function. You would just use that function with an onclick function tied to the a tag or a button if you like.

Regular expression for matching latitude/longitude coordinates?

I believe you're using \w (word character) where you ought to be using \s (whitespace). Word characters typically consist of [A-Za-z0-9_], so that excludes your space, which then further fails to match on the optional minus sign or a digit.

Creating a button in Android Toolbar

They are called menu items or action buttons in toolbar/actionbar. Here you have Google tutorial how it works and how to add them https://developer.android.com/training/basics/actionbar/adding-buttons.html

Convert objective-c typedef to its string equivalent

My solution:

edit: I've added even a better solution at the end, using Modern Obj-C

1.
Put names as keys in an array.
Make sure the indexes are the appropriate enums, and in the right order (otherwise exception).
note: names is a property synthesized as *_names*;

code was not checked for compilation, but I used the same technique in my app.

typedef enum {
  JSON,
  XML,
  Atom,
  RSS
} FormatType;

+ (NSArray *)names
{
    static NSMutableArray * _names = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _names = [NSMutableArray arrayWithCapacity:4];
        [_names insertObject:@"JSON" atIndex:JSON];
        [_names insertObject:@"XML" atIndex:XML];
        [_names insertObject:@"Atom" atIndex:Atom];
        [_names insertObject:@"RSS" atIndex:RSS];
    });

    return _names;
}

+ (NSString *)nameForType:(FormatType)type
{
    return [[self names] objectAtIndex:type];
}


//

2.
Using Modern Obj-C you we can use a dictionary to tie descriptions to keys in the enum.
Order DOES NOT matter.

typedef NS_ENUM(NSUInteger, UserType) {
    UserTypeParent = 0,
    UserTypeStudent = 1,
    UserTypeTutor = 2,
    UserTypeUnknown = NSUIntegerMax
};  

@property (nonatomic) UserType type;

+ (NSDictionary *)typeDisplayNames
{
    return @{@(UserTypeParent) : @"Parent",
             @(UserTypeStudent) : @"Student",
             @(UserTypeTutor) : @"Tutor",
             @(UserTypeUnknown) : @"Unknown"};
}

- (NSString *)typeDisplayName
{
    return [[self class] typeDisplayNames][@(self.type)];
}


Usage (in a class instance method):

NSLog(@"%@", [self typeDisplayName]);


How to assign the output of a Bash command to a variable?

You can also do way more complex commands, just to round out the examples above. So, say I want to get the number of processes running on the system and store it in the ${NUM_PROCS} variable.

All you have to so is generate the command pipeline and stuff it's output (the process count) into the variable.

It looks something like this:

NUM_PROCS=$(ps -e | sed 1d | wc -l)

I hope that helps add some handy information to this discussion.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Define make variable at rule execution time

In your example, the TMP variable is set (and the temporary directory created) whenever the rules for out.tar are evaluated. In order to create the directory only when out.tar is actually fired, you need to move the directory creation down into the steps:

out.tar : 
    $(eval TMP := $(shell mktemp -d))
    @echo hi $(TMP)/hi.txt
    tar -C $(TMP) cf $@ .
    rm -rf $(TMP)

The eval function evaluates a string as if it had been typed into the makefile manually. In this case, it sets the TMP variable to the result of the shell function call.

edit (in response to comments):

To create a unique variable, you could do the following:

out.tar : 
    $(eval $@_TMP := $(shell mktemp -d))
    @echo hi $($@_TMP)/hi.txt
    tar -C $($@_TMP) cf $@ .
    rm -rf $($@_TMP)

This would prepend the name of the target (out.tar, in this case) to the variable, producing a variable with the name out.tar_TMP. Hopefully, that is enough to prevent conflicts.

How can query string parameters be forwarded through a proxy_pass with nginx?

I modified @kolbyjack code to make it work for

http://website1/service
http://website1/service/

with parameters

location ~ ^/service/?(.*) {
    return 301 http://service_url/$1$is_args$args;
}

Open local folder from link

add on click open local directory o local file to google chrome:

The solution from JFish222 works ( URL file solution )

For Webkid Browsers like Chrome on Apache Servers just add to .htaccess o http.config this code:

SetEnvIf Request_URI ".url$" requested_url=url Header add Content-Disposition "attachment" env=requested_url

And by the first downlod of your url file click on the file in chromes downloadbar and select "always open this file".

Create a git patch from the uncommitted changes in the current working directory

We could also specify the files, to include just the files with relative changes, particularly when they span multiple directories e.x.

git diff ~/path1/file1.ext ~/path2/file2.ext...fileN.ext > ~/whatever_path/whatever_name.patch

I found this to be not specified in the answers or comments, which are all relevant and correct, so chose to add it. Explicit is better than implicit!

Calculate rolling / moving average in C++

I used a deque... seems to work for me. This example has a vector, but you could skip that aspect and simply add them to deque.

#include <deque>

template <typename T>
double mov_avg(vector<T> vec, int len){
  deque<T> dq = {};
  for(auto i = 0;i < vec.size();i++){
    if(i < len){
      dq.push_back(vec[i]);
    }
    else {
      dq.pop_front();
      dq.push_back(vec[i]);
    }
  }
  double cs = 0;
  for(auto i : dq){
    cs += i;
  }
  return cs / len;
}



//Skip the vector portion, track the input number (or size of deque), and the value.


  double len = 10;
  double val; //Accept as input
  double instance; //Increment each time input accepted.

  deque<double> dq;
  if(instance < len){
      dq.push_back(val);
  }
  else {
      dq.pop_front();
      dq.push_back(val);
    }
  }
  double cs = 0;
  for(auto i : dq){
    cs += i;
  }
  double rolling_avg = cs / len;

//To simplify further -- add values to this, then simply average the deque.

 int MAX_DQ = 3;
 void add_to_dq(deque<double> &dq, double value){
    if(dq.size() < MAX_DQ){
      dq.push_back(value);
    }else {
      dq.pop_front();
      dq.push_back(value);
    }
  }
 

Another sort of hack I use occasionally is using mod to overwrite values in a vector.

  vector<int> test_mod = {0,0,0,0,0};
  int write = 0;
  int LEN = 5;
  
  int instance = 0; //Filler for N -- of Nth Number added.
  int value = 0; //Filler for new number.

  write = instance % LEN;
  test_mod[write] = value;
  //Will write to 0, 1, 2, 3, 4, 0, 1, 2, 3, ...
  //Then average it for MA.

  //To test it...
  int write_idx = 0;
  int len = 5;
  int new_value;
  for(auto i=0;i<100;i++){
      cin >> new_value;
      write_idx = i % len;
      test_mod[write_idx] = new_value;

This last (hack) has no buckets, buffers, loops, nothing. Simply a vector that's overwritten. And it's 100% accurate (for avg / values in vector). Proper order is rarely maintained, as it starts rewriting backwards (at 0), so 5th index would be at 0 in example {5,1,2,3,4}, etc.

C# 4.0: Convert pdf to byte[] and vice versa

// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);

// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself

// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);

How to validate domain name in PHP?

Firstly, you should clarify whether you mean:

  1. individual domain name labels
  2. entire domain names (i.e. multiple dot-separate labels)
  3. host names

The reason the distinction is necessary is that a label can technically include any characters, including the NUL, @ and '.' characters. DNS is 8-bit capable and it's perfectly possible to have a zone file containing an entry reading "an\0odd\.l@bel". It's not recommended of course, not least because people would have difficulty telling a dot inside a label from those separating labels, but it is legal.

However, URLs require a host name in them, and those are governed by RFCs 952 and 1123. Valid host names are a subset of domain names. Specifically only letters, digits and hyphen are allowed. Furthermore the first and last characters cannot be a hyphen. RFC 952 didn't permit a number for the first character, but RFC 1123 subsequently relaxed that.

Hence:

  • a - valid
  • 0 - valid
  • a- - invalid
  • a-b - valid
  • xn--dasdkhfsd - valid (punycode encoding of an IDN)

Off the top of my head I don't think it's possible to invalidate the a- example with a single simple regexp. The best I can come up with to check a single host label is:

if (preg_match('/^[a-z\d][a-z\d-]{0,62}$/i', $label) &&
   !preg_match('/-$/', $label))
{
    # label is legal within a hostname
}

To further complicate matters, some domain name entries (typically SRV records) use labels prefixed with an underscore, e.g. _sip._udp.example.com. These are not host names, but are legal domain names.

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

The book seems to indicate that those commands yield the same effect:

The simple case is the example you just saw, running git checkout -b [branch] [remotename]/[branch]. If you have Git version 1.6.2 or later, you can also use the --track shorthand:

$ git checkout --track origin/serverfix 
Branch serverfix set up to track remote branch serverfix from origin. 
Switched to a new branch 'serverfix' 

To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:

$ git checkout -b sf origin/serverfix

That's particularly handy when your bash or oh-my-zsh git completions are able to pull the origin/serverfix name for you - just append --track (or -t) and you are on your way.

How to debug "ImagePullBackOff"?

I faced the similar situation and it turned out that with the actualisation of Docker Desktop I was signed out and after I signed back in all works fine again.

Correct way to use StringBuilder in SQL

[[ There are some good answers here but I find that they still are lacking a bit of information. ]]

return (new StringBuilder("select id1, " + " id2 " + " from " + " table"))
     .toString();

So as you point out, the example you give is a simplistic but let's analyze it anyway. What happens here is the compiler actually does the + work here because "select id1, " + " id2 " + " from " + " table" are all constants. So this turns into:

return new StringBuilder("select id1,  id2  from  table").toString();

In this case, obviously, there is no point in using StringBuilder. You might as well do:

// the compiler combines these constant strings
return "select id1, " + " id2 " + " from " + " table";

However, even if you were appending any fields or other non-constants then the compiler would use an internal StringBuilder -- there's no need for you to define one:

// an internal StringBuilder is used here
return "select id1, " + fieldName + " from " + tableName;

Under the covers, this turns into code that is approximately equivalent to:

StringBuilder sb = new StringBuilder("select id1, ");
sb.append(fieldName).append(" from ").append(tableName);
return sb.toString();

Really the only time you need to use StringBuilder directly is when you have conditional code. For example, code that looks like the following is desperate for a StringBuilder:

// 1 StringBuilder used in this line
String query = "select id1, " + fieldName + " from " + tableName;
if (where != null) {
   // another StringBuilder used here
   query += ' ' + where;
}

The + in the first line uses one StringBuilder instance. Then the += uses another StringBuilder instance. It is more efficient to do:

// choose a good starting size to lower chances of reallocation
StringBuilder sb = new StringBuilder(64);
sb.append("select id1, ").append(fieldName).append(" from ").append(tableName);
// conditional code
if (where != null) {
   sb.append(' ').append(where);
}
return sb.toString();

Another time that I use a StringBuilder is when I'm building a string from a number of method calls. Then I can create methods that take a StringBuilder argument:

private void addWhere(StringBuilder sb) {
   if (where != null) {
      sb.append(' ').append(where);
   }
}

When you are using a StringBuilder, you should watch for any usage of + at the same time:

sb.append("select " + fieldName);

That + will cause another internal StringBuilder to be created. This should of course be:

sb.append("select ").append(fieldName);

Lastly, as @T.J.rowder points out, you should always make a guess at the size of the StringBuilder. This will save on the number of char[] objects created when growing the size of the internal buffer.

Update multiple rows with different values in a single SQL query

There's a couple of ways to accomplish this decently efficiently.

First -
If possible, you can do some sort of bulk insert to a temporary table. This depends somewhat on your RDBMS/host language, but at worst this can be accomplished with a simple dynamic SQL (using a VALUES() clause), and then a standard update-from-another-table. Most systems provide utilities for bulk load, though

Second -
And this is somewhat RDBMS dependent as well, you could construct a dynamic update statement. In this case, where the VALUES(...) clause inside the CTE has been created on-the-fly:

WITH Tmp(id, px, py) AS (VALUES(id1, newsPosX1, newPosY1), 
                               (id2, newsPosX2, newPosY2),
                               ......................... ,
                               (idN, newsPosXN, newPosYN))

UPDATE TableToUpdate SET posX = (SELECT px
                                 FROM Tmp
                                 WHERE TableToUpdate.id = Tmp.id),
                         posY = (SELECT py
                                 FROM Tmp
                                 WHERE TableToUpdate.id = Tmp.id)


WHERE id IN (SELECT id
             FROM Tmp)

(According to the documentation, this should be valid SQLite syntax, but I can't get it to work in a fiddle)

What does the PHP error message "Notice: Use of undefined constant" mean?

Insert single quotes.

Example

$department = mysql_real_escape_string($_POST['department']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST['message']); 

error while loading shared libraries: libncurses.so.5:

In Fedora 28 use:

sudo dnf install ncurses-compat-libs

Specifying and saving a figure with exact size in pixels

Matplotlib doesn't work with pixels directly, but rather physical sizes and DPI. If you want to display a figure with a certain pixel size, you need to know the DPI of your monitor. For example this link will detect that for you.

If you have an image of 3841x7195 pixels it is unlikely that you monitor will be that large, so you won't be able to show a figure of that size (matplotlib requires the figure to fit in the screen, if you ask for a size too large it will shrink to the screen size). Let's imagine you want an 800x800 pixel image just for an example. Here's how to show an 800x800 pixel image in my monitor (my_dpi=96):

plt.figure(figsize=(800/my_dpi, 800/my_dpi), dpi=my_dpi)

So you basically just divide the dimensions in inches by your DPI.

If you want to save a figure of a specific size, then it is a different matter. Screen DPIs are not so important anymore (unless you ask for a figure that won't fit in the screen). Using the same example of the 800x800 pixel figure, we can save it in different resolutions using the dpi keyword of savefig. To save it in the same resolution as the screen just use the same dpi:

plt.savefig('my_fig.png', dpi=my_dpi)

To to save it as an 8000x8000 pixel image, use a dpi 10 times larger:

plt.savefig('my_fig.png', dpi=my_dpi * 10)

Note that the setting of the DPI is not supported by all backends. Here, the PNG backend is used, but the pdf and ps backends will implement the size differently. Also, changing the DPI and sizes will also affect things like fontsize. A larger DPI will keep the same relative sizes of fonts and elements, but if you want smaller fonts for a larger figure you need to increase the physical size instead of the DPI.

Getting back to your example, if you want to save a image with 3841 x 7195 pixels, you could do the following:

plt.figure(figsize=(3.841, 7.195), dpi=100)
( your code ...)
plt.savefig('myfig.png', dpi=1000)

Note that I used the figure dpi of 100 to fit in most screens, but saved with dpi=1000 to achieve the required resolution. In my system this produces a png with 3840x7190 pixels -- it seems that the DPI saved is always 0.02 pixels/inch smaller than the selected value, which will have a (small) effect on large image sizes. Some more discussion of this here.

How can I get the Windows last reboot reason

Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).

scipy.misc module has no attribute imread?

I have all the packages required for the image extraction on jupyter notebook, but even then it shows me the same error.

Error on Jupyter Notebook

Reading the above comments, I have installed the required packages. Please do tell if I have missed some packages.

pip3 freeze | grep -i -E "pillow|scipy|scikit-image"
Pillow==5.4.1
scikit-image==0.14.2

scipy==1.2.1

Running a simple shell script as a cronjob

The easiest way would be to use a GUI:

For Gnome use gnome-schedule (universe)

sudo apt-get install gnome-schedule 

For KDE use kde-config-cron

It should be pre installed on Kubuntu

But if you use a headless linux or don´t want GUI´s you may use:

crontab -e

If you type it into Terminal you´ll get a table.
You have to insert your cronjobs now.
Format a job like this:

*     *     *     *     *  YOURCOMMAND
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- Day in Week (0 to 7) (Sunday is 0 and 7)
|     |     |     +------- Month (1 to 12)
|     |     +--------- Day in Month (1 to 31)
|     +----------- Hour (0 to 23)
+------------- Minute (0 to 59)

There are some shorts, too (if you don´t want the *):

@reboot --> only once at startup
@daily ---> once a day
@midnight --> once a day at midnight
@hourly --> once a hour
@weekly --> once a week
@monthly --> once a month
@annually --> once a year
@yearly --> once a year

If you want to use the shorts as cron (because they don´t work or so):

@daily --> 0 0 * * *
@midnight --> 0 0 * * *
@hourly --> 0 * * * *
@weekly --> 0 0 * * 0
@monthly --> 0 0 1 * *
@annually --> 0 0 1 1 *
@yearly --> 0 0 1 1 *

Access Tomcat Manager App from different host

Each deployed webapp has a context.xml file that lives in

$CATALINA_BASE/conf/[enginename]/[hostname]

(conf/Catalina/localhost by default)

and has the same name as the webapp (manager.xml in this case). If no file is present, default values are used.

So, you need to create a file conf/Catalina/localhost/manager.xml and specify the rule you want to allow remote access. For example, the following content of manager.xml will allow access from all machines:

<Context privileged="true" antiResourceLocking="false" 
         docBase="${catalina.home}/webapps/manager">
    <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^YOUR.IP.ADDRESS.HERE$" />
</Context>

Note that the allow attribute of the Valve element is a regular expression that matches the IP address of the connecting host. So substitute your IP address for YOUR.IP.ADDRESS.HERE (or some other useful expression).

Other Valve classes cater for other rules (e.g. RemoteHostValve for matching host names). Earlier versions of Tomcat use a valve class org.apache.catalina.valves.RemoteIpValve for IP address matching.

Once the changes above have been made, you should be presented with an authentication dialog when accessing the manager URL. If you enter the details you have supplied in tomcat-users.xml you should have access to the Manager.

Stopword removal with NLTK

You can use string.punctuation with built-in NLTK stopwords list:

from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from string import punctuation

words = tokenize(text)
wordsWOStopwords = removeStopWords(words)

def tokenize(text):
        sents = sent_tokenize(text)
        return [word_tokenize(sent) for sent in sents]

def removeStopWords(words):
        customStopWords = set(stopwords.words('english')+list(punctuation))
        return [word for word in words if word not in customStopWords]

NLTK stopwords complete list

How can I copy columns from one sheet to another with VBA in Excel?

Selecting is often unnecessary. Try this

Sub OneCell()
    Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
End Sub

Limit text length to n lines using CSS

Working Cross-browser Solution

This problem has been plaguing us all for years.

To help in all cases, I have laid out the CSS only approach, and a jQuery approach in case the css caveats are a problem.

Here's a CSS only solution I came up with that works in all circumstances, with a few minor caveats.

The basics are simple, it hides the overflow of the span, and sets the max height based on the line height as suggested by Eugene Xa.

Then there is a pseudo class after the containing div that places the ellipsis nicely.

Caveats

This solution will always place the ellipsis, regardless if there is need for it.

If the last line ends with an ending sentence, you will end up with four dots....

You will need to be happy with justified text alignment.

The ellipsis will be to the right of the text, which can look sloppy.

Code + Snippet

jsfiddle

_x000D_
_x000D_
.text {_x000D_
  position: relative;_x000D_
  font-size: 14px;_x000D_
  color: black;_x000D_
  width: 250px; /* Could be anything you like. */_x000D_
}_x000D_
_x000D_
.text-concat {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  word-wrap: break-word;_x000D_
  overflow: hidden;_x000D_
  max-height: 3.6em; /* (Number of lines you want visible) * (line-height) */_x000D_
  line-height: 1.2em;_x000D_
  text-align:justify;_x000D_
}_x000D_
_x000D_
.text.ellipsis::after {_x000D_
  content: "...";_x000D_
  position: absolute;_x000D_
  right: -12px; _x000D_
  bottom: 4px;_x000D_
}_x000D_
_x000D_
/* Right and bottom for the psudo class are px based on various factors, font-size etc... Tweak for your own needs. */
_x000D_
<div class="text ellipsis">_x000D_
  <span class="text-concat">_x000D_
Lorem ipsum dolor sit amet, nibh eleifend cu his, porro fugit mandamus no mea. Sit tale facete voluptatum ea, ad sumo altera scripta per, eius ullum feugait id duo. At nominavi pericula persecuti ius, sea at sonet tincidunt, cu posse facilisis eos. Aliquid philosophia contentiones id eos, per cu atqui option disputationi, no vis nobis vidisse. Eu has mentitum conclusionemque, primis deterruisset est in._x000D_
_x000D_
Virtute feugait ei vim. Commune honestatis accommodare pri ex. Ut est civibus accusam, pro principes conceptam ei, et duo case veniam. Partiendo concludaturque at duo. Ei eirmod verear consequuntur pri. Esse malis facilisis ex vix, cu hinc suavitate scriptorem pri._x000D_
  </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery Approach

In my opinion this is the best solution, but not everyone can use JS. Basically, the jQuery will check any .text element, and if there are more chars than the preset max var, it will cut the rest off and add an ellipsis.

There are no caveats to this approach, however this code example is meant only to demonstrate the basic idea - I wouldn't use this in production without improving on it for a two reasons:

1) It will rewrite the inner html of .text elems. whether needed or not. 2) It does no test to check that the inner html has no nested elems - so you are relying a lot on the author to use the .text correctly.

Edited

Thanks for the catch @markzzz

Code & Snippet

jsfiddle

_x000D_
_x000D_
setTimeout(function()_x000D_
{_x000D_
 var max = 200;_x000D_
  var tot, str;_x000D_
  $('.text').each(function() {_x000D_
   str = String($(this).html());_x000D_
   tot = str.length;_x000D_
    str = (tot <= max)_x000D_
     ? str_x000D_
      : str.substring(0,(max + 1))+"...";_x000D_
    $(this).html(str);_x000D_
  });_x000D_
},500); // Delayed for example only.
_x000D_
.text {_x000D_
  position: relative;_x000D_
  font-size: 14px;_x000D_
  color: black;_x000D_
  font-family: sans-serif;_x000D_
  width: 250px; /* Could be anything you like. */_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p class="text">_x000D_
Old men tend to forget what thought was like in their youth; they forget the quickness of the mental jump, the daring of the youthful intuition, the agility of the fresh insight. They become accustomed to the more plodding varieties of reason, and because this is more than made up by the accumulation of experience, old men think themselves wiser than the young._x000D_
</p>_x000D_
_x000D_
<p class="text">_x000D_
Old men tend to forget what thought was like in their youth;_x000D_
</p>_x000D_
 <!-- Working Cross-browser Solution_x000D_
_x000D_
This is a jQuery approach to limiting a body of text to n words, and end with an ellipsis -->
_x000D_
_x000D_
_x000D_

PHP: Update multiple MySQL fields in single query

Add your multiple columns with comma separations:

UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'

However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?

Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.

How to animate GIFs in HTML document?

By default browser always plays animated gifs, and you can't change that behaviour. If gif image does not animate there can be 2 ways to look: something wrong with the browser, something wrong with the image. Then to exclude the first variant just check trusted image in your browser (run snippet below, this gif definitely animated and works in all browsers).

Your code looks OK. Can you check if this snippet is animated for you?
If YES, then something is bad with your gif, if NO something is wrong with your browser.

_x000D_
_x000D_
<img src="http://i.stack.imgur.com/SBv4T.gif" alt="this slowpoke moves"  width=250/>
_x000D_
_x000D_
_x000D_

Failed to resolve: com.google.firebase:firebase-core:16.0.1

I was able to solve the issue by following these steps-

1.) This error occurs when you didn't connect your project to firebase. Do that from Tools->Firebase if you are using Android studio version 2.2 or above.

2.) Make sure you have replaced the compile with implementation in dependencies in app/build.gradle

3.) Include your firebase dependency from the firebase docs. Everything should work fine now

php random x digit number

the simplest way i can think of is using rand function with str_pad

<?php
echo str_pad(rand(0,999), 5, "0", STR_PAD_LEFT);
?>

In above example , it will generate random number in range 0 to 999.

And having 5 digits.

OPENSSL file_get_contents(): Failed to enable crypto

Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html

For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432

Here is the example:

    $url = 'https://www.example.com/api/list';
    $cn_match = 'www.example.com';

    $data = array (     
        'apikey' => '[example api key here]',               
        'limit' => intval($limit),
        'offset' => intval($offset)
        );

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',                
            'content' => http_build_query($data)                
            )
        , 'ssl' => array(
            'verify_peer' => true,
            'cafile' => [path to file] . "cacert.pem",
            'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
            'CN_match' => $cn_match,
            'disable_compression' => true,
            )
        );

    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

Hope that helps

How to get the last value of an ArrayList

The last item in the list is list.size() - 1. The collection is backed by an array and arrays start at index 0.

So element 1 in the list is at index 0 in the array

Element 2 in the list is at index 1 in the array

Element 3 in the list is at index 2 in the array

and so on..

What is the difference between Forking and Cloning on GitHub?

In case you did what the questioner hinted at (forgot to fork and just locally cloned a repo, made changes and now need to issue a pull request) you can get back on track:

  1. fork the repo you want to send pull request to
  2. push your local changes to your remote
  3. issue pull request

Concatenation of strings in Lua

Concatenation:

The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in §2.2.1. Otherwise, the "concat" metamethod is called (see §2.8).

from: http://www.lua.org/manual/5.1/manual.html#2.5.4

Finding multiple occurrences of a string within a string in Python

I think there's no need to test for length of text; just keep finding until there's nothing left to find. Like this:

    >>> text = 'Allowed Hello Hollow'
    >>> place = 0
    >>> while text.find('ll', place) != -1:
            print('ll found at', text.find('ll', place))
            place = text.find('ll', place) + 2


    ll found at 1
    ll found at 10
    ll found at 16

Javascript - User input through HTML input tag to set a Javascript variable?

Late reading this, but.. The way I read your question, you only need to change two lines of code:

Accept user input, function writes back on screen.

<input type="text" id="userInput"=> give me input</input>
<button onclick="test()">Submit</button>

<!-- add this line for function to write into -->
<p id="demo"></p>   

<script type="text/javascript">
function test(){
    var userInput = document.getElementById("userInput").value;
    document.getElementById("demo").innerHTML = userInput;
}
</script>

How to get Enum Value from index in Java?

Here's three ways to do it.

public enum Months {
    JAN(1), FEB(2), MAR(3), APR(4), MAY(5), JUN(6), JUL(7), AUG(8), SEP(9), OCT(10), NOV(11), DEC(12);


    int monthOrdinal = 0;

    Months(int ord) {
        this.monthOrdinal = ord;
    }

    public static Months byOrdinal2ndWay(int ord) {
        return Months.values()[ord-1]; // less safe
    }

    public static Months byOrdinal(int ord) {
        for (Months m : Months.values()) {
            if (m.monthOrdinal == ord) {
                return m;
            }
        }
        return null;
    }
    public static Months[] MONTHS_INDEXED = new Months[] { null, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

}




import static junit.framework.Assert.assertEquals;

import org.junit.Test;

public class MonthsTest {

@Test
public void test_indexed_access() {
    assertEquals(Months.MONTHS_INDEXED[1], Months.JAN);
    assertEquals(Months.MONTHS_INDEXED[2], Months.FEB);

    assertEquals(Months.byOrdinal(1), Months.JAN);
    assertEquals(Months.byOrdinal(2), Months.FEB);


    assertEquals(Months.byOrdinal2ndWay(1), Months.JAN);
    assertEquals(Months.byOrdinal2ndWay(2), Months.FEB);
}

}

jQuery changing css class to div

An HTML element like div can have more than one classes. Let say div is assigned two styles using addClass method. If style1 has 3 properties like font-size, weight and color, and style2 has 4 properties like font-size, weight, color and background-color, the resultant effective properties set (style), i think, will have 4 properties i.e. union of all style sets. Common properties, in our case, color,font-size, weight, will have one occuerance with latest values. If div is assigned style1 first and style2 second, the common prpoerties will be overwritten by style2 values.

Further, I have written a post at Using JQuery to Apply,Remove and Manage Styles, I hope it will help you

Regards Awais

"git rm --cached x" vs "git reset head --? x"?

Perhaps an example will help:

git rm --cached asd
git commit -m "the file asd is gone from the repository"

versus

git reset HEAD -- asd
git commit -m "the file asd remains in the repository"

Note that if you haven't changed anything else, the second commit won't actually do anything.

How to access the elements of a function's return array?

you can do this:

list($a, $b, $c) = data();

print "$a $b $c"; // "abc def ghi"

Darken background image on hover

Add css:

.image{
    opacity:.5;
}

.image:hover{
    // CSS properties
    opacity:1;
}

Shell Scripting: Using a variable to define a path

Don't use spaces...

(Incorrect)

SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'

(Correct)

SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'

How to open a web server port on EC2 instance

You need to configure the security group as stated by cyraxjoe. Along with that you also need to open System port. Steps to open port in windows :-

  1. On the Start menu, click Run, type WF.msc, and then click OK.
  2. In the Windows Firewall with Advanced Security, in the left pane, right-click Inbound Rules, and then click New Rule in the action pane.
  3. In the Rule Type dialog box, select Port, and then click Next.
  4. In the Protocol and Ports dialog box, select TCP. Select Specific local ports, and then type the port number , such as 8787 for the default instance. Click Next.
  5. In the Action dialog box, select Allow the connection, and then click Next.
  6. In the Profile dialog box, select any profiles that describe the computer connection environment when you want to connect , and then click Next.
  7. In the Name dialog box, type a name and description for this rule, and then click Finish.

Ref:- Microsoft Docs for port Opening

Chosen Jquery Plugin - getting selected values

As of 2016, you can do this more simply than in any of the answers already given:

$('#myChosenBox').val();

where "myChosenBox" is the id of the original select input. Or, in the change event:

$('#myChosenBox').on('change', function(e, params) {
    alert(e.target.value); // OR
    alert(this.value); // OR
    alert(params.selected); // also in Panagiotis Kousaris' answer
}

In the Chosen doc, in the section near the bottom of the page on triggering events, it says "Chosen triggers a number of standard and custom events on the original select field." One of those standard events is the change event, so you can use it in the same way as you would with a standard select input. You don't have to mess around with using Chosen's applied classes as selectors if you don't want to. (For the change event, that is. Other events are often a different matter.)