Programs & Examples On #Capitalization

Capitalize words in string

If you're using lodash in your JavaScript application, You can use _.capitalize:

_x000D_
_x000D_
console.log( _.capitalize('ÿöur striñg') );_x000D_
 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Is there a way to style a TextView to uppercase all of its letters?

It is really very disappointing that you can't do it with styles (<item name="android:textAllCaps">true</item>) or on each XML layout file with the textAllCaps attribute, and the only way to do it is actually using theString.toUpperCase() on each of the strings when you do a textViewXXX.setText(theString).

In my case, I did not wanted to have theString.toUpperCase() everywhere in my code but to have a centralized place to do it because I had some Activities and lists items layouts with TextViews that where supposed to be capitalized all the time (a title) and other who did not... so... some people may think is an overkill, but I created my own CapitalizedTextView class extending android.widget.TextView and overrode the setText method capitalizing the text on the fly.

At least, if the design changes or I need to remove the capitalized text in future versions, I just need to change to normal TextView in the layout files.

Now, take in consideration that I did this because the App's Designer actually wanted this text (the titles) in CAPS all over the App no matter the original content capitalization, and also I had other normal TextViews where the capitalization came with the the actual content.

This is the class:

package com.realactionsoft.android.widget;

import android.content.Context; 
import android.util.AttributeSet; 
import android.view.ViewTreeObserver; 
import android.widget.TextView;


public class CapitalizedTextView extends TextView implements ViewTreeObserver.OnPreDrawListener {

    public CapitalizedTextView(Context context) {
        super(context);
    }

    public CapitalizedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CapitalizedTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text.toString().toUpperCase(), type);
    }

}

And whenever you need to use it, just declare it with all the package in the XML layout:

<com.realactionsoft.android.widget.CapitalizedTextView 
        android:id="@+id/text_view_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

Some will argue that the correct way to style text on a TextView is to use a SpannableString, but I think that would be even a greater overkill, not to mention more resource-consuming because you'll be instantiating another class than TextView.

Capitalize only first character of string and leave others alone? (Rails)

Note that if you need to deal with multi-byte characters, i.e. if you have to internationalize your site, the s[0] = ... solution won't be adequate. This Stack Overflow question suggests using the unicode-util gem

Ruby 1.9: how can I properly upcase & downcase multibyte strings?

EDIT

Actually an easier way to at least avoid strange string encodings is to just use String#mb_chars:

s = s.mb_chars
s[0] = s.first.upcase
s.to_s

How can I capitalize the first letter of each word in a string?

Although all the answers are already satisfactory, I'll try to cover the two extra cases along with the all the previous case.

if the spaces are not uniform and you want to maintain the same

string = hello    world i  am    here.

if all the string are not starting from alphabets

string = 1 w 2 r 3g

Here you can use this:

def solve(s):
    a = s.split(' ')
    for i in range(len(a)):
        a[i]= a[i].capitalize()
    return ' '.join(a)

This will give you:

output = Hello    World I  Am    Here
output = 1 W 2 R 3g

How to capitalize the first character of each word in a string

The short and precise way is as follows:

String name = "test";

name = (name.length() != 0) ?name.toString().toLowerCase().substring(0,1).toUpperCase().concat(name.substring(1)): name;
--------------------
Output
--------------------
Test
T 
empty
--------------------

It works without error if you try and change the name value to the three of values. Error free.

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

My attempt.

Only acts if all text is lowercase or all uppercase, uses Locale case conversion. Attempts to respect intentional case difference or a ' or " in names. Happens on Blur as to not cause annoyances on phones. Although left in selection start/end so if changed to keyup maybe useful still. Should work on phones but have not tried.

$.fn.capitalize = function() {
    $(this).blur(function(event) {
        var box = event.target;
        var txt = $(this).val();
        var lc = txt.toLocaleLowerCase();
        var startingWithLowerCaseLetterRegex = new RegExp("\b([a-z])", "g");
        if (!/([-'"])/.test(txt) && txt === lc || txt === txt.toLocaleUpperCase()) {
            var stringStart = box.selectionStart;
            var stringEnd = box.selectionEnd;
            $(this).val(lc.replace(startingWithLowerCaseLetterRegex, function(c) { return c.toLocaleUpperCase() }).trim());
            box.setSelectionRange(stringStart, stringEnd);
        }
    });
   return this;
}

// Usage:
$('input[type=text].capitalize').capitalize();

Install apk without downloading

you can use this code .may be solve the problem

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Sometimes, you create new application pool and cann't solve it via DCOMCNFG. Then there is another method to do:

Set the Identity (Model Name) of application pool to LocalSystem.

I don't know the root cause, but it solve my problem one time.

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

its awful oracle installer:

[INS-13001]

I got it as I used MY_PC as NETBIOS name instead of MYPC (Underscore is bad for it..)

Can be an historical reason.. but message is obscure.

Git: How to find a deleted file in the project commit history?

Get a list of the deleted files and copy the full path of the deleted file

git log --diff-filter=D --summary | grep delete

Execute the next command to find commit id of that commit and copy the commit id

git log --all -- FILEPATH

Show diff of deleted file

git show COMMIT_ID -- FILE_PATH

Remember, you can write output to a file using > like

git show COMMIT_ID -- FILE_PATH > deleted.diff

Frontend tool to manage H2 database

There's a shell client built in too which is handy.

java -cp h2*.jar org.h2.tools.Shell

http://opensource-soa.blogspot.com.au/2009/03/how-to-use-h2-shell.html

$ java -cp h2.jar org.h2.tools.Shell -help
Interactive command line tool to access a database using JDBC.
Usage: java org.h2.tools.Shell <options>
Options are case sensitive. Supported options are:
[-help] or [-?]        Print the list of options
[-url "<url>"]         The database URL (jdbc:h2:...)
[-user <user>]         The user name
[-password <pwd>]      The password
[-driver <class>]      The JDBC driver class to use (not required in most cases)
[-sql "<statements>"]  Execute the SQL statements and exit
[-properties "<dir>"]  Load the server properties from this directory
If special characters don't work as expected, you may need to use
 -Dfile.encoding=UTF-8 (Mac OS X) or CP850 (Windows).
See also http://h2database.com/javadoc/org/h2/tools/Shell.html

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();
    }

Merge (with squash) all changes from another branch as a single commit

Found it! Merge command has a --squash option

git checkout master
git merge --squash WIP

at this point everything is merged, possibly conflicted, but not committed. So I can now:

git add .
git commit -m "Merged WIP"

How to create empty constructor for data class in Kotlin Android

Along with @miensol answer, let me add some details:

If you want a Java-visible empty constructor using data classes, you need to define it explicitely.

Using default values + constructor specifier is quite easy:

data class Activity(
    var updated_on: String = "",
    var tags: List<String> = emptyList(),
    var description: String = "",
    var user_id: List<Int> = emptyList(),
    var status_id: Int = -1,
    var title: String = "",
    var created_at: String = "",
    var data: HashMap<*, *> = hashMapOf<Any, Any>(),
    var id: Int = -1,
    var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
) {
    constructor() : this(title = "") // this constructor is an explicit
                                     // "empty" constructor, as seen by Java.
}

This means that with this trick you can now serialize/deserialize this object with the standard Java serializers (Jackson, Gson etc).

Perform debounce in React.js

If you are using redux you can do this in a very elegant way with middleware. You can define a Debounce middleware as:

var timeout;
export default store => next => action => {
  const { meta = {} } = action;
  if(meta.debounce){
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      next(action)
    }, meta.debounce)
  }else{
    next(action)
  }
}

You can then add debouncing to action creators, such as:

export default debouncedAction = (payload) => ({
  type : 'DEBOUNCED_ACTION',
  payload : payload,
  meta : {debounce : 300}
}

There's actually already middleware you can get off npm to do this for you.

Oracle timestamp data type

Quite simply the number is the precision of the timestamp, the fraction of a second held in the column:

SQL> create table t23
  2  (ts0 timestamp(0)
  3   , ts3 timestamp(3)
  4  , ts6 timestamp(6)
  5  )
  6  /

Table created.

SQL> insert into t23 values (systimestamp, systimestamp, systimestamp)
  2  /

1 row created.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM


SQL> 

If we don't specify a precision then the timestamp defaults to six places.

SQL> alter table t23 add ts_def timestamp;

Table altered.

SQL> update t23      
  2  set ts_def = systimestamp
  3  /

1 row updated.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM


SQL> 

Note that I'm running on Linux so my TIMESTAMP column actually gives me precision to six places i.e. microseconds. This would also be the case on most (all?) flavours of Unix. On Windows the limit is three places i.e. milliseconds. (Is this still true of the most modern flavours of Windows - citation needed).

As might be expected, the documentation covers this. Find out more.


"when you create timestamp(9) this gives you nanos right"

Only if the OS supports it. As you can see, my OEL appliance does not:

SQL> alter table t23 add ts_nano timestamp(9)
  2  /

Table altered.

SQL> update t23 set ts_nano = systimestamp(9)
  2  /

1 row updated.

SQL> select * from t23
  2  /

TS0
---------------------------------------------------------------------------
TS3
---------------------------------------------------------------------------
TS6
---------------------------------------------------------------------------
TS_DEF
---------------------------------------------------------------------------
TS_NANO
---------------------------------------------------------------------------
24-JAN-12 05.57.12 AM
24-JAN-12 05.57.12.003 AM
24-JAN-12 05.57.12.002648 AM
24-JAN-12 05.59.27.293305 AM
24-JAN-12 08.28.03.990557000 AM


SQL> 

(Those trailing zeroes could be a coincidence but they aren't.)

How do I increment a DOS variable in a FOR /F loop?

The problem with your code snippet is the way variables are expanded. Variable expansion is usually done when a statement is first read. In your case the whole FOR loop and its block is read and all variables, except the loop variables are expanded to their current value.

This means %c% in your echo %%i, %c% expanded instantly and so is actually used as echo %%i, 1 in each loop iteration.

So what you need is the delayed variable expansion. Find some good explanation about it here.

Variables that should be delay expanded are referenced with !VARIABLE! instead of %VARIABLE%. But you need to activate this feature with setlocal ENABLEDELAYEDEXPANSION and reset it with a matching endlocal.

Your modified code would look something like that:

set TEXT_T="myfile.txt"

set /a c=1

setlocal ENABLEDELAYEDEXPANSION

FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
  set /a c=c+1

  echo %%i, !c!
)

endlocal

String length in bytes in JavaScript

There is no way to do it in JavaScript natively. (See Riccardo Galli's answer for a modern approach.)


For historical reference or where TextEncoder APIs are still unavailable.

If you know the character encoding, you can calculate it yourself though.

encodeURIComponent assumes UTF-8 as the character encoding, so if you need that encoding, you can do,

function lengthInUtf8Bytes(str) {
  // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
  var m = encodeURIComponent(str).match(/%[89ABab]/g);
  return str.length + (m ? m.length : 0);
}

This should work because of the way UTF-8 encodes multi-byte sequences. The first encoded byte always starts with either a high bit of zero for a single byte sequence, or a byte whose first hex digit is C, D, E, or F. The second and subsequent bytes are the ones whose first two bits are 10. Those are the extra bytes you want to count in UTF-8.

The table in wikipedia makes it clearer

Bits        Last code point Byte 1          Byte 2          Byte 3
  7         U+007F          0xxxxxxx
 11         U+07FF          110xxxxx        10xxxxxx
 16         U+FFFF          1110xxxx        10xxxxxx        10xxxxxx
...

If instead you need to understand the page encoding, you can use this trick:

function lengthInPageEncoding(s) {
  var a = document.createElement('A');
  a.href = '#' + s;
  var sEncoded = a.href;
  sEncoded = sEncoded.substring(sEncoded.indexOf('#') + 1);
  var m = sEncoded.match(/%[0-9a-f]{2}/g);
  return sEncoded.length - (m ? m.length * 2 : 0);
}

How to print pthread_t

In this case, it depends on the operating system, since the POSIX standard no longer requires pthread_t to be an arithmetic type:

IEEE Std 1003.1-2001/Cor 2-2004, item XBD/TC2/D6/26 is applied, adding pthread_t to the list of types that are not required to be arithmetic types, thus allowing pthread_t to be defined as a structure.

You will need to look in your sys/types.h header and see how pthread_t is implemented; then you can print it how you see fit. Since there isn't a portable way to do this and you don't say what operating system you are using, there's not a whole lot more to say.

Edit: to answer your new question, GDB assigns its own thread ids each time a new thread starts:

For debugging purposes, gdb associates its own thread number—always a single integer—with each thread in your program.

If you are looking at printing a unique number inside of each thread, your cleanest option would probably be to tell each thread what number to use when you start it.

What's the default password of mariadb on fedora?

By default, a MariaDB installation has an anonymous user, allowing anyone to log into MariaDB without having to have a user account created for them. This is intended only for testing, and to make the installation go a bit smoother. You should remove them before moving into a production environment.

Android soft keyboard covers EditText field

I had the same issue and searching the people said to add adjustPan, while in my case adjustResize worked.

<activity
    android:name=".YOUR.ACTIVITY"
    ...
    android:windowSoftInputMode="adjustResize"
/>

Call int() function on every list element?

Another way,

for i, v in enumerate(numbers): numbers[i] = int(v)

How to stop line breaking in vim

It is correct that set nowrap will allow you to paste in a long line without vi/vim adding newlines, but then the line is not visually wrapped for easy reading. It is instead just one long line that you have to scroll through.

To have the line visually wrap but not have newline characters inserted into it, have set wrap (which is probably default so not needed to set) and set textwidth=0.

On some systems the setting of textwidth=0 is default. If you don't find that to be the case, add set textwidth=0 to your .exrc file so that it becomes your user's default for all vi/vim sessions.

Should URL be case sensitive?

All “insensitive”s are boldened for readability.

Domain names are case insensitive according to RFC 4343. The rest of URL is sent to the server via the GET method. This may be case sensitive or not.

Take this page for example, stackoverflow.com receives GET string /questions/7996919/should-url-be-case-sensitive, sending a HTML document to your browser. Stackoverflow.com is case insensitive because it produces the same result for /QUEStions/7996919/Should-url-be-case-sensitive.

On the other hand, Wikipedia is case sensitive except the first character of the title. The URLs https://en.wikipedia.org/wiki/Case_sensitivity and https://en.wikipedia.org/wiki/case_sensitivity leads to the same article, but https://en.wikipedia.org/wiki/CASE_SENSITIVITY returns 404.

check output from CalledProcessError

Thanx @krd, I am using your error catch process, but had to update the print and except statements. I am using Python 2.7.6 on Linux Mint 17.2.

Also, it was unclear where the output string was coming from. My update:

import subprocess

# Output returned in error handler
try:
    print("Ping stdout output on success:\n" + 
           subprocess.check_output(["ping", "-c", "2", "-w", "2", "1.1.1.1"]))
except subprocess.CalledProcessError as e:
    print("Ping stdout output on error:\n" + e.output)

# Output returned normally
try:
    print("Ping stdout output on success:\n" + 
           subprocess.check_output(["ping", "-c", "2", "-w", "2", "8.8.8.8"]))
except subprocess.CalledProcessError as e:
    print("Ping stdout output on error:\n" + e.output)

I see an output like this:

Ping stdout output on error:
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.

--- 1.1.1.1 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1007ms


Ping stdout output on success:
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=59 time=37.8 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=59 time=38.8 ms

--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 37.840/38.321/38.802/0.481 ms

Encrypting & Decrypting a String in C#

If you need to store a password in memory and would like to have it encrypted you should use SecureString:

http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx

For more general uses I would use a FIPS approved algorithm such as Advanced Encryption Standard, formerly known as Rijndael. See this page for an implementation example:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx

Add column to SQL Server

Adding a column using SSMS or ALTER TABLE .. ADD will not drop any existing data.

Can anyone explain IEnumerable and IEnumerator to me?

IEnumerable and IEnumerator (and their generic counterparts IEnumerable<T> and IEnumerator<T>) are base interfaces of iterator implementations in .Net Framework Class Libray collections.

IEnumerable is the most common interface you would see in the majority of the code out there. It enables the foreach loop, generators (think yield) and because of its tiny interface, it's used to create tight abstractions. IEnumerable depends on IEnumerator.

IEnumerator, on the other hand, provides a slightly lower level iteration interface. It's referred to as the explicit iterator which gives the programmer more control over the iteration cycle.

IEnumerable

IEnumerable is a standard interface that enables iterating over collections that supports it (in fact, all collection types I can think of today implements IEnumerable). Compiler support allows language features like foreach. In general terms, it enables this implicit iterator implementation.

foreach Loop

foreach (var value in list)
  Console.WriteLine(value);

I think foreach loop is one of the main reasons for using IEnumerable interfaces. foreach has a very succinct syntax and very easy to understand compared to classic C style for loops where you need to check the various variables to see what it was doing.

yield Keyword

Probably a lesser known feature is that IEnumerable also enables generators in C# with the use of yield return and yield break statements.

IEnumerable<Thing> GetThings() {
   if (isNotReady) yield break;
   while (thereIsMore)
     yield return GetOneMoreThing();
}

Abstractions

Another common scenario in practice is using IEnumerable to provide minimalistic abstractions. Because it is a minuscule and read-only interface, you are encouraged to expose your collections as IEnumerable (rather than List for example). That way you are free to change your implementation without breaking your client's code (change List to a LinkedList for instance).

Gotcha

One behaviour to be aware of is that in streaming implementations (e.g. retrieving data row by row from a database, instead of loading all the results in memory first) you cannot iterate over the collection more than once. This is in contrast to in-memory collections like List, where you can iterate multiple times without problems. ReSharper, for example, has a code inspection for Possible multiple enumeration of IEnumerable.

IEnumerator

IEnumerator, on the other hand, is the behind the scenes interface which makes IEnumerble-foreach-magic work. Strictly speaking, it enables explicit iterators.

var iter = list.GetEnumerator();
while (iter.MoveNext())
    Console.WriteLine(iter.Current);

In my experience IEnumerator is rarely used in common scenarios due to its more verbose syntax and slightly confusing semantics (at least to me; e.g. MoveNext() returns a value as well, which the name doesn't suggest at all).

Use case for IEnumerator

I only used IEnumerator in particular (slightly lower level) libraries and frameworks where I was providing IEnumerable interfaces. One example is a data stream processing library which provided series of objects in a foreach loop even though behind the scenes data was collected using various file streams and serialisations.

Client code

foreach(var item in feed.GetItems())
    Console.WriteLine(item);

Library

IEnumerable GetItems() {
    return new FeedIterator(_fileNames)
}

class FeedIterator: IEnumerable {
    IEnumerator GetEnumerator() {
        return new FeedExplicitIterator(_stream);
    }
}

class FeedExplicitIterator: IEnumerator {
    DataItem _current;

    bool MoveNext() {
        _current = ReadMoreFromStream();
        return _current != null;           
    }

    DataItem Current() {
        return _current;   
    }
}

How to get the current URL within a Django template?

In Django 3, you want to use url template tag:

{% url 'name-of-your-user-profile-url' possible_context_variable_parameter %}

For an example, see the documentation

Check if PHP session has already started

You can use the following solution to check if a PHP session has already started:

if(session_id()== '')
{
   echo"Session isn't Start";
}
else
{
    echo"Session Started";
}

How to compare two files in Notepad++ v6.6.8

Update:

  • for Notepad++ 7.5 and above use Compare v2.0.0
  • for Notepad++ 7.7 and above use Compare v2.0.0 for Notepad++ 7.7, if you need to install manually follow the description below, otherwise use "Plugin Admin".

I use Compare plugin 2 for notepad++ 7.5 and newer versions. Notepad++ 7.5 and newer versions does not have plugin manager. You have to download and install plugins manually. And YES it matters if you use 64bit or 32bit (86x).

So Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin, and the same valid for 32bit.

I wrote a guideline how to install it:

  1. Start your Notepad++ as administrator mode.
  2. Press F1 to find out if your Notepad++ is 64bit or 32bit (86x), hence you need to download the correct plugin version. Download Compare-plugin 2.
  3. Unzip Compare-plugin in temporary folder.
  4. Import plugin from the temporary folder.
  5. The plugin should appear under Plugins menu.

Note:
It is also possible to drag and drop the plugin .dll file directly in plugin folder.
64bit: %programfiles%\Notepad++\plugins
32bit: %programfiles(x86)%\Notepad++\plugins

Update Thanks to @TylerH with this update: Notepad++ Now has "Plugin Admin" as a replacement for the old Plugin Manager. But this method (answer) is still valid for adding plugins manually for almost any Notepad++ plugins.

Disclaimer: the link of this guideline refer to my personal web site.

UIBarButtonItem in navigation bar programmatically?

func viewDidLoad(){
let homeBtn: UIButton = UIButton(type: UIButtonType.custom)

        homeBtn.setImage(UIImage(named: "Home.png"), for: [])

        homeBtn.addTarget(self, action: #selector(homeAction), for: UIControlEvents.touchUpInside)

        homeBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)

        let homeButton = UIBarButtonItem(customView: homeBtn)


        let backBtn: UIButton = UIButton(type: UIButtonType.custom)

        backBtn.setImage(UIImage(named: "back.png"), for: [])

        backBtn.addTarget(self, action: #selector(backAction), for: UIControlEvents.touchUpInside)

        backBtn.frame = CGRect(x: -10, y: 0, width: 30, height: 30)

        let backButton = UIBarButtonItem(customView: backBtn)
        self.navigationItem.setLeftBarButtonItems([backButton,homeButton], animated: true)
}

}

Java abstract interface

Why is it necessary for an interface to be "declared" abstract?

It's not.

public abstract interface Interface {
       \___.__/
           |
           '----> Neither this...

    public void interfacing();
    public abstract boolean interfacing(boolean really);
           \___.__/
               |
               '----> nor this, are necessary.
}

Interfaces and their methods are implicitly abstract and adding that modifier makes no difference.

Is there other rules that applies with an abstract interface?

No, same rules apply. The method must be implemented by any (concrete) implementing class.

If abstract is obsolete, why is it included in Java? Is there a history for abstract interface?

Interesting question. I dug up the first edition of JLS, and even there it says "This modifier is obsolete and should not be used in new Java programs".

Okay, digging even further... After hitting numerous broken links, I managed to find a copy of the original Oak 0.2 Specification (or "manual"). Quite interesting read I must say, and only 38 pages in total! :-)

Under Section 5, Interfaces, it provides the following example:

public interface Storing {
    void freezeDry(Stream s) = 0;
    void reconstitute(Stream s) = 0;
}

And in the margin it says

In the future, the " =0" part of declaring methods in interfaces may go away.

Assuming =0 got replaced by the abstract keyword, I suspect that abstract was at some point mandatory for interface methods!


Related article: Java: Abstract interfaces and abstract interface methods

How can I convert a comma-separated string to an array?

var array = string.split(',');

MDN reference, mostly helpful for the possibly unexpected behavior of the limit parameter. (Hint: "a,b,c".split(",", 2) comes out to ["a", "b"], not ["a", "b,c"].)

How to quickly test some javascript code?

Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.

How to select only the records with the highest date in LINQ

Go a simple way to do this :-

Created one class to hold following information

  • Level (number)
  • Url (Url of the site)

Go the list of sites stored on a ArrayList object. And executed following query to sort it in descending order by Level.

var query = from MyClass object in objCollection 
    orderby object.Level descending 
    select object

Once I got the collection sorted in descending order, I wrote following code to get the Object that comes as top row

MyClass topObject = query.FirstRow<MyClass>()

This worked like charm.

error: passing xxx as 'this' argument of xxx discards qualifiers

Let's me give a more detail example. As to the below struct:

struct Count{
    uint32_t c;

    Count(uint32_t i=0):c(i){}

    uint32_t getCount(){
        return c;
    }

    uint32_t add(const Count& count){
        uint32_t total = c + count.getCount();
        return total;
    }
};

enter image description here

As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object. In the method add count is declared as const object, but the method getCount is not const method, so count.getCount() may change the members in count.

Compile error as below(core message in my compiler):

error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]

To solve the above problem, you can:

  1. change the method uint32_t getCount(){...} to uint32_t getCount() const {...}. So count.getCount() won't change the members in count.

or

  1. change uint32_t add(const Count& count){...} to uint32_t add(Count& count){...}. So count don't care about changing members in it.

As to you problem, objects in the std::set are stored as const StudentT, but the method getId and getName are not const, so you give the above error.

You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.

How to set root password to null

The answer by user64141

use mysql;
update user set password=null where User='root';
flush privileges;
quit;

didn't work for me in MariaDB 10.1.5 (supposed to be a drop in replacement for MySQL). While didn't tested it in MySQL 5.6 to see if is an upstream change, the error I got was:

ERROR 1048 (23000): Column 'Password' cannot be null

But replacing the null with empty single or double quotes worked fine.

update user set password='' where User='root';

or

update user set password="" where User='root';

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

Why controllers are needed

The difference between link and controller comes into play when you want to nest directives in your DOM and expose API functions from the parent directive to the nested ones.

From the docs:

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

Say you want to have two directives my-form and my-text-input and you want my-text-input directive to appear only inside my-form and nowhere else.

In that case, you will say while defining the directive my-text-input that it requires a controller from the parent DOM element using the require argument, like this: require: '^myForm'. Now the controller from the parent element will be injected into the link function as the fourth argument, following $scope, element, attributes. You can call functions on that controller and communicate with the parent directive.

Moreover, if such a controller is not found, an error will be raised.

Why use link at all

There is no real need to use the link function if one is defining the controller since the $scope is available on the controller. Moreover, while defining both link and controller, one does need to be careful about the order of invocation of the two (controller is executed before).

However, in keeping with the Angular way, most DOM manipulation and 2-way binding using $watchers is usually done in the link function while the API for children and $scope manipulation is done in the controller. This is not a hard and fast rule, but doing so will make the code more modular and help in separation of concerns (controller will maintain the directive state and link function will maintain the DOM + outside bindings).

Spring boot - configure EntityManager

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the

application.properties

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true

Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    @PersistenceContext
    private EntityManager em;

}

This should be in your pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
</dependencies>

What is the difference between a pandas Series and a single-column DataFrame?

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index. The basic method to create a Series is to call:

s = pd.Series(data, index=index)

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.

 d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
 two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
 df = pd.DataFrame(d)

Python: How to increase/reduce the fontsize of x and y tick labels?

You can set the fontsize directly in the call to set_xticklabels and set_yticklabels (as noted in previous answers). This will only affect one Axes at a time.

ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)

You can also set the ticklabel font size globally (i.e. for all figures/subplots in a script) using rcParams:

import matplotlib.pyplot as plt

plt.rc('xtick',labelsize=8)
plt.rc('ytick',labelsize=8)

Or, equivalently:

