Programs & Examples On #Getdibits

String Array object in Java

First, as for your Athlete class, you can remove your Getter and Setter methods since you have declared your instance variables with an access modifier of public. You can access the variables via <ClassName>.<variableName>.

However, if you really want to use that Getter and Setter, change the public modifier to private instead.

Second, for the constructor, you're trying to do a simple technique called shadowing. Shadowing is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing:
----------Shadowing sample----------
You have the following class:

public String name;

public Person(String name){
    this.name = name; // This is Shadowing
}

In your main method for example, you instantiate the Person class as follow:
Person person = new Person("theolc");

Variable name will be equal to "theolc".
----------End of shadowing----------

Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter. Remove your parameters on your constructor.

public class Athlete {

public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};

public Athlete() {

}

In your main method, you could do this.

public static void main(String[] args) {
       Athlete art = new Athlete();   

       System.out.println(art.name[0]);
       System.out.println(art.country[0]);
    }
}

How to add two edit text fields in an alert dialog

Check the following code. It shows 2 edit text fields programmatically without any layout xml. Change 'this' to 'getActivity()' if you use it in a fragment.

The tricky thing is we have to set the second text field's input type after creating alert dialog, otherwise, the second text field shows texts instead of dots.

    public void showInput() {
        OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
            @Override
            public void onFocusChange(final View v, boolean hasFocus) {
                if (hasFocus) {
                    // Must use message queue to show keyboard
                    v.post(new Runnable() {
                        @Override
                        public void run() {
                            InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                            inputMethodManager.showSoftInput(v, 0);
                        }
                    });
                }
            }
        };

        final EditText editTextName = new EditText(this);
        editTextName.setHint("Name");
        editTextName.setFocusable(true);
        editTextName.setClickable(true);
        editTextName.setFocusableInTouchMode(true);
        editTextName.setSelectAllOnFocus(true);
        editTextName.setSingleLine(true);
        editTextName.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        editTextName.setOnFocusChangeListener(onFocusChangeListener);

        final EditText editTextPassword = new EditText(this);
        editTextPassword.setHint("Password");
        editTextPassword.setFocusable(true);
        editTextPassword.setClickable(true);
        editTextPassword.setFocusableInTouchMode(true);
        editTextPassword.setSelectAllOnFocus(true);
        editTextPassword.setSingleLine(true);
        editTextPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
        editTextPassword.setOnFocusChangeListener(onFocusChangeListener);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(editTextName);
        linearLayout.addView(editTextPassword);

        DialogInterface.OnClickListener alertDialogClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    // Done button clicked
                    break;
                case DialogInterface.BUTTON_NEGATIVE:
                    // Cancel button clicked
                    break;
                }
            }
        };
        final AlertDialog alertDialog = (new AlertDialog.Builder(this)).setMessage("Please enter name and password")
                .setView(linearLayout)
                .setPositiveButton("Done", alertDialogClickListener)
                .setNegativeButton("Cancel", alertDialogClickListener)
                .create();

        editTextName.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                editTextPassword.requestFocus(); // Press Return to focus next one
                return false;
            }
        });
        editTextPassword.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // Press Return to invoke positive button on alertDialog.
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
                return false;
            }
        });

        // Must set password mode after creating alert dialog.
        editTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
        editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        alertDialog.show();
    }

Change primary key column in SQL Server

Assuming that your current primary key constraint is called pk_history, you can replace the following lines:

ALTER TABLE history ADD PRIMARY KEY (id)

ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name

with these:

ALTER TABLE history DROP CONSTRAINT pk_history

ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)

If you don't know what the name of the PK is, you can find it with the following query:

SELECT * 
  FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
 WHERE TABLE_NAME = 'history'

How to add reference to a method parameter in javadoc?

The correct way of referring to a method parameter is like this:

enter image description here

Reading CSV file and storing values into an array

Here's a special case where one of data field has semicolon (";") as part of it's data in that case most of answers above will fail.

Solution it that case will be

string[] csvRows = System.IO.File.ReadAllLines(FullyQaulifiedFileName);
string[] fields = null;
List<string> lstFields;
string field;
bool quoteStarted = false;
foreach (string csvRow in csvRows)
{
    lstFields = new List<string>();
    field = "";
    for (int i = 0; i < csvRow.Length; i++)
    {
        string tmp = csvRow.ElementAt(i).ToString();
        if(String.Compare(tmp,"\"")==0)
        {
            quoteStarted = !quoteStarted;
        }
        if (String.Compare(tmp, ";") == 0 && !quoteStarted)
        {
            lstFields.Add(field);
            field = "";
        }
        else if (String.Compare(tmp, "\"") != 0)
        {
            field += tmp;
        }
    }
    if(!string.IsNullOrEmpty(field))
    {
        lstFields.Add(field);
        field = "";
    }
// This will hold values for each column for current row under processing
    fields = lstFields.ToArray(); 
}

How to implement a material design circular progress bar in android

Was looking for a way to do this using simple xml, but couldn't find any helpful answers, so came up with this.

This works on pre-lollipop versions too, and is pretty close to the material design progress bar. You just need to use this drawable as the indeterminate drawable in the ProgressBar layout.

<?xml version="1.0" encoding="utf-8"?><!--<layer-list>-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360">
    <layer-list>
        <item>
            <rotate xmlns:android="http://schemas.android.com/apk/res/android"
                android:fromDegrees="-90"
                android:toDegrees="-90">
                <shape
                    android:innerRadiusRatio="2.5"
                    android:shape="ring"
                    android:thickness="2dp"
                    android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->

                    <gradient
                        android:angle="0"
                        android:endColor="#007DD6"
                        android:startColor="#007DD6"
                        android:type="sweep"
                        android:useLevel="false" />
                </shape>
            </rotate>
        </item>
        <item>
            <rotate xmlns:android="http://schemas.android.com/apk/res/android"
                android:fromDegrees="0"
                android:toDegrees="270">
                <shape
                    android:innerRadiusRatio="2.6"
                    android:shape="ring"
                    android:thickness="4dp"
                    android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->
                    <gradient
                        android:angle="0"
                        android:centerColor="#FFF"
                        android:endColor="#FFF"
                        android:startColor="#FFF"
                        android:useLevel="false" />
                </shape>
            </rotate>
        </item>
    </layer-list>
</rotate>

set the above drawable in ProgressBar as follows:

  android:indeterminatedrawable="@drawable/above_drawable"

nvarchar(max) vs NText

VARCHAR(MAX) is big enough to accommodate TEXT field. TEXT, NTEXT and IMAGE data types of SQL Server 2000 will be deprecated in future version of SQL Server, SQL Server 2005 provides backward compatibility to data types but it is recommended to use new data types which are VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX).

SQL injection that gets around mysql_real_escape_string()

The short answer is yes, yes there is a way to get around mysql_real_escape_string(). #For Very OBSCURE EDGE CASES!!!

The long answer isn't so easy. It's based off an attack demonstrated here.

The Attack

So, let's start off by showing the attack...

mysql_query('SET NAMES gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:

  1. Selecting a Character Set

    mysql_query('SET NAMES gbk');
    

    For this attack to work, we need the encoding that the server's expecting on the connection both to encode ' as in ASCII i.e. 0x27 and to have some character whose final byte is an ASCII \ i.e. 0x5c. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: big5, cp932, gb2312, gbk and sjis. We'll select gbk here.

    Now, it's very important to note the use of SET NAMES here. This sets the character set ON THE SERVER. If we used the call to the C API function mysql_set_charset(), we'd be fine (on MySQL releases since 2006). But more on why in a minute...

  2. The Payload

    The payload we're going to use for this injection starts with the byte sequence 0xbf27. In gbk, that's an invalid multibyte character; in latin1, it's the string ¿'. Note that in latin1 and gbk, 0x27 on its own is a literal ' character.

    We have chosen this payload because, if we called addslashes() on it, we'd insert an ASCII \ i.e. 0x5c, before the ' character. So we'd wind up with 0xbf5c27, which in gbk is a two character sequence: 0xbf5c followed by 0x27. Or in other words, a valid character followed by an unescaped '. But we're not using addslashes(). So on to the next step...

  3. mysql_real_escape_string()

    The C API call to mysql_real_escape_string() differs from addslashes() in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using latin1 for the connection, because we never told it otherwise. We did tell the server we're using gbk, but the client still thinks it's latin1.

    Therefore the call to mysql_real_escape_string() inserts the backslash, and we have a free hanging ' character in our "escaped" content! In fact, if we were to look at $var in the gbk character set, we'd see:

    ?' OR 1=1 /*

    Which is exactly what the attack requires.

  4. The Query

    This part is just a formality, but here's the rendered query:

    SELECT * FROM test WHERE name = '?' OR 1=1 /*' LIMIT 1
    

Congratulations, you just successfully attacked a program using mysql_real_escape_string()...

The Bad

It gets worse. PDO defaults to emulating prepared statements with MySQL. That means that on the client side, it basically does a sprintf through mysql_real_escape_string() (in the C library), which means the following will result in a successful injection:

$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Now, it's worth noting that you can prevent this by disabling emulated prepared statements:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

This will usually result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently fallback to emulating statements that MySQL can't prepare natively: those that it can are listed in the manual, but beware to select the appropriate server version).

The Ugly

I said at the very beginning that we could have prevented all of this if we had used mysql_set_charset('gbk') instead of SET NAMES gbk. And that's true provided you are using a MySQL release since 2006.

If you're using an earlier MySQL release, then a bug in mysql_real_escape_string() meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes even if the client had been correctly informed of the connection encoding and so this attack would still succeed. The bug was fixed in MySQL 4.1.20, 5.0.22 and 5.1.11.

But the worst part is that PDO didn't expose the C API for mysql_set_charset() until 5.3.6, so in prior versions it cannot prevent this attack for every possible command! It's now exposed as a DSN parameter.

The Saving Grace

As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. utf8mb4 is not vulnerable and yet can support every Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is utf8, which is also not vulnerable and can support the whole of the Unicode Basic Multilingual Plane.

Alternatively, you can enable the NO_BACKSLASH_ESCAPES SQL mode, which (amongst other things) alters the operation of mysql_real_escape_string(). With this mode enabled, 0x27 will be replaced with 0x2727 rather than 0x5c27 and thus the escaping process cannot create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. 0xbf27 is still 0xbf27 etc.)—so the server will still reject the string as invalid. However, see @eggyal's answer for a different vulnerability that can arise from using this SQL mode.

Safe Examples

The following examples are safe:

mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because the server's expecting utf8...

mysql_set_charset('gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because we've properly set the character set so the client and the server match.

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've turned off emulated prepared statements.

$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've set the character set properly.

$mysqli->query('SET NAMES gbk');
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "\xbf\x27 OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();

Because MySQLi does true prepared statements all the time.

Wrapping Up

If you:

  • Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) AND mysql_set_charset() / $mysqli->set_charset() / PDO's DSN charset parameter (in PHP = 5.3.6)

OR

  • Don't use a vulnerable character set for connection encoding (you only use utf8 / latin1 / ascii / etc)

You're 100% safe.

Otherwise, you're vulnerable even though you're using mysql_real_escape_string()...

How to take the nth digit of a number in python

I was curious about the relative speed of the two popular approaches - casting to string and using modular arithmetic - so I profiled them and was surprised to see how close they were in terms of performance.

(My use-case was slightly different, I wanted to get all digits in the number.)

The string approach gave:

         10000002 function calls in 1.113 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.113    0.000    1.113    0.000 sandbox.py:1(get_digits_str)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

While the modular arithmetic approach gave:


         10000002 function calls in 1.102 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.102    0.000    1.102    0.000 sandbox.py:6(get_digits_mod)
        1    0.000    0.000    0.000    0.000 cProfile.py:133(__exit__)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

There were 10^7 tests run with a max number size less than 10^28.

Code used for reference:

def get_digits_str(num):
    for n_str in str(num):
        yield int(n_str)


def get_digits_mod(num, radix=10):

    remaining = num
    yield remaining % radix

    while remaining := remaining // radix:
        yield remaining % radix


if __name__ == '__main__':

    import cProfile
    import random

    random_inputs = [random.randrange(0, 10000000000000000000000000000) for _ in range(10000000)]

    with cProfile.Profile() as str_profiler:
        for rand_num in random_inputs:
            get_digits_str(rand_num)

    str_profiler.print_stats(sort='cumtime')

    with cProfile.Profile() as mod_profiler:
        for rand_num in random_inputs:
            get_digits_mod(rand_num)

    mod_profiler.print_stats(sort='cumtime')

Regular expression include and exclude special characters

For the allowed characters you can use

^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$

to validate a complete string that should consist of only allowed characters. Note that - is at the end (because otherwise it'd be a range) and a few characters are escaped.

For the invalid characters you can use

[<>'"/;`%]

to check for them.

To combine both into a single regex you can use

^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])

but you'd need a regex engine that allows lookahead.

Is it possible to center text in select box?

2020, Im using:

select {
    text-align: center;
    text-align-last: center;
    -moz-text-align-last: center;
}

How to JUnit test that two List<E> contain the same elements in the same order?

assertTrue()/assertFalse() : to use only to assert boolean result returned

assertTrue(Iterables.elementsEqual(argumentComponents, returnedComponents));

You want to use Assert.assertTrue() or Assert.assertFalse() as the method under test returns a boolean value.
As the method returns a specific thing such as a List that should contain some expected elements, asserting with assertTrue() in this way : Assert.assertTrue(myActualList.containsAll(myExpectedList) is an anti pattern.
It makes the assertion easy to write but as the test fails, it also makes it hard to debug because the test runner will only say to you something like :

expected true but actual is false

Assert.assertEquals(Object, Object) in JUnit4 or Assertions.assertIterableEquals(Iterable, Iterable) in JUnit 5 : to use only as both equals() and toString() are overrided for the classes (and deeply) of the compared objects

It matters because the equality test in the assertion relies on equals() and the test failure message relies on toString() of the compared objects.
As String overrides both equals() and toString(), it is perfectly valid to assert the List<String> with assertEquals(Object,Object). And about this matter : you have to override equals() in a class because it makes sense in terms of object equality, not only to make assertions easier in a test with JUnit.
To make assertions easier you have other ways (that you can see in the next points of the answer).

Is Guava a way to perform/build unit test assertions ?

Is Google Guava Iterables.elementsEqual() the best way, provided I have the library in my build path, to compare those two lists?

No it is not. Guava is not an library to write unit test assertions.
You don't need it to write most (all I think) of unit tests.

What's the canonical way to compare lists for unit tests?

As a good practice I favor assertion/matcher libraries.

I cannot encourage JUnit to perform specific assertions because this provides really too few and limited features : it performs only an assertion with a deep equals.
Sometimes you want to allow any order in the elements, sometimes you want to allow that any elements of the expected match with the actual, and so for...

So using a unit test assertion/matcher library such as Hamcrest or AssertJ is the correct way.
The actual answer provides a Hamcrest solution. Here is a AssertJ solution.

org.assertj.core.api.ListAssert.containsExactly() is what you need : it verifies that the actual group contains exactly the given values and nothing else, in order as stated :

Verifies that the actual group contains exactly the given values and nothing else, in order.

Your test could look like :

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

@Test
void ofComponent_AssertJ() throws Exception {
   MyObject myObject = MyObject.ofComponents("One", "Two", "Three");
   Assertions.assertThat(myObject.getComponents())
             .containsExactly("One", "Two", "Three");
}

A AssertJ good point is that declaring a List as expected is needless : it makes the assertion straighter and the code more readable :

Assertions.assertThat(myObject.getComponents())
         .containsExactly("One", "Two", "Three");

And if the test fails :

// Fail : Three was not expected 
Assertions.assertThat(myObject.getComponents())
          .containsExactly("One", "Two");

you get a very clear message such as :

java.lang.AssertionError:

Expecting:

<["One", "Two", "Three"]>

to contain exactly (and in same order):

<["One", "Two"]>

but some elements were not expected:

<["Three"]>

Assertion/matcher libraries are a must because these will really further

Suppose that MyObject doesn't store Strings but Foos instances such as :

public class MyFooObject {

    private List<Foo> values;
    @SafeVarargs
    public static MyFooObject ofComponents(Foo... values) {
        // ...
    }

    public List<Foo> getComponents(){
        return new ArrayList<>(values);
    }
}

That is a very common need. With AssertJ the assertion is still simple to write. Better you can assert that the list content are equal even if the class of the elements doesn't override equals()/hashCode() while JUnit ways require that :

import org.assertj.core.api.Assertions;
import static org.assertj.core.groups.Tuple.tuple;
import org.junit.jupiter.api.Test;

@Test
void ofComponent() throws Exception {
    MyFooObject myObject = MyFooObject.ofComponents(new Foo(1, "One"), new Foo(2, "Two"), new Foo(3, "Three"));

    Assertions.assertThat(myObject.getComponents())
              .extracting(Foo::getId, Foo::getName)
              .containsExactly(tuple(1, "One"),
                               tuple(2, "Two"),
                               tuple(3, "Three"));
}

Resizing Images in VB.NET

This is basically Muhammad Saqib's answer except two diffs:

1: Adds width and height function parameters.

2: This is a small nuance which can be ignored... Saying 'As Bitmap', instead of 'As Image'. 'As Image' does work just fine. I just prefer to match Return types. See Image VS Bitmap Class.

Public Shared Function ResizeImage(ByVal InputBitmap As Bitmap, width As Integer, height As Integer) As Bitmap
    Return New Bitmap(InputImage, New Size(width, height))
End Function

Ex.

Dim someimage As New Bitmap("C:\somefile")
someimage = ResizeImage(someimage,800,600)

Differences between TCP sockets and web sockets, one more time

When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.

But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.

Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.

Best way to convert strings to symbols in hash

If you would like vanilla ruby solution and as me do not have access to ActiveSupport here is deep symbolize solution (very similar to previous ones)

    def deep_convert(element)
      return element.collect { |e| deep_convert(e) } if element.is_a?(Array)
      return element.inject({}) { |sh,(k,v)| sh[k.to_sym] = deep_convert(v); sh } if element.is_a?(Hash)
      element
    end

How to merge a Series and DataFrame

If I could suggest setting up your dataframes like this (auto-indexing):

df = pd.DataFrame({'a':[np.nan, 1, 2], 'b':[4, 5, 6]})

then you can set up your s1 and s2 values thus (using shape() to return the number of rows from df):

s = pd.DataFrame({'s1':[5]*df.shape[0], 's2':[6]*df.shape[0]})

then the result you want is easy:

display (df.merge(s, left_index=True, right_index=True))

Alternatively, just add the new values to your dataframe df:

df = pd.DataFrame({'a':[nan, 1, 2], 'b':[4, 5, 6]})
df['s1']=5
df['s2']=6
display(df)

Both return:

     a  b  s1  s2
0  NaN  4   5   6
1  1.0  5   5   6
2  2.0  6   5   6

If you have another list of data (instead of just a single value to apply), and you know it is in the same sequence as df, eg:

s1=['a','b','c']

then you can attach this in the same way:

df['s1']=s1

returns:

     a  b s1
0  NaN  4  a
1  1.0  5  b
2  2.0  6  c

window.onload vs document.onload

According to Parsing HTML documents - The end,

  1. The browser parses the HTML source and runs deferred scripts.

  2. A DOMContentLoaded is dispatched at the document when all the HTML has been parsed and have run. The event bubbles to the window.

  3. The browser loads resources (like images) that delay the load event.

  4. A load event is dispatched at the window.

Therefore, the order of execution will be

  1. DOMContentLoaded event listeners of window in the capture phase
  2. DOMContentLoaded event listeners of document
  3. DOMContentLoaded event listeners of window in the bubble phase
  4. load event listeners (including onload event handler) of window

A bubble load event listener (including onload event handler) in document should never be invoked. Only capture load listeners might be invoked, but due to the load of a sub-resource like a stylesheet, not due to the load of the document itself.

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('window - DOMContentLoaded - capture'); // 1st_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('document - DOMContentLoaded - capture'); // 2nd_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('document - DOMContentLoaded - bubble'); // 2nd_x000D_
});_x000D_
window.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('window - DOMContentLoaded - bubble'); // 3rd_x000D_
});_x000D_
_x000D_
window.addEventListener('load', function() {_x000D_
  console.log('window - load - capture'); // 4th_x000D_
}, true);_x000D_
document.addEventListener('load', function(e) {_x000D_
  /* Filter out load events not related to the document */_x000D_
  if(['style','script'].indexOf(e.target.tagName.toLowerCase()) < 0)_x000D_
    console.log('document - load - capture'); // DOES NOT HAPPEN_x000D_
}, true);_x000D_
document.addEventListener('load', function() {_x000D_
  console.log('document - load - bubble'); // DOES NOT HAPPEN_x000D_
});_x000D_
window.addEventListener('load', function() {_x000D_
  console.log('window - load - bubble'); // 4th_x000D_
});_x000D_
_x000D_
window.onload = function() {_x000D_
  console.log('window - onload'); // 4th_x000D_
};_x000D_
document.onload = function() {_x000D_
  console.log('document - onload'); // DOES NOT HAPPEN_x000D_
};
_x000D_
_x000D_
_x000D_

How to get exception message in Python properly

To improve on the answer provided by @artofwarfare, here is what I consider a neater way to check for the message attribute and print it or print the Exception object as a fallback.

try:
    pass 
except Exception as e:
    print getattr(e, 'message', repr(e))

The call to repr is optional, but I find it necessary in some use cases.


Update #1:

Following the comment by @MadPhysicist, here's a proof of why the call to repr might be necessary. Try running the following code in your interpreter:

try:
    raise Exception 
except Exception as e:
    print(getattr(e, 'message', repr(e)))
    print(getattr(e, 'message', str(e)))

Update #2:

Here is a demo with specifics for Python 2.7 and 3.5: https://gist.github.com/takwas/3b7a6edddef783f2abddffda1439f533

JavaScript backslash (\) in variables is causing an error

If you want to use special character in javascript variable value, Escape Character (\) is required.

Backslash in your example is special character, too.

So you should do something like this,

var ttt = "aa ///\\\\\\"; // --> ///\\\

or

var ttt = "aa ///\\"; // --> ///\

But Escape Character not require for user input.

When you press / in prompt box or input field then submit, that means single /.

How to send an HTTP request with a header parameter?

With your own Code and a Slight Change withou jQuery,

function testingAPI(){ 
    var key = "8a1c6a354c884c658ff29a8636fd7c18"; 
    var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
    console.log(httpGet(url,key)); 
}


function httpGet(url,key){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

Thank You

How to inherit constructors?

The problem is not that Bar and Bah have to copy 387 constructors, the problem is that Foo has 387 constructors. Foo clearly does too many things - refactor quick! Also, unless you have a really good reason to have values set in the constructor (which, if you provide a parameterless constructor, you probably don't), I'd recommend using property getting/setting.

Link to "pin it" on pinterest without generating a button

For such cases, I found very useful the Share Link Generator, it helps creating Facebook, Google+, Twitter, Pinterest, LinkedIn share buttons.

How to open standard Google Map application from my application?

You can also simply use http://maps.google.com/maps as your URI

String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "&daddr=" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);

or you can make sure that the Google Maps app only is used, this stops the intent filter (dialog) from appearing, by using

intent.setPackage("com.google.android.apps.maps");

like so:

String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "&daddr=" + destinationLatitude + "," + destinationLongitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

or you can add labels to the locations by adding a string inside parentheses after each set of coordinates like so:

String uri = "http://maps.google.com/maps?saddr=" + sourceLatitude + "," + sourceLongitude + "(" + "Home Sweet Home" + ")&daddr=" + destinationLatitude + "," + destinationLongitude + " (" + "Where the party is at" + ")";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

To use the users current location as the starting point (unfortunately I haven't found a way to label the current location) then just drop off the saddr parameter as follows:

String uri = "http://maps.google.com/maps?daddr=" + destinationLatitude + "," + destinationLongitude + " (" + "Where the party is at" + ")";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

For completeness, if the user doesn't have the maps app installed then it's going to be a good idea to catch the ActivityNotFoundException, as @TonyQ states, then we can start the activity again without the maps app restriction, we can be pretty sure that we will never get to the Toast at the end since an internet browser is a valid application to launch this url scheme too.

        String uri = "http://maps.google.com/maps?daddr=" + 12f + "," + 2f + " (" + "Where the party is at" + ")";
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        intent.setPackage("com.google.android.apps.maps");
        try
        {
            startActivity(intent);
        }
        catch(ActivityNotFoundException ex)
        {
            try
            {
                Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                startActivity(unrestrictedIntent);
            }
            catch(ActivityNotFoundException innerEx)
            {
                Toast.makeText(this, "Please install a maps application", Toast.LENGTH_LONG).show();
            }
        }

EDIT:

For directions, a navigation intent is now supported with google.navigation

Uri navigationIntentUri = Uri.parse("google.navigation:q=" + 12f + "," + 2f);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, navigationIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);

How can I remove an SSH key?

Unless I'm misunderstanding, you lost your .ssh directory containing your private key on your local machine and so you want to remove the public key which was on a server and which allowed key-based login.

In that case, it will be stored in the .ssh/authorized_keys file in your home directory on the server. You can just edit this file with a text editor and delete the relevant line if you can identify it (even easier if it's the only entry!).

I hope that key wasn't your only method of access to the server and you have some other way of logging in and editing the file. You can either manually add a new public key to authorised_keys file or use ssh-copy-id. Either way, you'll need password authentication set up for your account on the server, or some other identity or access method to get to the authorized_keys file on the server.

ssh-add adds identities to your SSH agent which handles management of your identities locally and "the connection to the agent is forwarded over SSH remote logins, and the user can thus use the privileges given by the identities anywhere in the network in a secure way." (man page), so I don't think it's what you want in this case. It doesn't have any way to get your public key onto a server without you having access to said server via an SSH login as far as I know.

Permissions for /var/www/html

You just need 775 for /var/www/html as long as you are logging in as myuser. The 7 octal in the middle (which is for "group" acl) ensures that the group has permission to read/write/execute. As long as you belong to the group that owns the files, "myuser" should be able to write to them. You may need to give group permissions to all the files in the docuemnt root, though:

chmod -R g+w /var/www/html

Comment out HTML and PHP together

PHP parser will search your entire code for <?php (or <? if short_open_tag = On), so HTML comment tags have no effect on PHP parser behavior & if you don't want to parse your PHP code, you have to use PHP commenting directives(/* */ or //).

What do two question marks together mean in C#?

For your amusement only (knowing you are all C# guys ;-).

I think it originated in Smalltalk, where it has been around for many years. It is defined there as:

in Object:

? anArgument
    ^ self

in UndefinedObject (aka nil's class):

? anArgument
    ^ anArgument

There are both evaluating (?) and non-evaluating versions (??) of this.
It is often found in getter-methods for lazy-initialized private (instance) variables, which are left nil until really needed.

Using LINQ to group a list of objects

var result = from cx in CustomerList
         group cx by cx.GroupID into cxGroup
     orderby cxGroup.Key
     select cxGroup; 

foreach (var cxGroup in result) { 
Console.WriteLine(String.Format("GroupID = {0}", cxGroup.Key)); 
  foreach (var cx in cxGroup) { 
    Console.WriteLine(String.Format("\tUserID = {0}, UserName = {1}, GroupID = {2}", 
      new object[] { cx.ID, cx.Name, cx.GroupID })); 
  }
}

How to do while loops with multiple conditions

condition1 = False
condition2 = False
val = -1
#here is the function getstuff is not defined, i hope you define it before
#calling it into while loop code

while condition1 and condition2 is False and val == -1:
#as you can see above , we can write that in a simplified syntax.
    val,something1,something2 = getstuff()

    if something1 == 10:
        condition1 = True

    elif something2 == 20:
# here you don't have to use "if" over and over, if have to then write "elif" instead    
    condition2 = True
# ihope it can be helpfull

How can I generate Unix timestamps?

First of all, the Unix 'epoch' or zero-time is 1970-01-01 00:00:00Z (meaning midnight of 1st January 1970 in the Zulu or GMT or UTC time zone). A Unix time stamp is the number of seconds since that time - not accounting for leap seconds.

Generating the current time in Perl is rather easy:

perl -e 'print time, "\n"'

Generating the time corresponding to a given date/time value is rather less easy. Logically, you use the strptime() function from POSIX. However, the Perl POSIX::strptime module (which is separate from the POSIX module) has the signature:

($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = 
                                     POSIX::strptime("string", "Format");

The function mktime in the POSIX module has the signature:

mktime(sec, min, hour, mday, mon, year, wday = 0, yday = 0, isdst = 0)

So, if you know the format of your data, you could write a variant on:

perl -MPOSIX -MPOSIX::strptime -e \
    'print mktime(POSIX::strptime("2009-07-30 04:30", "%Y-%m-%d %H:%M")), "\n"'

MS SQL Date Only Without Time

that is very bad for performance, take a look at Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code

functions on the left side of the operator are bad

here is what you need to do

declare @d datetime
select @d =  '2008-12-1 14:30:12'

where tstamp >= dateadd(dd, datediff(dd, 0, @d)+0, 0)
and tstamp < dateadd(dd, datediff(dd, 0, @d)+1, 0)

Run this to see what it does

select dateadd(dd, datediff(dd, 0, getdate())+1, 0)
select dateadd(dd, datediff(dd, 0, getdate())+0, 0)

Why do I get the "Unhandled exception type IOException"?

You should add "throws IOException" to your main method:

public static void main(String[] args) throws IOException {

You can read a bit more about checked exceptions (which are specific to Java) in JLS.

How do I check if file exists in jQuery or pure JavaScript?

This doesn't address the OP's question, but for anyone who is returning results from a database: here's a simple method I used.

If the user didn't upload an avatar the avatar field would be NULL, so I'd insert a default avatar image from the img directory.

function getAvatar(avatar) {
    if(avatar == null) {
        return '/img/avatar.jpg';
    } else {
        return '/avi/' + avatar;
    }
}

then

<img src="' + getAvatar(data.user.avatar) + '" alt="">

Setting the number of map tasks and reduce tasks

  • Use -D property=value rather than -D property = value (eliminate extra whitespaces). Thus -D mapred.reduce.tasks=value would work fine.

  • Setting number of map tasks doesnt always reflect the value you have set since it depends on split size and InputFormat used.

  • Setting the number of reduces will definitely override the number of reduces set on cluster/client-side configuration.

XSS prevention in JSP/Servlet web application

XSS can be prevented in JSP by using JSTL <c:out> tag or fn:escapeXml() EL function when (re)displaying user-controlled input. This includes request parameters, headers, cookies, URL, body, etc. Anything which you extract from the request object. Also the user-controlled input from previous requests which is stored in a database needs to be escaped during redisplaying.

For example:

<p><c:out value="${bean.userControlledValue}"></p>
<p><input name="foo" value="${fn:escapeXml(param.foo)}"></p>

This will escape characters which may malform the rendered HTML such as <, >, ", ' and & into HTML/XML entities such as &lt;, &gt;, &quot;, &apos; and &amp;.

Note that you don't need to escape them in the Java (Servlet) code, since they are harmless over there. Some may opt to escape them during request processing (as you do in Servlet or Filter) instead of response processing (as you do in JSP), but this way you may risk that the data unnecessarily get double-escaped (e.g. & becomes &amp;amp; instead of &amp; and ultimately the enduser would see &amp; being presented), or that the DB-stored data becomes unportable (e.g. when exporting data to JSON, CSV, XLS, PDF, etc which doesn't require HTML-escaping at all). You'll also lose social control because you don't know anymore what the user has actually filled in. You'd as being a site admin really like to know which users/IPs are trying to perform XSS, so that you can easily track them and take actions accordingly. Escaping during request processing should only and only be used as latest resort when you really need to fix a train wreck of a badly developed legacy web application in the shortest time as possible. Still, you should ultimately rewrite your JSP files to become XSS-safe.

If you'd like to redisplay user-controlled input as HTML wherein you would like to allow only a specific subset of HTML tags like <b>, <i>, <u>, etc, then you need to sanitize the input by a whitelist. You can use a HTML parser like Jsoup for this. But, much better is to introduce a human friendly markup language such as Markdown (also used here on Stack Overflow). Then you can use a Markdown parser like CommonMark for this. It has also builtin HTML sanitizing capabilities. See also Markdown or HTML.

The only concern in the server side with regard to databases is SQL injection prevention. You need to make sure that you never string-concatenate user-controlled input straight in the SQL or JPQL query and that you're using parameterized queries all the way. In JDBC terms, this means that you should use PreparedStatement instead of Statement. In JPA terms, use Query.


An alternative would be to migrate from JSP/Servlet to Java EE's MVC framework JSF. It has builtin XSS (and CSRF!) prevention over all place. See also CSRF, XSS and SQL Injection attack prevention in JSF.

How can I get just the first row in a result set AFTER ordering?

You can nest your queries:

select * from (
    select bla
    from bla
    where bla
    order by finaldate desc
)
where rownum < 2

Datatable to html Table

If your'e using Web Forms then Grid View can work very nicely for this

The code looks a little like this.

aspx page.

<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name,Size,Quantity,Amount,Duration"></asp:GridView>

You can either input the data manually or use the source method in the code side

public class Room
{
    public string Name
    public double Size {get; set;}
    public int Quantity {get; set;}
    public double Amount {get; set;}
    public int Duration {get; set;}
}

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)//this is so you can keep any data you want for the list
    {
        List<Room> rooms=new List<Room>();
        //then use the rooms.Add() to add the rooms you need.
        GridView1.DataSource=rooms
        GridView1.Databind()
    }
}

Personally I like MVC4 the client side code ends up much lighter than Web Forms. It is similar to the above example with using a class but you use a view and Controller instead.

The View would look like this.

@model YourProject.Model.IEnumerable<Room>

<table>
    <th>
        <td>@Html.LabelFor(model => model.Name)</td>
        <td>@Html.LabelFor(model => model.Size)</td>
        <td>@Html.LabelFor(model => model.Quantity)</td>
        <td>@Html.LabelFor(model => model.Amount)</td>
        <td>@Html.LabelFor(model => model.Duration)</td>
   </th>
foreach(item in model)
{
    <tr>
        <td>@model.Name</td>
        <td>@model.Size</td>
        <td>@model.Quantity</td>
        <td>@model.Amount</td>
        <td>@model.Duration</td>
   </tr>
}
</table>

The controller might look something like this.

public ActionResult Index()
{
    List<Room> rooms=new List<Room>();
    //again add the items you need

    return View(rooms);
}

Hope this helps :)

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

The justify-self and justify-items properties are not implemented in flexbox. This is due to the one-dimensional nature of flexbox, and that there may be multiple items along the axis, making it impossible to justify a single item. To align items along the main, inline axis in flexbox you use the justify-content property.

Reference: Box alignment in CSS Grid Layout

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

what this means ? is there any problem in my code

It means that you are accessing a location or index which is not present in collection.

To find this, Make sure your Gridview has 5 columns as you are using it's 5th column by this line

dataGridView1.Columns[4].Name = "Amount";

Here is the image which shows the elements of an array. So if your gridview has less column then the (index + 1) by which you are accessing it, then this exception arises.

enter image description here

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

Angular 2: How to access an HTTP response body?

Here is an example to access response body using angular2 built in Response

import { Injectable } from '@angular/core';
import {Http,Response} from '@angular/http';

@Injectable()
export class SampleService {
  constructor(private http:Http) { }

  getData(){

    this.http.get(url)
   .map((res:Response) => (
       res.json() //Convert response to JSON
       //OR
       res.text() //Convert response to a string
   ))
   .subscribe(data => {console.log(data)})

  }
}

Delete all documents from index/type without deleting type

From ElasticSearch 5.x, delete_by_query API is there by default

POST: http://localhost:9200/index/type/_delete_by_query

{
    "query": { 
        "match_all": {}
    }
}

How to check if a socket is connected/disconnected in C#?

The accepted answer doesn't seem to work if you unplug the network cable. Or the server crashes. Or your router crashes. Or if you forget to pay your internet bill. Set the TCP keep-alive options for better reliability.

public static class SocketExtensions
{
    public static void SetSocketKeepAliveValues(this Socket instance, int KeepAliveTime, int KeepAliveInterval)
    {
        //KeepAliveTime: default value is 2hr
        //KeepAliveInterval: default value is 1s and Detect 5 times

        //the native structure
        //struct tcp_keepalive {
        //ULONG onoff;
        //ULONG keepalivetime;
        //ULONG keepaliveinterval;
        //};

        int size = Marshal.SizeOf(new uint());
        byte[] inOptionValues = new byte[size * 3]; // 4 * 3 = 12
        bool OnOff = true;

        BitConverter.GetBytes((uint)(OnOff ? 1 : 0)).CopyTo(inOptionValues, 0);
        BitConverter.GetBytes((uint)KeepAliveTime).CopyTo(inOptionValues, size);
        BitConverter.GetBytes((uint)KeepAliveInterval).CopyTo(inOptionValues, size * 2);

        instance.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
    }
}



// ...
Socket sock;
sock.SetSocketKeepAliveValues(2000, 1000);

The time value sets the timeout since data was last sent. Then it attempts to send and receive a keep-alive packet. If it fails it retries 10 times (number hardcoded since Vista AFAIK) in the interval specified before deciding the connection is dead.

So the above values would result in 2+10*1 = 12 second detection. After that any read / wrtie / poll operations should fail on the socket.

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

I was facing same issue so I have reinstall MySQL 8 with different Authentication Method "Use Legacy Authentication Method (Retain MySQL 5.x compatibility)" then work properly.

Choose Second Method of Authentication while installing.

Where does gcc look for C and C++ header files?

`gcc -print-prog-name=cc1plus` -v

This command asks gcc which C++ preprocessor it is using, and then asks that preprocessor where it looks for includes.

You will get a reliable answer for your specific setup.

Likewise, for the C preprocessor:

`gcc -print-prog-name=cpp` -v

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

The answer is misleading because it attempts to fix a problem that is not a problem. You actually CAN have a WHERE CLAUSE in each segment of a UNION. You cannot have an ORDER BY except in the last segment. Therefore, this should work...

select top 2 t1.ID, t1.ReceivedDate
from Table t1
where t1.Type = 'TYPE_1'
-----remove this-- order by ReceivedDate desc
union
select top 2 t2.ID,  t2.ReceivedDate --- add second column
  from Table t2
 where t2.Type = 'TYPE_2'
order by ReceivedDate desc

jQuery hyperlinks - href value?

you shoud use <a href="javascript:void(0)" ></a> instead of <a href="#" ></a>

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

Try this

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String userName = authentication.getName();

Compare a string using sh shell

You should use the = operator for string comparison:

Sourcesystem="ABC"

if [ "$Sourcesystem" = "XYZ" ]; then 
    echo "Sourcesystem Matched" 
else
    echo "Sourcesystem is NOT Matched $Sourcesystem"  
fi;

man test says that you use -z to match for empty strings.

Set timeout for ajax (jQuery)

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

Live Demo

Promise with jQuery 1.8+

Promise.resolve(
  $.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
  })
).then(function(){
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
  {     
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?
  }
});