plt.rcParams['xtick.labelsize']=8
plt.rcParams['ytick.labelsize']=8

Finally, if this is a setting that you would like to be set for all your matplotlib plots, you could also set these two rcParams in your matplotlibrc file:

xtick.labelsize      : 8 # fontsize of the x tick labels
ytick.labelsize      : 8 # fontsize of the y tick labels

Passing 'this' to an onclick event

The code that you have would work, but is executed from the global context, which means that this refers to the global object.

<script type="text/javascript">
var foo = function(param) {
    param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>

You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this.

<script type="text/javascript">
document.getElementById('bar').onclick = function() {
    this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>

C# Debug - cannot start debugging because the debug target is missing

Try these:

  1. Make sure that output path of project is correct (Project > Properties > Build > Output path)

  2. Go in menu to Build > Configuration Manager, and check if your main/entry project has checked Build. If not, check it.

SQL Server : check if variable is Empty or NULL for WHERE clause

Old post but worth a look for someone who stumbles upon like me

ISNULL(NULLIF(ColumnName, ' '), NULL) IS NOT NULL

ISNULL(NULLIF(ColumnName, ' '), NULL) IS NULL

Download files in laravel using Response::download

 HTML link click 
<a class="download" href="{{route('project.download',$post->id)}}">DOWNLOAD</a>


// Route

Route::group(['middleware'=>['auth']], function(){
    Route::get('file-download/{id}', 'PostController@downloadproject')->name('project.download');
});

public function downloadproject($id) {

        $book_cover = Post::where('id', $id)->firstOrFail();
        $path = public_path(). '/storage/uploads/zip/'. $book_cover->zip;
        return response()->download($path, $book_cover
            ->original_filename, ['Content-Type' => $book_cover->mime]);

    }

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

The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.

Getting the Label Near the Radio Button

I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float: territory):

  • Use <br />s to split the options apart and some CSS to vertically align them:
<style type='text/css'>
    .input input
    {
        width: 20px;
    }
</style>
<div class="input radio">
    <fieldset>
        <legend>What color is the sky?</legend>
        <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />

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

Applying a Style to the Currently Selected Label + Radio Button

Styling the <label> is why you'll need to resort to Javascript. A library like jQuery is perfect for this:

<style type='text/css'>
    .input label.focused
    {
        background-color: #EEEEEE;
        font-style: italic;
    }
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
    $(document).ready(function() {
        $('.input :radio').focus(updateSelectedStyle);
        $('.input :radio').blur(updateSelectedStyle);
        $('.input :radio').change(updateSelectedStyle);
    })

    function updateSelectedStyle() {
        $('.input :radio').removeClass('focused').next().removeClass('focused');
        $('.input :radio:checked').addClass('focused').next().addClass('focused');
    }
</script>

The focus and blur hooks are needed to make this work in IE.

Read .doc file with python

Prerequisites :

install antiword : sudo apt-get install antiword

install docx : pip install docx

from subprocess import Popen, PIPE

from docx import opendocx, getdocumenttext
from cStringIO import StringIO
def document_to_text(filename, file_path):
    cmd = ['antiword', file_path]
    p = Popen(cmd, stdout=PIPE)
    stdout, stderr = p.communicate()
    return stdout.decode('ascii', 'ignore')

print document_to_text('your_file_name','your_file_path')

Notice – New versions of python-docx removed this function. Make sure to pip install docx and not the new python-docx

How to prevent gcc optimizing some statements in C?

Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile type qualifier.

// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];

The volatile type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.

This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma or __attribute__ syntax.

Python group by

result = []
# Make a set of your "types":
input_set = set([tpl[1] for tpl in input])
>>> set(['ETH', 'KAT', 'NOT'])
# Iterate over the input_set
for type_ in input_set:
    # a dict to gather things:
    D = {}
    # filter all tuples from your input with the same type as type_
    tuples = filter(lambda tpl: tpl[1] == type_, input)
    # write them in the D:
    D["type"] = type_
    D["itmes"] = [tpl[0] for tpl in tuples]
    # append D to results:
    result.append(D)

result
>>> [{'itmes': ['9085267', '11788544'], 'type': 'NOT'}, {'itmes': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'itmes': ['11013331', '9843236'], 'type': 'KAT'}]

Access host database from a docker container

If you want access to a Docker container where there is a DB, you have to add a bash:

docker exec -it postgresql bash

postgresql is the container name.

Once inside, from the bash, access to DB e.g:

$psql -U postgres

Android Service Stops When App Is Closed

make you service like this in your Mainifest

 <service
            android:name=".sys.service.youservice"
            android:exported="true"
        android:process=":ServiceProcess" />

then your service will run on other process named ServiceProcess


if you want make your service never die :

  1. onStartCommand() return START_STICKY

  2. onDestroy() -> startself

  3. create a Deamon service

  4. jin -> create a Native Deamon process, you can find some open-source projects on github

  5. startForeground() , there is a way to startForeground without Notification ,google it

iOS 6 apps - how to deal with iPhone 5 screen size?

You need to add a 640x1136 pixels PNG image ([email protected]) as a 4 inch default splash image of your project, and it will use extra spaces (without efforts on simple table based applications, games will require more efforts).

I've created a small UIDevice category in order to deal with all screen resolutions. You can get it here, but the code is as follows:

File UIDevice+Resolutions.h:

enum {
    UIDeviceResolution_Unknown           = 0,
    UIDeviceResolution_iPhoneStandard    = 1,    // iPhone 1,3,3GS Standard Display  (320x480px)
    UIDeviceResolution_iPhoneRetina4    = 2,    // iPhone 4,4S Retina Display 3.5"  (640x960px)
    UIDeviceResolution_iPhoneRetina5     = 3,    // iPhone 5 Retina Display 4"       (640x1136px)
    UIDeviceResolution_iPadStandard      = 4,    // iPad 1,2,mini Standard Display   (1024x768px)
    UIDeviceResolution_iPadRetina        = 5     // iPad 3 Retina Display            (2048x1536px)
}; typedef NSUInteger UIDeviceResolution;

@interface UIDevice (Resolutions)

- (UIDeviceResolution)resolution;

NSString *NSStringFromResolution(UIDeviceResolution resolution);

@end

File UIDevice+Resolutions.m:

#import "UIDevice+Resolutions.h"

@implementation UIDevice (Resolutions)

- (UIDeviceResolution)resolution
{
    UIDeviceResolution resolution = UIDeviceResolution_Unknown;
    UIScreen *mainScreen = [UIScreen mainScreen];
    CGFloat scale = ([mainScreen respondsToSelector:@selector(scale)] ? mainScreen.scale : 1.0f);
    CGFloat pixelHeight = (CGRectGetHeight(mainScreen.bounds) * scale);

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
        if (scale == 2.0f) {
            if (pixelHeight == 960.0f)
                resolution = UIDeviceResolution_iPhoneRetina4;
            else if (pixelHeight == 1136.0f)
                resolution = UIDeviceResolution_iPhoneRetina5;

        } else if (scale == 1.0f && pixelHeight == 480.0f)
            resolution = UIDeviceResolution_iPhoneStandard;

    } else {
        if (scale == 2.0f && pixelHeight == 2048.0f) {
            resolution = UIDeviceResolution_iPadRetina;

        } else if (scale == 1.0f && pixelHeight == 1024.0f) {
            resolution = UIDeviceResolution_iPadStandard;
        }
    }

    return resolution;
 }

 @end

This is how you need to use this code.

1) Add the above UIDevice+Resolutions.h & UIDevice+Resolutions.m files to your project

2) Add the line #import "UIDevice+Resolutions.h" to your ViewController.m

3) Add this code to check what versions of device you are dealing with

int valueDevice = [[UIDevice currentDevice] resolution];

    NSLog(@"valueDevice: %d ...", valueDevice);

    if (valueDevice == 0)
    {
        //unknow device - you got me!
    }
    else if (valueDevice == 1)
    {
        //standard iphone 3GS and lower
    }
    else if (valueDevice == 2)
    {
        //iphone 4 & 4S
    }
    else if (valueDevice == 3)
    {
        //iphone 5
    }
    else if (valueDevice == 4)
    {
        //ipad 2
    }
    else if (valueDevice == 5)
    {
        //ipad 3 - retina display
    }

Delete all objects in a list

To delete all objects in a list, you can directly write list = []

Here is example:

>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a = []
>>> a
[]

HTML5 best practices; section/header/aside/article elements

I want to clarify this question more precisely,correct me if I am wrong Lets take an example of Facebook Wall

1.Wall comes under "section" tag,which denotes it is separate from page.

2.All posts come under "article" tag.

3.Then we have single post,which comes under "section" tag.

3.We have heading "X user post this" for this we can use "heading" tag.

4.Then inside post we have three section one is Images/text,like-share-comment button and comment box.

5.For comment box we can use article tag.

How to set up devices for VS Code for a Flutter emulator

ctrl+shift+p

then type Flutter:launch emulator or

run this command in your VS code terminal flutter emulators then see the result if you have installed any emulator it will show you , then to run one of them use flutter emulators --launch your_emulator_id in my case flutter emulators --launch Nexus 6 API 28 but if you havent installed any emulator you can install one with flutter emulators --create [--name xyz] then run your project flutter run inside the root directory of the project

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

Getting value of select (dropdown) before change

please don't use a global var for this - store the prev value at the data here is an example: http://jsbin.com/uqupu3/2/edit

the code for ref:

$(document).ready(function(){
  var sel = $("#sel");
  sel.data("prev",sel.val());

  sel.change(function(data){
     var jqThis = $(this);
     alert(jqThis.data("prev"));
     jqThis.data("prev",jqThis.val());
  });
});

just saw that you have many selects on page - this approach will also work for you since for each select you will store the prev value on the data of the select

How to access session variables from any class in ASP.NET?

(Updated for completeness)
You can access session variables from any page or control using Session["loginId"] and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].

But please read on for my original answer...


I always use a wrapper class around the ASP.NET session to simplify access to session variables:

public class MySession
{
    // private constructor
    private MySession()
    {
      Property1 = "default value";
    }

    // Gets the current session.
    public static MySession Current
    {
      get
      {
        MySession session =
          (MySession)HttpContext.Current.Session["__MySession__"];
        if (session == null)
        {
          session = new MySession();
          HttpContext.Current.Session["__MySession__"] = session;
        }
        return session;
      }
    }

    // **** add your session properties here, e.g like this:
    public string Property1 { get; set; }
    public DateTime MyDate { get; set; }
    public int LoginId { get; set; }
}

This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:

int loginId = MySession.Current.LoginId;

string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;

DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;

This approach has several advantages:

  • it saves you from a lot of type-casting
  • you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]
  • you can document your session items by adding XML doc comments on the properties of MySession
  • you can initialize your session variables with default values (e.g. assuring they are not null)

Show Console in Windows Application?

Easiest way is to start a WinForms application, go to settings and change the type to a console application.

How to detect pressing Enter on keyboard using jQuery?

I found this to be more cross-browser compatible:

$(document).keypress(function(event) {
    var keycode = event.keyCode || event.which;
    if(keycode == '13') {
        alert('You pressed a "enter" key in somewhere');    
    }
});

How to use Fiddler to monitor WCF service

Standard WCF Tracing/Diagnostics

If for some reason you are unable to get Fiddler to work, or would rather log the requests another way, another option is to use the standard WCF tracing functionality. This will produce a file that has a nice viewer.

Docs

See https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/tracing-and-message-logging

Configuration

Add the following to your config, make sure c:\logs exists, rebuild, and make requests:

  <system.serviceModel>
    <diagnostics>
      <!-- Enable Message Logging here. -->
      <!-- log all messages received or sent at the transport or service model levels -->
      <messageLogging logEntireMessage="true"
                      maxMessagesToLog="300"
                      logMessagesAtServiceLevel="true"
                      logMalformedMessages="true"
                      logMessagesAtTransportLevel="true" />
    </diagnostics>
  </system.serviceModel>

  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel" switchValue="Information,ActivityTracing"
        propagateActivity="true">
        <listeners>
          <add name="xml" />
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="xml" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="C:\logs\TracingAndLogging-client.svclog" type="System.Diagnostics.XmlWriterTraceListener"
        name="xml" />
    </sharedListeners>
    <trace autoflush="true" />
  </system.diagnostics>

How to prevent a browser from storing passwords

I needed this a couple of years ago for a specific situation: Two people who know their network passwords access the same machine at the same time to sign a legal agreement.

You don't want either password saved in that situation because saving a password is a legal issue, not a technical one where both the physical and temporal presence of both individuals is mandatory. Now, I'll agree that this is a rare situation to encounter, but such situations do exist and built-in password managers in web browsers are unhelpful.

My technical solution to the above was to swap between password and text types and make the background color match the text color when the field is a plain text field (thereby continuing to hide the password). Browsers don't ask to save passwords that are stored in plain text fields.

jQuery plugin:

https://github.com/cubiclesoft/php-flexforms-modules/blob/master/password-manager/jquery.stoppasswordmanager.js

Relevant source code from the above link:

(function($) {
$.fn.StopPasswordManager = function() {
    return this.each(function() {
        var $this = $(this);

        $this.addClass('no-print');
        $this.attr('data-background-color', $this.css('background-color'));
        $this.css('background-color', $this.css('color'));
        $this.attr('type', 'text');
        $this.attr('autocomplete', 'off');

        $this.focus(function() {
            $this.attr('type', 'password');
            $this.css('background-color', $this.attr('data-background-color'));
        });

        $this.blur(function() {
            $this.css('background-color', $this.css('color'));
            $this.attr('type', 'text');
            $this[0].selectionStart = $this[0].selectionEnd;
        });

        $this.on('keydown', function(e) {
            if (e.keyCode == 13)
            {
                $this.css('background-color', $this.css('color'));
                $this.attr('type', 'text');
                $this[0].selectionStart = $this[0].selectionEnd;
            }
        });
    });
}
}(jQuery));

Demo:

https://barebonescms.com/demos/admin_pack/admin.php

Click "Add Entry" in the menu and then scroll to the bottom of the page to "Module: Stop Password Manager".

Run PHP function on html button click

A php file is run whenever you access it via an HTTP request be it GET,POST, PUT.

You can use JQuery/Ajax to send a request on a button click, or even just change the URL of the browser to navigate to the php address.

Depending on the data sent in the POST/GET you can have a switch statement running a different function.

Specifying Function via GET

You can utilize the code here: How to call PHP function from string stored in a Variable along with a switch statement to automatically call the appropriate function depending on data sent.

So on PHP side you can have something like this:

<?php

//see http://php.net/manual/en/function.call-user-func-array.php how to use extensively
if(isset($_GET['runFunction']) && function_exists($_GET['runFunction']))
call_user_func($_GET['runFunction']);
else
echo "Function not found or wrong input";

function test()
{
echo("test");
}

function hello()
{
echo("hello");
}

?>

and you can make the simplest get request using the address bar as testing:

http://127.0.0.1/test.php?runFunction=hellodddddd

results in:

Function not found or wrong input

http://127.0.0.1/test.php?runFunction=hello

results in:

hello

Sending the Data

GET Request via JQuery

See: http://api.jquery.com/jQuery.get/

$.get("test.cgi", { name: "John"})
.done(function(data) {
  alert("Data Loaded: " + data);
});

POST Request via JQuery

See: http://api.jquery.com/jQuery.post/

$.post("test.php", { name: "John"} );

GET Request via Javascript location

See: http://www.javascripter.net/faq/buttonli.htm

<input type=button 
value="insert button text here"
onClick="self.location='Your_URL_here.php?name=hello'">

Reading the Data (PHP)

See PHP Turotial for reading post and get: http://www.tizag.com/phpT/postget.php

Useful Links

http://php.net/manual/en/function.call-user-func.php http://php.net/manual/en/function.function-exists.php

How to install lxml on Ubuntu

As @Pepijn commented on @Druska 's answer, on ubuntu 13.04 x64, there is no need to use lib32z1-dev, zlib1g-dev is enough:

sudo apt-get install libxml2-dev libxslt-dev python-dev zlib1g-dev

Python: json.loads returns items prefixing with 'u'

The u- prefix just means that you have a Unicode string. When you really use the string, it won't appear in your data. Don't be thrown by the printed output.

For example, try this:

print mail_accounts[0]["i"]

You won't see a u.

How to get full width in body element

You can use CSS to do it for example

<style>
html{
    width:100%;
    height:100%;
}
body{
    width:100%;
    height:100%;
    background-color:#DDD;
}
</style>

Confused about Service vs Factory

Service style: (probably the simplest one) returns the actual function: Useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference.

A service in AngularJS is a singleton JavaScript object which contains a set of functions

var myModule = angular.module("myModule", []);

myModule.value  ("myValue"  , "12345");

function MyService(myValue) {
    this.doIt = function() {
        console.log("done: " + myValue;
    }
}

myModule.service("myService", MyService);
myModule.controller("MyController", function($scope, myService) {

    myService.doIt();

});

Factory style: (more involved but more sophisticated) returns the function's return value: instantiate an object like new Object() in java.

Factory is a function that creates values. When a service, controller etc. needs a value injected from a factory, the factory creates the value on demand. Once created, the value is reused for all services, controllers etc. which need it injected.

var myModule = angular.module("myModule", []);

myModule.value("numberValue", 999);

myModule.factory("myFactory", function(numberValue) {
    return "a value: " + numberValue;
})  
myModule.controller("MyController", function($scope, myFactory) {

    console.log(myFactory);

});

Provider style: (full blown, configurable version) returns the output of the function's $get function: Configurable.

Providers in AngularJS is the most flexible form of factory you can create. You register a provider with a module just like you do with a service or factory, except you use the provider() function instead.

var myModule = angular.module("myModule", []);

myModule.provider("mySecondService", function() {
    var provider = {};
    var config   = { configParam : "default" };

    provider.doConfig = function(configParam) {
        config.configParam = configParam;
    }

    provider.$get = function() {
        var service = {};

        service.doService = function() {
            console.log("mySecondService: " + config.configParam);
        }

        return service;
    }

    return provider;
});

myModule.config( function( mySecondServiceProvider ) {
    mySecondServiceProvider.doConfig("new config param");
});

myModule.controller("MyController", function($scope, mySecondService) {

    $scope.whenButtonClicked = function() {
        mySecondService.doIt();
    }

});

src jenkov

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
    <html ng-app="app">_x000D_
    <head>_x000D_
     <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script>_x000D_
     <meta charset=utf-8 />_x000D_
     <title>JS Bin</title>_x000D_
    </head>_x000D_
    <body ng-controller="MyCtrl">_x000D_
     {{serviceOutput}}_x000D_
     <br/><br/>_x000D_
     {{factoryOutput}}_x000D_
     <br/><br/>_x000D_
     {{providerOutput}}_x000D_
    _x000D_
     <script>_x000D_
    _x000D_
      var app = angular.module( 'app', [] );_x000D_
    _x000D_
      var MyFunc = function() {_x000D_
    _x000D_
       this.name = "default name";_x000D_
    _x000D_
       this.$get = function() {_x000D_
        this.name = "new name"_x000D_
        return "Hello from MyFunc.$get(). this.name = " + this.name;_x000D_
       };_x000D_
    _x000D_
       return "Hello from MyFunc(). this.name = " + this.name;_x000D_
      };_x000D_
    _x000D_
      // returns the actual function_x000D_
      app.service( 'myService', MyFunc );_x000D_
    _x000D_
      // returns the function's return value_x000D_
      app.factory( 'myFactory', MyFunc );_x000D_
    _x000D_
      // returns the output of the function's $get function_x000D_
      app.provider( 'myProv', MyFunc );_x000D_
    _x000D_
      function MyCtrl( $scope, myService, myFactory, myProv ) {_x000D_
    _x000D_
       $scope.serviceOutput = "myService = " + myService;_x000D_
       $scope.factoryOutput = "myFactory = " + myFactory;_x000D_
       $scope.providerOutput = "myProvider = " + myProv;_x000D_
    _x000D_
      }_x000D_
    _x000D_
     </script>_x000D_
    _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

jsbin

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="myApp">_x000D_
<head>_x000D_
 <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script>_x000D_
 <meta charset=utf-8 />_x000D_
 <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div ng-controller="MyCtrl">_x000D_
    {{hellos}}_x000D_
</div>_x000D_
 <script>_x000D_
_x000D_
 var myApp = angular.module('myApp', []);_x000D_
_x000D_
//service style, probably the simplest one_x000D_
myApp.service('helloWorldFromService', function() {_x000D_
    this.sayHello = function() {_x000D_
        return "Hello, World!"_x000D_
    };_x000D_
});_x000D_
_x000D_
//factory style, more involved but more sophisticated_x000D_
myApp.factory('helloWorldFromFactory', function() {_x000D_
    return {_x000D_
        sayHello: function() {_x000D_
            return "Hello, World!"_x000D_
        }_x000D_
    };_x000D_
});_x000D_
    _x000D_
//provider style, full blown, configurable version     _x000D_
myApp.provider('helloWorld', function() {_x000D_
_x000D_
    this.name = 'Default';_x000D_
_x000D_
    this.$get = function() {_x000D_
        var name = this.name;_x000D_
        return {_x000D_
            sayHello: function() {_x000D_
                return "Hello, " + name + "!"_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
_x000D_
    this.setName = function(name) {_x000D_
        this.name = name;_x000D_
    };_x000D_
});_x000D_
_x000D_
//hey, we can configure a provider!            _x000D_
myApp.config(function(helloWorldProvider){_x000D_
    helloWorldProvider.setName('World');_x000D_
});_x000D_
        _x000D_
_x000D_
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {_x000D_
    _x000D_
    $scope.hellos = [_x000D_
        helloWorld.sayHello(),_x000D_
        helloWorldFromFactory.sayHello(),_x000D_
        helloWorldFromService.sayHello()];_x000D_
}_x000D_
 </script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

jsfiddle

Regular expression to limit number of characters to 10

/^[a-z]{0,10}$/ should work. /^[a-z]{1,10}$/ if you want to match at least one character, like /^[a-z]+$/ does.

When to use the !important property in CSS

You use !important to override a css property.

For example, you have a control in ASP.NET and it renders a control with a background blue (in the HTML). You want to change it, and you don't have the source control so you attach a new CSS file and write the same selector and change the color and after it add !important.

Best practices is when you are branding / redesigning SharePoint sites, you use it a lot to override the default styles.

Web scraping with Java

Normally I use selenium, which is software for testing automation. You can control a browser through a webdriver, so you will not have problems with javascripts and it is usually not very detected if you use the full version. Headless browsers can be more identified.

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

You need to treat a table valued udf like a table, eg JOIN it

select Emp_Id 
from Employee E JOIN dbo.Splitfn(@Id,',') CSV ON E.Emp_Id = CSV.items 

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

Selecting Folder Destination in Java?

I found a good example of what you need in this link.

import javax.swing.JFileChooser;

public class Main {
  public static void main(String s[]) {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("choosertitle");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
      System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else {
      System.out.println("No Selection ");
    }
  }
}

Can I set an unlimited length for maxJsonLength in web.config?

if this maxJsonLength value is a int then how big is its int 32bit/64bit/16bit.... i just want to be sure whats the maximum value i can set as my maxJsonLength

<scripting>
        <webServices>
            <jsonSerialization maxJsonLength="2147483647">
            </jsonSerialization>
        </webServices>
    </scripting>

What do the return values of Comparable.compareTo mean in Java?

It can be used for sorting, and 0 means "equal" while -1, and 1 means "less" and "more (greater)".

Any return value that is less than 0 means that left operand is lesser, and if value is bigger than 0 then left operand is bigger.

View more than one project/solution in Visual Studio

If you have two separate solutions, then you cannot view them simultaneously in the same VS instance. However, you can open multiple instances of VS and tab between them.

An alternative would be to import the projects from one solution into the other, thus putting all of your projects into one solution. You can do this by following these steps:

  1. In the Solution Explorer, select the Solution into which you want to import a project. Right-click, and select Add->Existing Project from the context menu.

  2. In the file chooser, find the project file that you want to import (it will end in .XXproj where XX is the language you're using).

  3. Click Open and voila! Your project is imported.

How to overcome root domain CNAME restrictions?

My company does the same thing for a number of customers where we host a web site for them although in our case it's xyz.company.com rather than www.company.com. We do get them to set the A record on xyz.company.com to point to an IP address we allocate them.

As to how you could cope with a change in IP address I don't think there is a perfect solution. Some ideas are:

  • Use a NAT or IP load balancer and give your customers an IP address belonging to it. If the IP address of the web server needs to change you could make an update on the NAT or load balancer,

  • Offer a DNS hosting service as well and get your customers to host their domain with you so that you'd be in a position to update the A records,

  • Get your customers to set their A record up to one main web server and use a HTTP redirect for each customer's web requests.

C# catch a stack overflow exception

Yes from CLR 2.0 stack overflow is considered a non-recoverable situation. So the runtime still shut down the process.

For details please see the documentation http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

Read binary file as string in Ruby

You can probably encode the tar file in Base64. Base 64 will give you a pure ASCII representation of the file that you can store in a plain text file. Then you can retrieve the tar file by decoding the text back.

You do something like:

require 'base64'

file_contents = Base64.encode64(tar_file_data)

Have look at the Base64 Rubydocs to get a better idea.

SQL query to select distinct row with minimum value

SELECT * from room
INNER JOIN
  (
  select DISTINCT hotelNo, MIN(price) MinPrice
  from room
 Group by hotelNo
  ) NewT   
 on room.hotelNo = NewT.hotelNo and room.price = NewT.MinPrice;

Convert a date format in PHP

Use this function to convert from any format to any format

function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
    $date_aux = date_create_from_format($from_format, $date);
    return date_format($date_aux,$to_format);
}

Prevent jQuery UI dialog from setting focus to first textbox

Simple workaround:

Just create a invisible element with tabindex=1 ... This will not focus the datepicker ...

eg.:

<a href="" tabindex="1"></a>
...
Here comes the input element

Changing Node.js listening port

you can get the nodejs configuration from http://nodejs.org/
The important thing you need to keep in your mind is about its configuration in file app.js which consists of port number host and other settings these are settings working for me

backendSettings = {
"scheme":"https / http ",
"host":"Your website url",
"port":49165, //port number 
'sslKeyPath': 'Path for key',
'sslCertPath': 'path for SSL certificate',
'sslCAPath': '',
"resource":"/socket.io",
"baseAuthPath": '/nodejs/',
"publishUrl":"publish",
"serviceKey":"",
"backend":{
"port":443,
"scheme": 'https / http', //whatever is your website scheme
"host":"host name",
"messagePath":"/nodejs/message/"},
"clientsCanWriteToChannels":false,
"clientsCanWriteToClients":false,
"extensions":"",
"debug":false,
"addUserToChannelUrl": 'user/channel/add/:channel/:uid',
"publishMessageToContentChannelUrl": 'content/token/message',
"transports":["websocket",
"flashsocket",
"htmlfile",
"xhr-polling",
"jsonp-polling"],
"jsMinification":true,
"jsEtag":true,
"logLevel":1};

In this if you are getting "Error: listen EADDRINUSE" then please change the port number i.e, here I am using "49165" so you can use other port such as 49170 or some other port. For this you can refer to the following article
http://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-shared-hosting-accounts

The FastCGI process exited unexpectedly

For Issue C:\PHP\php-cgi.exe - The FastCGI process exited unexpectedly.

I resolved this by installing the Visual C++ Redistributable for Visual Studio 2015.(Microsoft Visual C++ 2015 Redistributable Update 3) and Visual C++ Redistributable for Visual Studio 2012 Update 4 in 32 and 64bit versions. and also make sure in php.info file cgi.fix_pathinfo=0 enabled.

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

I had this issue for a server instance on my local machine and found that it was because I was pointing to 127.0.0.1 with something other than "localhost" in my hosts file. There are two ways to fix this issue in my case:

  1. Clear the offending entry pointing to 127.0.0.1 in the hosts file
  2. use "localhost" instead of the other name that in the hosts file that points to 127.0.0.1

*This only worked for me when I was running the sql server instance on my local box and attempting to access it from the same machine.

Check if string matches pattern

Please try the following:

import re

name = ["A1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]

# Match names.
for element in name:
     m = re.match("(^[A-Z]\d[A-Z]\d)", element)
     if m:
        print(m.groups())

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

function createNumberArray(lowEnd, highEnd) {
    var start = lowEnd;
    var array = [start];
    while (start < highEnd) {
        array.push(start);
        start++;
    }
} 

How to do a redirect to another route with react-router?

Easiest solution for web!

Up to date 2020
confirmed working with:

"react-router-dom": "^5.1.2"
"react": "^16.10.2"

Use the useHistory() hook!

import React from 'react';
import { useHistory } from "react-router-dom";


export function HomeSection() {
  const history = useHistory();
  const goLogin = () => history.push('login');

  return (
    <Grid>
      <Row className="text-center">          
        <Col md={12} xs={12}>
          <div className="input-group">
            <span className="input-group-btn">
              <button onClick={goLogin} type="button" />
            </span>
          </div>
        </Col>
      </Row>
    </Grid>
  );
}

Easy way to pull latest of all git submodules

All you need to do now is a simple git checkout

Just make sure to enable it via this global config: git config --global submodule.recurse true

Error in finding last used cell in Excel with VBA

Since the original question is about problems with finding the last cell, in this answer I will list the various ways you can get unexpected results; see my answer to "How can I find last row that contains data in the Excel sheet with a macro?" for my take on solving this.

I'll start by expanding on the answer by sancho.s and the comment by GlennFromIowa, adding even more detail:

[...] one has first to decide what is considered used. I see at least 6 meanings. Cell has:

  • 1) data, i.e., a formula, possibly resulting in a blank value;
  • 2) a value, i.e., a non-blank formula or constant;
  • 3) formatting;
  • 4) conditional formatting;
  • 5) a shape (including Comment) overlapping the cell;
  • 6) involvement in a Table (List Object).