jQuery 1.8+

$.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
}).done(function(){
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {     
        alert('Failed from timeout'); 
        //do something. Try again perhaps?
    }
});?

jQuery <= 1.7.2

$.ajax({
    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
        {     
             alert('Failed from timeout');         
            //do something. Try again perhaps?
        }
    },
    success: function(){
        //do something
    },
    timeout:3000 //3 second timeout
});

Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

src: http://api.jquery.com/jQuery.ajax/

Replace multiple characters in one replace call

For replacing with nothing, tckmn's answer is the best.

If you need to replace with specific strings corresponding to the matches, here's a variation on Voicu's and Christophe's answers that avoids duplicating what's being matched, so that you don't have to remember to add new matches in two places:

const replacements = {
  '’': "'",
  '“': '"',
  '”': '"',
  '—': '---',
  '–': '--',
};
const replacement_regex = new RegExp(Object
  .keys(replacements)
  // escape any regex literals found in the replacement keys:
  .map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
  .join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);

What could cause java.lang.reflect.InvocationTargetException?

You've added an extra level of abstraction by calling the method with reflection. The reflection layer wraps any exception in an InvocationTargetException, which lets you tell the difference between an exception actually caused by a failure in the reflection call (maybe your argument list wasn't valid, for example) and a failure within the method called.

Just unwrap the cause within the InvocationTargetException and you'll get to the original one.

How to kill all active and inactive oracle sessions for user

The KILL SESSION command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.

Check the status to confirm:

SELECT sid, serial#, status, username FROM v$session;

You could also use IMMEDIATE clause:

ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;

The IMMEDIATE clause does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill. Have a look at Killing Oracle Sessions.

Update If you want to kill all the sessions, you could just prepare a small script.

SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' FROM v$session;

Spool the above to a .sql file and execute it, or, copy paste the output and run it.

Using DataContractSerializer to serialize, but can't deserialize back

This best for XML Deserialize

 public static object Deserialize(string xml, Type toType)
    {

        using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
            System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
            return xSerializer.Deserialize(str);
        }

    }

How to return rows from left table not found in right table?

If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:

  1. A cross join is simplest of all. It implements only one logical query processing phase, a Cartesian Product. This phase operates on the two tables provided as inputs to the join and produces a Cartesian product of the two. That is, each row from one input is matched with all rows from the other. So if you have m rows in one table and n rows in the other, you get m×n rows in the result.
  2. Then are Inner joins : They apply two logical query processing phases: A Cartesian product between the two input tables as in a cross join, and then it filters rows based on a predicate that you specify in ON clause (also known as Join condition).
  3. Next comes the third type of joins, Outer Joins:

    In an outer join, you mark a table as a preserved table by using the keywords LEFT OUTER JOIN, RIGHT OUTER JOIN, or FULL OUTER JOIN between the table names. The OUTER keyword is optional. The LEFT keyword means that the rows of the left table are preserved; the RIGHT keyword means that the rows in the right table are preserved; and the FULL keyword means that the rows in both the left and right tables are preserved.

    The third logical query processing phase of an outer join identifies the rows from the preserved table that did not find matches in the other table based on the ON predicate. This phase adds those rows to the result table produced by the first two phases of the join, and uses NULL marks as placeholders for the attributes from the nonpreserved side of the join in those outer rows.

Now if we look at the question: To return records from the left table which are not found in the right table use Left outer join and filter out the rows with NULL values for the attributes from the right side of the join.

Loop until a specific user input

Your code won't work because you haven't assigned anything to n before you first use it. Try this:

def oracle():
    n = None
    while n != 'Correct':
        # etc...

A more readable approach is to move the test until later and use a break:

def oracle():
    guess = 50

    while True:
        print 'Current number = {0}'.format(guess)
        n = raw_input("lower, higher or stop?: ")
        if n == 'stop':
            break
        # etc...

Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.

Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.

Compiling/Executing a C# Source File in Command Prompt

Once you write the c# code and save it. You can use the command prompt to execute it just like the other code.

In command prompt you enter the directory your file is in and type

To Compile:

mcs yourfilename.cs

To Execute:

mono yourfilename.exe 

if you want your .exe file to be different with a different name, type

To Compile:

mcs yourfilename.cs -out:anyname.exe 

To Execute:

mono anyname.exe 

This should help!

Localhost not working in chrome and firefox

For Firefox:

  1. Go to LAN Settings: Options->Advanced->Network. In the "Connection" section of the "Network" tab press "Settings" button to open "Connection Settings" dialog box.
  2. Select "Manual proxy configuration:" radio button
  3. The "No proxy for:" textbox should contain the following text: "localhost, 127.0.0.1"

Disable nginx cache for JavaScript files

I have the following nginx virtual host (static content) for local development work to disable all browser caching:

server {
    listen 8080;
    server_name localhost;

    location / {
        root /your/site/public;
        index index.html;

        # kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
    }
}

No cache headers sent:

$ curl -I http://localhost:8080
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Mon, 24 Jul 2017 16:19:30 GMT
Content-Type: text/html
Content-Length: 2076
Connection: keep-alive
Last-Modified: Monday, 24-Jul-2017 16:19:30 GMT
Cache-Control: no-store
Accept-Ranges: bytes

Last-Modified is always current time.

Total memory used by Python process?

On unix, you can use the ps tool to monitor it:

$ ps u -p 1347 | awk '{sum=sum+$6}; END {print sum/1024}'

where 1347 is some process id. Also, the result is in MB.

Java HashMap: How to get a key and value by index?

HashMaps don't keep your key/value pairs in a specific order. They are ordered based on the hash that each key's returns from its Object.hashCode() method. You can however iterate over the set of key/value pairs using an iterator with:

for (String key : hashmap.keySet()) 
{
    for (list : hashmap.get(key))
    {
        //list.toString()
    }
}

java.io.FileNotFoundException: the system cannot find the file specified

i think it always boils to the classpath. having said that if you run from the same folder where your .class is then change Scanner input = new Scanner(new File("word.txt")); to Scanner input = new Scanner(new File("./word.txt")); that should work

how to cancel/abort ajax request in axios

Using cp-axios wrapper you able to abort your requests with three diffent types of the cancellation API:

1. Promise cancallation API (CPromise):

Live browser example

 const cpAxios= require('cp-axios');
 const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
 
 const chain = cpAxios(url)
      .timeout(5000)
      .then(response=> {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });
 
 setTimeout(() => {
    chain.cancel();
 }, 500);

2. Using AbortController signal API:

 const cpAxios= require('cp-axios');
 const CPromise= require('c-promise2');
 const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
 
 const abortController = new CPromise.AbortController();
 const {signal} = abortController;
 
 const chain = cpAxios(url, {signal})
      .timeout(5000)
      .then(response=> {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });
 
 setTimeout(() => {
    abortController.abort();
 }, 500);

3. Using a plain axios cancelToken:

 const cpAxios= require('cp-axios');
 const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';

 const source = cpAxios.CancelToken.source();
 
 cpAxios(url, {cancelToken: source.token})
      .timeout(5000)
      .then(response=> {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });
 
 setTimeout(() => {
    source.cancel();
 }, 500);

Async await in linq select

I wanted to call Select(...) but ensure it ran in sequence because running in parallel would cause some other concurrency problems, so I ended up with this. I cannot call .Result because it will block the UI thread.

public static class TaskExtensions
{
    public static async Task<IEnumerable<TResult>> SelectInSequenceAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> asyncSelector)
    {
        var result = new List<TResult>();
        foreach (var s in source)
        {
            result.Add(await asyncSelector(s));
        }
        
        return result;
    }
}

Usage:

var inputs = events.SelectInSequenceAsync(ev => ProcessEventAsync(ev))
                   .Where(i => i != null)
                   .ToList();

I am aware that Task.WhenAll is the way to go when we can run in parallel.

How to use paths in tsconfig.json?

if typescript + webpack 2 + at-loader is being used, there is an additional step (@mleko's solution was only partially working for me):

// tsconfig.json
{
  "compilerOptions": {
    ...
    "rootDir": ".",
    "paths": {
      "lib/*": [
        "src/org/global/lib/*"
      ]
    }
  }
}    

// webpack.config.js
const { TsConfigPathsPlugin } = require('awesome-typescript-loader');

resolve: {
    plugins: [
        new TsConfigPathsPlugin(/* { tsconfig, compiler } */)
    ]
}

Advanced path resolution in TypeScript 2.0

Style bottom Line in Android

A Simple solution :

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="-1dp"
        android:left="-1dp"
        android:right="-1dp"
        android:top="-1dp">

        <shape android:shape="rectangle">

            <solid android:color="#AARRGGBB" />

            <stroke
                android:width="5dp"
                android:color="@android:color/red"
                android:dashWidth="10dp"
                android:dashGap="12dp" />

        </shape>
    </item>
</layer-list>

And finally we have something like that :)

enter image description here

error::make_unique is not a member of ‘std’

If you have latest compiler, you can change the following in your build settings:

 C++ Language Dialect    C++14[-std=c++14]