Which combination do you want to test for? Some (such as Tables) may be more difficult to test for, and some may be rare (such as a shape outside of data range), but others may vary based on the situation (e.g., formulas with blank values).

Other things you might want to consider:

  • A) Can there be hidden rows (e.g. autofilter), blank cells or blank rows?
  • B) What kind of performance is acceptable?
  • C) Can the VBA macro affect the workbook or the application settings in any way?

With that in mind, let's see how the common ways of getting the "last cell" can produce unexpected results:

  • The .End(xlDown) code from the question will break most easily (e.g. with a single non-empty cell or when there are blank cells in between) for the reasons explained in the answer by Siddharth Rout here (search for "xlDown is equally unreliable.")
  • Any solution based on Counting (CountA or Cells*.Count) or .CurrentRegion will also break in presence of blank cells or rows
  • A solution involving .End(xlUp) to search backwards from the end of a column will, just as CTRL+UP, look for data (formulas producing a blank value are considered "data") in visible rows (so using it with autofilter enabled might produce incorrect results ??).

    You have to take care to avoid the standard pitfalls (for details I'll again refer to the answer by Siddharth Rout here, look for the "Find Last Row in a Column" section), such as hard-coding the last row (Range("A65536").End(xlUp)) instead of relying on sht.Rows.Count.

  • .SpecialCells(xlLastCell) is equivalent to CTRL+END, returning the bottom-most and right-most cell of the "used range", so all caveats that apply to relying on the "used range", apply to this method as well. In addition, the "used range" is only reset when saving the workbook and when accessing worksheet.UsedRange, so xlLastCell might produce stale results?? with unsaved modifications (e.g. after some rows were deleted). See the nearby answer by dotNET.
  • sht.UsedRange (described in detail in the answer by sancho.s here) considers both data and formatting (though not conditional formatting) and resets the "used range" of the worksheet, which may or may not be what you want.

    Note that a common mistake ?is to use .UsedRange.Rows.Count??, which returns the number of rows in the used range, not the last row number (they will be different if the first few rows are blank), for details see newguy's answer to How can I find last row that contains data in the Excel sheet with a macro?

  • .Find allows you to find the last row with any data (including formulas) or a non-blank value in any column. You can choose whether you're interested in formulas or values, but the catch is that it resets the defaults in the Excel's Find dialog ????, which can be highly confusing to your users. It also needs to be used carefully, see the answer by Siddharth Rout here (section "Find Last Row in a Sheet")
  • More explicit solutions that check individual Cells' in a loop are generally slower than re-using an Excel function (although can still be performant), but let you specify exactly what you want to find. See my solution based on UsedRange and VBA arrays to find the last cell with data in the given column -- it handles hidden rows, filters, blanks, does not modify the Find defaults and is quite performant.

Whatever solution you pick, be careful

  • to use Long instead of Integer to store the row numbers (to avoid getting Overflow with more than 65k rows) and
  • to always specify the worksheet you're working with (i.e. Dim ws As Worksheet ... ws.Range(...) instead of Range(...))
  • when using .Value (which is a Variant) avoid implicit casts like .Value <> "" as they will fail if the cell contains an error value.

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

Since React uses JSX code to create an HTML we cannot refer dom using regulation methods like documment.querySelector or getElementById.

Instead we can use React ref system to access and manipulate Dom as shown in below example:

constructor(props){

    super(props);
    this.imageRef = React.createRef(); // create react ref
}

componentDidMount(){

    **console.log(this.imageRef)** // acessing the attributes of img tag when dom loads
}


render = (props) => {

const {urls,description} = this.props.image;
    return (

            <img
             **ref = {this.imageRef} // assign the ref of img tag here**
             src = {urls.regular} 
             alt = {description}
             />

        );

}

}

Check if string contains only digits

it checks valid number integers or float or double not a string

regex that i used

simple regex

 1. ^[0-9]*[.]?[0-9]*$

advance regex

 2. ^-?[\d.]+(?:e-?\d+)?$    

eg:only numbers

_x000D_
_x000D_
var str='1232323';
var reg=/^[0-9]*[.]?[0-9]*$/;

console.log(reg.test(str))
_x000D_
_x000D_
_x000D_

it allows

eg:123434

eg:.1232323

eg:12.3434434

it does not allow

eg:1122212.efsffasf

eg:2323fdf34434

eg:0.3232rf3333

advance regex

////////////////////////////////////////////////////////////////////

int or float or exponent all types of number in string

^-?[\d.]+(?:e-?\d+)?$

eg:13123123

eg:12344.3232

eg:2323323e4

eg:0.232332

hide/show a image in jquery

What image do you want to hide? Assuming all images, the following should work:

$("img").hide();

Otherwise, using selectors, you could find all images that are child elements of the containing div, and hide those.

However, i strongly recommend you read the Jquery docs, you could have figured it out yourself: http://docs.jquery.com/Main_Page

Redirect within component Angular 2

first configure routing

import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';

and

@RouteConfig([
  { path: '/addDisplay', component: AddDisplay, as: 'addDisplay' },
  { path: '/<secondComponent>', component: '<secondComponentName>', as: 'secondComponentAs' },
])

then in your component import and then inject Router

import {Router} from 'angular2/router'

export class AddDisplay {
  constructor(private router: Router)
}

the last thing you have to do is to call

this.router.navigateByUrl('<pathDefinedInRouteConfig>');

or

this.router.navigate(['<aliasInRouteConfig>']);

shell script to remove a file if it already exist

Don't bother checking if the file exists, just try to remove it.

rm -f /p/a/t/h
# or
rm /p/a/t/h 2> /dev/null

Note that the second command will fail (return a non-zero exit status) if the file did not exist, but the first will succeed owing to the -f (short for --force) option. Depending on the situation, this may be an important detail.

But more likely, if you are appending to the file it is because your script is using >> to redirect something into the file. Just replace >> with >. It's hard to say since you've provided no code.

Note that you can do something like test -f /p/a/t/h && rm /p/a/t/h, but doing so is completely pointless. It is quite possible that the test will return true but the /p/a/t/h will fail to exist before you try to remove it, or worse the test will fail and the /p/a/t/h will be created before you execute the next command which expects it to not exist. Attempting this is a classic race condition. Don't do it.

Get list of JSON objects with Spring RestTemplate

Maybe this way...

ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity(urlGETList, Object[].class);
Object[] objects = responseEntity.getBody();
MediaType contentType = responseEntity.getHeaders().getContentType();
HttpStatus statusCode = responseEntity.getStatusCode();

Controller code for the RequestMapping

@RequestMapping(value="/Object/getList/", method=RequestMethod.GET)
public @ResponseBody List<Object> findAllObjects() {

    List<Object> objects = new ArrayList<Object>();
    return objects;
}

ResponseEntity is an extension of HttpEntity that adds a HttpStatus status code. Used in RestTemplate as well @Controller methods. In RestTemplate this class is returned by getForEntity() and exchange().

Node.js request CERT_HAS_EXPIRED

Try to temporarily modify request.js and harcode everywhere rejectUnauthorized = true, but it would be better to get the certificate extended as a long-term solution.

How do I add indices to MySQL tables?

A better option is to add the constraints directly during CREATE TABLE query (assuming you have the information about the tables)

CREATE TABLE products(
    productId INT AUTO_INCREMENT PRIMARY KEY,
    productName varchar(100) not null,
    categoryId INT NOT NULL,
    CONSTRAINT fk_category
    FOREIGN KEY (categoryId) 
    REFERENCES categories(categoryId)
        ON UPDATE CASCADE
        ON DELETE CASCADE
) ENGINE=INNODB;

Command line tool to dump Windows DLL version?

Using Powershell it is possible to get just the Version string, i.e. 2.3.4 from any dll or exe with the following command

(Get-Item "C:\program files\OpenVPN\bin\openvpn.exe").VersionInfo.ProductVersion

Tested on Windows 10

Is there a way to get a list of column names in sqlite?

An alternative to the cursor.description solution from smallredstone could be to use row.keys():

import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
connection.row_factory = sqlite3.Row
cursor = connection.execute('select * from bar')
# instead of cursor.description:
row = cursor.fetchone()
names = row.keys()

The drawback: it only works if there is at least a row returned from the query.

The benefit: you can access the columns by their name (row['your_column_name'])

Read more about the Row objects in the python documentation.

Overriding the java equals() method - not working?

If you use eclipse just go to the top menu

Source --> Generate equals() and hashCode()

Maven not found in Mac OSX mavericks

if you don't want to install homebrew (or any other package manager) just for installing maven, you can grab the binary from their site:

http://maven.apache.org/download.cgi

extract the content to a folder (e.g. /Applications/apache-maven-3.1.1) with

$ tar -xvf apache-maven-3.1.1-bin.tar.gz

and finally adjust your ~/.bash_profile with any texteditor you like to include

export M2_HOME=/Applications/apache-maven-3.1.1
export PATH=$PATH:$M2_HOME/bin

restart the terminal and test it with

$ mvn -version

Apache Maven 3.1.1 (0728685237757ffbf44136acec0402957f723d9a; 2013-09-17 17:22:22+0200)
Maven home: /Applications/apache-maven-3.1.1
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: de_DE, platform encoding: MacRoman
OS name: "mac os x", version: "10.9", arch: "x86_64", family: "mac"

Mongoose query where value is not null

total count the documents where the value of the field is not equal to the specified value.

async function getRegisterUser() {
    return Login.count({"role": { $ne: 'Super Admin' }}, (err, totResUser) => {
        if (err) {
            return err;
        }
        return totResUser;
    })
}

@import vs #import - iOS 7

History:

#include => #import => .pch => @import

[#include vs #import]
[.pch - Precompiled header]

Module - @import

Product Name == Product Module Name 

@import module declaration says to compiler to load a precompiled binary of framework which decrease a building time. Modular Framework contains .modulemap[About]

If module feature is enabled in Xcode project #include and #import directives are automatically converted to @import that brings all advantages

enter image description here

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

Update OpenSSL on OS X with Homebrew

In a terminal, run:

export PATH=/usr/local/bin:$PATH
brew link --force openssl

You may have to unlink openssl first if you get a warning: brew unlink openssl

This ensures we're linking the correct openssl for this situation. (and doesn't mess with .profile)

Hat tip to @Olaf's answer and @Felipe's comment. Some people - such as myself - may have some pretty messed up PATH vars.

Saving response from Requests to file

You can use the response.text to write to a file:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()

How can I do an asc and desc sort using underscore.js?

Similar to Underscore library there is another library called as 'lodash' that has one method "orderBy" which takes in the parameter to determine in which order to sort it. You can use it like

_.orderBy('collection', 'propertyName', 'desc')

For some reason, it's not documented on the website docs.

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

Tested on a Huawei P20:

  1. Uninstall (or disable) Play Store.
  2. Reinstall Google Play: (Source)

    1. Download the latest version of Google Play Store from APK Mirror.
    2. Install the app simply by opening the APK file.
  3. Restart device.

Note: before finding this solution, I followed the instructions from some of the other answers here: removed my Google account from my device and added it again, cleared data and cache from various google play apps. This may or may not be necessary; feedback is welcome.

How to refresh page on back button click?

window.onbeforeunload = function() { redirect(window.history.back(1)); };

How to run ssh-add on windows?

The Git GUI for Windows has a window-based application that allows you to paste in locations for ssh keys and repo url etc:

https://gitforwindows.org/

MySQL wait_timeout Variable - GLOBAL vs SESSION

As noted by Riedsio, the session variables do not change after connecting unless you specifically set them; setting the global variable only changes the session value of your next connection.

For example, if you have 100 connections and you lower the global wait_timeout then it will not affect the existing connections, only new ones after the variable was changed.

Specifically for the wait_timeout variable though, there is a twist. If you are using the mysql client in the interactive mode, or the connector with CLIENT_INTERACTIVE set via mysql_real_connect() then you will see the interactive_timeout set for @@session.wait_timeout

Here you can see this demonstrated:

> ./bin/mysql -Bsse 'select @@session.wait_timeout, @@session.interactive_timeout, @@global.wait_timeout, @@global.interactive_timeout' 
70      60      70      60

> ./bin/mysql -Bsse 'select @@wait_timeout'                                                                                                 
70

> ./bin/mysql                                                                                                                               
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.12-5 MySQL Community Server (GPL)

Copyright (c) 2009-2016 Percona LLC and/or its affiliates
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select @@wait_timeout;
+----------------+
| @@wait_timeout |
+----------------+
|             60 |
+----------------+
1 row in set (0.00 sec)

So, if you are testing this using the client it is the interactive_timeout that you will see when connecting and not the value of wait_timeout

How to redirect verbose garbage collection output to a file?

To add to the above answers, there's a good article: Useful JVM Flags – Part 8 (GC Logging) by Patrick Peschlow.

A brief excerpt:

The flag -XX:+PrintGC (or the alias -verbose:gc) activates the “simple” GC logging mode

By default the GC log is written to stdout. With -Xloggc:<file> we may instead specify an output file. Note that this flag implicitly sets -XX:+PrintGC and -XX:+PrintGCTimeStamps as well.

If we use -XX:+PrintGCDetails instead of -XX:+PrintGC, we activate the “detailed” GC logging mode which differs depending on the GC algorithm used.

With -XX:+PrintGCTimeStamps a timestamp reflecting the real time passed in seconds since JVM start is added to every line.

If we specify -XX:+PrintGCDateStamps each line starts with the absolute date and time.

Node package ( Grunt ) installed but not available

Other solution is to remove the ubuntu bundler in my case i used:

sudo apt-get remove ruby-bundler 

That worked for me.

How to write a caption under an image?

For responsive images. You can add the picture and source tags within the figure tag.

<figure>
  <picture>
    <source media="(min-width: 750px)" srcset="images/image_2x.jpg"/>
    <source media="(min-width: 500px)" srcset="images/image.jpg" />
    <img src="images.jpg" alt="An image">
  </picture>
  <figcaption>Caption goes here</figcaption>
</figure>

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

There is a new spec called the Native File System API that allows you to do this properly like this:

const result = await window.chooseFileSystemEntries({ type: "save-file" });

There is a demo here, but I believe it is using an origin trial so it may not work in your own website unless you sign up or enable a config flag, and it obviously only works in Chrome. If you're making an Electron app this might be an option though.

How to disable horizontal scrolling of UIScrollView?

I struggled with this for some time trying unsuccessfully the various suggestions in this and other threads.

However, in another thread (not sure where) someone suggested that using a negative constraint on the UIScrollView worked for him.

So I tried various combinations of constraints with inconsistent results. What eventually worked for me was to add leading and trailing constraints of -32 to the scrollview and add an (invisible) textview with a width of 320 (and centered).

How to detect if URL has changed after hash in JavaScript

While doing a little chrome extension, I faced the same problem with an additionnal problem : Sometimes, the page change but not the URL.

For instance, just go to the Facebook Homepage, and click on the 'Home' button. You will reload the page but the URL won't change (one-page app style).

99% of the time, we are developping websites so we can get those events from Frameworks like Angular, React, Vue etc..

BUT, in my case of a Chrome extension (in Vanilla JS), I had to listen to an event that will trigger for each "page change", which can generally be caught by URL changed, but sometimes it doesn't.

My homemade solution was the following :

listen(window.history.length);
var oldLength = -1;
function listen(currentLength) {
  if (currentLength != oldLength) {
    // Do your stuff here
  }

  oldLength = window.history.length;
  setTimeout(function () {
    listen(window.history.length);
  }, 1000);
}

So basically the leoneckert solution, applied to window history, which will change when a page changes in a single page app.

Not rocket science, but cleanest solution I found, considering we are only checking an integer equality here, and not bigger objects or the whole DOM.

Are Git forks actually Git clones?

I think fork is a copy of other repository but with your account modification. for example, if you directly clone other repository locally, the remote object origin is still using the account who you clone from. You can't commit and contribute your code. It is just a pure copy of codes. Otherwise, If you fork a repository, it will clone the repo with the update of your account setting in you github account. And then cloning the repo in the context of your account, you can commit your codes.

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

Something like this?

function delete_folder($folder) {
    $glob = glob($folder);
    foreach ($glob as $g) {
        if (!is_dir($g)) {
            unlink($g);
        } else {
            delete_folder("$g/*");
            rmdir($g);
        }
    }
}

How to read all rows from huge table?

At lest in my case the problem was on the client that tries to fetch the results.

Wanted to get a .csv with ALL the results.

I found the solution by using

psql -U postgres -d dbname  -c "COPY (SELECT * FROM T) TO STDOUT WITH DELIMITER ','"

(where dbname the name of the db...) and redirecting to a file.

Android Camera Preview Stretched

Very important point here to understand , the SurfaceView size must be the same as the camera parameters size , it means they have the same aspect ratio then the Stretch effect will go off .

You have to get the correct supported camera preview size using params.getSupportedPreviewSizes() choose one of them and then change your SurfaceView and its holders to this size.

Html Agility Pack get all elements by class

You can use the following script:

var findclasses = _doc.DocumentNode.Descendants("div").Where(d => 
    d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("float")
);

Import module from subfolder

Just create an empty __init__.py file and add it in root as well as all the sub directory/folder of your python application where you have other python modules. See https://docs.python.org/3/tutorial/modules.html#packages

How to split a string of space separated numbers into integers?

Just use strip() to remove empty spaces and apply explicit int conversion on the variable.

Ex:

a='1  ,  2, 4 ,6 '
f=[int(i.strip()) for i in a]

Python - difference between two strings

The answer to my comment above on the Original Question makes me think this is all he wants:

loopnum = 0
word = 'afrykanerskojezyczny'
wordlist = ['afrykanerskojezycznym','afrykanerskojezyczni','nieafrykanerskojezyczni']
for i in wordlist:
    wordlist[loopnum] = word
    loopnum += 1

This will do the following:

For every value in wordlist, set that value of the wordlist to the origional code.

All you have to do is put this piece of code where you need to change wordlist, making sure you store the words you need to change in wordlist, and that the original word is correct.

Hope this helps!

Shortcut to create properties in Visual Studio?

Using VsVim the code snippets seem to work a little funny. The shortcut I was looking for when I ended up here is much simpler: after a member name type {g;s;

I have delimiter auto-closing turned on, so the closing brace appears on {, and typing a semicolon triggers an autocomplete for get and set.

It works on VS2013 and VS2015, and VS2012 just lacks the automatic brace matching.

Running Git through Cygwin from Windows

I can tell you from personal experience this is a bad idea. Native Windows programs cannot accept Cygwin paths. For example with Cygwin you might run a command

grep -r --color foo /opt

with no issue. With Cygwin / represents the root directory. Native Windows programs have no concept of this, and will likely fail if invoked this way. You should not mix Cygwin and Native Windows programs unless you have no other choice.

Uninstall what Git you have and install the Cygwin git package, save yourself the headache.

How to force the browser to reload cached CSS and JavaScript files

Google Chrome has the Hard Reload as well as the Empty Cache and Hard Reload option. You can click and hold the reload button (in Inspect Mode) to select one.

How to downgrade to older version of Gradle

Got to

gradle-wrapper.properties

Change the version of the below mentioned distribution (gradle-5.6.4-bin.zip)

distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-bin.zip

Simulate string split function in Excel formula

The following returns the first word in cell A1 when separated by a space (works in Excel 2003):

=LEFT(A1, SEARCH(" ",A1,1))

What does (function($) {})(jQuery); mean?

Actually, this example helped me to understand what does (function($) {})(jQuery); mean.

Consider this:

// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4

And now consider this:

  • jQuery is a variable holding jQuery object.
  • $ is a variable name like any other (a, $b, a$b etc.) and it doesn't have any special meaning like in PHP.

Knowing that we can take another look at our example:

var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4

Inline CSS styles in React: how to implement a:hover?

Full CSS support is exactly the reason this huge amount of CSSinJS libraries, to do this efficiently, you need to generate actual CSS, not inline styles. Also inline styles are much slower in react in a bigger system. Disclaimer - I maintain JSS.

How to get the index of an element in an IEnumerable?

I'd question the wisdom, but perhaps:

source.TakeWhile(x => x != value).Count();

(using EqualityComparer<T>.Default to emulate != if needed) - but you need to watch to return -1 if not found... so perhaps just do it the long way

public static int IndexOf<T>(this IEnumerable<T> source, T value)
{
    int index = 0;
    var comparer = EqualityComparer<T>.Default; // or pass in as a parameter
    foreach (T item in source)
    {
        if (comparer.Equals(item, value)) return index;
        index++;
    }
    return -1;
}

Convert decimal to binary in python

n=int(input('please enter the no. in decimal format: '))
x=n
k=[]
while (n>0):
    a=int(float(n%2))
    k.append(a)
    n=(n-a)/2
k.append(0)
string=""
for j in k[::-1]:
    string=string+str(j)
print('The binary no. for %d is %s'%(x, string))

Inserting an image with PHP and FPDF

You can use $pdf->GetX() and $pdf->GetY() to get current cooridnates and use them to insert image.

$pdf->Image($image1, 5, $pdf->GetY(), 33.78);

or even

$pdf->Image($image1, 5, null, 33.78);

(ALthough in first case you can add a number to create a bit of a space)

$pdf->Image($image1, 5, $pdf->GetY() + 5, 33.78);

Is there a limit on number of tcp/ip connections between machines on linux?

You might wanna check out /etc/security/limits.conf

Can I edit an iPad's host file?

The previous answer is correct, but if the effect you are looking for is to redirect HTTP traffic for a domain to another IP there is a way.

Since it technically is not answering your question, I have asked and answered the question here:

How can I redirect HTTP requests made from an iPad?

How to initialize/instantiate a custom UIView class with a XIB file in Swift

Universal way of loading view from xib:

Example:

let myView = Bundle.loadView(fromNib: "MyView", withType: MyView.self)

Implementation:

extension Bundle {

    static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
        if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
            return view
        }

        fatalError("Could not load view with type " + String(describing: type))
    }
}

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

In Python 3, dict.values() (along with dict.keys() and dict.items()) returns a view, rather than a list. See the documentation here. You therefore need to wrap your call to dict.values() in a call to list like so:

v = list(d.values())
{names[i]:v[i] for i in range(len(names))}

"Insufficient Storage Available" even there is lot of free space in device memory

I got the same error message in case the package name was too long (>128 chars). Just using a shorter name fixed the issue.

How to map and remove nil values in Ruby

Ruby 2.7+

There is now!

Ruby 2.7 is introducing filter_map for this exact purpose. It's idiomatic and performant, and I'd expect it to become the norm very soon.

For example:

numbers = [1, 2, 5, 8, 10, 13]
enum.filter_map { |i| i * 2 if i.even? }
# => [4, 16, 20]

In your case, as the block evaluates to falsey, simply:

items.filter_map { |x| process_x url }

"Ruby 2.7 adds Enumerable#filter_map" is a good read on the subject, with some performance benchmarks against some of the earlier approaches to this problem:

N = 100_000
enum = 1.upto(1_000)
Benchmark.bmbm do |x|
  x.report("select + map")  { N.times { enum.select { |i| i.even? }.map{ |i| i + 1 } } }
  x.report("map + compact") { N.times { enum.map { |i| i + 1 if i.even? }.compact } }
  x.report("filter_map")    { N.times { enum.filter_map { |i| i + 1 if i.even? } } }
end

# Rehearsal -------------------------------------------------
# select + map    8.569651   0.051319   8.620970 (  8.632449)
# map + compact   7.392666   0.133964   7.526630 (  7.538013)
# filter_map      6.923772   0.022314   6.946086 (  6.956135)
# --------------------------------------- total: 23.093686sec
# 
#                     user     system      total        real
# select + map    8.550637   0.033190   8.583827 (  8.597627)
# map + compact   7.263667   0.131180   7.394847 (  7.405570)
# filter_map      6.761388   0.018223   6.779611 (  6.790559)