This works for me.

jQuery bind to Paste Event, how to get the content of the paste

This work on all browser to get pasted value. And also to creating common method for all text box.

$("#textareaid").bind("paste", function(e){       
    var pastedData = e.target.value;
    alert(pastedData);
} )

Error :The remote server returned an error: (401) Unauthorized

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;

Set width of dropdown element in HTML select dropdown options

I find the best way to handle long dropdown boxes is to put it inside a fixed width div container and use width:auto on the select tag. Most browsers will contain the dropdown within the div, but when you click on it, it will expand to display the full option value. It does not work with IE explorer, but there is a fix (like is always needed with IE). Your code would look something like this.

HTML

<div class="dropdown_container">
  <select class="my_dropdown" id="my_dropdown">
    <option value="1">LONG OPTION</option>
    <option value="2">short</option>
  </select>
</div>

CSS

div.dropdown_container {
    width:10px;
}

select.my_dropdown {
    width:auto;
}

/*IE FIX */
select#my_dropdown {
    width:100%;
}

select:focus#my_dropdown {
    width:auto\9;
}

Draw path between two points using Google Maps Android API v2

Try below solution to draw path with animation and also get time and distance between two points.

DirectionHelper.java

public class DirectionHelper {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude));
                            hm.put("lng", Double.toString((list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }


        return routes;
    }

    //Method to decode polyline points
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

GetPathFromLocation.java

public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {

    private Context context;
    private String TAG = "GetPathFromLocation";
    private LatLng source, destination;
    private ArrayList<LatLng> wayPoint;
    private GoogleMap mMap;
    private boolean animatePath, repeatDrawingPath;
    private DirectionPointListener resultCallback;
    private ProgressDialog progressDialog;

    //https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
    //https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/

    public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
        this.context = context;
        this.source = source;
        this.destination = destination;
        this.wayPoint = wayPoint;
        this.mMap = mMap;
        this.animatePath = animatePath;
        this.repeatDrawingPath = repeatDrawingPath;
        this.resultCallback = resultCallback;
    }

    synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {

        String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
                + source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
        for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
            if (centerPoint == 0) {
                url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            } else {
                url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            }
        }
        url = url + "&key=" + context.getResources().getString(R.string.google_api_key);

        return url;
    }

    public int getRandomColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... url) {

        String data;

        try {
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                URL directionUrl = new URL(getUrl(source, destination, wayPoint));
                connection = (HttpURLConnection) directionUrl.openConnection();
                connection.connect();
                inputStream = connection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }

                data = stringBuffer.toString();
                bufferedReader.close();

            } catch (Exception e) {
                Log.e(TAG, "Exception : " + e.toString());
                return null;
            } finally {
                inputStream.close();
                connection.disconnect();
            }
            Log.e(TAG, "Background Task data : " + data);

            //Second AsyncTask

            JSONObject jsonObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jsonObject = new JSONObject(data);
                // Starts parsing data
                DirectionHelper helper = new DirectionHelper();
                routes = helper.parse(jsonObject);
                Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);

                return routes;

            } catch (Exception e) {
                Log.e(TAG, "Exception in Executing Routes : " + e.toString());
                return null;
            }

        } catch (Exception e) {
            Log.e(TAG, "Background Task Exception : " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        super.onPostExecute(result);

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        String distance = "";
        String duration = "";

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            //lineOptions.color(getRandomColor());

            if (animatePath) {
                final ArrayList<LatLng> finalPoints = points;
                ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PolylineOptions polylineOptions;
                        final Polyline greyPolyLine, blackPolyline;
                        final ValueAnimator polylineAnimator;

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : finalPoints) {
                            builder.include(latLng);
                        }
                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED);
                        polylineOptions.width(8);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(ROUND);
                        polylineOptions.addAll(finalPoints);
                        greyPolyLine = mMap.addPolyline(polylineOptions);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.width(8);
                        polylineOptions.color(Color.WHITE);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.zIndex(5f);
                        polylineOptions.jointType(ROUND);

                        blackPolyline = mMap.addPolyline(polylineOptions);
                        polylineAnimator = ValueAnimator.ofInt(0, 100);
                        polylineAnimator.setDuration(5000);
                        polylineAnimator.setInterpolator(new LinearInterpolator());
                        polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                List<LatLng> points = greyPolyLine.getPoints();
                                int percentValue = (int) valueAnimator.getAnimatedValue();
                                int size = points.size();
                                int newPoints = (int) (size * (percentValue / 100.0f));
                                List<LatLng> p = points.subList(0, newPoints);
                                blackPolyline.setPoints(p);
                            }
                        });

                        polylineAnimator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (repeatDrawingPath) {
                                    List<LatLng> greyLatLng = greyPolyLine.getPoints();
                                    if (greyLatLng != null) {
                                        greyLatLng.clear();

                                    }
                                    polylineAnimator.start();
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                                polylineAnimator.cancel();
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                        polylineAnimator.start();
                    }
                });
            }

            Log.e(TAG, "PolylineOptions Decoded");
        }

        // Drawing polyline in the Google Map for the i-th route
        if (resultCallback != null && lineOptions != null)
            resultCallback.onPath(lineOptions, distance, duration);
    }
}

DirectionPointListener

public interface DirectionPointListener {
    public void onPath(PolylineOptions polyLine,String distance,String duration);
}

Now draw path using below code in your Activity

private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;

mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();

                /*Add Source Marker*/
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(source);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.addMarker(markerOptions);
                builder.include(source);

                /*Add Destination Marker*/
                markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                mMap.addMarker(markerOptions);
                builder.include(destination);

                LatLngBounds bounds = builder.build();

                int width = mapFragment.getView().getMeasuredWidth();
                int height = mapFragment.getView().getMeasuredHeight();
                int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen

                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

                mMap.animateCamera(cu);

                new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
                    @Override
                    public void onPath(PolylineOptions polyLine, String distance, String duration) {
                        mMap.addPolyline(polyLine);
                        Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);

                        binding.txtDistance.setText(String.format(" %s", distance));
                        binding.txtDuration.setText(String.format(" %s", duration));
                    }
                }).execute();
            }
        });
    }

OutPut

enter image description here

I hope this can help you!

Thank You.

What's the Kotlin equivalent of Java's String[]?

This example works perfectly in Android

In kotlin you can use a lambda expression for this. The Kotlin Array Constructor definition is:

Array(size: Int, init: (Int) -> T)

Which evaluates to:

skillsSummaryDetailLinesArray = Array(linesLen) {
        i: Int -> skillsSummaryDetailLines!!.getString(i)
}

Or:

skillsSummaryDetailLinesArray = Array<String>(linesLen) {
        i: Int -> skillsSummaryDetailLines!!.getString(i)
}

In this example the field definition was:

private var skillsSummaryDetailLinesArray: Array<String>? = null

Hope this helps

jQuery scroll to ID from different page

You basically need to do this:

  • include the target hash into the link pointing to the other page (href="other_page.html#section")
  • in your ready handler clear the hard jump scroll normally dictated by the hash and as soon as possible scroll the page back to the top and call jump() - you'll need to do this asynchronously
  • in jump() if no event is given, make location.hash the target
  • also this technique might not catch the jump in time, so you'll better hide the html,body right away and show it back once you scrolled it back to zero

This is your code with the above added:

var jump=function(e)
{
   if (e){
       e.preventDefault();
       var target = $(this).attr("href");
   }else{
       var target = location.hash;
   }

   $('html,body').animate(
   {
       scrollTop: $(target).offset().top
   },2000,function()
   {
       location.hash = target;
   });

}

$('html, body').hide();

$(document).ready(function()
{
    $('a[href^=#]').bind("click", jump);

    if (location.hash){
        setTimeout(function(){
            $('html, body').scrollTop(0).show();
            jump();
        }, 0);
    }else{
        $('html, body').show();
    }
});

Verified working in Chrome/Safari, Firefox and Opera. I don't know about IE though.

Find and Replace string in all files recursive using grep and sed

grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"

Set output of a command as a variable (with pipes)

THIS DOESN'T USE PIPEs, but requires a single tempfile
I used this to put simplified timestamps into a lowtech daily maintenance batfile

We have already Short-formatted our System-Time to HHmm, (which is 2245 for 10:45PM)
I direct output of Maint-Routines to logfiles with a $DATE%@%TIME% timestamp;
. . . but %TIME% is a long ugly string (ex. 224513.56, for down to the hundredths of a sec)

SOLUTION OVERVIEW:
1. Use redirection (">") to send the command "TIME /T" everytime to OVERWRITE a temp-file in the %TEMP% DIRECTORY
2. Then use that tempfile as the input to set a new variable (I called it NOW)
3. Replace

echo $DATE%@%TIME% blah-blah-blah >> %logfile%
      with
echo $DATE%@%NOW% blah-blah-blah >> %logfile%


====DIFFERENCE IN OUTPUT:
BEFORE:
SUCCESSFUL TIMESYNCH [email protected]
AFTER:
SUCCESSFUL TIMESYNCH 29Dec14@2252


ACTUAL CODE:

TIME /T > %TEMP%\DailyTemp.txt
SET /p NOW=<%TEMP%\DailyTemp.txt
echo $DATE%@%NOW% blah-blah-blah >> %logfile%


AFTERMATH:
All that remains afterwards is the appended logfile, and constantly overwritten tempfile. And if the Tempfile is ever deleted, it will be re-created as necessary.

How to use 'find' to search for files created on a specific date?

I found this scriplet in a script that deletes all files older than 14 days:

CNT=0
for i in $(find -type f -ctime +14); do
  ((CNT = CNT + 1))
  echo -n "." >> $PROGRESS
  rm -f $i
done
echo deleted $CNT files, done at $(date "+%H:%M:%S") >> $LOG

I think a little additional "man find" and looking for the -ctime / -atime etc. parameters will help you here.

PreparedStatement IN clause alternatives?

No simple way AFAIK. If the target is to keep statement cache ratio high (i.e to not create a statement per every parameter count), you may do the following:

  1. create a statement with a few (e.g. 10) parameters:

    ... WHERE A IN (?,?,?,?,?,?,?,?,?,?) ...

  2. Bind all actuall parameters

    setString(1,"foo"); setString(2,"bar");

  3. Bind the rest as NULL

    setNull(3,Types.VARCHAR) ... setNull(10,Types.VARCHAR)

NULL never matches anything, so it gets optimized out by the SQL plan builder.

The logic is easy to automate when you pass a List into a DAO function:

while( i < param.size() ) {
  ps.setString(i+1,param.get(i));
  i++;
}

while( i < MAX_PARAMS ) {
  ps.setNull(i+1,Types.VARCHAR);
  i++;
}

Enter triggers button click

Using

<button type="button">Whatever</button>

should do the trick.

The reason is because a button inside a form has its type implicitly set to submit. As zzzzBoz says, the Spec says that the first button or input with type="submit" is what is triggered in this situation. If you specifically set type="button", then it's removed from consideration by the browser.

How to create Java gradle project

Finally after comparing all solution, I think starting from build.gradle file can be convenient.

Gradle distribution has samples folder with a lot of examples, and there is gradle init --type basic comand see Chapter 47. Build Init Plugin. But they all needs some editing.

You can use template below as well, then run gradle initSourceFolders eclipse

/*
* Nodeclipse/Enide build.gradle template for basic Java project
*   https://github.com/Nodeclipse/nodeclipse-1/blob/master/org.nodeclipse.enide.editors.gradle/docs/java/basic/build.gradle
* Initially asked on
*   http://stackoverflow.com/questions/14017364/how-to-create-java-gradle-project
* Usage
*   1. create folder (or general Eclipse project) and put this file inside
*   2. run `gradle initSourceFolders eclipse` or `gradle initSourceFolders idea`
* @author Paul Verest; 
* based on `gradle init --type basic`, that does not create source folders 
*/

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'

task initSourceFolders { // add << before { to prevent executing during configuration phase
   sourceSets*.java.srcDirs*.each { it.mkdirs() }
   sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.11'
}

// In this section you declare where to find the dependencies of your project
repositories {
    // Use Maven Central for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    mavenCentral()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    //compile fileTree(dir: 'libs', include: '*.jar')
    // The production code uses the SLF4J logging API at compile time
    //compile 'org.slf4j:slf4j-api:1.7.5'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile "junit:junit:4.11"
}

The result is like below.

overview

That can be used without any Gradle plugin for Eclipse,
or with (Enide) Gradle for Eclipse, Jetty, Android alternative to Gradle Integration for Eclipse

editbox

C99 stdint.h header and MS Visual Studio

Visual Studio 2003 - 2008 (Visual C++ 7.1 - 9) don't claim to be C99 compatible. (Thanks to rdentato for his comment.)

How to query for today's date and 7 days before data?

Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):

select * from tab
where DateCol between adddate(now(),-7) and now() 

How do I move files in node.js?

Using the rename function:

fs.rename(getFileName, __dirname + '/new_folder/' + getFileName); 

where

getFilename = file.extension (old path)
__dirname + '/new_folder/' + getFileName

assumming that you want to keep the file name unchanged.

How do I retrieve query parameters in Spring Boot?

While the accepted answer by afraisse is absolutely correct in terms of using @RequestParam, I would further suggest to use an Optional<> as you cannot always ensure the right parameter is used. Also, if you need an Integer or Long just use that data type to avoid casting types later on in the DAO.

@RequestMapping(value="/data", method = RequestMethod.GET)
public @ResponseBody
Item getItem(@RequestParam("itemid") Optional<Integer> itemid) { 
    if( itemid.isPresent()){
         Item i = itemDao.findOne(itemid.get());              
         return i;
     } else ....
}

Using context in a fragment

getContext() method helps to use the Context of the class in a fragment activity.

How to split a number into individual digits in c#?

Substring and Join methods are usable for this statement.

string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;

   for (int i = 0; i < no.Length; i++)
   {
     numberArray[i] = no.Substring(counter, 1); // 1 is split length
     counter++;
   }

Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5

How to open a file / browse dialog using javascript?

I know this is an old post, but another simple option is using the INPUT TYPE="FILE" tag according to compatibility most major browser support this feature.

Value Change Listener to JTextField

If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.

usernameTextField.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        JTextField textField = (JTextField) e.getSource();
        String text = textField.getText();
        textField.setText(text.toUpperCase());
    }
});

How to download a file from my server using SSH (using PuTTY on Windows)

There's no way to initiate a file transfer back to/from local Windows from a SSH session opened in PuTTY window.

Though PuTTY supports connection-sharing.

While you still need to run a compatible file transfer client (pscp or psftp), no new login is required, it automatically (if enabled) makes use of an existing PuTTY session.

To enable the sharing see:
Sharing an SSH connection between PuTTY tools.


Even without connection-sharing, you can still use the psftp or pscp from Windows command line.

See How to use PSCP to copy file from Unix machine to Windows machine ...?

Note that the scp is OpenSSH program. It's primarily *nix program, but you can run it via Windows Subsystem for Linux or get a Windows build from Win32-OpenSSH (it is already built-in in the latest versions of Windows 10).


If you really want to download the files to a local desktop, you have to specify a target path as %USERPROFILE%\Desktop (what typically resolves to a path like C:\Users\username\Desktop).


Alternative way is to use WinSCP, a GUI SFTP/SCP client. While you browse the remote site, you can anytime open SSH terminal to the same site using Open in PuTTY command.
See Opening Session in PuTTY.

With an additional setup, you can even make PuTTY automatically navigate to the same directory you are browsing with WinSCP.
See Opening PuTTY in the same directory.

(I'm the author of WinSCP)

How do I set environment variables from Java?

Linux/MacOS only

Setting single environment variables (based on answer by Edward Campbell):

public static void setEnv(String key, String value) {
    try {
        Map<String, String> env = System.getenv();
        Class<?> cl = env.getClass();
        Field field = cl.getDeclaredField("m");
        field.setAccessible(true);
        Map<String, String> writableEnv = (Map<String, String>) field.get(env);
        writableEnv.put(key, value);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to set environment variable", e);
    }
}

Usage:

First, put the method in any class you want, e.g. SystemUtil. Then call it statically:

SystemUtil.setEnv("SHELL", "/bin/bash");

If you call System.getenv("SHELL") after this, you'll get "/bin/bash" back.

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

As of iOS 11 this is publicly available in UITableViewDelegate. Here's some sample code:

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive
                                                                         title:@"DELETE"
                                                                       handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
                                                                           NSLog(@"index path of delete: %@", indexPath);
                                                                           completionHandler(YES);
                                                                       }];

    UIContextualAction *rename = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal
                                                                         title:@"RENAME"
                                                                       handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
                                                                           NSLog(@"index path of rename: %@", indexPath);
                                                                           completionHandler(YES);
                                                                       }];

    UISwipeActionsConfiguration *swipeActionConfig = [UISwipeActionsConfiguration configurationWithActions:@[rename, delete]];
    swipeActionConfig.performsFirstActionWithFullSwipe = NO;

    return swipeActionConfig;
}

Also available:

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView leadingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath;

Docs: https://developer.apple.com/documentation/uikit/uitableviewdelegate/2902367-tableview?language=objc

Best practice for REST token-based authentication with JAX-RS and Jersey

How token-based authentication works

In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.

In a few words, an authentication scheme based on tokens follow these steps:

  1. The client sends their credentials (username and password) to the server.
  2. The server authenticates the credentials and, if they are valid, generate a token for the user.
  3. The server stores the previously generated token in some storage along with the user identifier and an expiration date.
  4. The server sends the generated token to the client.
  5. The client sends the token to the server in each request.
  6. The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
    • If the token is valid, the server accepts the request.
    • If the token is invalid, the server refuses the request.
  7. Once the authentication has been performed, the server performs authorization.
  8. The server can provide an endpoint to refresh tokens.

Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).

What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)

This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.

It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml descriptor. It's a custom authentication.

Authenticating a user with their username and password and issuing a token

Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:

@Path("/authentication")
public class AuthenticationEndpoint {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username, 
                                     @FormParam("password") String password) {

        try {

            // Authenticate the user using the credentials provided
            authenticate(username, password);

            // Issue a token for the user
            String token = issueToken(username);

            // Return the token on the response
            return Response.ok(token).build();

        } catch (Exception e) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }      
    }

    private void authenticate(String username, String password) throws Exception {
        // Authenticate against a database, LDAP, file or whatever
        // Throw an Exception if the credentials are invalid
    }

    private String issueToken(String username) {
        // Issue a token (can be a random String persisted to a database or a JWT token)
        // The issued token must be associated to a user
        // Return the issued token
    }
}

If any exceptions are thrown when validating the credentials, a response with the status 403 (Forbidden) will be returned.

If the credentials are successfully validated, a response with the status 200 (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.

When consuming application/x-www-form-urlencoded, the client must to send the credentials in the following format in the request payload:

username=admin&password=123456

Instead of form params, it's possible to wrap the username and the password into a class:

public class Credentials implements Serializable {

    private String username;
    private String password;

    // Getters and setters omitted
}

And then consume it as JSON:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {

    String username = credentials.getUsername();
    String password = credentials.getPassword();

    // Authenticate the user, issue a token and return a response
}

Using this approach, the client must to send the credentials in the following format in the payload of the request:

{
  "username": "admin",
  "password": "123456"
}

Extracting the token from the request and validating it

The client should send the token in the standard HTTP Authorization header of the request. For example:

Authorization: Bearer <token-goes-here>

The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.

JAX-RS provides @NameBinding, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured annotation as following:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }

The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext can be used to access the HTTP request headers and then extract the token:

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String REALM = "example";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the Authorization header from the request
        String authorizationHeader =
                requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validate the Authorization header
        if (!isTokenBasedAuthentication(authorizationHeader)) {
            abortWithUnauthorized(requestContext);
            return;
        }

        // Extract the token from the Authorization header
        String token = authorizationHeader
                            .substring(AUTHENTICATION_SCHEME.length()).trim();

        try {

            // Validate the token
            validateToken(token);

        } catch (Exception e) {
            abortWithUnauthorized(requestContext);
        }
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

        // Check if the Authorization header is valid
        // It must not be null and must be prefixed with "Bearer" plus a whitespace
        // The authentication scheme comparison must be case-insensitive
        return authorizationHeader != null && authorizationHeader.toLowerCase()
                    .startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {

        // Abort the filter chain with a 401 status code response
        // The WWW-Authenticate header is sent along with the response
        requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE, 
                                AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
                        .build());
    }

    private void validateToken(String token) throws Exception {
        // Check if the token was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
    }
}

If any problems happen during the token validation, a response with the status 401 (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.

Securing your REST endpoints

To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.

If some methods or classes do not need authentication, simply do not annotate them:

@Path("/example")
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myUnsecuredMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // The authentication filter won't be executed before invoking this method
        ...
    }

    @DELETE
    @Secured
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response mySecuredMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured
        // The authentication filter will be executed before invoking this method
        // The HTTP request must be performed with a valid token
        ...
    }
}

In the example shown above, the filter will be executed only for the mySecuredMethod(Long) method because it's annotated with @Secured.

Identifying the current user

It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:

Overriding the security context of the current request

Within your ContainerRequestFilter.filter(ContainerRequestContext) method, a new SecurityContext instance can be set for the current request. Then override the SecurityContext.getUserPrincipal(), returning a Principal instance:

final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> username;
        }

    @Override
    public boolean isUserInRole(String role) {
        return true;
    }

    @Override
    public boolean isSecure() {
        return currentSecurityContext.isSecure();
    }

    @Override
    public String getAuthenticationScheme() {
        return AUTHENTICATION_SCHEME;
    }
});

Use the token to look up the user identifier (username), which will be the Principal's name.

Inject the SecurityContext in any JAX-RS resource class:

@Context
SecurityContext securityContext;

The same can be done in a JAX-RS resource method:

@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id, 
                         @Context SecurityContext securityContext) {
    ...
}

And then get the Principal:

Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();

Using CDI (Context and Dependency Injection)

If, for some reason, you don't want to override the SecurityContext, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.

Create a CDI qualifier:

@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }

In your AuthenticationFilter created above, inject an Event annotated with @AuthenticatedUser:

@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;

If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):

userAuthenticatedEvent.fire(username);

It's very likely that there's a class that represents a user in your application. Let's call this class User.

Create a CDI bean to handle the authentication event, find a User instance with the correspondent username and assign it to the authenticatedUser producer field:

@RequestScoped
public class AuthenticatedUserProducer {

    @Produces
    @RequestScoped
    @AuthenticatedUser
    private User authenticatedUser;

    public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
        this.authenticatedUser = findUser(username);
    }

    private User findUser(String username) {
        // Hit the the database or a service to find a user by its username and return it
        // Return the User instance
    }
}

The authenticatedUser field produces a User instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User instance (in fact, it's a CDI proxy):

@Inject
@AuthenticatedUser
User authenticatedUser;

Note that the CDI @Produces annotation is different from the JAX-RS @Produces annotation:

Be sure you use the CDI @Produces annotation in your AuthenticatedUserProducer bean.

The key here is the bean annotated with @RequestScoped, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.

Compared to the approach that overrides the SecurityContext, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.

Supporting role-based authorization

Please refer to my other answer for details on how to support role-based authorization.

Issuing tokens

A token can be:

  • Opaque: Reveals no details other than the value itself (like a random string)
  • Self-contained: Contains details about the token itself (like JWT).

See details below:

Random string as token

A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:

Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);

JWT (JSON Web Token)

JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.

It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):

  • iss: Principal that issued the token.
  • sub: Principal that is the subject of the JWT.
  • exp: Expiration date for the token.
  • nbf: Time on which the token will start to be accepted for processing.
  • iat: Time on which the token was issued.
  • jti: Unique identifier for the token.

Be aware that you must not store sensitive data, such as passwords, in the token.

The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.

You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti claim) along with some other details such as the user you issued the token for, the expiration date, etc.

When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.

Using JWT

There are a few Java libraries to issue and validate JWT tokens such as:

To find some other great resources to work with JWT, have a look at http://jwt.io.

Handling token revocation with JWT

If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.

The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti claim against the token identifiers you have on server side.

For security purposes, revoke all the tokens for a user when they change their password.

Additional information

  • It doesn't matter which type of authentication you decide to use. Always do it on the top of a HTTPS connection to prevent the man-in-the-middle attack.
  • Take a look at this question from Information Security for more information about tokens.
  • In this article you will find some useful information about token-based authentication.

Counting the number of elements with the values of x in a vector

Using table but without comparing with names:

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435)
x <- 67
numbertable <- table(numbers)
numbertable[as.character(x)]
#67 
# 2 

table is useful when you are using the counts of different elements several times. If you need only one count, use sum(numbers == x)

MVC3 DropDownListFor - a simple example?

I think this will help : In Controller get the list items and selected value

public ActionResult Edit(int id)
{
    ItemsStore item = itemStoreRepository.FindById(id);
    ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(), 
                                        "Id", "Name",item.CategoryId);

    // ViewBag to pass values to View and SelectList
    //(get list of items,valuefield,textfield,selectedValue)

    return View(item);
}

and in View

@Html.DropDownList("CategoryId",String.Empty)

How to style the menu items on an Android action bar

You have to change

<style name="MyActionBar.MenuTextStyle"
parent="android:style/TextAppearance.Holo.Widget.ActionBar.Title">

to

<style name="MyActionBar.MenuTextStyle"
parent="android:style/TextAppearance.Holo.Widget.ActionBar.Menu">

as well. This works for me.

How to read PDF files using Java?

with Apache PDFBox it goes like this:

PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
    PDFTextStripper stripper = new PDFTextStripper();
    String text = stripper.getText(document);
    System.out.println("Text:" + text);
}
document.close();

Git: list only "untracked" files (also, custom commands)

All previous answers which I checked would list the files to be committed, too. Here is a simple and easy solution that only lists files which are not yet in the repo and not subject to .gitignore.

git status --porcelain | awk '/^\?\?/ { print $2; }'

or

git status --porcelain | grep -v '\?\?'

What HTTP status response code should I use if the request is missing a required parameter?

I often use a 403 Forbidden error. The reasoning is that the request was understood, but I'm not going to do as asked (because things are wrong). The response entity explains what is wrong, so if the response is an HTML page, the error messages are in the page. If it's a JSON or XML response, the error information is in there.

From rfc2616:

10.4.4 403 Forbidden

The server understood the request, but is refusing to fulfill it.
Authorization will not help and the request SHOULD NOT be repeated.
If the request method was not HEAD and the server wishes to make
public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404
(Not Found) can be used instead.

Callback when DOM is loaded in react.js

I applied componentDidUpdate to table to have all columns same height. it works same as on $(window).load() in jquery.

eg:

componentDidUpdate: function() {
        $(".tbl-tr").height($(".tbl-tr ").height());
    }

Lombok annotations do not compile under Intellij idea

IDEA 2016.1:

  • Install lombok plugin
  • Settings -> Compiler -> Annotation Processors -> Enable annotation processing: checked (default configuration)
  • Settings -> Compiler -> Annotation Processors -> Annotation Processors add "lombok.launch.AnnotationProcessorHider$AnnotationProcessor"
  • Also if you are using maven add to maven-compiler-plugin configuration -> annotationProcessors -> annotationProcessor: lombok.launch.AnnotationProcessorHider$AnnotationProcessor

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>${maven.plugin.compiler.version}</version>
      <configuration>
        <compilerVersion>${java.version}</compilerVersion>
        <source>${java.version}</source>
        <target>${java.version}</target>
        <annotationProcessors>
          <annotationProcessor>lombok.launch.AnnotationProcessorHider$AnnotationProcessor</annotationProcessor>
        </annotationProcessors>
      </configuration>
    </plugin>
    

ionic build Android | error: No installed build tools found. Please install the Android build tools

as the error says 'No installed build tools found' it means that

1 : It really really really did not found build tools

2 : To make him find build tools you need to define these paths correctly

PATH IS SAME FOR UBUNTU(.bashrc) AND MAC(.bash_profile)

export ANDROID_HOME=/Users/vijay/Software/android-sdk-macosx
export PATH=${PATH}:/Users/vijay/Software/android-sdk-macosx/tools
export PATH=${PATH}:/Users/vijay/Software/android-sdk-macosx/platform-tools

3 : IMPORTANT IMPORTANT as soon as you set environmental variables you need to reload evnironmental variables.

//For ubuntu
$source .bashrc 

//For macos
$source .bash_profile

4 : Then check in terminal

$printenv ANDROID_HOME
$printenv PATH

Note : if you did not find your changes in printenv then restart the pc and try again printenv PATH, printenv ANDROID_HOME .There is also command to reload environmental variables .

4 : then open terminal and write HALF TEXT '$and' and hit tab. On hitting tab you should see full '$android' name.this verifys all paths are correct

5 : write $android in terminal and hit enter

Where does PHP's error log reside in XAMPP?

You can simply check you log path from phpmyadmin

run this:

http://localhost/dashboard/

now click PHPInfo (top right corner) or you can simply run this url in your browser

http://localhost/dashboard/phpinfo.php

now search for "error_log"(without quotes) You will get log path.

Enjoy!

No grammar constraints (DTD or XML schema) detected for the document

A new clean way might be to write your xml like so:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE rootElement>

<rootElement>
 ....
</rootElement>

The above works in Eclipse Juno+

What command means "do nothing" in a conditional in Bash?

Although I'm not answering the original question concering the no-op command, many (if not most) problems when one may think "in this branch I have to do nothing" can be bypassed by simply restructuring the logic so that this branch won't occur.

I try to give a general rule by using the OPs example

do nothing when $a is greater than "10", print "1" if $a is less than "5", otherwise, print "2"

we have to avoid a branch where $a gets more than 10, so $a < 10 as a general condition can be applied to every other, following condition.

In general terms, when you say do nothing when X, then rephrase it as avoid a branch where X. Usually you can make the avoidance happen by simply negating X and applying it to all other conditions.

So the OPs example with the rule applied may be restructured as:

if [ "$a" -lt 10 ] && [ "$a" -le 5 ]
then
    echo "1"
elif [ "$a" -lt 10 ]
then
    echo "2"
fi

Just a variation of the above, enclosing everything in the $a < 10 condition:

if [ "$a" -lt 10 ]
then
    if [ "$a" -le 5 ]
    then
        echo "1"
    else
        echo "2"
    fi
fi

(For this specific example @Flimzys restructuring is certainly better, but I wanted to give a general rule for all the people searching how to do nothing.)

Convert base64 string to image

This assumes a few things, that you know what the output file name will be and that your data comes as a string. I'm sure you can modify the following to meet your needs:

// Needed Imports
import java.io.ByteArrayInputStream;
import sun.misc.BASE64Decoder;


def sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==';

// tokenize the data
def parts = sourceData.tokenize(",");
def imageString = parts[1];

// create a buffered image
BufferedImage image = null;
byte[] imageByte;

BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();

// write the image to a file
File outputfile = new File("image.png");
ImageIO.write(image, "png", outputfile);

Please note, this is just an example of what parts are involved. I haven't optimized this code at all and it's written off the top of my head.

Are there any standard exit status codes in Linux?

Programs return a 16 bit exit code. If the program was killed with a signal then the high order byte contains the signal used, otherwise the low order byte is the exit status returned by the programmer.

How that exit code is assigned to the status variable $? is then up to the shell. Bash keeps the lower 7 bits of the status and then uses 128 + (signal nr) for indicating a signal.

The only "standard" convention for programs is 0 for success, non-zero for error. Another convention used is to return errno on error.

ORA-00907: missing right parenthesis

Firstly, in histories_T, you are referencing table T_customer (should be T_customers) and secondly, you are missing the FOREIGN KEY clause that REFERENCES orders; which is not being created (or dropped) with the code you provided.

There may be additional errors as well, and I admit Oracle has never been very good at describing the cause of errors - "Mutating Tables" is a case in point.

Let me know if there additional problems you are missing.

How do you clone an Array of Objects in Javascript?

function deepCloneArray(array) {
    return Array.from(Object.create(array));
}