LINQ to read XML

Here are a couple of complete working examples that build on the @bendewey & @dommer examples. I needed to tweak each one a bit to get it to work, but in case another LINQ noob is looking for working examples, here you go:

//bendewey's example using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ1
{
    static void Main( )
    {
        //Load xml
        XDocument xdoc = XDocument.Load(@"c:\\data.xml"); //you'll have to edit your path

        //Run query
        var lv1s = from lv1 in xdoc.Descendants("level1")
           select new 
           { 
               Header = lv1.Attribute("name").Value,
               Children = lv1.Descendants("level2")
            };

        StringBuilder result = new StringBuilder(); //had to add this to make the result work
        //Loop through results
        foreach (var lv1 in lv1s)
        {
            result.AppendLine("  " + lv1.Header);
            foreach(var lv2 in lv1.Children)
            result.AppendLine("    " + lv2.Attribute("name").Value);
        }
        Console.WriteLine(result.ToString()); //added this so you could see the output on the console
    }
}

And next:

//Dommer's example, using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ
{
static void Main( )
    {
        XElement rootElement = XElement.Load(@"c:\\data.xml"); //you'll have to edit your path
        Console.WriteLine(GetOutline(0, rootElement));  
    }

static private string GetOutline(int indentLevel, XElement element)
    {
        StringBuilder result = new StringBuilder();
        if (element.Attribute("name") != null)
        {
            result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
        }
        foreach (XElement childElement in element.Elements())
        {
            result.Append(GetOutline(indentLevel + 1, childElement));
        }
        return result.ToString();
    }
}

These both compile & work in VS2010 using csc.exe version 4.0.30319.1 and give the exact same output. Hopefully these help someone else who's looking for working examples of code.

EDIT: added @eglasius' example as well since it became useful to me:

//@eglasius example, still using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ2
{
    static void Main( )
    {
        StringBuilder result = new StringBuilder(); //needed for result below
        XDocument xdoc = XDocument.Load(@"c:\\deg\\data.xml"); //you'll have to edit your path
        var lv1s = xdoc.Root.Descendants("level1"); 
        var lvs = lv1s.SelectMany(l=>
             new string[]{ l.Attribute("name").Value }
             .Union(
                 l.Descendants("level2")
                 .Select(l2=>"   " + l2.Attribute("name").Value)
              )
            );
        foreach (var lv in lvs)
        {
           result.AppendLine(lv);
        }
        Console.WriteLine(result);//added this so you could see the result
    }
}

What is the difference between partitioning and bucketing a table in Hive ?

Hive Partitioning:

Partition divides large amount of data into multiple slices based on value of a table column(s).

Assume that you are storing information of people in entire world spread across 196+ countries spanning around 500 crores of entries. If you want to query people from a particular country (Vatican city), in absence of partitioning, you have to scan all 500 crores of entries even to fetch thousand entries of a country. If you partition the table based on country, you can fine tune querying process by just checking the data for only one country partition. Hive partition creates a separate directory for a column(s) value.

Pros:

  1. Distribute execution load horizontally
  2. Faster execution of queries in case of partition with low volume of data. e.g. Get the population from "Vatican city" returns very fast instead of searching entire population of world.

Cons:

  1. Possibility of too many small partition creations - too many directories.
  2. Effective for low volume data for a given partition. But some queries like group by on high volume of data still take long time to execute. e.g. Grouping of population of China will take long time compared to grouping of population in Vatican city. Partition is not solving responsiveness problem in case of data skewing towards a particular partition value.

Hive Bucketing:

Bucketing decomposes data into more manageable or equal parts.

With partitioning, there is a possibility that you can create multiple small partitions based on column values. If you go for bucketing, you are restricting number of buckets to store the data. This number is defined during table creation scripts.

Pros

  1. Due to equal volumes of data in each partition, joins at Map side will be quicker.
  2. Faster query response like partitioning

Cons

  1. You can define number of buckets during table creation but loading of equal volume of data has to be done manually by programmers.

TypeError: p.easing[this.easing] is not a function

I got this error today whilst trying to initiate a slide effect on a div. Thanks to the answer from 'I Hate Lazy' above (which I've upvoted), I went looking for a custom jQuery UI script, and you can in fact build your own file directly on the jQuery ui website http://jqueryui.com/download/. All you have to do is mark the effect(s) that you're looking for and then download.

I was looking for the slide effect. So I first unchecked all the checkboxes, then clicked on the 'slide effect' checkbox and the page automatically then checks those other components necessary to make the slide effect work. Very simple.

easeOutBounce is an easing effect, for which you'll need to check the 'Effects Core' checkbox.

Java Try Catch Finally blocks without Catch

The inner finally is executed prior to throwing the exception to the outer block.

public class TryCatchFinally {

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

    try{
        System.out.println('A');
        try{
            System.out.println('B');
            throw new Exception("threw exception in B");
        }
        finally
        {
            System.out.println('X');
        }
        //any code here in the first try block 
        //is unreachable if an exception occurs in the second try block
    }
    catch(Exception e)
    {
        System.out.println('Y');
    }
    finally
    {
        System.out.println('Z');
    }
  }
}

Results in

A
B
X
Y
Z

libclntsh.so.11.1: cannot open shared object file.

For the benefit of anyone else coming here by far the best thing to do is to update cx_Oracle to the latest version (6+). This version does not need LD_LIBRARY_PATH set at all.

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

Running AMP (apache mysql php) on Android

There are no PHP interpreters that I know of for Android or IOS (or WebOS or BlackBerryOS).

If you want to run a web site as an app on a mobile device or tablet as a native application, all functionality needs to be in Javascript and wrapped with a library like PhoneGap or Titanium. Android and IOS web apps are both able to use local storage databases where data can be kept until a network connection is made. Any server-side logic would require a call out to your web server and an active internet connection on the device.

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

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

Convert data file to blob

async function FileToString (file) {
    try {
        let res = await file.raw.text();
        console.log(res);
    } catch (err) {
        throw err;
    }
}

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

getting JRE system library unbound error in build path

oh boy, this got resolved, I just had to name my Installed JRE appropriately. I had only the jdk installed and eclipse had taken the default jdk name, i renamed it to JavaSE-1.6 and voila it worked, though i had to redo everthing from the scratch.

CHECK constraint in MySQL is not working

Update to MySQL 8.0.16 to use checks:

As of MySQL 8.0.16, CREATE TABLE permits the core features of table and column CHECK constraints, for all storage engines. CREATE TABLE permits the following CHECK constraint syntax, for both table constraints and column constraints

MySQL Checks Documentation

How to Convert unsigned char* to std::string in C++?

Here is the complete code

#include <bits/stdc++.h>

using namespace std;

typedef unsigned char BYTE;

int main() {
  //method 1;
  std::vector<BYTE> data = {'H','E','L','L','O','1','2','3'};
  //string constructor accepts only const char
  std::string s((const char*)&(data[0]), data.size());
  std::cout << s << std::endl;

  //method 2
  std::string s2(data.begin(),data.end());
  std::cout << s2 << std::endl;

  //method 3
  std::string s3(reinterpret_cast<char const*>(&data[0]), data.size()) ;
  std::cout << s3 << std::endl;
 
  return 0;
}

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

How to copy a map?

I'd use recursion just in case so you can deep copy the map and avoid bad surprises in case you were to change a map element that is a map itself.

Here's an example in a utils.go:

package utils

func CopyMap(m map[string]interface{}) map[string]interface{} {
    cp := make(map[string]interface{})
    for k, v := range m {
        vm, ok := v.(map[string]interface{})
        if ok {
            cp[k] = CopyMap(vm)
        } else {
            cp[k] = v
        }
    }

    return cp
}

And its test file (i.e. utils_test.go):

package utils

import (
    "testing"

    "github.com/stretchr/testify/require"
)

func TestCopyMap(t *testing.T) {
    m1 := map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
    }

    m2 := CopyMap(m1)

    m1["a"] = "zzz"
    delete(m1, "b")

    require.Equal(t, map[string]interface{}{"a": "zzz"}, m1)
    require.Equal(t, map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
    }, m2)
}

It should easy enough to adapt if you need the map key to be something else instead of a string.

Hibernate error - QuerySyntaxException: users is not mapped [from users]

For example: your bean class name is UserDetails

Query query = entityManager. createQuery("Select UserName from **UserDetails** "); 

You do not give your table name on the Db. you give the class name of bean.

Seedable JavaScript random number generator

The code you listed kind of looks like a Lehmer RNG. If this is the case, then 2147483647 is the largest 32-bit signed integer, 2147483647 is the largest 32-bit prime, and 48271 is a full-period multiplier that is used to generate the numbers.

If this is true, you could modify RandomNumberGenerator to take in an extra parameter seed, and then set this.seed to seed; but you'd have to be careful to make sure the seed would result in a good distribution of random numbers (Lehmer can be weird like that) -- but most seeds will be fine.

Omit rows containing specific column of NA

Omit row if either of two specific columns contain <NA>.

DF[!is.na(DF$x)&!is.na(DF$z),]

Side-by-side plots with ggplot2

In my experience gridExtra:grid.arrange works perfectly, if you are trying to generate plots in a loop.

Short Code Snippet:

gridExtra::grid.arrange(plot1, plot2, ncol = 2)

** Updating this comment to show how to use grid.arrange() within a for loop to generate plots for different factors of a categorical variable.

for (bin_i in levels(athlete_clean$BMI_cat)) {

plot_BMI <- athlete_clean %>% filter(BMI_cat == bin_i) %>% group_by(BMI_cat,Team) %>% summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Participating Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

plot_BMI_Medal <- athlete_clean %>% 
          filter(!is.na(Medal), BMI_cat == bin_i) %>% 
          group_by(BMI_cat,Team) %>% 
          summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Winning Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

gridExtra::grid.arrange(plot_BMI, plot_BMI_Medal, ncol = 2)

}

One of the Sample Plots from the above for loop is included below. The above loop will produce multiple plots for all levels of BMI category.

Sample Image

If you wish to see a more comprehensive use of grid.arrange() within for loops, check out https://rpubs.com/Mayank7j_2020/olympic_data_2000_2016

How to see the changes between two commits without commits in-between?

git diff <a-commit> <another-commit> path

Example:

git diff commit1 commit2 config/routes.rb

It shows the difference on that file between those commits.

Get exit code of a background process

Our team had the same need with a remote SSH-executed script which was timing out after 25 minutes of inactivity. Here is a solution with the monitoring loop checking the background process every second, but printing only every 10 minutes to suppress an inactivity timeout.

long_running.sh & 
pid=$!

# Wait on a background job completion. Query status every 10 minutes.
declare -i elapsed=0
# `ps -p ${pid}` works on macOS and CentOS. On both OSes `ps ${pid}` works as well.
while ps -p ${pid} >/dev/null; do
  sleep 1
  if ((++elapsed % 600 == 0)); then
    echo "Waiting for the completion of the main script. $((elapsed / 60))m and counting ..."
  fi
done

# Return the exit code of the terminated background process. This works in Bash 4.4 despite what Bash docs say:
# "If neither jobspec nor pid specifies an active child process of the shell, the return status is 127."
wait ${pid}

Convert list of ints to one number?

pseudo-code:

int magic(list nums)
{
  int tot = 0

  while (!nums.isEmpty())
  {
    int digit = nums.takeFirst()
    tot *= 10
    tot += digit
  }

  return tot
}

Define the selected option with the old input in Laravel / Blade

      <select class="form-control" name="kategori_id">
        <option value="">-- PILIH --</option>
        @foreach($kategori as $id => $nama)
            @if(old('kategori_id', $produk->kategori_id) == $id )
            <option value="{{ $id }}" selected>{{ $nama }}</option>
            @else
            <option value="{{ $id }}">{{ $nama }}</option>
            @endif
        @endforeach
        </select>

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

If you use Windows 10 and has Windows Subsystem for Linux (WSL), it can be easily done by typing "file " from the shell.

For example:

$ file code.cpp

code.cpp: C source, UTF-8 Unicode (with BOM) text, with CRLF line terminators

Bootstrap 4 Change Hamburger Toggler Color

Use a font-awesome icon as the default icon of your navbar.

<span class="navbar-toggler-icon">   
    <i class="fas fa-bars" style="color:#fff; font-size:28px;"></i>
</span>

Or try this on old font-awesome versions:

<span class="navbar-toggler-icon">   
    <i class="fa fa-navicon" style="color:#fff; font-size:28px;"></i>
</span>

MySQL command line client for Windows

mysql.exe can do just that....

To connect,

mysql -u root -p (press enter)

It should prompt you to enter root password (u = username, p = password)

Then you can use SQL database commands to do pretty much anything....

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

Include an SVG (hosted on GitHub) in MarkDown

I contacted GitHub to say that github.io-hosted SVGs are no longer displayed in GitHub READMEs. I received this reply:

We have had to disable svg image rendering on GitHub.com due to potential cross site scripting vulnerabilities.

How do I make a relative reference to another workbook in Excel?

Presume you linking to a shared drive for example the S drive? If so, other people may have mapped the drive differently. You probably need to use the "official" drive name //euhkj002/forecasts/bla bla. Instead of S// in your link

Sort a list alphabetically

You can sort a list in-place just by calling List<T>.Sort:

list.Sort();

That will use the natural ordering of elements, which is fine in your case.