Disable mouse scroll wheel zoom on embedded Google Maps

Yes its quite easy. I faced a similar problem. Just add the css property "pointer-events" to the iframe div and set it to 'none'.

Example:< iframe style="pointer-events:none" src= ........ >

SideNote: This fix would disable all other mouse events on the map. It worked for me since we didnt require any user interaction on the map.

Java Replace Character At Specific Position Of String?

To replace a character at a specified position :

public static String replaceCharAt(String s, int pos, char c) {
   return s.substring(0,pos) + c + s.substring(pos+1);
}

OnClick in Excel VBA

I don't think so. But you can create a shape object ( or wordart or something similiar ) hook Click event and place the object to position of the specified cell.

How do you get total amount of RAM the computer has?

Compatible with .Net and Mono (tested with Win10/FreeBSD/CentOS)

Using ComputerInfo source code and PerformanceCounters for Mono and as backup for .Net:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;

public class SystemMemoryInfo
{
    private readonly PerformanceCounter _monoAvailableMemoryCounter;
    private readonly PerformanceCounter _monoTotalMemoryCounter;
    private readonly PerformanceCounter _netAvailableMemoryCounter;

    private ulong _availablePhysicalMemory;
    private ulong _totalPhysicalMemory;

    public SystemMemoryInfo()
    {
        try
        {
            if (PerformanceCounterCategory.Exists("Mono Memory"))
            {
                _monoAvailableMemoryCounter = new PerformanceCounter("Mono Memory", "Available Physical Memory");
                _monoTotalMemoryCounter = new PerformanceCounter("Mono Memory", "Total Physical Memory");
            }
            else if (PerformanceCounterCategory.Exists("Memory"))
            {
                _netAvailableMemoryCounter = new PerformanceCounter("Memory", "Available Bytes");
            }
        }
        catch
        {
            // ignored
        }
    }

    public ulong AvailablePhysicalMemory
    {
        [SecurityCritical]
        get
        {
            Refresh();

            return _availablePhysicalMemory;
        }
    }

    public ulong TotalPhysicalMemory
    {
        [SecurityCritical]
        get
        {
            Refresh();

            return _totalPhysicalMemory;
        }
    }

    [SecurityCritical]
    [DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer);

    [SecurityCritical]
    [DllImport("Kernel32", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);

    [SecurityCritical]
    private void Refresh()
    {
        try
        {
            if (_monoTotalMemoryCounter != null && _monoAvailableMemoryCounter != null)
            {
                _totalPhysicalMemory = (ulong) _monoTotalMemoryCounter.NextValue();
                _availablePhysicalMemory = (ulong) _monoAvailableMemoryCounter.NextValue();
            }
            else if (Environment.OSVersion.Version.Major < 5)
            {
                var memoryStatus = MEMORYSTATUS.Init();
                GlobalMemoryStatus(ref memoryStatus);

                if (memoryStatus.dwTotalPhys > 0)
                {
                    _availablePhysicalMemory = memoryStatus.dwAvailPhys;
                    _totalPhysicalMemory = memoryStatus.dwTotalPhys;
                }
                else if (_netAvailableMemoryCounter != null)
                {
                    _availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();
                }
            }
            else
            {
                var memoryStatusEx = MEMORYSTATUSEX.Init();

                if (GlobalMemoryStatusEx(ref memoryStatusEx))
                {
                    _availablePhysicalMemory = memoryStatusEx.ullAvailPhys;
                    _totalPhysicalMemory = memoryStatusEx.ullTotalPhys;
                }
                else if (_netAvailableMemoryCounter != null)
                {
                    _availablePhysicalMemory = (ulong) _netAvailableMemoryCounter.NextValue();
                }
            }
        }
        catch
        {
            // ignored
        }
    }

    private struct MEMORYSTATUS
    {
        private uint dwLength;
        internal uint dwMemoryLoad;
        internal uint dwTotalPhys;
        internal uint dwAvailPhys;
        internal uint dwTotalPageFile;
        internal uint dwAvailPageFile;
        internal uint dwTotalVirtual;
        internal uint dwAvailVirtual;

        public static MEMORYSTATUS Init()
        {
            return new MEMORYSTATUS
            {
                dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUS)))
            };
        }
    }

    private struct MEMORYSTATUSEX
    {
        private uint dwLength;
        internal uint dwMemoryLoad;
        internal ulong ullTotalPhys;
        internal ulong ullAvailPhys;
        internal ulong ullTotalPageFile;
        internal ulong ullAvailPageFile;
        internal ulong ullTotalVirtual;
        internal ulong ullAvailVirtual;
        internal ulong ullAvailExtendedVirtual;

        public static MEMORYSTATUSEX Init()
        {
            return new MEMORYSTATUSEX
            {
                dwLength = checked((uint) Marshal.SizeOf(typeof(MEMORYSTATUSEX)))
            };
        }
    }
}

GZIPInputStream reading line by line

The basic setup of decorators is like this:

InputStream fileStream = new FileInputStream(filename);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream, encoding);
BufferedReader buffered = new BufferedReader(decoder);

The key issue in this snippet is the value of encoding. This is the character encoding of the text in the file. Is it "US-ASCII", "UTF-8", "SHIFT-JIS", "ISO-8859-9", …? there are hundreds of possibilities, and the correct choice usually cannot be determined from the file itself. It must be specified through some out-of-band channel.

For example, maybe it's the platform default. In a networked environment, however, this is extremely fragile. The machine that wrote the file might sit in the neighboring cubicle, but have a different default file encoding.

Most network protocols use a header or other metadata to explicitly note the character encoding.

In this case, it appears from the file extension that the content is XML. XML includes the "encoding" attribute in the XML declaration for this purpose. Furthermore, XML should really be processed with an XML parser, not as text. Reading XML line-by-line seems like a fragile, special case.

Failing to explicitly specify the encoding is against the second commandment. Use the default encoding at your peril!

How can I get a Dialog style activity window to fill the screen?

You may add this values to your style android:windowMinWidthMajor and android:windowMinWidthMinor

<style name="Theme_Dialog" parent="android:Theme.Holo.Dialog">
    ...
    <item name="android:windowMinWidthMajor">97%</item>
    <item name="android:windowMinWidthMinor">97%</item>
</style>

How can I extract audio from video with ffmpeg?

To extract the audio stream without re-encoding:

ffmpeg -i input-video.avi -vn -acodec copy output-audio.aac
  • -vn is no video.
  • -acodec copy says use the same audio stream that's already in there.

Read the output to see what codec it is, to set the right filename extension.

Changing default startup directory for command prompt in Windows 7

hi if you want cmd to automatically open when the machine starts up you can place the cmd.exe executable in the startup folder(just search for startup and place a shortcut of cmd.exe there)

How do I get row id of a row in sql server

SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

How to properly validate input values with React.JS?

First, here is an example of what I'll mention below: http://jsbin.com/rixido/2/edit

How to properly validate input values with React.JS?

However you want. React is for rendering a data model. The data model should know what is valid or not. You can use Backbone models, JSON data, or anything you want to represent the data and it's error state.

More specifically:

React is generally agnostic towards your data. It's for rendering and dealing with events.

The rules to follow are:

  1. elements can change their state.
  2. they cannot change props.
  3. they can invoke a callback that will change top level props.

How to decide if something should be a prop or a state? Consider this: would ANY part of your app other than the text field want to know that the value entered is bad? If no, make it a state. If yes, it should be a prop.

For example, if you wanted a separate view to render "You have 2 errors on this page." then your error would have to be known to a toplevel data model.

Where should that error live?
If your app was rendering Backbone models (for example), the model itself would have a validate() method and validateError property you could use. You could render other smart objects that could do the same. React also says try to keep props to a minimum and generate the rest of the data. so if you had a validator (e.g. https://github.com/flatiron/revalidator) then your validations could trickle down and any component could check props with it's matching validation to see if it's valid.

It's largely up to you.

(I am personally using Backbone models and rendering them in React. I have a toplevel error alert that I show if there is an error anywhere, describing the error.)

How to get the current loop index when using Iterator?

just do something like this:

        ListIterator<String> it = list1.listIterator();
        int index = -1;
        while (it.hasNext()) {
            index++;
            String value = it.next();
            //At this point the index can be checked for the current element.

        }

Tracking CPU and Memory usage per process

I agree, perfmon.exe allows you to add counters (right click on the right panel) for any process you want to monitor.

Performance Object: Process Check "Select instances from list" and select firefox.

How to Parse a JSON Object In Android

In your JSON format, it do not have starting JSON object

Like :

{
    "info" :       <!-- this is starting JSON object -->
        {
        "caller":"getPoiById",
        "results":
        {
            "indexForPhone":0,
            "indexForEmail":"NULL",
            .
            .
         }
    }
}

Above Json starts with info as JSON object. So while executing :

JSONObject json = new JSONObject(result);    // create JSON obj from string
JSONObject json2 = json.getJSONObject("info");    // this will return correct

Now, we can access result field :

JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"

I think this was missing and so the problem was solved while we use JSONTokener like answer of yours.

Your answer is very fine. Just i think i add this information so i answered

Thank you

Save range to variable

To save a range and then call it later, you were just missing the "Set"

Set Remember_Range = Selection    or    Range("A3")
Remember_Range.Activate

But for copying and pasting, this quicker. Cuts out the middle man and its one line

Sheets("Copy").Range("A3").Value = Sheets("Paste").Range("A3").Value

java.text.ParseException: Unparseable date

Check your Pattern (DD-MMM-YYYY) and the input for the parse("29-11-2018") method. Input to the parse method should follow : DD-MMM-YYYY i,e. 21-AUG-2019

In My Code:

String pattern = "DD-MMM-YYYY";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

    try {
        startDate = simpleDateFormat.parse("29-11-2018");// here no pattern match 
        endDate = simpleDateFormat.parse("28-AUG-2019");// Ok 
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

No WebApplicationContext found: no ContextLoaderListener registered?

And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747

List<String> to ArrayList<String> conversion issue

Arrays.asList does not return instance of java.util.ArrayListbut it returns instance of java.util.Arrays.ArrayList.

You will need to convert to ArrayList if you want to access ArrayList specific information

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

How to download/upload files from/to SharePoint 2013 using CSOM?

I would suggest reading some Microsoft documentation on what you can do with CSOM. This might be one example of what you are looking for, but there is a huge API documented in msdn.

// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume there is a list item with ID=1. 
ListItem listItem = announcementsList.Items.GetById(1); 

// Write a new value to the Body field of the Announcement item.
listItem["Body"] = "This is my new value!!"; 
listItem.Update(); 

context.ExecuteQuery(); 

From: http://msdn.microsoft.com/en-us/library/fp179912.aspx

Bootstrap 3 collapsed menu doesn't close on click

$(".navbar-nav li a").click(function(event) {
    if (!$(this).parent().hasClass('dropdown'))
        $(".navbar-collapse").collapse('hide');
});

This would help in handling drop down in nav bar

Flattening a shallow list in Python

You almost have it! The way to do nested list comprehensions is to put the for statements in the same order as they would go in regular nested for statements.

Thus, this

for inner_list in outer_list:
    for item in inner_list:
        ...

corresponds to

[... for inner_list in outer_list for item in inner_list]

So you want

[image for menuitem in list_of_menuitems for image in menuitem]

Draw a connecting line between two elements

js-graph.it supports this use case, as seen by its getting started guide, supporting dragging elements without connection overlaps. Doesn't seem like it supports editing/creating connections. Doesn't seem it is maintained anymore.

How do I extend a class with c# extension methods?

I would do the same as Kumu

namespace ExtensionMethods
{
    public static class MyExtensionMethods
    {
        public static DateTime Tomorrow(this DateTime date)
        {
           return date.AddDays(1);
        }    
    }
}

but call it like this new DateTime().Tomorrow();

Think it makes more seens than DateTime.Now.Tomorrow();

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

We had this exact problem with fontawesome-webfont.woff2 throwing a 406 error on a shared host (Cpanel). I was working on the elusive "cookie-less domain" for a Wordpress Multisite project and my "www.domain.tld" pages would have the following error (3 times) in Chrome:

Font from origin 'http://static.domain.tld' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.domain.tld' is therefore not allowed access.

and in Firefox, a little more detail:

downloadable font: download failed (font-family: "FontAwesome" style:normal weight:normal stretch:normal src index:1): bad URI or cross-site access not allowed source: http://static.domain.tld/wp-content/themes/some-theme-here/fonts/fontawesome-webfont.woff2?v=4.7.0
font-awesome.min.css:4:14 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://static.domain.tld/wp-content/themes/some-theme-here/fonts/fontawesome-webfont.woff?v=4.7.0. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I got to QWANT-ing around (QWANT.com = fantastic) and found this SO post:

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

An hour in chat with different Shared Host support staff (one didn't even know about F12 in a browser...) then waiting for a response to the ticket that got cut after no joy while playing with mod_security. I tried to cobble the code for the .htaccess file together from the post in the meantime, and got this to work to remedy the 406 errors, flawlessly:

    <IfModule mod_headers.c>
    <IfModule mod_rewrite.c>
        SetEnvIf Origin "http(s)?://(.+\.)?domain\.tld(:\d{1,5})?$" CORS=$0
        Header set Access-Control-Allow-Origin "%{CORS}e" env=CORS
        Header merge  Vary "Origin"
    </IfModule>
    </IfModule>

I added that to the top of my .htaccess at the site root and now I have a new Uncle named Bob. (***of course change the domain.tld parts to whatever your domain that you are working with is...)

My FAVORITE part of this post though is the ability to RegEx OR (|) multiple sites into this CORS "hack" by doing:

To allow Multiple sites:

SetEnvIf Origin "http(s)?://(.+\.)?(othersite\.com|mywebsite\.com)(:\d{1,5})?$" CORS=$0

This fix honestly kind of blew my mind because I've ran into this issue before, working with Dev's at Fortune 500 companies that are MILES above my knowledgebase of Apache and couldn't solve problems like this without getting IT to tweak on Apache settings.

This is kind of the magic bullet to fix all those CDN issues with cookie-less (or near cookie-less if you use CloudFlare...) domains to reduce the amount of unnecessary web traffic from cookies that get sent with every image request only to be ditched like a bad blind date by the server.

Super Secure, Super Elegant. Love it: You don't have to open up your servers bandwidth to resource thieves / hot-link-er types.

Props to a collective effort from these 3 brilliant minds for solving what was once thought to unsolvable with .htaccess, whom I pieced this code together from:

@Noyo https://stackoverflow.com/users/357774/noyo

@DaveRandom https://stackoverflow.com/users/889949/daverandom

@pratap-koritala https://stackoverflow.com/users/4401569/pratap-koritala

What's the difference between `raw_input()` and `input()` in Python 3?

The difference is that raw_input() does not exist in Python 3.x, while input() does. Actually, the old raw_input() has been renamed to input(), and the old input() is gone, but can easily be simulated by using eval(input()). (Remember that eval() is evil. Try to use safer ways of parsing your input if possible.)

Fastest method of screen capturing on Windows

I use d3d9 to get the backbuffer, and save that to a png file using the d3dx library:

    IDirect3DSurface9 *surface ;

    // GetBackBuffer
    idirect3ddevice9->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &surface ) ;

    // save the surface
    D3DXSaveSurfaceToFileA( "filename.png", D3DXIFF_PNG, surface, NULL, NULL ) ;

    SAFE_RELEASE( surface ) ;

To do this you should create your swapbuffer with

d3dpps.SwapEffect = D3DSWAPEFFECT_COPY ; // for screenshots.

(So you guarantee the backbuffer isn't mangled before you take the screenshot).

Internal and external fragmentation

I am an operating system that only allocates you memory in 10mb partitions.

Internal Fragmentation

  • You ask for 17mb of memory
  • I give you 20mb of memory

Fulfilling this request has just led to 3mb of internal fragmentation.

External Fragmentation

  • You ask for 20mb of memory
  • I give you 20mb of memory
  • The 20mb of memory that I give you is not immediately contiguous next to another existing piece of allocated memory. In so handing you this memory, I have "split" a single unallocated space into two spaces.

Fulfilling this request has just led to external fragmentation

How to set maximum fullscreen in vmware?

Go to view and press "Switch to scale mode" which will adjust the virtual screen when you adjust the application.

bash echo number of lines of file given in a bash variable without the file name

wc can't get the filename if you don't give it one.

wc -l < "$JAVA_TAGS_FILE"

Facebook Javascript SDK Problem: "FB is not defined"

Facebook prefers that you load their SDK asynchronously so that it doesn't block any other scripts that you need for your page but due to the iframe there's a chance that the console tries to call a method on the FB object before the FB object is completely created even though FB is only called in the fbAsyncInit function.
Try loading the javascript synchronously and you shouldn't get the error anymore. To do this you can copy and paste the code that Facebook provides and place it in an external .js file and then include that .js file in a <script> tag in the <head> of your page. If you must load their SDK asynchronously then check for FB to be created first before calling the init function.

Default username password for Tomcat Application Manager

The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:

<?xml version='1.0' encoding='utf-8'?>  
<tomcat-users>  
    <role rolename="tomcat"/>  
    <role rolename="role1"/>  
    <role rolename="manager"/>  
    <user username="tomcat" password="tomcat" roles="tomcat"/>  
    <user username="both" password="tomcat" roles="tomcat,role1"/>  
    <user username="role1" password="tomcat" roles="role1"/>  
    <user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>  
</tomcat-users>  

It works for me very well

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

Base 64 encode and decode example code

First:

  • Choose an encoding. UTF-8 is generally a good choice; stick to an encoding which will definitely be valid on both sides. It would be rare to use something other than UTF-8 or UTF-16.

Transmitting end:

  • Encode the string to bytes (e.g. text.getBytes(encodingName))
  • Encode the bytes to base64 using the Base64 class
  • Transmit the base64

Receiving end:

  • Receive the base64
  • Decode the base64 to bytes using the Base64 class
  • Decode the bytes to a string (e.g. new String(bytes, encodingName))

So something like:

// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");

Or with StandardCharsets:

// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);

// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);

Dropdownlist width in IE

This is something l have done taking bits from other people's stuff.

        $(document).ready(function () {
        if (document.all) {

            $('#<%=cboDisability.ClientID %>').mousedown(function () {
                $('#<%=cboDisability.ClientID %>').css({ 'width': 'auto' });
            });

            $('#<%=cboDisability.ClientID %>').blur(function () {
                $(this).css({ 'width': '208px' });
            });

            $('#<%=cboDisability.ClientID %>').change(function () {
                $('#<%=cboDisability.ClientID %>').css({ 'width': '208px' });
            });

            $('#<%=cboEthnicity.ClientID %>').mousedown(function () {
                $('#<%=cboEthnicity.ClientID %>').css({ 'width': 'auto' });
            });

            $('#<%=cboEthnicity.ClientID %>').blur(function () {
                $(this).css({ 'width': '208px' });
            });

            $('#<%=cboEthnicity.ClientID %>').change(function () {
                $('#<%=cboEthnicity.ClientID %>').css({ 'width': '208px' });
            });

        }
    });

where cboEthnicity and cboDisability are dropdowns with option text wider than the width of the select itself.

As you can see, l have specified document.all as this only works in IE. Also, l encased the dropdowns within div elements like this:

<div id="dvEthnicity" style="width: 208px; overflow: hidden; position: relative; float: right;"><asp:DropDownList CssClass="select" ID="cboEthnicity" runat="server" DataTextField="description" DataValueField="id" Width="200px"></asp:DropDownList></div>

This takes care of the other elements moving out of place when your dropdown expands. The only downside here is that the menulist visual disappears when you are selecting but returns as soon as you have selected.

Hope this helps someone.

Create Table from JSON Data with angularjs and ng-repeat

To render any json in tabular format:

<table>
    <thead>
      <tr>
        <th ng-repeat="(key, value) in vm.records[0]">{{key}}</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="(key, value) in vm.records">
        <td ng-repeat="(key, value) in value">
          {{value}}
        </td>
      </tr>
    </tbody>
</table>

See complete code in detail with other features

Angular - Use pipes in services and components

As of Angular 6 you can import formatDate from @angular/common utility to use inside the components.

It was intruduced at https://github.com/smdunn/angular/commit/3adeb0d96344c15201f7f1a0fae7e533a408e4ae

I can be used as:

import {formatDate} from '@angular/common';
formatDate(new Date(), 'd MMM yy HH:mm', 'en');

Although the locale has to be supplied

How to list all Git tags?

For a GUI to do this I have just found that 'gitk' supports named views. The views have several options for selecting commits. One handy one is a box for selecting "All tags". That seems to work for me to see the tags.

Unit Testing C Code

API Sanity Checker — test framework for C/C++ libraries:

An automatic generator of basic unit tests for a shared C/C++ library. It is able to generate reasonable (in most, but unfortunately not all, cases) input data for parameters and compose simple ("sanity" or "shallow"-quality) test cases for every function in the API through the analysis of declarations in header files.

The quality of generated tests allows to check absence of critical errors in simple use cases. The tool is able to build and execute generated tests and detect crashes (segfaults), aborts, all kinds of emitted signals, non-zero program return code and program hanging.

Examples:

SQLRecoverableException: I/O Exception: Connection reset

Your exception says it all "Connection reset". The connection between your java process and the db server was lost, which could have happened for almost any reason(like network issues). The SQLRecoverableException just means that its recoverable, but the root cause is connection reset.

ASP.NET Web Application Message Box

You want to use an Alert. Unfortunately it's not as nice as with windows forms.

ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable + "');", true);

Similar to this question here: http://forums.asp.net/t/1461308.aspx/1

How to count the frequency of the elements in an unordered list?

Yet another solution with another algorithm without using collections:

def countFreq(A):
   n=len(A)
   count=[0]*n                     # Create a new list initialized with '0'
   for i in range(n):
      count[A[i]]+= 1              # increase occurrence for value A[i]
   return [x for x in count if x]  # return non-zero count

jQuery select child element by class with unknown path

According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector) is the fastest and most efficient way to do this.

How to change spinner text size and text color?

To prevent lagging, you need to not only set the text properties in the onItemSelected listener, but also in the Activity's onCreate method (but it's a little tricky).