EDIT: Note that in your code, you'd need

_details.Sort();

as the Sort method is only defined in List<T>, not IList<T>. If you need to sort it from the outside where you don't have access to it as a List<T> (you shouldn't cast it as the List<T> part is an implementation detail) you'll need to do a bit more work.

I don't know of any IList<T>-based in-place sorts in .NET, which is slightly odd now I come to think of it. IList<T> provides everything you'd need, so it could be written as an extension method. There are lots of quicksort implementations around if you want to use one of those.

If you don't care about a bit of inefficiency, you could always use:

public void Sort<T>(IList<T> list)
{
    List<T> tmp = new List<T>(list);
    tmp.Sort();
    for (int i = 0; i < tmp.Count; i++)
    {
        list[i] = tmp[i];
    }
}

In other words, copy, sort in place, then copy the sorted list back.


You can use LINQ to create a new list which contains the original values but sorted:

var sortedList = list.OrderBy(x => x).ToList();

It depends which behaviour you want. Note that your shuffle method isn't really ideal:

  • Creating a new Random within the method runs into some of the problems shown here
  • You can declare val inside the loop - you're not using that default value
  • It's more idiomatic to use the Count property when you know you're working with an IList<T>
  • To my mind, a for loop is simpler to understand than traversing the list backwards with a while loop

There are other implementations of shuffling with Fisher-Yates on Stack Overflow - search and you'll find one pretty quickly.

Python: Remove division decimal

>>> int(2.0)

You will get the answer as 2

Laravel 5.4 Specific Table Migration

You could try to use the --path= option to define the specific sub-folder you're wanting to execute and place specific migrations in there.

Alternatively you would need to remove reference and tables from the DB and migrations tables which isn't ideal :/

Could not load NIB in bundle

Your XIB file is probably outside your project folder. This leads to not showing up the Target Inspector. However, moving the XIB file into your project folder should fix it.

What is the difference between .NET Core and .NET Standard Class Library project types?

.NET Standard: Think of it as a big standard library. When using this as a dependency you can only make libraries (.DLLs), not executables. A library made with .NET standard as a dependency can be added to a Xamarin.Android, a Xamarin.iOS, a .NET Core Windows/OS X/Linux project.

.NET Core: Think of it as the continuation of the old .NET framework, just it's opensource and some stuff is not yet implemented and others got deprecated. It extends the .NET standard with extra functions, but it only runs on desktops. When adding this as a dependency you can make runnable applications on Windows, Linux and OS X. (Although console only for now, no GUIs). So .NET Core = .NET Standard + desktop specific stuff.

Also UWP uses it and the new ASP.NET Core uses it as a dependency too.

Getting the index of the returned max or min item using max()/min() on a list

Possibly a simpler solution would be to turn the array of values into an array of value,index-pairs, and take the max/min of that. This would give the largest/smallest index that has the max/min (i.e. pairs are compared by first comparing the first element, and then comparing the second element if the first ones are the same). Note that it's not necessary to actually create the array, because min/max allow generators as input.

values = [3,4,5]
(m,i) = max((v,i) for i,v in enumerate(values))
print (m,i) #(5, 2)

How to listen for a WebView finishing loading a URL?

@ian this is not 100% accurate. If you have several iframes in a page you will have multiple onPageFinished (and onPageStarted). And if you have several redirects it may also fail. This approach solves (almost) all the problems:

boolean loadingFinished = true;
boolean redirect = false;

mWebView.setWebViewClient(new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
        if (!loadingFinished) {
            redirect = true;
        }

        loadingFinished = false;
        webView.loadUrl(urlNewString);
        return true;
    }

    @Override
    public void onPageStarted(WebView view, String url) {
        loadingFinished = false;
        //SHOW LOADING IF IT ISNT ALREADY VISIBLE  
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (!redirect) {
           loadingFinished = true;
            //HIDE LOADING IT HAS FINISHED
        } else {
            redirect = false; 
        }
    }
});

UPDATE:

According to the documentation: onPageStarted will NOT be called when the contents of an embedded frame changes, i.e. clicking a link whose target is an iframe.

I found a specific case like that on Twitter where only a pageFinished was called and messed the logic a bit. To solve that I added a scheduled task to remove loading after X seconds. This is not needed in all the other cases.

UPDATE 2:

Now with current Android WebView implementation:

boolean loadingFinished = true;
boolean redirect = false;

    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(
                WebView view, WebResourceRequest request) {
            if (!loadingFinished) {
               redirect = true;
            }

            loadingFinished = false;
            webView.loadUrl(request.getUrl().toString());
            return true;
        }

        @Override
        public void onPageStarted(
                WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            loadingFinished = false;
            //SHOW LOADING IF IT ISNT ALREADY VISIBLE  
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (!redirect) {
               loadingFinished = true;
                //HIDE LOADING IT HAS FINISHED
            } else {
                redirect = false; 
            }
        }
    });

Elasticsearch query to return all records

To return all records from all indices you can do:

curl -XGET http://35.195.120.21:9200/_all/_search?size=50&pretty

Output:

  "took" : 866,
  "timed_out" : false,
  "_shards" : {
    "total" : 25,
    "successful" : 25,
    "failed" : 0
  },
  "hits" : {
    "total" : 512034694,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "grafana-dash",
      "_type" : "dashboard",
      "_id" : "test",
      "_score" : 1.0,
       ...

Spring Boot application.properties value not populating

The way you are performing the injection of the property will not work, because the injection is done after the constructor is called.

You need to do one of the following:

Better solution

@Component
public class MyBean {

    private final String prop;

    @Autowired
    public MyBean(@Value("${some.prop}") String prop) {
        this.prop = prop;
        System.out.println("================== " + prop + "================== ");
    }
}

Solution that will work but is less testable and slightly less readable

@Component
public class MyBean {

    @Value("${some.prop}")
    private String prop;

    public MyBean() {

    }

    @PostConstruct
    public void init() {
        System.out.println("================== " + prop + "================== ");
    }
}

Also note that is not Spring Boot specific but applies to any Spring application

Intermediate language used in scalac?

The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/

You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.

Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?

Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.

Using PUT method in HTML form

XHTML 1.x forms only support GET and POST. GET and POST are the only allowed values for the "method" attribute.

Remove Duplicate objects from JSON Array

_x000D_
_x000D_
var standardsList = [_x000D_
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math K", "Domain": "Geometry"},_x000D_
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},_x000D_
    {"Grade": "Math 1", "Domain": "Orders of Operation"},_x000D_
    {"Grade": "Math 2", "Domain": "Geometry"},_x000D_
    {"Grade": "Math 2", "Domain": "Geometry"}_x000D_
];_x000D_
_x000D_
standardsList = standardsList.filter((li, idx, self) => self.map(itm => itm.Grade+itm.Domain).indexOf(li.Grade+li.Domain) === idx)_x000D_
_x000D_
document.write(JSON.stringify(standardsList))
_x000D_
_x000D_
_x000D_

here is a functional way of doing it that is much easier

standardsList = standardsList.filter((li, idx, self) => self.map(itm => iem.Grade+itm.domain).indexOf(li.Grade+li.domain) === idx)

How to enable cURL in PHP / XAMPP

check if curl module is available

$ ls -la /etc/php5/mods-available/

enable the curl module

$ sudo php5enmod curl

source: http://baligena.com/installing-curl-ubuntu-server/

can't start MySql in Mac OS 10.6 Snow Leopard

Easiest Solution I've found:

After installing the MySQL package for Mac OS X Snow Leopard (check whether you have a 32bit or 64bit processor). Can always default to the 32bit version to be safe.

Simply click to install the MySQL preferences inside the dmg and when prompted whether to allow access for just you or for the entire system, choose entire system.

This worked great for me.

Difference between JOIN and INNER JOIN

INNER JOIN = JOIN

INNER JOIN is the default if you don't specify the type when you use the word JOIN.

You can also use LEFT OUTER JOIN or RIGHT OUTER JOIN, in which case the word OUTER is optional, or you can specify CROSS JOIN.

OR

For an inner join, the syntax is:

SELECT ...
FROM TableA
[INNER] JOIN TableB

(in other words, the "INNER" keyword is optional - results are the same with or without it)

Where is nodejs log file?

There is no log file. Each node.js "app" is a separate entity. By default it will log errors to STDERR and output to STDOUT. You can change that when you run it from your shell to log to a file instead.

node my_app.js > my_app_log.log 2> my_app_err.log

Alternatively (recommended), you can add logging inside your application either manually or with one of the many log libraries:

How much data / information can we save / store in a QR code?

See this table.

A 101x101 QR code, with high level error correction, can hold 3248 bits, or 406 bytes. Probably not enough for any meaningful SVG/XML data.

A 177x177 grid, depending on desired level of error correction, can store between 1273 and 2953 bytes. Maybe enough to store something small.

enter image description here

how to add a jpg image in Latex

You need to use a graphics library. Put this in your preamble:

\usepackage{graphicx}

You can then add images like this:

\begin{figure}[ht!]
\centering
\includegraphics[width=90mm]{fixed_dome1.jpg}
\caption{A simple caption \label{overflow}}
\end{figure}

This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure and \includegraphics. You can then refer to the image in your text using the label you gave in the figure:

And here we see figure \ref{overflow}.

Read this guide here for a more detailed instruction: http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions

git pull error :error: remote ref is at but expected

A hard reset will also resolve the problem

git reset --hard origin/master

Error during SSL Handshake with remote server

Faced the same problem as OP:

  • Tomcat returned response when accessing directly via SOAP UI
  • Didn't load html files
  • When used Apache properties mentioned by the previous answer, web-page appeared but AngularJS couldn't get HTTP response

Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

ngOnInit() is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

ngAfterViewInit() is called after a component's view, and its children's views, are created. Its a lifecycle hook that is called after a component's view has been fully initialized.

Why does AngularJS include an empty option in select?

Angular < 1.4

For anyone out there that treat "null" as valid value for one of the options (so imagine that "null" is a value of one of the items in typeOptions in example below), I found that simplest way to make sure that automatically added option is hidden is to use ng-if.

<select ng-options="option.value as option.name for option in typeOptions">
    <option value="" ng-if="false"></option>
</select>

Why ng-if and not ng-hide? Because you want css selectors that would target first option inside above select to target "real" option, not the one that's hidden. It gets useful when you're using protractor for e2e testing and (for whatever reason) you use by.css() to target select options.

Angular >= 1.4

Due to the refactoring of the select and options directives, using ng-if is no longer a viable option so you gotta turn to ng-show="false" to make it work again.

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

Judging from the messages you send via Socket.IO socket.emit('greet', { hello: 'Hey, Mr.Client!' });, it seems that you are using the hackathon-starter boilerplate. If so, the issue might be that express-status-monitor module is creating its own socket.io instance, as per: https://github.com/RafalWilinski/express-status-monitor#using-module-with-socketio-in-project

You can either:

  1. Remove that module
  2. Pass in your socket.io instance and port as websocket when you create the expressStatusMonitor instance like below:

    const server = require('http').Server(app);
    const io = require('socket.io')(server);
    ...
    app.use(expressStatusMonitor({ websocket: io, port: app.get('port') })); 
    

Python: Random numbers into a list

Fix the indentation of the print statement

import random

my_randoms=[]
for i in range (10):
    my_randoms.append(random.randrange(1,101,1))

print (my_randoms)

Uninstalling an MSI file from the command line without using msiexec

I would try the following syntax - it works for me.

msiexec /x filename.msi /q 

IPhone/IPad: How to get screen width programmatically?

This can be done in in 3 lines of code:

// grab the window frame and adjust it for orientation
UIView *rootView = [[[UIApplication sharedApplication] keyWindow] 
                                   rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];

HorizontalScrollView within ScrollView Touch Handling

Thank you Joel for giving me a clue on how to resolve this problem.

I have simplified the code(without need for a GestureDetector) to achieve the same effect:

public class VerticalScrollView extends ScrollView {
    private float xDistance, yDistance, lastX, lastY;

    public VerticalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDistance = yDistance = 0f;
                lastX = ev.getX();
                lastY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                xDistance += Math.abs(curX - lastX);
                yDistance += Math.abs(curY - lastY);
                lastX = curX;
                lastY = curY;
                if(xDistance > yDistance)
                    return false;
        }

        return super.onInterceptTouchEvent(ev);
    }
}

Change multiple files

I'm surprised nobody has mentioned the -exec argument to find, which is intended for this type of use-case, although it will start a process for each matching file name:

find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} \;

Alternatively, one could use xargs, which will invoke fewer processes:

find . -type f -name 'xa*' | xargs sed -i 's/asd/dsg/g'

Or more simply use the + exec variant instead of ; in find to allow find to provide more than one file per subprocess call:

find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} +

.htaccess or .htpasswd equivalent on IIS?

I've never used it but Trilead, a free ISAPI filter which enables .htaccess based control, looks like what you want.

jQuery function after .append

Although Marcus Ekwall is absolutely right about the synchronicity of append, I have also found that in odd situations sometimes the DOM isn't completely rendered by the browser when the next line of code runs.

In this scenario then shadowdiver solutions is along the correct lines - with using .ready - however it is a lot tidier to chain the call to your original append.

$('#root')
  .append(html)
  .ready(function () {
    // enter code here
  });

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

I solved this problem very easily after finding out this happens when you aren't outputting a proper JSON object, I simply used the echo json_encode($arrayName); instead of print_r($arrayName); With my php api.

Every programming language or at least most programming languages should have their own version of the json_encode() and json_decode() functions.