Specifically, you need to put this in onCreate after setting the adapter:

spinner.setSelection(0, true);
View v = spinner.getSelectedView();
((TextView)v).setTextColor(backgroundColor);

And then put this in onItemSelected:

((TextView) view).setTextColor(backgroundColor);

Here is a full example:

@Override  
protected void onCreate(Bundle savedInstanceState)
{  
    Spinner spinner = (Spinner) findViewById(R.id.spinner); 

    //Set the choices on the spinner by setting the adapter.  
    spinner.setAdapter(new SpinnerAdapter(toolbar.getContext(), new String[]{"Overview", "Story", "Specifications", "Poll", "Video"}, accentColor, backgroundColor));

    //Set the text color of the Spinner's selected view (not a drop down list view) 
    spinner.setSelection(0, true);
    View v = spinner.getSelectedView();
    ((TextView)v).setTextColor(backgroundColor);

    //Set the listener for when each option is clicked.  
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {  

        @Override  
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
        {  
           //Change the selected item's text color  
           ((TextView) view).setTextColor(backgroundColor);
        }  

        @Override  
        public void onNothingSelected(AdapterView<?> parent)
        {  
        }  
    });  

}  

For more details, see my question.

Best way to get hostname with php

The accepted answer gethostname() may infact give you inaccurate value as in my case

gethostname()         = my-macbook-pro     (incorrect)
$_SERVER['host_name'] = mysite.git         (correct)

The value from gethostname() is obvsiously wrong. Be careful with it.

Update as corrected by the comment

Host name gives you computer name, not website name, my bad. My result on local machine is

gethostname()         = my-macbook-pro     (which is my machine name)
$_SERVER['host_name'] = mysite.git         (which is my website name)

How to set focus on input field?

I edit Mark Rajcok's focusMe directive to work for multiple focus in one element.

HTML:

<input  focus-me="myInputFocus"  type="text">

in AngularJs Controller:

$scope.myInputFocus= true;

AngulaJS Directive:

app.directive('focusMe', function ($timeout, $parse) {
    return {
        link: function (scope, element, attrs) {
            var model = $parse(attrs.focusMe);
            scope.$watch(model, function (value) {
                if (value === true) {
                    $timeout(function () {
                        scope.$apply(model.assign(scope, false));
                        element[0].focus();
                    }, 30);
                }
            });
        }
    };
});

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

How to fix "unable to write 'random state' " in openssl

Or this in windows powershell

$env:RANDFILE=".rnd"

What is the correct JSON content type?

Content-Type: application/json - json
Content-Type: application/javascript - json-P
Content-Type: application/x-javascript - javascript
Content-Type: text/javascript - javascript BUT obsolete, older IE versions used to use as html attribute.
Content-Type: text/x-javascript - JavaScript Media Types BUT obsolete
Content-Type: text/x-json - json before application/json got officially registered.

Why do I get an error instantiating an interface?

You can't instantiate interfaces or abstract classes.

That's because it wouldn't have any logic to it.

Interfaces provide a contract of the methods that should be in a class, without implementation. (So there's no actual logic in the interface).

Abstract classes provide basic logic of a class, but are not fully functional (not everything is implemented). So again, you won't be able to do anything with it.

Best way to handle list.index(might-not-exist) in python?

I don't know why you should think it is dirty... because of the exception? if you want a oneliner, here it is:

thing_index = thing_list.index(elem) if thing_list.count(elem) else -1

but i would advise against using it; I think Ross Rogers solution is the best, use an object to encapsulate your desiderd behaviour, don't try pushing the language to its limits at the cost of readability.

How can I read the client's machine/computer name from the browser?

Try getting the client computer name in Mozilla Firefox by using the code given below.

netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' ); 

var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"]; 
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;

Also, the same piece of code can be put as an extension, and it can called from your web page.

Please find the sample code below.

Extension code:

var myExtension = {
  myListener: function(evt) {

//netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' ); 
var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"]; 
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
content.document.getElementById("compname").value = compName ;    
  }
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); //this event will raised from the webpage

Webpage Code:

<html>
<body onload = "load()">
<script>
function showcomp()
{
alert("your computer name is " + document.getElementById("compname").value);
}
function load()
{ 
//var element = document.createElement("MyExtensionDataElement");
//element.setAttribute("attribute1", "foobar");
//element.setAttribute("attribute2", "hello world");
//document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
//element.dispatchEvent(evt);
document.getElementById("compname").dispatchEvent(evt); //this raises the MyExtensionEvent event , which assigns the client computer name to the hidden variable.
}
</script>
<form name="login_form" id="login_form">
<input type = "text" name = "txtname" id = "txtnamee" tabindex = "1"/>
<input type="hidden" name="compname" value="" id = "compname" />
<input type = "button" onclick = "showcomp()" tabindex = "2"/>

</form>
</body>
</html>

How to remove certain characters from a string in C++?

Using std::wstring and wchar_t (requires the Unicode header):

//#include <tchar.h>
std::wstring phone(L"(555) 555-5555");

...fancy static range initializer next; not necessary to setup badChars2 this exact same way. It's overkill; more academic than anything else:

const wchar_t *tmp = L"()-"; 
const std::set<wchar_t> badChars2(tmp,tmp + sizeof(tmp)-1);

Simple, concise lambda:

  1. Uses phone in the lambda capture list.
  2. Uses Erase-remove idiom
  3. Removes all bad characters from phone

    for_each(badChars2.begin(), badChars2.end(), [&phone](wchar_t n){
         phone.erase(std::remove(phone.begin(), phone.end(), n), phone.end());
    });
    wcout << phone << endl;
    

Output: "555 5555555"

PHP display image BLOB from MySQL

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.

Thanks.

Verifying that a string contains only letters in C#

bool result = input.All(Char.IsLetter);

bool result = input.All(Char.IsLetterOrDigit);

bool result = input.All(c=>Char.IsLetterOrDigit(c) || c=='_');

What does numpy.random.seed(0) do?

All the random numbers generated after setting particular seed value are same across all the platforms/systems.

How to install maven on redhat linux

Pretty much what others said, but using "~/.bash_profile" and step by step (for beginners):

  1. Move to home folder and create a new folder for maven artifacts:
    • cd ~ && mkdir installed-packages
  2. Go to https://maven.apache.org/download.cgi and wget the latest artifact:
    • If you don't have wget installed: sudo yum install -y wget
    • cd ~/installed-packages
    • wget http://www-eu.apache.org/dist/maven/maven-3/3.5.0/binaries/apache-maven-3.5.0-bin.tar.gz
  3. Uncompress the downloaded file:
    • tar -xvf apache-maven-3.5.0-bin.tar.gz
  4. Create a symbolic link of the uncompressed file:
    • ln -s ~/installed-packages/apache-maven-3.5.0 /usr/local/apache-maven
  5. Edit ~/.bash_profile (This is where environment variables are commonly stored):
    • vi ~/.bash_profile
    • Add the variable: MVN_HOME=/usr/local/apache-maven (do this before PATH variable is defined)
      • (For those who don't know vi tool: Press i key to enable insert mode)
    • Go to the end of the line where PATH variable is defined and append the following: :$MVN_HOME:$MVN_HOME/bin
    • Save changes
      • (For those who don't know vi tool: Press esc key to exit insert mode and :wq! to save and quit file)
  6. Reload environment variables:
    • source ~/.bash_profile
  7. Confirm that maven command now works properly:
    • mvn --help

What is the difference between a token and a lexeme?

Lexeme- A lexeme is a string of character that is the lowest level syntactic unit in the programming language.

Token- The token is a syntactic category that forms a class of lexemes that means which class the lexeme belong is it a keyword or identifier or anything else. One of the major tasks of the lexical analyzer is to create a pair of lexemes and tokens, that is to collect all the characters.

Let us take an example:-

if(y<= t)

y=y-3;

Lexeme                      Token

if                                       KEYWORD

(                                 LEFT PARENTHESIS

y                                     IDENTIFIER

< =                                 COMPARISON

t                                     IDENTIFIER

)                                RIGHT PARENTHESIS

y                                    IDENTIFIER

=                                   ASSGNMENT

y                                   IDENTIFIER

_                                   ARITHMATIC

3                                     INTEGER

;                                    SEMICOLON

Relation between Lexeme and Token

Relation between lexeme and token

Using Postman to access OAuth 2.0 Google APIs

The current answer is outdated. Here's the up-to-date flow:

The approach outlined here still works (10.12.2020) as confirmed by alexwhan.

We will use the YouTube Data API for our example. Make changes accordingly.

Make sure you have enabled your desired API for your project.

Create the OAuth 2.0 Client

  1. Visit https://console.cloud.google.com/apis/credentials
  2. Click on CREATE CREDENTIALS
  3. Select OAuth client ID
  4. For Application Type choose Web Application
  5. Add a name
  6. Add following URI for Authorized redirect URIs
https://oauth.pstmn.io/v1/callback
  1. Click Save
  2. Click on the OAuth client you just generated
  3. In the Topbar click on DOWNLOAD JSON and save the file somewhere on your machine.

We will use the file later to authenticate Postman.

Authorize Postman via OAuth 2.0 Client

  1. In the Auth tab under TYPE choose OAuth 2.0
  2. For Access Token enter the Access Token found inside the client_secret_[YourClientID].json file we downloaded in step 9
  3. Click on Get New Access Token
  4. Make sure your settings are as follows:

Click here to see the settings

You can find everything else you need in your .json file.

  1. Click on Request Token
  2. A new browser tab/window will open
  3. Once the browser tab opens, login via the appropriate Google account
  4. Accept the consent screen
  5. Done

Ignore the browser message "Not safe" etc. This will be shown until your app has been screened by Google officials. In this case it will always be shown since Postman is the app.

How to add style from code behind?

:hover is a selector, and not a style. What you're doing in your example is adding inline styles to an element, and a selector equivalent for that obviously doesn't make much sense.

You can add a class to your link: hlRow.CssClass = 'abc'; And define your class as such:

a.abc:hover {
    ...
}

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

You module and class AthleteList have the same name. Change:

import AthleteList

to:

from AthleteList import AthleteList

This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList

JSHint and jQuery: '$' is not defined

Instead of recommending the usual "turn off the JSHint globals", I recommend using the module pattern to fix this problem. It keeps your code "contained" and gives a performance boost (based on Paul Irish's "10 things I learned about Jquery").

I tend to write my module patterns like this:

(function (window) {
    // Handle dependencies
    var angular = window.angular,
        $ = window.$,
        document = window.document;

    // Your application's code
}(window))

You can get these other performance benefits (explained more here):

  • When minifying code, the passed in window object declaration gets minified as well. e.g. window.alert() become m.alert().
  • Code inside the self-executing anonymous function only uses 1 instance of the window object.
  • You cut to the chase when calling in a window property or method, preventing expensive traversal of the scope chain e.g. window.alert() (faster) versus alert() (slower) performance.
  • Local scope of functions through "namespacing" and containment (globals are evil). If you need to break up this code into separate scripts, you can make a submodule for each of those scripts, and have them imported into one main module.

Get push notification while App in foreground iOS

As mentioned above, you should use UserNotification.framework to achieve this. But for my purposes I have to show it in app anyway and wanted to have iOS 11 style, so I've created a small helper view, maybe would be useful for someone.

GitHub iOS 11 Push Notification View.

How to format a phone number with jQuery

Don't forget to ensure you are working with purely integers.

var separator = '-';
$( ".phone" ).text( function( i, DATA ) {
    DATA
        .replace( /[^\d]/g, '' )
        .replace( /(\d{3})(\d{3})(\d{4})/, '$1' + separator + '$2' + separator + '$3' );
    return DATA;
});

Is Java "pass-by-reference" or "pass-by-value"?

The bottom line on pass-by-value: the called method can't change the caller's variable, although for object reference variables, the called method can change the object the variable referred to. What's the difference between changing the variable and changing the object? For object references, it means the called method can't reassign the caller's original reference variable and make it refer to a different object, or null.

I took this code and explanation from a book on Java Certification and made some minor changes.
I think it's a good illustration to the pass by value of an object. In the code below, reassigning g does not reassign f! At the end of the bar() method, two Foo objects have been created, one referenced by the local variable f and one referenced by the local (argument) variable g.

Because the doStuff() method has a copy of the reference variable, it has a way to get to the original Foo object, for instance to call the setName() method. But, the doStuff() method does not have a way to get to the f reference variable. So doStuff() can change values within the object f refers to, but doStuff() can't change the actual contents (bit pattern) of f. In other words, doStuff() can change the state of the object that f refers to, but it can't make f refer to a different object!

package test.abc;

public class TestObject {

    /**
     * @param args
     */
    public static void main(String[] args) {
        bar();
    }

    static void bar() {
        Foo f = new Foo();
        System.out.println("Object reference for f: " + f);
        f.setName("James");
        doStuff(f);
        System.out.println(f.getName());
        //Can change the state of an object variable in f, but can't change the object reference for f.
        //You still have 2 foo objects.
        System.out.println("Object reference for f: " + f);
        }

    static void doStuff(Foo g) {
            g.setName("Boo");
            g = new Foo();
            System.out.println("Object reference for g: " + g);
        }
}


package test.abc;

public class Foo {
    public String name = "";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Note that the object reference has not changed in the console output below:

Console output:

Object reference for f: test.abc.Foo@62f72617

Object reference for g: test.abc.Foo@4fe5e2c3

Boo Object reference for f: test.abc.Foo@62f72617

Difference between webdriver.get() and webdriver.navigate()

They both seems to navigate to the given webpage and quoting @matt answer:

navigate().to() and get() do exactly the same thing.

Single-Page Applications are an exception to this.

The difference between these two methods comes not from their behavior, but from the behavior in the way the application works and how browser deal with it.

navigate().to() navigates to the page by changing the URL like doing forward/backward navigation.

Whereas, get() refreshes the page to changing the URL.

So, in cases where application domain changes, both the method behaves similarly. That is, page is refreshed in both the cases. But, in single-page applications, while navigate().to() do not refreshes the page, get() do.

Moreover, this is the reason browser history is getting lost when get() is used due to application being refreshed.

Originally answered: https://stackoverflow.com/a/33868976/3619412

NodeJS / Express: what is "app.use"?

app.use applies the specified middleware to the main app middleware stack. When attaching middleware to the main app stack, the order of attachment matters; if you attach middleware A before middleware B, middleware A will always execute first. You can specify a path for which a particular middleware is applicable. In the below example, “hello world” will always be logged before “happy holidays.”

const express = require('express')
const app = express()

app.use(function(req, res, next) {
  console.log('hello world')
  next()
})

app.use(function(req, res, next) {
  console.log('happy holidays')
  next()
})

Using a dictionary to select function to execute

def p1( ):
    print("in p1")

def p2():
    print("in p2")

myDict={
    "P1": p1,
    "P2": p2

}

name=input("enter P1 or P2")

myDictname

Can I set state inside a useEffect hook

For future purposes, this may help too:

It's ok to use setState in useEffect you just need to have attention as described already to not create a loop.

But it's not the only problem that may occur. See below:

Imagine that you have a component Comp that receives props from parent and according to a props change you want to set Comp's state. For some reason, you need to change for each prop in a different useEffect:

DO NOT DO THIS

useEffect(() => {
  setState({ ...state, a: props.a });
}, [props.a]);

useEffect(() => {
  setState({ ...state, b: props.b });
}, [props.b]);

It may never change the state of a as you can see in this example: https://codesandbox.io/s/confident-lederberg-dtx7w

The reason why this happen in this example it's because both useEffects run in the same react cycle when you change both prop.a and prop.b so the value of {...state} when you do setState are exactly the same in both useEffect because they are in the same context. When you run the second setState it will replace the first setState.

DO THIS INSTEAD

The solution for this problem is basically call setState like this:

useEffect(() => {
  setState(state => ({ ...state, a: props.a }));
}, [props.a]);

useEffect(() => {
  setState(state => ({ ...state, b: props.b }));
}, [props.b]);

Check the solution here: https://codesandbox.io/s/mutable-surf-nynlx

Now, you always receive the most updated and correct value of the state when you proceed with the setState.

I hope this helps someone!

auto run a bat script in windows 7 at login

I hit this question looking for how to run batch scripts during user logon on a standalone windows server (workgroup not in domain). I found the answer in using group policy.

  1. gpedit.msc
  2. user configuration->administrative templates->system->logon->run these programs at user logon
  3. add batch scripts.
  4. you can add them using cmd /k mybatchfile.cmd if you want the command window to stay (on desktop) after batch script have finished.
  5. gpupdate - to update the group policy.

How to fix nginx throws 400 bad request headers on any header testing tools?

Just to clearify, in /etc/nginx/nginx.conf, you can put at the beginning of the file the line

error_log /var/log/nginx/error.log debug;

And then restart nginx:

sudo service nginx restart

That way you can detail what nginx is doing and why it is returning the status code 400.

How to get the selected date of a MonthCalendar control in C#

"Just set the MaxSelectionCount to 1 so that users cannot select more than one day. Then in the SelectionRange.Start.ToString(). There is nothing available to show the selection of only one day." - Justin Etheredge

From here.

Difference between java.lang.RuntimeException and java.lang.Exception

  1. User-defined Exception can be Checked Exception or Unchecked Exception, It depends on the class it is extending to.

  2. User-defined Exception can be Custom Checked Exception, if it is extending to Exception class

  3. User-defined Exception can be Custom Unchecked Exception , if it is extending to Run time Exception class.

  4. Define a class and make it a child to Exception or Run time Exception

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

If you are using Samsung Device and by any chance marked your app for Samsung Knox, then you need to uninstall it from My Knox app.

Uninstalling just from General apps won't uninstall it from Knox App. It has to be done explicitly!

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

Another issue you have to take care of: If your generated file names are not the default id_rsa and id_rsa.pub.

You have to create the .ssh/config file and define manually which id file you are going to use with the connection.

An example is here:

Host remote_host_name
    HostName 172.xx.xx.xx
    User my_user
    IdentityFile /home/my_user/.ssh/my_user_custom

Rolling back local and remote git repository by 1 commit

There are many way you can do this. Based on your requirement choose anything from below.

1. By REVERTing commit:

If you want to REVERT all the changes from you last COMMIT that means If you ADD something in your file that will be REMOVED after revert has been done. If you REMOVE something in your file the revert process will ADD those file.

You can REVERT the very last COMMIT. Like:

1.git revert head^
2.git push origin <Branch-Name>

Or you can revert to any previous commit using the hash of that commit.Like:

1.git revert <SHA>
2.git push origin  <Branch-Name>

2. By RESETing previous Head

If you want to just point to any previous commit use reset; it points your local environment back to a previous commit. You can reset your head to previous commit or reset your head to previous any commit.

Reset to previous commit.

1.git reset head^
2.git push -f origin <Branch-name>

Reset to any previous commit:

1.git reset <SHA>
2.git push -f origin <Branch-name>

Trade of between REVERT & RESET:

Why would you choose to do a revert over a reset operation? If you have already pushed your chain of commits to the remote repository (where others may have pulled your code and started working with it), a revert is a nicer way to cancel out changes for them. This is because the Git workflow works well for picking up additional commits at the end of a branch, but it can be challenging if a set of commits is no longer seen in the chain when someone resets the branch pointer back.

ERROR: Error 1005: Can't create table (errno: 121)

Foreign Key Constraint Names Have to be Unique Within a Database

Both @Dorvalla’s answer and this blog post mentioned above pointed me into the right direction to fix the problem for myself; quoting from the latter:

If the table you're trying to create includes a foreign key constraint, and you've provided your own name for that constraint, remember that it must be unique within the database.

I wasn’t aware of that. I have changed my foreign key constraint names according to the following schema which appears to be used by Ruby on Rails applications, too:

<TABLE_NAME>_<FOREIGN_KEY_COLUMN_NAME>_fk

For the OP’s table this would be Link_lession_id_fk, for example.

Carousel with Thumbnails in Bootstrap 3.0

Just found out a great plugin for this:

http://flexslider.woothemes.com/

Regards

Pass connection string to code-first DbContext

I have a little solution example for that problem.

MyDBContext.cs

 public MyDBContext(DBConnectionType ConnectionType) //: base("ConnMain")
  {
      if(ConnectionType==DBConnectionType.MainConnection)
       {
         this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnMain"].ConnectionString;
       }
      else if(ConnectionType==DBConnectionType.BackupConnection)
       {
         this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnBackup"].ConnectionString;
       }
  }

MyClass.cs

public enum DBConnectionType
 {
    MainConnection=0,
    BackupConnection=1
 }

frmMyForm.cs

 MyDBContext db = new MyDBContext(DBConnectionType.MainConnection);
                               //or
//MyDBContext db = new MyDBContext(DBConnectionType.BackupConnection);

Disabling same-origin policy in Safari

There is an option to disable cross-origin restrictions in Safari 9, different from local file restrictions as mentioned above.

Wait .5 seconds before continuing code VB.net

This question is old but here is another answer because it is useful fo others:

thread.sleep is not a good method for waiting, because usually it freezes the software until finishing its time, this function is better:

   Imports VB = Microsoft.VisualBasic

   Public Sub wait(ByVal seconds As Single)
     Static start As Single
     start = VB.Timer()
     Do While VB.Timer() < start + seconds
       System.Windows.Forms.Application.DoEvents()
     Loop
   End Sub

The above function waits for a specific time without freezing the software, however increases the CPU usage.

This function not only doesn't freeze the software, but also doesn't increase the CPU usage:

   Private Sub wait(ByVal seconds As Integer)
     For i As Integer = 0 To seconds * 100
       System.Threading.Thread.Sleep(10)
       Application.DoEvents()
     Next
   End Sub

.datepicker('setdate') issues, in jQuery

If you would like to support really old browsers you should parse the date string, since using the ISO8601 date format with the Date constructor is not supported pre IE9:

var queryDate = '2009-11-01',
    dateParts = queryDate.match(/(\d+)/g)
    realDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);  
                                    // months are 0-based!
// For >= IE9
var realDate = new Date('2009-11-01');  

$('#datePicker').datepicker({ dateFormat: 'yy-mm-dd' }); // format to show
$('#datePicker').datepicker('setDate', realDate);

Check the above example here.

Making text background transparent but not text itself

If you use RGBA for modern browsers you don't need let older IEs use only the non-transparent version of the given color with RGB.

If you don't stick to CSS-only solutions, give CSS3PIE a try. With this syntax you can see exactly the same result in older IEs that you see in modern browsers:

div {
    -pie-background: rgba(223,231,233,0.8);
    behavior: url(../PIE.htc);
}

How to use timer in C?

Yes, you need a loop. If you already have a main loop (most GUI event-driven stuff does) you can probably stick your timer into that. Use:

#include <time.h> 
time_t my_t, fire_t;

Then (for times over 1 second), initialize your timer by reading the current time:

my_t = time(NULL);

Add the number of seconds your timer should wait and store it in fire_t. A time_t is essentially a uint32_t, you may need to cast it.

Inside your loop do another

my_t = time(NULL);

if (my_t > fire_t) then consider the timer fired and do the stuff you want there. That will probably include resetting it by doing another fire_t = time(NULL) + seconds_to_wait for next time.

A time_t is a somewhat antiquated unix method of storing time as the number of seconds since midnight 1/1/1970 but it has many advantages. For times less than 1 second you need to use gettimeofday() (microseconds) or clock_gettime() (nanoseconds) and deal with a struct timeval or struct timespec which is a time_t and the microseconds or nanoseconds since that 1 second mark. Making a timer works the same way except when you add your time to wait you need to remember to manually do the carry (into the time_t) if the resulting microseconds or nanoseconds value goes over 1 second. Yes, it's messy. See man 2 time, man gettimeofday, man clock_gettime.

sleep(), usleep(), nanosleep() have a hidden benefit. You see it as pausing your program, but what they really do is release the CPU for that amount of time. Repeatedly polling by reading the time and comparing to the done time (are we there yet?) will burn a lot of CPU cycles which may slow down other programs running on the same machine (and use more electricity/battery). It's better to sleep() most of the time then start checking the time.

If you're trying to sleep and do work at the same time you need threads.

Why docker container exits immediately

I would like to extend or dare I say, improve answer mentioned by camposer

When you run

docker run -dit ubuntu

you are basically running the container in background in interactive mode.

When you attach and exit the container by CTRL+D (most common way to do it), you stop the container because you just killed the main process which you started your container with the above command.

Making advantage of an already running container, I would just fork another process of bash and get a pseudo TTY by running:

docker exec -it <container ID> /bin/bash

How can I consume a WSDL (SOAP) web service in Python?

I would recommend that you have a look at SUDS

"Suds is a lightweight SOAP python client for consuming Web Services."

How to encode a string in JavaScript for displaying in HTML?

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

So then with var unsafestring = "<oohlook&atme>"; you would use htmlEntities(unsafestring);

How to show data in a table by using psql command line interface?

Newer versions: (from 8.4 - mentioned in release notes)

TABLE mytablename;

Longer but works on all versions:

SELECT * FROM mytablename;

You may wish to use \x first if it's a wide table, for readability.

For long data:

SELECT * FROM mytable LIMIT 10;

or similar.

For wide data (big rows), in the psql command line client, it's useful to use \x to show the rows in key/value form instead of tabulated, e.g.

 \x
SELECT * FROM mytable LIMIT 10;

Note that in all cases the semicolon at the end is important.

How do I change a single value in a data.frame?

To change a cell value using a column name, one can use

iris$Sepal.Length[3]=999

How to view DLL functions?

For native code it's probably best to use Dependency Walker. It also possible to use dumpbin command line utility that comes with Visual Studio.

HTML entity for the middle dot

This can be done easily using &middot;. You can color or size the dot according to the tags you wrap it with. For example, try and run this

<h2> I &middot; love &middot; Coding </h2>

Get selected option from select element

Try following code

$('#ddlCodes').change(function() {
  $('#txtEntry2').val(  $('#ddlCodes :selected').text() );
});