Programs & Examples On #Compatibility

This tag should be used to identify questions regarding compatibility issues, for example between different versions of the same software product or, development kit or library.

How can I convert a dictionary into a list of tuples?

What you want is dict's items() and iteritems() methods. items returns a list of (key,value) tuples. Since tuples are immutable, they can't be reversed. Thus, you have to iterate the items and create new tuples to get the reversed (value,key) tuples. For iteration, iteritems is preferable since it uses a generator to produce the (key,value) tuples rather than having to keep the entire list in memory.

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>> 

IE11 Document mode defaults to IE7. How to reset?

By default, IE displays webpages in the Intranet zone in compatibility view. To change this:

  • Press Alt to display the IE menu.
  • Choose Tools | Compatibility View settings
  • Remove the checkmark next to Display intranet sites in Compatibility View.
  • Choose Close.

At this point, IE should rely on the webpage itself (or any relevant group policies) to determine the compatibility settings for your Intranet webpages.

Note that certain sites may no longer function correctly after making this change. You can use the same dialog box to add specific sites to enable compatibility view when needed.

How to find out if a Python object is a string?

If one wants to stay away from explicit type-checking (and there are good reasons to stay away from it), probably the safest part of the string protocol to check is:

str(maybe_string) == maybe_string

It won't iterate through an iterable or iterator, it won't call a list-of-strings a string and it correctly detects a stringlike as a string.

Of course there are drawbacks. For example, str(maybe_string) may be a heavy calculation. As so often, the answer is it depends.

EDIT: As @Tcll points out in the comments, the question actually asks for a way to detect both unicode strings and bytestrings. On Python 2 this answer will fail with an exception for unicode strings that contain non-ASCII characters, and on Python 3 it will return False for all bytestrings.

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Got this with flask :

Means that the port you're trying to bind to, is already in used by another service or process : got a hint on this in my code developed on Eclipse / windows :

if __name__ == "__main__":
     # Check the System Type before to decide to bind
     # If the system is a Linux machine -:) 
     if platform.system() == "Linux":
        app.run(host='0.0.0.0',port=5000, debug=True)
     # If the system is a windows /!\ Change  /!\ the   /!\ Port
     elif platform.system() == "Windows":
        app.run(host='0.0.0.0',port=50000, debug=True)

How to install both Python 2.x and Python 3.x in Windows

To install and run any version of Python in the same system follow my guide below.


For example say you want to install Python 2.x and Python 3.x on the same Windows system.

  1. Install both of their binary releases anywhere you want.

    • When prompted do not register their file extensions and
    • do not add them automatically to the PATH environment variable
  2. Running simply the command python the executable that is first met in PATH will be chosen for launch. In other words, add the Python directories manually. The one you add first will be selected when you type python. Consecutive python programs (increasing order that their directories are placed in PATH) will be chosen like so:

    • py -2 for the second python
    • py -3 for the third python etc..
  3. No matter the order of "pythons" you can:

    • run Python 2.x scripts using the command: py -2 (Python 3.x functionality) (ie. the first Python 2.x installation program found in your PATH will be selected)
    • run Python 3.x scripts using the command: or py -3 (ie. the first Python 3.x installation program found in your PATH will be selected)

In my example I have Python 2.7.14 installed first and Python 3.5.3. This is how my PATH variable starts with:

PATH=C:\Program Files\Microsoft MPI\Bin\;C:\Python27;C:\Program Files\Python_3.6\Scripts\;C:\Program Files\Python_3.6\;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Common Files\Intel\Shared

...

Note that Python 2.7 is first and Python 3.5 second.

  • So running python command will launch python 2.7 (if Python 3.5 the same command would launch Python 3.5).
  • Running py -2 launches Python 2.7 (because it happens that the second Python is Python 3.5 which is incompatible with py -2). Running py -3 launches Python 3.5 (because it's Python 3.x)
  • If you had another python later in your path you would launch like so: py -4. This may change if/when Python version 4 is released.

Now py -4 or py -5 etc. on my system outputs: Requested Python version (4) not installed or Requested Python version (5) not installed etc.

Hopefully this is clear enough.

Java 32-bit vs 64-bit compatibility

The Java JNI requires OS libraries of the same "bittiness" as the JVM. If you attempt to build something that depends, for example, on IESHIMS.DLL (lives in %ProgramFiles%\Internet Explorer) you need to take the 32bit version when your JVM is 32bit, the 64bit version when your JVM is 64bit. Likewise for other platforms.

Apart from that, you should be all set. The generated Java bytecode s/b the same.

Note that you should use 64bit Java compiler for larger projects because it can address more memory.

Which TensorFlow and CUDA version combinations are compatible?

I had a similar problem after upgrading to TF 2.0. The CUDA version that TF was reporting did not match what Ubuntu 18.04 thought I had installed. It said I was using CUDA 7.5.0, but apt thought I had the right version installed.

What I eventually had to do was grep recursively in /usr/local for CUDNN_MAJOR, and I found that /usr/local/cuda-10.0/targets/x86_64-linux/include/cudnn.h did indeed specify the version as 7.5.0.
/usr/local/cuda-10.1 got it right, and /usr/local/cuda pointed to /usr/local/cuda-10.1, so it was (and remains) a mystery to me why TF was looking at /usr/local/cuda-10.0.

Anyway, I just moved /usr/local/cuda-10.0 to /usr/local/old-cuda-10.0 so TF couldn't find it any more and everything then worked like a charm.

It was all very frustrating, and I still feel like I just did a random hack. But it worked :) and perhaps this will help someone with a similar issue.

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

I was able to fix this by downgrading RubyGems to 1.5.3, since it happens with RubyGems 1.6.0+ and Rails < 2.3.11:

gem update --system 1.5.3

If you had previously downgraded to an even earlier version and want to update to 1.5.3, you might get the following when trying to run that:

Updating RubyGems
ERROR:  While executing gem ... (RuntimeError)
    No gem names are allowed with the --system option

If you get that error, then update, so that it lets you specify the version, and then downgrade again:

gem update --system
gem update --system 1.5.3

Can I install Python 3.x and 2.x on the same Windows computer?

Here is how to run Python 2 and 3 on the same machine

  1. install Python 2.x
  2. install Python 3.x
  3. Start Powershell
  4. Type Python -2 to launch Python 2.x
  5. Type Python -3 to launch Python 2.x

The Python Launcher for Windows was embedded into Python since Version 3.3, as promised in 2011 when the Stand alone first made its debut:

Python Launcher for Windows

How to set IE11 Document mode to edge as default?

I ran into this problem with a particular webpage I was maintaining. No matter what settings I changed, it kept going back to IE8 compatibility mode.

It turned out X-UA-Compatible was set in the metadata in the head:

<meta http-equiv="X-UA-Compatible" content="IE=8" >

As I later discovered, and at least in Internet Explorer 11, you can see where it gets its "document mode" from, by going into developer tools (F12), then selecting the tab "Emulation", and checking the text below the drop down "Document mode".

Since we only support IE11 and higher, and Microsoft says document modes are deprecated, I just threw the whole thing out. That solved it.

Logging framework incompatibility

You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

Make sure:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

is the first <meta> tag on your page, otherwise IE may not respect it.

Alternatively, the problem may be that IE is using Enterprise Mode for this website:

  • Your question mentioned that the console shows: HTML1122: Internet Explorer is running in Enterprise Mode emulating IE8.
  • If so you may need to disable enterprise mode (or like this) or turn it off for that website from the Tools menu in IE.
  • However Enterprise Mode should in theory be overridden by the X-UA-Compatible tag, but IE might have a bug...

Possible to restore a backup of SQL Server 2014 on SQL Server 2012?

Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014

Just be sure to be using correct instance and connect each other

Just pay attention in Stored procs must be recompiled

Fragments onResume from back stack

I have used enum FragmentTags to define all my fragment classes.

TAG_FOR_FRAGMENT_A(A.class),
TAG_FOR_FRAGMENT_B(B.class),
TAG_FOR_FRAGMENT_C(C.class)

pass FragmentTags.TAG_FOR_FRAGMENT_A.name() as fragment tag.

and now on

@Override
public void onBackPressed(){
   FragmentManager fragmentManager = getFragmentManager();
   Fragment current
   = fragmentManager.findFragmentById(R.id.fragment_container);
    FragmentTags fragmentTag = FragmentTags.valueOf(current.getTag());

  switch(fragmentTag){
    case TAG_FOR_FRAGMENT_A:
        finish();
        break;
   case TAG_FOR_FRAGMENT_B:
        fragmentManager.popBackStack();
        break;
   case default: 
   break;
}

Is it possible to run a .NET 4.5 app on XP?

I hesitate to post this answer, it is actually technically possible but it doesn't work that well in practice. The version numbers of the CLR and the core framework assemblies were not changed in 4.5. You still target v4.0.30319 of the CLR and the framework assembly version numbers are still 4.0.0.0. The only thing that's distinctive about the assembly manifest when you look at it with a disassembler like ildasm.exe is the presence of a [TargetFramework] attribute that says that 4.5 is needed, that would have to be altered. Not actually that easy, it is emitted by the compiler.

The biggest difference is not that visible, Microsoft made a long-overdue change in the executable header of the assemblies. Which specifies what version of Windows the executable is compatible with. XP belongs to a previous generation of Windows, started with Windows 2000. Their major version number is 5. Vista was the start of the current generation, major version number 6.

.NET compilers have always specified the minimum version number to be 4.00, the version of Windows NT and Windows 9x. You can see this by running dumpbin.exe /headers on the assembly. Sample output looks like this:

OPTIONAL HEADER VALUES
             10B magic # (PE32)
            ...
            4.00 operating system version
            0.00 image version
            4.00 subsystem version              // <=== here!!
               0 Win32 version
            ...

What's new in .NET 4.5 is that the compilers change that subsystem version to 6.00. A change that was over-due in large part because Windows pays attention to that number, beyond just checking if it is small enough. It also turns on appcompat features since it assumes that the program was written to work on old versions of Windows. These features cause trouble, particularly the way Windows lies about the size of a window in Aero is troublesome. It stops lying about the fat borders of an Aero window when it can see that the program was designed to run on a Windows version that has Aero.

You can alter that version number and set it back to 4.00 by running Editbin.exe on your assemblies with the /subsystem option. This answer shows a sample postbuild event.

That's however about where the good news ends, a significant problem is that .NET 4.5 isn't very compatible with .NET 4.0. By far the biggest hang-up is that classes were moved from one assembly to another. Most notably, that happened for the [Extension] attribute. Previously in System.Core.dll, it got moved to Mscorlib.dll in .NET 4.5. That's a kaboom on XP if you declare your own extension methods, your program says to look in Mscorlib for the attribute, enabled by a [TypeForwardedTo] attribute in the .NET 4.5 version of the System.Core reference assembly. But it isn't there when you run your program on .NET 4.0

And of course there's nothing that helps you stop using classes and methods that are only available on .NET 4.5. When you do, your program will fail with a TypeLoadException or MissingMethodException when run on 4.0

Just target 4.0 and all of these problems disappear. Or break that logjam and stop supporting XP, a business decision that programmers cannot often make but can certainly encourage by pointing out the hassles that it is causing. There is of course a non-zero cost to having to support ancient operating systems, just the testing effort is substantial. A cost that isn't often recognized by management, Windows compatibility is legendary, unless it is pointed out to them. Forward that cost to the client and they tend to make the right decision a lot quicker :) But we can't help you with that.

How to run multiple Python versions on Windows

When you install Python, it will not overwrite other installs of other major versions. So installing Python 2.5.x will not overwrite Python 2.6.x, although installing 2.6.6 will overwrite 2.6.5.

So you can just install it. Then you call the Python version you want. For example:

C:\Python2.5\Python.exe

for Python 2.5 on windows and

C:\Python2.6\Python.exe

for Python 2.6 on windows, or

/usr/local/bin/python-2.5

or

/usr/local/bin/python-2.6

on Windows Unix (including Linux and OS X).

When you install on Unix (including Linux and OS X) you will get a generic python command installed, which will be the last one you installed. This is mostly not a problem as most scripts will explicitly call /usr/local/bin/python2.5 or something just to protect against that. But if you don't want to do that, and you probably don't you can install it like this:

./configure
make
sudo make altinstall

Note the "altinstall" that means it will install it, but it will not replace the python command.

On Windows you don't get a global python command as far as I know so that's not an issue.

How to evaluate http response codes from bash/shell script?

With netcat and awk you can handle the server response manually:

if netcat 127.0.0.1 8080 <<EOF | awk 'NR==1{if ($2 == "500") exit 0; exit 1;}'; then
GET / HTTP/1.1
Host: www.example.com

EOF

    apache2ctl restart;
fi

How can I save application settings in a Windows Forms application?

I wanted to share a library I've built for this. It's a tiny library, but a big improvement (IMHO) over .settings files.

The library is called Jot (GitHub). Here is an old The Code Project article I wrote about it.

Here's how you'd use it to keep track of a window's size and location:

public MainWindow()
{
    InitializeComponent();

    _stateTracker.Configure(this)
        .IdentifyAs("MyMainWindow")
        .AddProperties(nameof(Height), nameof(Width), nameof(Left), nameof(Top), nameof(WindowState))
        .RegisterPersistTrigger(nameof(Closed))
        .Apply();
}

The benefit compared to .settings files: There's considerably less code, and it's a lot less error-prone since you only need to mention each property once.

With a settings files you need to mention each property five times: once when you explicitly create the property and an additional four times in the code that copies the values back and forth.

Storage, serialization, etc. are completely configurable. When the target objects are created by an IoC container, you can [hook it up][] so that it applies tracking automatically to all objects it resolves, so that all you need to do to make a property persistent is slap a [Trackable] attribute on it.

It's highly configurable, and you can configure: - when data is persisted and applied globally or for each tracked object - how it's serialized - where it's stored (e.g. file, database, online, isolated storage, registry) - rules that can cancel applying/persisting data for a property

Trust me, the library is top notch!

Find the most frequent number in a NumPy array

Also if you want to get most frequent value(positive or negative) without loading any modules you can use the following code:

lVals = [1,2,3,1,2,1,1,1,3,2,2,1]
print max(map(lambda val: (lVals.count(val), val), set(lVals)))

Eclipse IDE: How to zoom in on text?

Too late but it could be helpful :

Go to Window Menu > Preferences > General > Appearance > Colors and Fonts

then go to Java > Java Editor Text Font > Edit

How to add an Access-Control-Allow-Origin header

Check this link.. It will definitely solve your problem.. There are plenty of solutions to make cross domain GET Ajax calls BUT POST REQUEST FOR CROSS DOMAIN IS SOLVED HERE. It took me 3 days to figure it out.

http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx

Submit two forms with one button

If you have a regular submit button, you could add an onclick event to it that does the follow:

document.getElementById('otherForm').submit();

Convert int to char in java

int a = 1;
char b = (char) a;
System.out.println(b);

will print out the char with Unicode code point 1 (start-of-heading char, which isn't printable; see this table: C0 Controls and Basic Latin, same as ASCII)

int a = '1';
char b = (char) a;
System.out.println(b);

will print out the char with Unicode code point 49 (one corresponding to '1')

If you want to convert a digit (0-9), you can add 48 to it and cast, or something like Character.forDigit(a, 10);.

If you want to convert an int seen as a Unicode code point, you can use Character.toChars(48) for example.

cannot open shared object file: No such file or directory

sudo ldconfig

ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories (/lib and /usr/lib).

Generally package manager takes care of this while installing the new library, but not always (specially when you install library with cmake).

And if the output of this is empty

$ echo $LD_LIBRARY_PATH

Please set the default path

$ LD_LIBRARY_PATH=/usr/local/lib

Cannot push to Git repository on Bitbucket

I am using macOS and although i had setup my public key in bitbucket the next time i tried to push i got

repository access denied.

fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

What i had to do was Step 2. Add the key to the ssh-agent as described in Bitbucket SSH keys setup guide and especially the 3rd step:

(macOS only) So that your computer remembers your password each time it restarts, open (or create) the ~/.ssh/config file and add these lines to the file:

Host *
UseKeychain yes

Hope it helps a mac user with the same issue.

How to get english language word database?

You can find what you need on infochimps.org.

They have a list of 350,000 simple (ie non-compound) words available for free download.

Word List - 350,000+ Simple English Words

Regarding other languages, you might want to poke around on Wiktionary. Here is a link to all the database backups - the information isnt organized so likely but if they have a language, you can download the data in SQL format.

Redirecting to authentication dialog - "An error occurred. Please try again later"

I had tried all the answers mentioned here. But it didn't work. I had to delete and create again. I am guessing it was due to new the "Authenticated Referral". If you have added Open Graph objects which are not approved, it might give you an error.

what does "dead beef" mean?

It's a magic number used in various places because it also happens to be readable in English, making it stand out. There's a partial list on Wikipedia.

UnicodeDecodeError, invalid continuation byte

If this error arises when manipulating a file that was just opened, check to see if you opened it in 'rb' mode

How to convert date into this 'yyyy-MM-dd' format in angular 2

_x000D_
_x000D_
const formatDate=(dateObj)=>{
const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

const dateOrdinal=(dom)=> {
    if (dom == 31 || dom == 21 || dom == 1) return dom + "st";
    else if (dom == 22 || dom == 2) return dom + "nd";
    else if (dom == 23 || dom == 3) return dom + "rd";
    else return dom + "th";
};
return dateOrdinal(dateObj.getDate())+', '+days[dateObj.getDay()]+' '+ months[dateObj.getMonth()]+', '+dateObj.getFullYear();
}
const ddate = new Date();
const result=formatDate(ddate)
document.getElementById("demo").innerHTML = result
_x000D_
<!DOCTYPE html>
<html>
<body>
<h2>Example:20th, Wednesday September, 2020 <h2>
<p id="demo"></p>
</body>
</html>
_x000D_
_x000D_
_x000D_

$(this).serialize() -- How to add a value?

While matt b's answer will work, you can also use .serializeArray() to get an array from the form data, modify it, and use jQuery.param() to convert it to a url-encoded form. This way, jQuery handles the serialisation of your extra data for you.

var data = $(this).serializeArray(); // convert form to array
data.push({name: "NonFormValue", value: NonFormValue});
$.ajax({
    type: 'POST',
    url: this.action,
    data: $.param(data),
});

How to convert Set<String> to String[]?

Use toArray(T[] a) method:

String[] array = set.toArray(new String[0]);

bootstrap datepicker setDate format dd/mm/yyyy

This line of code works for me

$("#datepicker").datepicker("option", "dateFormat", "dd/mm/yy");

you can change the id #datepicker with the class .input-group.date of course

Gson: Is there an easier way to serialize a map

In Gson 2.7.2 it's as easy as

Gson gson = new Gson();
String serialized = gson.toJson(map);

Best way to store data locally in .NET (C#)

A fourth option to those you mention are binary files. Although that sounds arcane and difficult, it's really easy with the serialization API in .NET.

Whether you choose binary or XML files, you can use the same serialization API, although you would use different serializers.

To binary serialize a class, it must be marked with the [Serializable] attribute or implement ISerializable.

You can do something similar with XML, although there the interface is called IXmlSerializable, and the attributes are [XmlRoot] and other attributes in the System.Xml.Serialization namespace.

If you want to use a relational database, SQL Server Compact Edition is free and very lightweight and based on a single file.

Moment js get first and last day of current month

Assuming you are using a Date range Picker to retrieve the dates. You could do something like to to get what you want.

$('#daterange-btn').daterangepicker({
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            startDate: moment().subtract(29, 'days'),
            endDate: moment()
        }, function (start, end) {
      alert( 'Date is between' + start.format('YYYY-MM-DD h:m') + 'and' + end.format('YYYY-MM-DD h:m')}

ISO C90 forbids mixed declarations and code in C

Up until the C99 standard, all declarations had to come before any statements in a block:

void foo()
{
  int i, j;
  double k;
  char *c;

  // code

  if (c)
  {
    int m, n;

    // more code
  }
  // etc.
}

C99 allowed for mixing declarations and statements (like C++). Many compilers still default to C89, and some compilers (such as Microsoft's) don't support C99 at all.

So, you will need to do the following:

  1. Determine if your compiler supports C99 or later; if it does, configure it so that it's compiling C99 instead of C89;

  2. If your compiler doesn't support C99 or later, you will either need to find a different compiler that does support it, or rewrite your code so that all declarations come before any statements within the block.

libz.so.1: cannot open shared object file

For Arch Linux, it is pacman -S lib32-zlib from multilib, not zlib.

How can change width of dropdown list?

try the !important argument to make sure the CSS is not conflicting with any other styles you have specified. Also using a reset.css is good before you add your own styles.

select#wgmstr {
    max-width: 50px;
    min-width: 50px;
    width: 50px !important;
}

or

<select name="wgtmsr" id="wgtmsr" style="width: 50px !important; min-width: 50px; max-width: 50px;">

How can I clear previous output in Terminal in Mac OS X?

Command + K will clear previous output.

To clear entered text, first jump left with Command + A and then clear the text to the right of the pointer with Control + K.

Visual examples:

Enter image description here

How to open a web page from my application?

You cannot launch a web page from an elevated application. This will raise a 0x800004005 exception, probably because explorer.exe and the browser are running non-elevated.

To launch a web page from an elevated application in a non-elevated web browser, use the code made by Mike Feng. I tried to pass the URL to lpApplicationName but that didn't work. Also not when I use CreateProcessWithTokenW with lpApplicationName = "explorer.exe" (or iexplore.exe) and lpCommandLine = url.

The following workaround does work: Create a small EXE-project that has one task: Process.Start(url), use CreateProcessWithTokenW to run this .EXE. On my Windows 8 RC this works fine and opens the web page in Google Chrome.

Sum columns with null values in oracle

The top-rated answer with NVL is totally valid. If you have any interest in making your SQL code more portable, you might want to use CASE, which is supported with the same syntax in both Oracle and SQL Server:

select 
  type,craft,
  SUM(
    case when regular is null
         then 0
         else regular
    end
    +
    case when overtime is null
         then 0
         else overtime
    end
  ) as total_hours
from 
  hours_t
group by
  type
 ,craft
order by
  type
 ,craft

Linking to an external URL in Javadoc?

This creates a "See Also" heading containing the link, i.e.:

/**
 * @see <a href="http://google.com">http://google.com</a>
 */

will render as:

See Also:
           http://google.com

whereas this:

/**
 * See <a href="http://google.com">http://google.com</a>
 */

will create an in-line link:

See http://google.com

The point of test %eax %eax

This checks if EAX is zero. The instruction test does bitwise AND between the arguments, and if EAX contains zero, the result sets the ZF, or ZeroFlag.

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

This is surely Eclipse related issue. The thing which worked for me is creating a new server in eclipse server tab. Then run your application in this new server, it should work.

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Thymeleaf using path variables to th:href

I think you can try this:

<a th:href="${'/category/edit/' + {category.id}}">view</a>

Or if you have "idCategory" this:

<a th:href="${'/category/edit/' + {category.idCategory}}">view</a>

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

In my case it was - no disk space left on the web server.

Javascript get object key name

This might be better understood if you modified the wording up a bit:

var buttons = {
  foo: 'bar',
  fiz: 'buz'
};

for ( var property in buttons ) {
  console.log( property ); // Outputs: foo, fiz or fiz, foo
}

Note here that you're iterating over the properties of the object, using property as a reference to each during each subsequent cycle.

MSDN says of for ( variable in [object | array ] ) the following:

Before each iteration of a loop, variable is assigned the next property name of object or the next element index of array. You can then use it in any of the statements inside the loop to reference the property of object or the element of array.

Note also that the property order of an object is not constant, and can change, unlike the index order of an array. That might come in handy.

Compile to stand alone exe for C# app in Visual Studio 2010

You can use the files from debug folder,however if you look at app debug informations with some inspection software,you can clearly see "Symbols File Name" which can reveals not wanted informations in path to the original exe file.

Check if all values of array are equal

Its Simple. Create a function and pass a parameter. In that function copy the first index into a new variable. Then Create a for loop and loop through the array. Inside a loop create an while loop with a condition checking whether the new created variable is equal to all the elements in the loop. if its equal return true after the for loop completes else return false inside the while loop.

function isUniform(arra){
    var k=arra[0];
    for (var i = 0; i < arra.length; i++) {
        while(k!==arra[i]){
            return false;
        }
    }
    return true;
}

Best way to format if statement with multiple conditions

The first one is easier, because, if you read it left to right you get: "If something AND somethingelse AND somethingelse THEN" , which is an easy to understand sentence. The second example reads "If something THEN if somethingelse THEN if something else THEN", which is clumsy.

Also, consider if you wanted to use some ORs in your clause - how would you do that in the second style?

Returning from a void function

The only reason to have a return in a void function would be to exit early due to some conditional statement:

void foo(int y)
{
    if(y == 0) return;

    // do stuff with y
}

As unwind said: when the code ends, it ends. No need for an explicit return at the end.

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

You can use javax.xml.bind.DatatypeConverter class

DatatypeConverter.printDateTime & DatatypeConverter.parseDateTime

How to handle onchange event on input type=file in jQuery?

Or could be:

$('input[type=file]').change(function () {
    alert("hola");
});

To be specific: $('input[type=file]#fileUpload1').change(...

How do I make a placeholder for a 'select' box?

See this answer :

<select>
        <option style="display: none;" value="" selected>SelectType</option>
        <option value="1">Type 1</option>
        <option value="2">Type 2</option>
        <option value="3">Type 3</option>
        <option value="4">Type 4</option>
</select>

Practical uses for AtomicInteger

Like gabuzo said, sometimes I use AtomicIntegers when I want to pass an int by reference. It's a built-in class that has architecture-specific code, so it's easier and likely more optimized than any MutableInteger I could quickly code up. That said, it feels like an abuse of the class.

Dart SDK is not configured

OS: Ubuntu 19.04

IntelliJ: 2019.1.2RC

I have read on all the previous answer and after some time trying to get this working I found that the IntelliJ Flutter plugin does not want the path to which flutter instead it needs the base installation folder.

So the 2 steps which fixed:

  1. Install IntelliJ Flutter plugin:
    • Ctrl + Shift + a (Open Actions)
    • Type in search 'Flutter' hit enter Install and restart IntelliJ
  2. Configure Flutter Plugin:
    • Ctrl + Alt + s (Open Settings)
    • Type in search 'Flutter', Select option under Language & Frameworks
    • Open terminal which flutter output PATH_TO_FLUTTER/bin/flutter you ONLY NEED the PATH_TO_FLUTTER so remove everything from /bin...
    • Paste the location on the Flutter SDK path input and apply.

That will then ask you to restart IntelliJ and you should get both Flutter and Dart configured:

enter image description here

Good luck!

How can I check whether Google Maps is fully loaded?

This was bothering me for a while with GMaps v3.

I found a way to do it like this:

google.maps.event.addListenerOnce(map, 'idle', function(){
    // do something only the first time the map is loaded
});

The "idle" event is triggered when the map goes to idle state - everything loaded (or failed to load). I found it to be more reliable then tilesloaded/bounds_changed and using addListenerOnce method the code in the closure is executed the first time "idle" is fired and then the event is detached.

See also the events section in the Google Maps Reference.

Trying to use Spring Boot REST to Read JSON String from POST

To further work with array of maps, the followings could help:

@RequestMapping(value = "/process", method = RequestMethod.POST, headers = "Accept=application/json")
public void setLead(@RequestBody Collection<? extends Map<String, Object>> payload) throws Exception {

  List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
  maps.addAll(payload);

}

Notify ObservableCollection when Item changes

The spot you have commented as // Code to trig on item change... will only trigger when the collection object gets changed, such as when it gets set to a new object, or set to null.

With your current implementation of TrulyObservableCollection, to handle the property changed events of your collection, register something to the CollectionChanged event of MyItemsSource

public MyViewModel()
{
    MyItemsSource = new TrulyObservableCollection<MyType>();
    MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged;

    MyItemsSource.Add(new MyType() { MyProperty = false });
    MyItemsSource.Add(new MyType() { MyProperty = true});
    MyItemsSource.Add(new MyType() { MyProperty = false });
}


void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    // Handle here
}

Personally I really don't like this implementation. You are raising a CollectionChanged event that says the entire collection has been reset, anytime a property changes. Sure it'll make the UI update anytime an item in the collection changes, but I see that being bad on performance, and it doesn't seem to have a way to identify what property changed, which is one of the key pieces of information I usually need when doing something on PropertyChanged.

I prefer using a regular ObservableCollection and just hooking up the PropertyChanged events to it's items on CollectionChanged. Providing your UI is bound correctly to the items in the ObservableCollection, you shouldn't need to tell the UI to update when a property on an item in the collection changes.

public MyViewModel()
{
    MyItemsSource = new ObservableCollection<MyType>();
    MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged;

    MyItemsSource.Add(new MyType() { MyProperty = false });
    MyItemsSource.Add(new MyType() { MyProperty = true});
    MyItemsSource.Add(new MyType() { MyProperty = false });
}

void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.NewItems != null)
        foreach(MyType item in e.NewItems)
            item.PropertyChanged += MyType_PropertyChanged;

    if (e.OldItems != null)
        foreach(MyType item in e.OldItems)
            item.PropertyChanged -= MyType_PropertyChanged;
}

void MyType_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "MyProperty")
        DoWork();
}

'too many values to unpack', iterating over a dict. key=>string, value=>list

data = (['President','George','Bush','is','.'],['O','B-PERSON','I-PERSON','O','O'])
corpus = []
for(doc,tags) in data:
    doc_tag = []
    for word,tag in zip(doc,tags):
        doc_tag.append((word,tag))
        corpus.append(doc_tag)
        print(corpus)

how to count the spaces in a java string?

This program will definitely help you.

class SpaceCount
{

    public static int spaceCount(String s)
    { int a=0;
        char ch[]= new char[s.length()];
        for(int i = 0; i < s.length(); i++) 

        {  ch[i]= s.charAt(i);
            if( ch[i]==' ' )
            a++;
                }   
        return a;
    }


    public static void main(String... s)
    {
        int m = spaceCount("Hello I am a Java Developer");
        System.out.println("The number of words in the String are :  "+m);

    }
}

How to convert Varchar to Double in sql?

use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

SELECT fullName, 
       CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info 
ORDER BY _totalBal DESC

How to convert image to byte array

This code retrieves first 100 rows from table in SQLSERVER 2012 and saves a picture per row as a file on local disk

 public void SavePicture()
    {
        SqlConnection con = new SqlConnection("Data Source=localhost;Integrated security=true;database=databasename");
        SqlDataAdapter da = new SqlDataAdapter("select top 100 [Name] ,[Picture] From tablename", con);
        SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
        DataSet ds = new DataSet("tablename");
        byte[] MyData = new byte[0];
        da.Fill(ds, "tablename");
        DataTable table = ds.Tables["tablename"];
           for (int i = 0; i < table.Rows.Count;i++ )               
               {
                DataRow myRow;
                myRow = ds.Tables["tablename"].Rows[i];
                MyData = (byte[])myRow["Picture"];
                int ArraySize = new int();
                ArraySize = MyData.GetUpperBound(0);
                FileStream fs = new FileStream(@"C:\NewFolder\" + myRow["Name"].ToString() + ".jpg", FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(MyData, 0, ArraySize);
                fs.Close();
               }

    }

please note: Directory with NewFolder name should exist in C:\

Phone: numeric keyboard for text input

For me the best solution was:

For integer numbers, which brings up the 0-9 pad on android and iphone

<label for="ting">
<input id="ting" name="ting" type="number" pattern="[\d]*" />

You also may want to do this to hide the spinners in firefox/chrome/safari, most clients think they look ugly

 input[type=number]::-webkit-inner-spin-button,
 input[type=number]::-webkit-outer-spin-button {
      -webkit-appearance: none;
      margin: 0;
 }

 input[type=number] {
      -moz-appearance:textfield;
 }

And add novalidate='novalidate' to your form element, if your doing custom validation

Ps just in case you actually wanted floating point numbers after all,step to whatever precision you fancy, will add '.' to android

<label for="ting">
<input id="ting" name="ting" type="number" pattern="[\d\.]*" step="0.01" />

Variable name as a string in Javascript

var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];

This isn't able to be made into a function as it returns the name of the function's variable.

// THIS DOESN'T WORK
function getVarName(v) {
    return Object.keys({v})[0];
}
// Returns "v"

Edit: Thanks to @Madeo for pointing out how to make this into a function.

function debugVar(varObj) {
    var varName = Object.keys(varObj)[0];
    console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}

You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.

How do I download a binary file over HTTP?

Here is my Ruby http to file using open(name, *rest, &block).

require "open-uri"
require "fileutils"

def download(url, path)
  case io = open(url)
  when StringIO then File.open(path, 'w') { |f| f.write(io.read) }
  when Tempfile then io.close; FileUtils.mv(io.path, path)
  end
end

The main advantage here it is concise and simple, because open does much of the heavy lifting. And it does not read the whole response in memory.

The open method will stream responses > 1kb to a Tempfile. We can exploit this knowledge to implement this lean download to file method. See the OpenURI::Buffer implementation here.

Please be careful with user provided input! open(name, *rest, &block) is unsafe if name is coming from user input!

Modify the legend of pandas bar plot

To change the labels for Pandas df.plot() use ax.legend([...]):

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);

enter image description here

Another approach is to do the same by plt.legend([...]):

import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);

enter image description here

Post form data using HttpWebRequest

Use this code:

internal void SomeFunction() {
    Dictionary<string, string> formField = new Dictionary<string, string>();
    
    formField.Add("Name", "Henry");
    formField.Add("Age", "21");
    
    string body = GetBodyStringFromDictionary(formField);
    // output : Name=Henry&Age=21
}

internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
    string body = string.Empty;
    foreach (var pair in formField)
    {
        body += $"{pair.Key}={pair.Value}&";   
    }

    // delete last "&"
    body = body.Substring(0, body.Length - 1);

    return body;
}

What are .iml files in Android Studio?

Those files are created and used by Android Studio editor.

You don't need to check in those files to version control.

Git uses .gitignore file, that contains list of files and directories, to know the list of files and directories that don't need to be checked in.

Android studio automatically creates .gitingnore files listing all files and directories which don't need to be checked in to any version control.

Printing *s as triangles in Java?

// This is for normal triangle

for (int i = 0; i < 5; i++)
        {
            for (int j = 5; j > i; j--)
            {
                System.out.print(" ");
            }
            for (int k = 1; k <= i + 1; k++) {
                System.out.print(" *");
            }
            System.out.print("\n");
        }

// This is for left triangle, just removed space before printing *

for (int i = 0; i < 5; i++)
        {
            for (int j = 5; j > i; j--)
            {
                System.out.print(" ");
            }
            for (int k = 1; k <= i + 1; k++) {
                System.out.print("*");
            }
            System.out.print("\n");
        }

extract date only from given timestamp in oracle sql

This is exactly what TO_DATE() is for: to convert timestamp to date.

Just use TO_DATE(sysdate) instead of TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS').

SQLFiddle demo

UPDATE:

Per your update, your cdate column is not real DATE or TIMESTAMP type, but VARCHAR2. It is not very good idea to use string types to keep dates. It is very inconvenient and slow to search, compare and do all other kinds of math on dates.

You should convert your cdate VARCHAR2 field into real TIMESTAMP. Assuming there are no other users for this field except for your code, you can convert cdate to timestamp as follows:

BEGIN TRANSACTION;
-- add new temp field tdate:
ALTER TABLE mytable ADD tdate TIMESTAMP;
-- save cdate to tdate while converting it:
UPDATE mytable SET tdate = to_date(cdate, 'YYYY-MM-DD HH24:MI:SS');

-- you may want to check contents of tdate before next step!!!

-- drop old field
ALTER TABLE mytable DROP COLUMN cdate;
-- rename tdate to cdate:
ALTER TABLE mytable RENAME COLUMN tdate TO cdate;
COMMIT;

SQLFiddle Demo

Clear data in MySQL table with PHP?

TRUNCATE will blank your table and reset primary key DELETE will also make your table blank but it will not reset primary key.

we can use for truncate

TRUNCATE TABLE tablename

we can use for delete

DELETE FROM tablename

we can also give conditions as below

DELETE FROM tablename WHERE id='xyz'

Boolean vs tinyint(1) for boolean values in MySQL

boolean isn't a distinct datatype in MySQL; it's just a synonym for tinyint. See this page in the MySQL manual.

Personally I would suggest use tinyint as a preference, because boolean doesn't do what you think it does from the name, so it makes for potentially misleading code. But at a practical level, it really doesn't matter -- they both do the same thing, so you're not gaining or losing anything by using either.

Remove accents/diacritics in a string in JavaScript

Here's a very simple solution without too much code using a very simple map of diacritics that includes some or all that map to ascii equivalents containing more than one character, i.e. Æ => AE, ? => ffi, etc... Also included some very basic functional tests

var diacriticsMap = {
  '\u00C0': 'A',  // À => A
  '\u00C1': 'A',   // Á => A
  '\u00C2': 'A',   // Â => A
  '\u00C3': 'A',   // Ã => A
  '\u00C4': 'A',   // Ä => A
  '\u00C5': 'A',   // Å => A
  '\u00C6': 'AE', // Æ => AE
  '\u00C7': 'C',   // Ç => C
  '\u00C8': 'E',   // È => E
  '\u00C9': 'E',   // É => E
  '\u00CA': 'E',   // Ê => E
  '\u00CB': 'E',   // Ë => E
  '\u00CC': 'I',   // Ì => I
  '\u00CD': 'I',   // Í => I
  '\u00CE': 'I',   // Î => I
  '\u00CF': 'I',   // Ï => I
  '\u0132': 'IJ', // ? => IJ
  '\u00D0': 'D',   // Ð => D
  '\u00D1': 'N',   // Ñ => N
  '\u00D2': 'O',   // Ò => O
  '\u00D3': 'O',   // Ó => O
  '\u00D4': 'O',   // Ô => O
  '\u00D5': 'O',   // Õ => O
  '\u00D6': 'O',   // Ö => O
  '\u00D8': 'O',   // Ø => O
  '\u0152': 'OE', // Π=> OE
  '\u00DE': 'TH', // Þ => TH
  '\u00D9': 'U',   // Ù => U
  '\u00DA': 'U',   // Ú => U
  '\u00DB': 'U',   // Û => U
  '\u00DC': 'U',   // Ü => U
  '\u00DD': 'Y',   // Ý => Y
  '\u0178': 'Y',   // Ÿ => Y
  '\u00E0': 'a',   // à => a
  '\u00E1': 'a',   // á => a
  '\u00E2': 'a',   // â => a
  '\u00E3': 'a',   // ã => a
  '\u00E4': 'a',   // ä => a
  '\u00E5': 'a',   // å => a
  '\u00E6': 'ae', // æ => ae
  '\u00E7': 'c',   // ç => c
  '\u00E8': 'e',   // è => e
  '\u00E9': 'e',   // é => e
  '\u00EA': 'e',   // ê => e
  '\u00EB': 'e',   // ë => e
  '\u00EC': 'i',   // ì => i
  '\u00ED': 'i',   // í => i
  '\u00EE': 'i',   // î => i
  '\u00EF': 'i',   // ï => i
  '\u0133': 'ij', // ? => ij
  '\u00F0': 'd',   // ð => d
  '\u00F1': 'n',   // ñ => n
  '\u00F2': 'o',   // ò => o
  '\u00F3': 'o',   // ó => o
  '\u00F4': 'o',   // ô => o
  '\u00F5': 'o',   // õ => o
  '\u00F6': 'o',   // ö => o
  '\u00F8': 'o',   // ø => o
  '\u0153': 'oe', // œ => oe
  '\u00DF': 'ss', // ß => ss
  '\u00FE': 'th', // þ => th
  '\u00F9': 'u',   // ù => u
  '\u00FA': 'u',   // ú => u
  '\u00FB': 'u',   // û => u
  '\u00FC': 'u',   // ü => u
  '\u00FD': 'y',   // ý => y
  '\u00FF': 'y',   // ÿ => y
  '\uFB00': 'ff', // ? => ff
  '\uFB01': 'fi',   // ? => fi
  '\uFB02': 'fl', // ? => fl
  '\uFB03': 'ffi',  // ? => ffi
  '\uFB04': 'ffl',  // ? => ffl
  '\uFB05': 'ft', // ? => ft
  '\uFB06': 'st'  // ? => st
};

function replaceDiacritics(str) {
  var returnStr = '';
  if(str) {
    for (var i = 0; i < str.length; i++) {
      if (diacriticsMap[str[i]]) {
        returnStr += diacriticsMap[str[i]];
      } else {
        returnStr += str[i];
      }
    }
  }
  return returnStr;
}

function testStripDiacritics(input, expected) {
  var coChar = replaceDiacritics(input);
  console.log('The character passed in was ' + input);
  console.log('The character that came out was ' + coChar);
  console.log('The character expected was' + expected);
}

testStripDiacritics('À','A');
testStripDiacritics('A','A');
testStripDiacritics('Æ','AE');
testStripDiacritics('AE','AE');
testStripDiacritics('ÇhÀrlËšYŸZŽ','ChArlEsYYZZ');

How to make ng-repeat filter out duplicate results

None of the above filters fixed my issue so I had to copy the filter from official github doc. And then use it as explained in the above answers

angular.module('yourAppNameHere').filter('unique', function () {

return function (items, filterOn) {

if (filterOn === false) {
  return items;
}

if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
  var hashCheck = {}, newItems = [];

  var extractValueToCompare = function (item) {
    if (angular.isObject(item) && angular.isString(filterOn)) {
      return item[filterOn];
    } else {
      return item;
    }
  };

  angular.forEach(items, function (item) {
    var valueToCheck, isDuplicate = false;

    for (var i = 0; i < newItems.length; i++) {
      if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
        isDuplicate = true;
        break;
      }
    }
    if (!isDuplicate) {
      newItems.push(item);
    }

  });
  items = newItems;
}
return items;
  };

});

In Laravel, the best way to pass different types of flash messages in the session

Another solution would be to create a helper class How to Create helper classes here

class Helper{
     public static function format_message($message,$type)
    {
         return '<p class="alert alert-'.$type.'">'.$message.'</p>'
    }
}

Then you can do this.

Redirect::to('users/login')->with('message', Helper::format_message('A bla blah occured','error'));

or

Redirect::to('users/login')->with('message', Helper::format_message('Thanks for registering!','info'));

and in your view

@if(Session::has('message'))
    {{Session::get('message')}}
@endif

How to hide html source & disable right click and text copy?

It's a horrible thing to do, as everybody else has said, but if you really are intent on doing it, use this code, and put a load of returns at the top of the page's source:

<html>
  <head>
    <script>
      function disableClick(){
        document.onclick=function(event){
          if (event.button == 2) {
            alert('Right Click Message');
            return false;
          }
        }
      }
    </script>
  </head>
  <body onLoad="disableClick()">
  </body>
</html>

How to get Domain name from URL using jquery..?

This worked for me.

http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery

$(location).attr('host');                        www.test.com:8082
$(location).attr('hostname');                    www.test.com
$(location).attr('port');                        8082
$(location).attr('protocol');                    http:
$(location).attr('pathname');                    index.php
$(location).attr('href');                        http://www.test.com:8082/index.php#tab2
$(location).attr('hash');                       #tab2
$(location).attr('search');                     ?foo=123

What is the difference between SQL, PL-SQL and T-SQL?

SQL is a standard and there are many database vendors like Microsoft,Oracle who implements this standard using their own proprietary language.

Microsoft uses T-SQL to implement SQL standard to interact with data whereas oracle uses PL/SQL.

On select change, get data attribute value

$('#foo option:selected').data('id');

How to handle-escape both single and double quotes in an SQL-Update statement

Use two single quotes to escape them in the sql statement. The double quotes should not be a problem:

SELECT 'How is my son''s school helping him learn?  "Not as good as Stack Overflow would!"'

Print:

How is my son's school helping him learn? "Not as good as Stack Overflow would!"

JQuery Event for user pressing enter in a textbox?

HTML Code:-

<input type="text" name="txt1" id="txt1" onkeypress="return AddKeyPress(event);" />      

<input type="button" id="btnclick">

Java Script Code

function AddKeyPress(e) { 
        // look for window.event in case event isn't passed in
        e = e || window.event;
        if (e.keyCode == 13) {
            document.getElementById('btnEmail').click();
            return false;
        }
        return true;
    }

Your Form do not have Default Submit Button

UIImageView - How to get the file name of the image assigned?

There is no native way to do this; however, you could easily create this behavior yourself.

You can subclass UIImageView and add a new instance variable:

NSString* imageFileName;

Then you could override setImage, first setting imageFileName to the filename of the image you're setting, and then calling [super setImage:imageFileName]. Something like this:

-(void) setImage:(NSString*)fileName
{
   imageFileName = fileName;
   [super setImage:fileName];
}

Just because it can't be done natively doesn't mean it isn't possible :)

proper hibernate annotation for byte[]

I'm using the Hibernate 4.2.7.SP1 with Postgres 9.3 and following works for me:

@Entity
public class ConfigAttribute {
  @Lob
  public byte[] getValueBuffer() {
    return m_valueBuffer;
  }
}

as Oracle has no trouble with that, and for Postgres I'm using custom dialect:

public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {

    @Override
    public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
      return BinaryTypeDescriptor.INSTANCE;
    }
    return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
  }
}

the advantage of this solution I consider, that I can keep hibernate jars untouched.

For more Postgres/Oracle compatibility issues with Hibernate, see my blog post.

Meaning of *& and **& in C++

First is a reference to a pointer, second is a reference to a pointer to a pointer. See also FAQ on how pointers and references differ.

void foo(int*& x, int**& y) {
    // modifying x or y here will modify a or b in main
}

int main() {
    int val = 42;
    int *a  = &val;
    int **b = &a;

    foo(a, b);
    return 0;
}

App not setup: This app is still in development mode

2021 UPDATE

I have done successfully Login with Facebook by doing below things. Now it is working fine.

As per described by George Mano

Visit Facebook Apps Page and select your application.

Go to Settings -> Basic.

Add a 1 Contact Email, 2 Privacy Policy URL, 3 User Data Deletion and choose 4 Category and Last 5. Live your application

The Privacy Policy URL should be a webpage where you have hosted the terms and conditions of your application and data used.

The General Data Protection Regulation (GDPR) requires developers to provide a way for people to request that their data be deleted. To be compliant with these requirements, you must provide either a data deletion request callback or instructions to inform people how to delete their data from your app or website

Toggle the button in the top of the screen, as seen below, in order to switch from Development to Live.

enter image description here

Is there an easy way to convert jquery code to javascript?

I can see a reason, unrelated to the original post, to automatically compile jQuery code into standard JavaScript:

16k -- or whatever the gzipped, minified jQuery library is -- might be too much for your website that is intended for a mobile browser. The w3c is recommending that all HTTP requests for mobile websites should be a maximum of 20k.

w3c specs for mobile

So I enjoy coding in my nice, terse, chained jQuery. But now I need to optimize for mobile. Should I really go back and do the difficult, tedious work of rewriting all the helper functions I used in the jQuery library? Or is there some kind of convenient app that will help me recompile?

That would be very sweet. Sadly, I don't think such a thing exists.

How can I set selected option selected in vue.js 2?

You simply need to remove v-bind (:) from selected and required attributes. Like this :-

_x000D_
_x000D_
<template>_x000D_
    <select class="form-control" v-model="selected" required @change="changeLocation">_x000D_
        <option selected>Choose Province</option>_x000D_
        <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>_x000D_
    </select>_x000D_
</template>
_x000D_
_x000D_
_x000D_

You are not binding anything to the vue instance through these attributes thats why it is giving error.

PostgreSQL psql terminal command

These are not command line args. Run psql. Manage to log into database (so pass the hostname, port, user and database if needed). And then write it in the psql program.

Example (below are two commands, write the first one, press enter, wait for psql to login, write the second):

psql -h host -p 5900 -U username database
\pset format aligned

Checking if date is weekend PHP

This works for me and is reusable.

function isThisDayAWeekend($date) {

    $timestamp = strtotime($date);

    $weekday= date("l", $timestamp );

    if ($weekday =="Saturday" OR $weekday =="Sunday") { return true; } 
    else {return false; }

}

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

Openssl is not recognized as an internal or external command

IDK if this is relevant here, but if you have Git Installed, you can find the openssl in the "C:\Program Files\Git\usr\bin" and that location you can use in the Terminal for your Keystore Command.

oh and yeah the command:

keytool -exportcert -alias keystore -keystore "C:\Users\YOURPATH/filename.jks" | "C:\Program Files\Git\usr\bin\openssl" sha1 -binary | "C:\Program Files\Git\usr\bin\openssl" base64

Regex for parsing directory and filename

Most languages have path parsing functions that will give you this already. If you have the ability, I'd recommend using what comes to you for free out-of-the-box.

Assuming / is the path delimiter...

^(.*/)([^/]*)$

The first group will be whatever the directory/path info is, the second will be the filename. For example:

  • /foo/bar/baz.log: "/foo/bar/" is the path, "baz.log" is the file
  • foo/bar.log: "foo/" is the path, "bar.log" is the file
  • /foo/bar: "/foo/" is the path, "bar" is the file
  • /foo/bar/: "/foo/bar/" is the path and there is no file.

How to change HTML Object element data attribute value in javascript

The following code works if you use jquery

$( "object" ).replaceWith('<object data="http://www.google.com"></object>');

What's the difference between utf8_general_ci and utf8_unicode_ci?

There are two big difference the sorting and the character matching:

Sorting:

  • utf8mb4_general_ci removes all accents and sorts one by one which may create incorrect sort results.
  • utf8mb4_unicode_ci sorts accurate.

Character Matching

They match characters differently.

For example, in utf8mb4_unicode_ci you have i != i, but in utf8mb4_general_ci it holds i=i.

For example, imagine you have a row with name="Yilmaz". Then

select id from users where name='Yilmaz';

would return the row if collocation is utf8mb4_general_ci, but if it is collocated with utf8mb4_unicode_ci it would not return the row!

On the other hand we have that a=ª and ß=ss in utf8mb4_unicode_ci which is not the case in utf8mb4_general_ci. So imagine you have a row with name="ªßi", then

select id from users where name='assi';

would return the row if collocation is utf8mb4_unicode_ci, but would not return a row if collocation is set to utf8mb4_general_ci.

A full list of matches for each collocation may be found here.

How to find out when an Oracle table was updated the last time

Could you run a checksum of some sort on the result and store that locally? Then when your application queries the database, you can compare its checksum and determine if you should import it?

It looks like you may be able to use the ORA_HASH function to accomplish this.

Update: Another good resource: 10g’s ORA_HASH function to determine if two Oracle tables’ data are equal

Linux: where are environment variables stored?

It's stored in the process (shell) and since you've exported it, any processes that process spawns.

Doing the above doesn't store it anywhere in the filesystem like /etc/profile. You have to put it there explicitly for that to happen.

Nginx 403 error: directory index of [folder] is forbidden

If you're simply trying to list directory contents use autoindex on; like:

location /somedir {
       autoindex on;
}

server {
        listen   80;
        server_name  domain.com www.domain.com;
        access_log  /var/...........................;
        root   /path/to/root;
        location / {
                index  index.php index.html index.htm;
        }
        location /somedir {
               autoindex on;
        }
}

IntelliJ: Error:java: error: release version 5 not supported

Took me a while to aggregate an actual solution, but here's how to get rid of this compile error.

  1. Open IntelliJ preferences.

  2. Search for "compiler" (or something like "compi").

  3. Scroll down to Maven -->java compiler. In the right panel will be a list of modules and their associated java compile version "target bytecode version."

  4. Select a version >1.5. You may need to upgrade your jdk if one is not available.

enter image description here

how to set radio option checked onload with jQuery

Don't need all that. With simple and old HTML you can achieve what you want. If you let the radio you want checked by default like this:
<input type='radio' name='gender' checked='true' value='Male'>
When page loads, it'll come checked.

How to use setArguments() and getArguments() methods in Fragments?

You have a method called getArguments() that belongs to Fragment class.

Should I use the Reply-To header when sending emails as a service to others?

You may want to consider placing the customer's name in the From header and your address in the Sender header:

From: Company A <[email protected]>
Sender: [email protected]

Most mailers will render this as "From [email protected] on behalf of Company A", which is accurate. And then a Reply-To of Company A's address won't seem out of sorts.

From RFC 5322:

The "From:" field specifies the author(s) of the message, that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. The "Sender:" field specifies the mailbox of the agent responsible for the actual transmission of the message. For example, if a secretary were to send a message for another person, the mailbox of the secretary would appear in the "Sender:" field and the mailbox of the actual author would appear in the "From:" field.

Excluding files/directories from Gulp task

Quick answer

On src, you can always specify files to ignore using "!".

Example (you want to exclude all *.min.js files on your js folder and subfolder:

gulp.src(['js/**/*.js', '!js/**/*.min.js'])

You can do it as well for individual files.

Expanded answer:

Extracted from gulp documentation:

gulp.src(globs[, options])

Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.

glob refers to node-glob syntax or it can be a direct file path.

So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.

On minimatch documentation, they point out the following:

if the pattern starts with a ! character, then it is negated.

And that is why using ! symbol will exclude files / directories from a gulp task

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

If running on IIS as the server and .net 4/4.5 it might be missing mime / file extension definitions in Web.config - like this:

_x000D_
_x000D_
<system.webServer>_x000D_
 <staticContent>_x000D_
      <remove fileExtension=".eot" />_x000D_
      <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />_x000D_
      <remove fileExtension=".ttf" />_x000D_
      <mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />_x000D_
      <remove fileExtension=".svg" />_x000D_
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />_x000D_
      <remove fileExtension=".woff" />_x000D_
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />_x000D_
    </staticContent>_x000D_
</system.webServer>
_x000D_
_x000D_
_x000D_

Change color and appearance of drop down arrow

Not easily done I am afraid. The problem is Css cannot replace the arrow in a select as this is rendered by the browser. But you can build a new control from div and input elements and Javascript to perform the same function as the select.

Try looking at some of the autocomplete plugins for Jquery for example.

Otherwise there is some info on the select element here:

http://www.devarticles.com/c/a/Web-Style-Sheets/Taming-the-Select/

How to make MySQL table primary key auto increment with some prefix

If you really need this you can achieve your goal with help of separate table for sequencing (if you don't mind) and a trigger.

Tables

CREATE TABLE table1_seq
(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
  id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0', name VARCHAR(30)
);

Now the trigger

DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
  INSERT INTO table1_seq VALUES (NULL);
  SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;

Then you just insert rows to table1

INSERT INTO Table1 (name) 
VALUES ('Jhon'), ('Mark');

And you'll have

|      ID | NAME |
------------------
| LHPL001 | Jhon |
| LHPL002 | Mark |

Here is SQLFiddle demo

What are the most common font-sizes for H1-H6 tags

Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.

How to center form in bootstrap 3

The total columns in a row has to add up to 12. So you can do col-md-4 col-md-offset-4. So your breaking up your columns into 3 groups of 4 columns each. Right now you have a 4 column form with an offset by 6 so you are only getting 2 columns to the right side of your form. You can also do col-md-8 col-md-offset-2 which would give you a 8 column form with 2 columns each of space left and right or col-md-6 col-md-offset-3 (6 column form with 3 columns space on each side), etc.

Simple VBA selection: Selecting 5 cells to the right of the active cell

This example selects a new Range of Cells defined by the current cell to a cell 5 to the right.

Note that .Offset takes arguments of Offset(row, columns) and can be quite useful.


Sub testForStackOverflow()
    Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub

https with WCF error: "Could not find base address that matches scheme https"

Look at your base address and your endpoint address (can't see it in your sample code). most likely you missed a column or some other typo e.g. https// instead of https://

How to add RSA key to authorized_keys file?

>ssh user@serverip -p portnumber 
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys

How to focus on a form input text field on page load using jQuery?

This is what I prefer to use:

<script type="text/javascript">
    $(document).ready(function () {
        $("#fieldID").focus(); 
    });
</script>

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

When you want to return a JSON response in MVC .Net Core You can also use:

Response.StatusCode = (int)HttpStatusCode.InternalServerError;//Equals to HTTPResponse 500
return Json(new { responseText = "my error" });

This will return both JSON result and HTTPStatus. I use it for returning results to jQuery.ajax().

GROUP BY to combine/concat a column

A good question. Should tell you it took some time to crack this one. Here is my result.

DECLARE @TABLE TABLE
(  
ID INT,  
USERS VARCHAR(10),  
ACTIVITY VARCHAR(10),  
PAGEURL VARCHAR(10)  
)

INSERT INTO @TABLE  
VALUES  (1, 'Me', 'act1', 'ab'),
        (2, 'Me', 'act1', 'cd'),
        (3, 'You', 'act2', 'xy'),
        (4, 'You', 'act2', 'st')


SELECT T1.USERS, T1.ACTIVITY,   
        STUFF(  
        (  
        SELECT ',' + T2.PAGEURL  
        FROM @TABLE T2  
        WHERE T1.USERS = T2.USERS  
        FOR XML PATH ('')  
        ),1,1,'')  
FROM @TABLE T1  
GROUP BY T1.USERS, T1.ACTIVITY

How to view the assembly behind the code using Visual C++?

Additional note: there is big difference between Debug assembler output and Release one. The first one is good to learn how compiler produces assembler code from C++. The second one is good to learn how compiler optimizes various C++ constructs. In this case some C++-to-asm transformations are not obvious.

How to use sys.exit() in Python

Using 2.7:

from functools import partial
from random import randint

for roll in iter(partial(randint, 1, 8), 1):
    print 'you rolled: {}'.format(roll)
print 'oops you rolled a 1!'

you rolled: 7
you rolled: 7
you rolled: 8
you rolled: 6
you rolled: 8
you rolled: 5
oops you rolled a 1!

Then change the "oops" print to a raise SystemExit

Convert.ToDateTime: how to set format

You can use Convert.ToDateTime is it is shown at How to convert a Datetime string to a current culture datetime string

DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;

var result = Convert.ToDateTime("12/01/2011", usDtfi)

Basic HTTP authentication with Node and Express 4

I used the code for the original basicAuth to find the answer:

app.use(function(req, res, next) {
    var user = auth(req);

    if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
        res.statusCode = 401;
        res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
        res.end('Unauthorized');
    } else {
        next();
    }
});

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

Replace text inside td using jQuery having td containing other elements

Remove the textnode, and replace the <b> tag with whatever you need without ever touching the inputs :

$('#demoTable').find('tr > td').contents().filter(function() {
    return this.nodeType===3;
}).remove().end().end()
  .find('b').replaceWith($('<span />', {text: 'Hello Kitty'}));

FIDDLE

Casting interfaces for deserialization in JSON.NET

To enable deserialization of multiple implementations of interfaces, you can use JsonConverter, but not through an attribute:

Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Converters.Add(new DTOJsonConverter());
Interfaces.IEntity entity = serializer.Deserialize(jsonReader);

DTOJsonConverter maps each interface with a concrete implementation:

class DTOJsonConverter : Newtonsoft.Json.JsonConverter
{
    private static readonly string ISCALAR_FULLNAME = typeof(Interfaces.IScalar).FullName;
    private static readonly string IENTITY_FULLNAME = typeof(Interfaces.IEntity).FullName;


    public override bool CanConvert(Type objectType)
    {
        if (objectType.FullName == ISCALAR_FULLNAME
            || objectType.FullName == IENTITY_FULLNAME)
        {
            return true;
        }
        return false;
    }

    public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
    {
        if (objectType.FullName == ISCALAR_FULLNAME)
            return serializer.Deserialize(reader, typeof(DTO.ClientScalar));
        else if (objectType.FullName == IENTITY_FULLNAME)
            return serializer.Deserialize(reader, typeof(DTO.ClientEntity));

        throw new NotSupportedException(string.Format("Type {0} unexpected.", objectType));
    }

    public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

DTOJsonConverter is required only for the deserializer. The serialization process is unchanged. The Json object do not need to embed concrete types names.

This SO post offers the same solution one step further with a generic JsonConverter.

What is float in Java?

In Java, when you type a decimal number as 3.6, its interpreted as a double. double is a 64-bit precision IEEE 754 floating point, while floatis a 32-bit precision IEEE 754 floating point. As a float is less precise than a double, the conversion cannot be performed implicitly.

If you want to create a float, you should end your number with f (i.e.: 3.6f).

For more explanation, see the primitive data types definition of the Java tutorial.

How do I change the font color in an html table?

table td{
  color:#0000ff;
}

<table>
  <tbody>
    <tr>
    <td>
      <select name="test">
        <option value="Basic">Basic : $30.00 USD - yearly</option>
        <option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
        <option value="Supporting">Supporting : $120.00 USD - yearly</option>
      </select>
    </td>
    </tr>
  </tbody>
</table>

Can an ASP.NET MVC controller return an Image?

You can create your own extension and do this way.

public static class ImageResultHelper
{
    public static string Image<T>(this HtmlHelper helper, Expression<Action<T>> action, int width, int height)
            where T : Controller
    {
        return ImageResultHelper.Image<T>(helper, action, width, height, "");
    }

    public static string Image<T>(this HtmlHelper helper, Expression<Action<T>> action, int width, int height, string alt)
            where T : Controller
    {
        var expression = action.Body as MethodCallExpression;
        string actionMethodName = string.Empty;
        if (expression != null)
        {
            actionMethodName = expression.Method.Name;
        }
        string url = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection).Action(actionMethodName, typeof(T).Name.Remove(typeof(T).Name.IndexOf("Controller"))).ToString();         
        //string url = LinkBuilder.BuildUrlFromExpression<T>(helper.ViewContext.RequestContext, helper.RouteCollection, action);
        return string.Format("<img src=\"{0}\" width=\"{1}\" height=\"{2}\" alt=\"{3}\" />", url, width, height, alt);
    }
}

public class ImageResult : ActionResult
{
    public ImageResult() { }

    public Image Image { get; set; }
    public ImageFormat ImageFormat { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        // verify properties 
        if (Image == null)
        {
            throw new ArgumentNullException("Image");
        }
        if (ImageFormat == null)
        {
            throw new ArgumentNullException("ImageFormat");
        }

        // output 
        context.HttpContext.Response.Clear();
        context.HttpContext.Response.ContentType = GetMimeType(ImageFormat);
        Image.Save(context.HttpContext.Response.OutputStream, ImageFormat);
    }

    private static string GetMimeType(ImageFormat imageFormat)
    {
        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
        return codecs.First(codec => codec.FormatID == imageFormat.Guid).MimeType;
    }
}
public ActionResult Index()
    {
  return new ImageResult { Image = image, ImageFormat = ImageFormat.Jpeg };
    }
    <%=Html.Image<CapchaController>(c => c.Index(), 120, 30, "Current time")%>

Can I assume (bool)true == (int)1 for any C++ compiler?

Yes. The casts are redundant. In your expression:

true == 1

Integral promotion applies and the bool value will be promoted to an int and this promotion must yield 1.

Reference: 4.7 [conv.integral] / 4: If the source type is bool... true is converted to one.

Php - testing if a radio button is selected and get the value

my form:

<form method="post" action="radio.php">
   select your gender: 
    <input type="radio" name="radioGender" value="female">
    <input type="radio" name="radioGender" value="male">
    <input type="submit" name="btnSubmit" value="submit">
</form>

my php:

   <?php
      if (isset($_POST["btnSubmit"])) {
        if (isset($_POST["radioGender"])) {
        $answer = $_POST['radioGender'];
           if ($answer == "female") {
               echo "female";
           } else {
               echo "male";
           }    
        }else{
            echo "please select your gender";
             }
      }
  ?>

MYSQL query between two timestamps

Try:

SELECT * 
FROM eventList 
WHERE  `date` BETWEEN FROM_UNIXTIME(1364256001) AND FROM_UNIXTIME(1364342399)

Or

SELECT * 
FROM eventList WHERE  `date` 
BETWEEN '2013-03-26 00:00:01' AND '2013-03-26 23:59:59'

Runnable with a parameter?

I use the following class which implements the Runnable interface. With this class you can easily create new threads with arguments

public abstract class RunnableArg implements Runnable {

    Object[] m_args;

    public RunnableArg() {
    }

    public void run(Object... args) {
        setArgs(args);
        run();
    }

    public void setArgs(Object... args) {
        m_args = args;
    }

    public int getArgCount() {
        return m_args == null ? 0 : m_args.length;
    }

    public Object[] getArgs() {
        return m_args;
    }
}

How to slice a Pandas Data Frame by position?

I can see at least three options:

1.

df[:10]

2. Using head

df.head(10)

For negative values of n, this function returns all rows except the last n rows, equivalent to df[:-n] [Source].

3. Using iloc

df.iloc[:10]

Access iframe elements in JavaScript

Make sure your iframe is already loaded. Old but reliable way without jQuery:

<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>

<script>
function access() {
   var iframe = document.getElementById("iframe");
   var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
   console.log(innerDoc.body);
}
</script>

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar

You should not have any server-specific libraries in the /WEB-INF/lib. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib (and also in JRE/lib and JRE/lib/ext if you have placed any of them there).

A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.

How to stop mysqld

For MAMP

  1. Stop servers (but you may notice MySQL stays on)
  2. Remove or rename /Applications/MAMP/tmp/mysql/ which holds the mysql.pid and mysql.sock.lock files
  3. When you go back to Mamp, you'll see MySQL is now off. You can "Start Servers" again.

How do I convert a number to a letter in Java?

You can convert the input to base 26 (Hexavigesimal) and convert each "digit" back to base 10 individually and apply the ASCII mapping. Since A is mapped to 0, you will get results A, B, C,..., Y, Z, BA, BB, BC,...etc, which may or may not be desirable depending on your requirements for input values > 26, since it may be natural to think AA comes after Z.

public static String getCharForNumber(int i){

    // return null for bad input
    if(i < 0){
        return null;
    }

    // convert to base 26
    String s = Integer.toString(i, 26);

    char[] characters = s.toCharArray();

    String result = "";
    for(char c : characters){
        // convert the base 26 character back to a base 10 integer
        int x = Integer.parseInt(Character.valueOf(c).toString(), 26);
        // append the ASCII value to the result
        result += String.valueOf((char)(x + 'A'));          
    }

    return result;
}

Pandas Replace NaN with blank/empty string

df = df.fillna('')

or just

df.fillna('', inplace=True)

This will fill na's (e.g. NaN's) with ''.

If you want to fill a single column, you can use:

df.column1 = df.column1.fillna('')

One can use df['column1'] instead of df.column1.

Html.Textbox VS Html.TextboxFor

The TextBoxFor is a newer MVC input extension introduced in MVC2.

The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.

See this page.

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

Jenkins CI: How to trigger builds on SVN commit

I made a tool using Python with some bash to trigger a Jenkins build. Basically you have to collect these two values from post-commit when a commit hits the SVN server:

REPOS="$1"
REV="$2"

Then you use "svnlook dirs-changed $1 -r $2" to get the path which is has just committed. Then from that you can check which repository you want to build. Imagine you have hundred of thousand of projects. You can't check the whole repository, right?

You can check out my script from GitHub.

How do I use WPF bindings with RelativeSource?

I created a library to simplify the binding syntax of WPF including making it easier to use RelativeSource. Here are some examples. Before:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}
{Binding Path=Text, ElementName=MyTextBox}

After:

{BindTo PathToProperty}
{BindTo Ancestor.typeOfAncestor.PathToProperty}
{BindTo Template.PathToProperty}
{BindTo #MyTextBox.Text}

Here is an example of how method binding is simplified. Before:

// C# code
private ICommand _saveCommand;
public ICommand SaveCommand {
 get {
  if (_saveCommand == null) {
   _saveCommand = new RelayCommand(x => this.SaveObject());
  }
  return _saveCommand;
 }
}

private void SaveObject() {
 // do something
}

// XAML
{Binding Path=SaveCommand}

After:

// C# code
private void SaveObject() {
 // do something
}

// XAML
{BindTo SaveObject()}

You can find the library here: http://www.simplygoodcode.com/2012/08/simpler-wpf-binding.html

Note in the 'BEFORE' example that I use for method binding that code was already optimized by using RelayCommand which last I checked is not a native part of WPF. Without that the 'BEFORE' example would have been even longer.

PHP: Show yes/no confirmation dialog

I was also looking for a way to do it and figured it out like this using forms and the formaction attribute:

<input type="submit" name="del_something" formaction="<addresstothispage>" value="delete" />
<?php if(isset($_POST['del_something'])) print '<div>Are you sure? <input type="submit" name="del_confirm" value="yes!" formaction="action.php" />
<input type="submit" name="del_no" value="no!" formaction="<addresstothispage>" />';?>

action.php would check for isset($_POST['del_confirm']) and call the corresponding php script (for database actions or whatever). Voilà, no javascript needed. Using the formaction attribute, the delete button can be part of any form and still call a different form action (such as refer back to the same page, but with the button set).

If the button was pressed, the confirm buttons will show.

Dependency injection with Jersey 2.0

If you prefer to use Guice and you don't want to declare all the bindings, you can also try this adapter:

guice-bridge-jit-injector

Push local Git repo to new remote including all branches and tags

To push all your branches, use either (replace REMOTE with the name of the remote, for example "origin"):

git push REMOTE '*:*'
git push REMOTE --all

To push all your tags:

git push REMOTE --tags

Finally, I think you can do this all in one command with:

git push REMOTE --mirror

However, in addition --mirror, will also push your remotes, so this might not be exactly what you want.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

My version of luvlss's command:

Mac OSX 10.10.5

MySQL 5.6.27

Passenger 5.0.21

sudo ln -s /usr/local/mysql-5.6.27-osx10.8-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

If you're trying lots of different links, like I did, do some clean-up with:

sudo unlink /usr/lib/libmysqlclient.18.dylib

Spring 3 MVC accessing HttpRequest from controller

Spring MVC will give you the HttpRequest if you just add it to your controller method signature:

For instance:

/**
 * Generate a PDF report...
 */
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
        @PathVariable("objectId") Long objectId, 
        HttpServletRequest request, 
        HttpServletResponse response) {

    // ...
    // Here you can use the request and response objects like:
    // response.setContentType("application/pdf");
    // response.getOutputStream().write(...);

}

As you see, simply adding the HttpServletRequest and HttpServletResponse objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want the HttpSession object too.

EDIT: It seems that HttpServletRequest/Response are not working for some people under Spring 3. Try using Spring WebRequest/WebResponse objects as Eduardo Zola pointed out.

I strongly recommend you to have a look at the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods.

Convert NaN to 0 in javascript

Write your own method, and use it everywhere you want a number value:

function getNum(val) {
   if (isNaN(val)) {
     return 0;
   }
   return val;
}

Set scroll position

Also worth noting window.scrollBy(dx,dy) (ref)

How can I put a database under git (version control)?

I think X-Istence is on the right track, but there are a few more improvements you can make to this strategy. First, use:

$pg_dump --schema ... 

to dump the tables, sequences, etc and place this file under version control. You'll use this to separate the compatibility changes between your branches.

Next, perform a data dump for the set of tables that contain configuration required for your application to operate (should probably skip user data, etc), like form defaults and other data non-user modifiable data. You can do this selectively by using:

$pg_dump --table=.. <or> --exclude-table=..

This is a good idea because the repo can get really clunky when your database gets to 100Mb+ when doing a full data dump. A better idea is to back up a more minimal set of data that you require to test your app. If your default data is very large though, this may still cause problems though.

If you absolutely need to place full backups in the repo, consider doing it in a branch outside of your source tree. An external backup system with some reference to the matching svn rev is likely best for this though.

Also, I suggest using text format dumps over binary for revision purposes (for the schema at least) since these are easier to diff. You can always compress these to save space prior to checking in.

Finally, have a look at the postgres backup documentation if you haven't already. The way you're commenting on backing up 'the database' rather than a dump makes me wonder if you're thinking of file system based backups (see section 23.2 for caveats).

Can I invoke an instance method on a Ruby module without including it?

If you want to call these methods without including module in another class then you need to define them as module methods:

module UsefulThings
  def self.get_file; ...
  def self.delete_file; ...

  def self.format_text(x); ...
end

and then you can call them with

UsefulThings.format_text("xxx")

or

UsefulThings::format_text("xxx")

But anyway I would recommend that you put just related methods in one module or in one class. If you have problem that you want to include just one method from module then it sounds like a bad code smell and it is not good Ruby style to put unrelated methods together.

How to make the HTML link activated by clicking on the <li>?

You could try an "onclick" event inside the LI tag, and change the "location.href" as in javascript.

You could also try placing the li tags within the a tags, however this is probably not valid HTML.

How can I make window.showmodaldialog work in chrome 37?

The window.showModalDialog is deprecated (Intent to Remove: window.showModalDialog(), Removing showModalDialog from the Web platform). [...]The latest plan is to land the showModalDialog removal in Chromium 37. This means the feature will be gone in Opera 24 and Chrome 37, both of which should be released in September.[...]

How to cin to a vector

#include<iostream>
#include<vector>
#include<sstream>
using namespace std;

int main()
{
    vector<string> v;
    string line,t;
    getline(cin,line);
    istringstream iss(line);
    while(iss>>t)
        v.push_back(t);

    vector<string>::iterator it;
    for(it=v.begin();it!=v.end();it++)
        cout<<*it<<endl;
    return 0;
}

Difference between socket and websocket?

You'd have to use WebSockets (or some similar protocol module e.g. as supported by the Flash plugin) because a normal browser application simply can't open a pure TCP socket.

The Socket.IO module available for node.js can help a lot, but note that it is not a pure WebSocket module in its own right.

It's actually a more generic communications module that can run on top of various other network protocols, including WebSockets, and Flash sockets.

Hence if you want to use Socket.IO on the server end you must also use their client code and objects. You can't easily make raw WebSocket connections to a socket.io server as you'd have to emulate their message protocol.

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

Vue 2 - Mutating props vue-warn

This has to do with the fact that mutating a prop locally is considered an anti-pattern in Vue 2

What you should do now, in case you want to mutate a prop locally, is to declare a field in your data that uses the props value as its initial value and then mutate the copy:

Vue.component('task', {
    template: '#task-template',
    props: ['list'],
    data: function () {
        return {
            mutableList: JSON.parse(this.list);
        }
    }
});

You can read more about this on Vue.js official guide


Note 1: Please note that you should not use the same name for your prop and data, i.e.:

data: function () { return { list: JSON.parse(this.list) } // WRONG!!

Note 2: Since I feel there is some confusion regarding props and reactivity, I suggest you to have a look on this thread

Why do I need to explicitly push a new branch?

The actual reason is that, in a new repo (git init), there is no branch (no master, no branch at all, zero branches)

So when you are pushing for the first time to an empty upstream repo (generally a bare one), that upstream repo has no branch of the same name.

And:

In both cases, since the upstream empty repo has no branch:

  • there is no matching named branch yet
  • there is no upstream branch at all (with or without the same name! Tracking or not)

That means your local first push has no idea:

  • where to push
  • what to push (since it cannot find any upstream branch being either recorded as a remote tracking branch, and/or having the same name)

So you need at least to do a:

git push origin master

But if you do only that, you:

  • will create an upstream master branch on the upstream (now non-empty repo): good.
  • won't record that the local branch 'master' needs to be pushed to upstream (origin) 'master' (upstream branch): bad.

That is why it is recommended, for the first push, to do a:

git push -u origin master

That will record origin/master as a remote tracking branch, and will enable the next push to automatically push master to origin/master.

git checkout master
git push

And that will work too with push policies 'current' or 'upstream'.
In each case, after the initial git push -u origin master, a simple git push will be enough to continue pushing master to the right upstream branch.

Python: How to keep repeating a program until a specific input is obtained?

There are two ways to do this. First is like this:

while True:             # Loop continuously
    inp = raw_input()   # Get the input
    if inp == "":       # If it is a blank line...
        break           # ...break the loop

The second is like this:

inp = raw_input()       # Get the input
while inp != "":        # Loop until it is a blank line
    inp = raw_input()   # Get the input again

Note that if you are on Python 3.x, you will need to replace raw_input with input.

Create text file and fill it using bash

Assuming you mean UNIX shell commands, just run

echo >> file.txt

echo prints a newline, and the >> tells the shell to append that newline to the file, creating if it doesn't already exist.

In order to properly answer the question, though, I'd need to know what you would want to happen if the file already does exist. If you wanted to replace its current contents with the newline, for example, you would use

echo > file.txt

EDIT: and in response to Justin's comment, if you want to add the newline only if the file didn't already exist, you can do

test -e file.txt || echo > file.txt

At least that works in Bash, I'm not sure if it also does in other shells.

Check if DataRow exists by column name in c#?

You can use

try {
   user.OtherFriend = row["US_OTHERFRIEND"].ToString();
}
catch (Exception ex)
{
   // do something if you want 
}

jQuery validate: How to add a rule for regular expression validation?

This is working code.

function validateSignup()
{   
    $.validator.addMethod(
            "regex",
            function(value, element, regexp) 
            {
                if (regexp.constructor != RegExp)
                    regexp = new RegExp(regexp);
                else if (regexp.global)
                    regexp.lastIndex = 0;
                return this.optional(element) || regexp.test(value);
            },
            "Please check your input."
    );

    $('#signupForm').validate(
    {

        onkeyup : false,
        errorClass: "req_mess",
        ignore: ":hidden",
        validClass: "signup_valid_class",
        errorClass: "signup_error_class",

        rules:
        {

            email:
            {
                required: true,
                email: true,
                regex: /^[A-Za-z0-9_]+\@[A-Za-z0-9_]+\.[A-Za-z0-9_]+/,
            },

            userId:
            {
                required: true,
                minlength: 6,
                maxlength: 15,
                regex: /^[A-Za-z0-9_]{6,15}$/,
            },

            phoneNum:
            {
                required: true,
                regex: /^[+-]{1}[0-9]{1,3}\-[0-9]{10}$/,
            },

        },
        messages: 
        {
            email: 
            {
                required: 'You must enter a email',
                regex: 'Please enter a valid email without spacial chars, ie, [email protected]'
            },

            userId:
            {
                required: 'Alphanumeric, _, min:6, max:15',
                regex: "Please enter any alphaNumeric char of length between 6-15, ie, sbp_arun_2016"
            },

            phoneNum: 
            {
                required: "Please enter your phone number",
                regex: "e.g. +91-1234567890"    
            },

        },

        submitHandler: function (form)
        {
            return true;
        }
    });
}

How to change port for jenkins window service when 8080 is being used

Check in Jenkins.xml and update like below

<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8090</arguments>

stringstream, string, and char* conversion confusion

stringstream.str() returns a temporary string object that's destroyed at the end of the full expression. If you get a pointer to a C string from that (stringstream.str().c_str()), it will point to a string which is deleted where the statement ends. That's why your code prints garbage.

You could copy that temporary string object to some other string object and take the C string from that one:

const std::string tmp = stringstream.str();
const char* cstr = tmp.c_str();

Note that I made the temporary string const, because any changes to it might cause it to re-allocate and thus render cstr invalid. It is therefor safer to not to store the result of the call to str() at all and use cstr only until the end of the full expression:

use_c_str( stringstream.str().c_str() );

Of course, the latter might not be easy and copying might be too expensive. What you can do instead is to bind the temporary to a const reference. This will extend its lifetime to the lifetime of the reference:

{
  const std::string& tmp = stringstream.str();   
  const char* cstr = tmp.c_str();
}

IMO that's the best solution. Unfortunately it's not very well known.

Spring JPA and persistence.xml

I'm confused. You're injecting a PU into the service layer and not the persistence layer? I don't get that.

I inject the persistence layer into the service layer. The service layer contains business logic and demarcates transaction boundaries. It can include more than one DAO in a transaction.

I don't get the magic in your save() method either. How is the data saved?

In production I configure spring like this:

<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/ThePUname" />

along with the reference in web.xml

For unit testing I do this:

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource" p:persistence-xml-location="classpath*:META-INF/test-persistence.xml"
    p:persistence-unit-name="RealPUName" p:jpaDialect-ref="jpaDialect"
    p:jpaVendorAdapter-ref="jpaVendorAdapter" p:loadTimeWeaver-ref="weaver">
</bean>

jQuery and AJAX response header

The unfortunate truth about AJAX and the 302 redirect is that you can't get the headers from the return because the browser never gives them to the XHR. When a browser sees a 302 it automatically applies the redirect. In this case, you would see the header in firebug because the browser got it, but you would not see it in ajax, because the browser did not pass it. This is why the success and the error handlers never get called. Only the complete handler is called.

http://www.checkupdown.com/status/E302.html

The 302 response from the Web server should always include an alternative URL to which redirection should occur. If it does, a Web browser will immediately retry the alternative URL. So you never actually see a 302 error in a Web browser

Here are some stackoverflow posts on the subject. Some of the posts describe hacks to get around this issue.

How to manage a redirect request after a jQuery Ajax call

Catching 302 FOUND in JavaScript

HTTP redirect: 301 (permanent) vs. 302 (temporary)

How to convert AAR to JAR

Android Studio (version: 1.3.2) allows you to seamlessly access the .jar inside a .aar.

Bonus: it automatically decompiles the classes!

Simply follow these steps:

  1. File > New > New Module > Import .JAR/.AAR Package to import you .aar as a module

  2. Add the newly created module as a dependency to your main project (not sure if needed)

  3. Right click on "classes.jar" as shown in the capture below, and click "Show in explorer". Here is your .jar.

access .jar from .aar

Bat file to run a .exe at the command prompt

Just put that line in the bat file...

Alternatively you can even make a shortcut for svcutil.exe, then add the arguments in the 'target' window.

How to dynamically allocate memory space for a string and get that string from user?

char* load_string()
 {

char* string = (char*) malloc(sizeof(char));
*string = '\0';

int key;
int sizer = 2;

char sup[2] = {'\0'};

while( (key = getc(stdin)) != '\n')
{
    string = realloc(string,sizer * sizeof(char));
    sup[0] = (char) key;
    strcat(string,sup);
    sizer++

}
return string;

}

int main()
  {
char* str;
str = load_string();

return 0;
  }

Nodejs convert string into UTF-8

I'd recommend using the Buffer class:

var someEncodedString = Buffer.from('someString', 'utf-8');

This avoids any unnecessary dependencies that other answers require, since Buffer is included with node.js, and is already defined in the global scope.

Get list of JSON objects with Spring RestTemplate

In my case I preferred to extract a String then browse the context using JsonNode interface

    var response =  restTemplate.exchange("https://my-url", HttpMethod.GET, entity,  String.class);
    if (response.getStatusCode() == HttpStatus.OK) {
        var jsonString = response.getBody();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(jsonString);           
        
        System.out.println(actualObj);  
    }

or quickly

ObjectNode actualObj= restTemplate.getForObject("https://my-url", ObjectNode.class);

then read inner data with path expression i.e.

boolean b = actualObj.at("/0/states/0/no_data").asBoolean();

Disable F5 and browser refresh using JavaScript

You can directly use hotkey from rich faces if you are using JSF.

<rich:hotKey key="backspace" onkeydown="if (event.keyCode == 8) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="f5" onkeydown="if (event.keyCode == 116) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="ctrl+R" onkeydown="if (event.keyCode == 123) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="ctrl+f5" onkeydown="if (event.keyCode == 154) return false;" handler="return false;" disableInInput="true" /> 

Delete files older than 10 days using shell script in Unix

If you can afford working via the file data, you can do

find -mmin +14400 -delete

Is there a decorator to simply cache function return values?

functools.cache is released in Python 3.9 (docs):

from functools import cache

@cache
def factorial(n):
    return n * factorial(n-1) if n else 1

In previous versions, one of the early answers is still a valid solution using lru_cache as an ordinary cache without limit and lru feature. (docs)

If maxsize is set to None, the LRU feature is disabled and the cache can grow without bound.

Here is a prettier version of it:

cache = lru_cache(maxsize=None)

@cache
def func(param1):
   pass

How do I install boto?

While trying out the

pip install boto

command, I encounter the error

ImportError: No module named pkg_resources

To resolve this, issue another command to handle the setuptools using curl

curl https://bootstrap.pypa.io/ez_setup.py | python

After doing that, the following command will work perfectly.

pip install boto

Change border-bottom color using jquery?

$("selector").css("border-bottom-color", "#fff");
  1. construct your jQuery object which provides callable methods first. In this case, say you got an #mydiv, then $("#mydiv")
  2. call the .css() method provided by jQuery to modify specified object's css property values.

Content Type text/xml; charset=utf-8 was not supported by service

I've seen this behavior today when the

   <service name="A.B.C.D" behaviorConfiguration="returnFaults">
        <endpoint contract="A.B.C.ID" binding="basicHttpBinding" address=""/>
    </service>

was missing from the web.config. The service.svc file was there and got served. It took a while to realize that the problem was not in the binding configuration it self...

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

I usually use float: left; and add overflow: auto; to solve the collapsing parent problem (as to why this works, overflow: auto will expand the parent instead of adding scrollbars if you do not give it explicit height, overflow: hidden works as well). Most of the vertical alignment needs I had are for one-line of text in menu bars, which can be solved using line-height property. If I really need to vertical align a block element, I'd set an explicit height on the parent and the vertically aligned item, position absolute, top 50%, and negative margin.

The reason I don't use display: table-cell is the way it overflows when you have more items than the site's width can handle. table-cell will force the user to scroll horizontally, while floats will wrap the overflow menu, making it still usable without the need for horizontal scrolling.

The best thing about float: left and overflow: auto is that it works all the way back to IE6 without hacks, probably even further.

enter image description here

How do I sort a two-dimensional (rectangular) array in C#?

Here is an archived article from Jim Mischel at InformIt that handles sorting for both rectangular and jagged multi-dimensional arrays.

PyCharm import external library

updated on May 26-2018

If the external library is in a folder that is under the project then

File -> Settings -> Project -> Project structure -> select the folder and Mark as Sources!

If not, add content root, and do similar things.

Set min-width in HTML table's <td>

try this one:

_x000D_
_x000D_
<table style="border:1px solid">
<tr>
    <td style="min-width:50px">one</td>
    <td style="min-width:100px">two</td>
</tr>
</table>
_x000D_
_x000D_
_x000D_

Owl Carousel Won't Autoplay

Owl Carousel version matters a lot, as of now (2nd Aug 2020) the version is 2.3.4 and the right options for autoplay are:

$(".owl-carousel").owlCarousel({
    autoplay : true,
    autoplayTimeout: 3000,//Autoplay interval timeout.
    loop:true,//Infinity loop. Duplicate last and first items to get loop illusion.
    items:1 //The number of items you want to see on the screen.
});

Read more Owl configurations

How do I convert NSMutableArray to NSArray?

Objective-C

Below is way to convert NSMutableArray to NSArray:

//oldArray is having NSMutableArray data-type.
//Using Init with Array method.
NSArray *newArray1 = [[NSArray alloc]initWithArray:oldArray];

//Make copy of array
NSArray *newArray2 = [oldArray copy];

//Make mutablecopy of array
NSArray *newArray3 = [oldArray mutableCopy];

//Directly stored NSMutableArray to NSArray.
NSArray *newArray4 = oldArray;

Swift

In Swift 3.0 there is new data type Array. Declare Array using let keyword then it would become NSArray And if declare using var keyword then it's become NSMutableArray.

Sample code:

let newArray = oldArray as Array

'Conda' is not recognized as internal or external command

If you don't want to add Anaconda to env. path and you are using Windows try this:

  • Open cmd;
  • Type path to your folder instalation. It's something like: C:\Users\your_home folder\Anaconda3\Scripts
  • Test Anaconda, for exemple type conda --version.
  • Update Anaconda: conda update conda or conda update --all or conda update anaconda.

Update Spyder:

  • conda update qt pyqt
  • conda update spyder

How to get an IFrame to be responsive in iOS Safari?

This issue is also present on iOS Chrome.

I glanced through all the solutions above, most are very hacky.

If you don't need support for older browsers, just set the iframe width to 100vw;

iframe {
  max-width: 100%; /* Limits width to 100% of container */
  width: 100vw; /* Sets width to 100% of the viewport width while respecting the max-width above */
}

Note : Check support for viewport units https://caniuse.com/#feat=viewport-units

What is the .idea folder?

There is no problem in deleting this. It's not only the WebStorm IDE creating this file, but also PhpStorm and all other of JetBrains' IDEs.

It is safe to delete it but if your project is from GitLab or GitHub then you will see a warning.

Angular2 Material Dialog css, dialog size

Content in md-dialog-content is automatically scrollable.

You can manually set the size in the call to MdDialog.open

let dialogRef = dialog.open(MyComponent, {
  height: '400px',
  width: '600px',
});

Further documentation / examples for scrolling and sizing: https://material.angular.io/components/dialog/overview

Some colors should be determined by your theme. See here for theming docs: https://material.angular.io/guide/theming

If you want to override colors and such, use Elmer's technique of just adding the appropriate css.

Note that you must have the HTML 5 <!DOCTYPE html> on your page for the size of your dialog to fit the contents correctly ( https://github.com/angular/material2/issues/2351 )

How can I override inline styles with external CSS?

You can easily override inline style except inline !important style

so

<div style="font-size: 18px; color: red;">
    Hello World, How Can I Change The Color To Blue?
</div>

div {
   color: blue !important; 
   /* This will  Work */
}

but if you have

<div style="font-size: 18px; color: red !important;">
    Hello World, How Can I Change The Color To Blue?
</div>

div {
   color: blue !important; 
   /* This Isn't Working */
}

now it will be red only .. and you can not override it

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

In case someone lands here after making the same mistake I did:

  1. Switched to plugin="mysql_native_password" temporarily. Performed my tasks.
  2. Attempted to switch back to the "auth_socket" plugin, but incorrectly referenced it as plugin="auth_socket" which resulted in mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"
  3. Lacking a way to login to fix this mistake, I was forced to have to stop mysql and use mysql_safe to bypass authentication in order to switch to the appropriate plugin plugin="unix_socket"

Hopefully this saves someone some time if they receive the original poster's error message, but the true cause was flubbing the plugin name, not actually lacking the existence of the "auth_socket" plugin itself, which according to the MariaDB documentation:

In MariaDB 10.4.3 and later, the unix_socket authentication plugin is installed by default, and it is used by the 'root'@'localhost' user account by default.

How to declare or mark a Java method as deprecated?

Take a look at the @Deprecated annotation.

Assert a function/method was not called using Mock

With python >= 3.5 you can use mock_object.assert_not_called().

What is the Auto-Alignment Shortcut Key in Eclipse?

auto-alignment shortcut key Ctrl+Shift+F

to change the shortcut keys Goto Window > Preferences > Java > Editor > Save Actions

Sort a list by multiple attributes?

Here's one way: You basically re-write your sort function to take a list of sort functions, each sort function compares the attributes you want to test, on each sort test, you look and see if the cmp function returns a non-zero return if so break and send the return value. You call it by calling a Lambda of a function of a list of Lambdas.

Its advantage is that it does single pass through the data not a sort of a previous sort as other methods do. Another thing is that it sorts in place, whereas sorted seems to make a copy.

I used it to write a rank function, that ranks a list of classes where each object is in a group and has a score function, but you can add any list of attributes. Note the un-lambda-like, though hackish use of a lambda to call a setter. The rank part won't work for an array of lists, but the sort will.

#First, here's  a pure list version
my_sortLambdaLst = [lambda x,y:cmp(x[0], y[0]), lambda x,y:cmp(x[1], y[1])]
def multi_attribute_sort(x,y):
    r = 0
    for l in my_sortLambdaLst:
        r = l(x,y)
        if r!=0: return r #keep looping till you see a difference
    return r

Lst = [(4, 2.0), (4, 0.01), (4, 0.9), (4, 0.999),(4, 0.2), (1, 2.0), (1, 0.01), (1, 0.9), (1, 0.999), (1, 0.2) ]
Lst.sort(lambda x,y:multi_attribute_sort(x,y)) #The Lambda of the Lambda
for rec in Lst: print str(rec)

Here's a way to rank a list of objects

class probe:
    def __init__(self, group, score):
        self.group = group
        self.score = score
        self.rank =-1
    def set_rank(self, r):
        self.rank = r
    def __str__(self):
        return '\t'.join([str(self.group), str(self.score), str(self.rank)]) 


def RankLst(inLst, group_lambda= lambda x:x.group, sortLambdaLst = [lambda x,y:cmp(x.group, y.group), lambda x,y:cmp(x.score, y.score)], SetRank_Lambda = lambda x, rank:x.set_rank(rank)):
    #Inner function is the only way (I could think of) to pass the sortLambdaLst into a sort function
    def multi_attribute_sort(x,y):
        r = 0
        for l in sortLambdaLst:
            r = l(x,y)
            if r!=0: return r #keep looping till you see a difference
        return r

    inLst.sort(lambda x,y:multi_attribute_sort(x,y))
    #Now Rank your probes
    rank = 0
    last_group = group_lambda(inLst[0])
    for i in range(len(inLst)):
        rec = inLst[i]
        group = group_lambda(rec)
        if last_group == group: 
            rank+=1
        else:
            rank=1
            last_group = group
        SetRank_Lambda(inLst[i], rank) #This is pure evil!! The lambda purists are gnashing their teeth

Lst = [probe(4, 2.0), probe(4, 0.01), probe(4, 0.9), probe(4, 0.999), probe(4, 0.2), probe(1, 2.0), probe(1, 0.01), probe(1, 0.9), probe(1, 0.999), probe(1, 0.2) ]

RankLst(Lst, group_lambda= lambda x:x.group, sortLambdaLst = [lambda x,y:cmp(x.group, y.group), lambda x,y:cmp(x.score, y.score)], SetRank_Lambda = lambda x, rank:x.set_rank(rank))
print '\t'.join(['group', 'score', 'rank']) 
for r in Lst: print r

How to print a specific row of a pandas DataFrame?

To print a specific row we have couple of pandas method

  1. loc - It only get label i.e column name or Features
  2. iloc - Here i stands for integer, actually row number
  3. ix - It is a mix of label as well as integer

How to use for specific row

  1. loc
df.loc[row,column]

For first row and all column

df.loc[0,:]

For first row and some specific column

df.loc[0,'column_name']
  1. iloc

For first row and all column

df.iloc[0,:]

For first row and some specific column i.e first three cols

df.iloc[0,0:3]

How to hide the keyboard when I press return key in a UITextField?

In viewDidLoad declare:

[yourTextField setDelegate:self];

Then, include the override of the delegate method:

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

Overriding fields or properties in subclasses

I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.

abstract class Base 
{
 protected int myInt;
 protected abstract void setMyInt();
}

class Derived : Base 
{
 override protected void setMyInt()
 {
   myInt = 3;
 }
}

By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.

abstract class Father
{
    abstract public int MyInt { get; }
}

class Son : Father
{
    public override int MyInt
    {
        get { return 1; }
    }
}

.NET - How do I retrieve specific items out of a Dataset?

The DataSet object has a Tables array. If you know the table you want, it will have a Row array, each object of which has an ItemArray array. In your case the code would most likely be

int var1 = int.Parse(ds.Tables[0].Rows[0].ItemArray[4].ToString());

and so forth. This would give you the 4th item in the first row. You can also use Columns instead of ItemArray and specify the column name as a string instead of remembering it's index. That approach can be easier to keep up with if the table structure changes. So that would be

int var1 = int.Parse(ds.Tables[0].Rows[0]["MyColumnName"].ToString());

How to find MAC address of an Android device programmatically

See this post where I have submitted Utils.java example to provide pure-java implementations and works without WifiManager. Some android devices may not have wifi available or are using ethernet wiring.

Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6 

How to install mcrypt extension in xampp

The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.

What is a "thread" (really)?

In order to define a thread formally, we must first understand the boundaries of where a thread operates.

A computer program becomes a process when it is loaded from some store into the computer's memory and begins execution. A process can be executed by a processor or a set of processors. A process description in memory contains vital information such as the program counter which keeps track of the current position in the program (i.e. which instruction is currently being executed), registers, variable stores, file handles, signals, and so forth.

A thread is a sequence of such instructions within a program that can be executed independently of other code. The figure shows the concept: enter image description here

Threads are within the same process address space, thus, much of the information present in the memory description of the process can be shared across threads.

Some information cannot be replicated, such as the stack (stack pointer to a different memory area per thread), registers and thread-specific data. This information suffices to allow threads to be scheduled independently of the program's main thread and possibly one or more other threads within the program.

Explicit operating system support is required to run multithreaded programs. Fortunately, most modern operating systems support threads such as Linux (via NPTL), BSD variants, Mac OS X, Windows, Solaris, AIX, HP-UX, etc. Operating systems may use different mechanisms to implement multithreading support.

Here, graphically, the concept is represented.

Here, you can find more information about the topic. That was also my information-source.

Let me just add a sentence coming from Introduction to Embedded System by Edward Lee and Seshia:

Threads are imperative programs that run concurrently and share a memory space. They can access each others’ variables. Many practitioners in the field use the term “threads” more narrowly to refer to particular ways of constructing programs that share memory, [others] to broadly refer to any mechanism where imperative programs run concurrently and share memory. In this broad sense, threads exist in the form of interrupts on almost all microprocessors, even without any operating system at all (bare iron).

How do I hide the bullets on my list for the sidebar?

You have a selector ul on line 252 which is setting list-style: square outside none (a square bullet). You'll have to change it to list-style: none or just remove the line.

If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:

ul#groups-list.items-list { list-style: none }

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

Fast way to upgrade ruby to v2.4+

brew upgrade ruby

or

sudo gem update --system 

How do you get AngularJS to bind to the title attribute of an A tag?

The issue here is your version of AngularJS; ng-attr is not working due to the fact that it was introduced in version 1.1.4. I am unsure as to why title="{{product.shortDesc}}" isn't working for you, but I imagine it is for similar reasons (old Angular version). I tested this on 1.2.9 and it is working for me.

As for the other answers here, this is NOT among the few use cases for ng-attr! This is a simple double-curly-bracket situation:

<a title="{{product.shortDesc}}" ng-bind="product.shortDesc" />

Vertically centering Bootstrap modal window

Because most of the answer here didn't work, or only partially worked:

body.modal-open .modal[style]:not([style='display: none;']) {
    display: flex !important;
    height: 100%;
} 

body.modal-open .modal[style]:not([style='display: none;']) .modal-dialog {
    margin: auto;
}

You have to use the [style] selector to only apply the style on the modal that is currently active instead of all the modals. .in would have been great, but it appears to be added only after the transition is complete which is too late and makes for some really bad transitions. Fortunately it appears bootstrap always applies a style attribute on the modal just as it is starting to show so this is a bit hacky, but it works.

The :not([style='display: none;']) portion is a workaround to bootstrap not correctly removing the style attribute and instead setting the style display to none when you close the dialog.

CSS media query to target only iOS devices

Short answer No. CSS is not specific to brands.

Below are the articles to implement for iOS using media only.

https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

http://stephen.io/mediaqueries/

Infact you can use PHP, Javascript to detect the iOS browser and according to that you can call CSS file. For instance

http://www.kevinleary.net/php-detect-ios-mobile-users/

Difference between single and double quotes in Bash

Others explained very well and just want to give with simple examples.

Single quotes can be used around text to prevent the shell from interpreting any special characters. Dollar signs, spaces, ampersands, asterisks and other special characters are all ignored when enclosed within single quotes.

$ echo 'All sorts of things are ignored in single quotes, like $ & * ; |.' 

It will give this:

All sorts of things are ignored in single quotes, like $ & * ; |.

The only thing that cannot be put within single quotes is a single quote.

Double quotes act similarly to single quotes, except double quotes still allow the shell to interpret dollar signs, back quotes and backslashes. It is already known that backslashes prevent a single special character from being interpreted. This can be useful within double quotes if a dollar sign needs to be used as text instead of for a variable. It also allows double quotes to be escaped so they are not interpreted as the end of a quoted string.

$ echo "Here's how we can use single ' and double \" quotes within double quotes"

It will give this:

Here's how we can use single ' and double " quotes within double quotes

It may also be noticed that the apostrophe, which would otherwise be interpreted as the beginning of a quoted string, is ignored within double quotes. Variables, however, are interpreted and substituted with their values within double quotes.

$ echo "The current Oracle SID is $ORACLE_SID"

It will give this:

The current Oracle SID is test

Back quotes are wholly unlike single or double quotes. Instead of being used to prevent the interpretation of special characters, back quotes actually force the execution of the commands they enclose. After the enclosed commands are executed, their output is substituted in place of the back quotes in the original line. This will be clearer with an example.

$ today=`date '+%A, %B %d, %Y'`
$ echo $today 

It will give this:

Monday, September 28, 2015 

In Tensorflow, get the names of all the Tensors in a graph

tf.all_variables() can get you the information you want.

Also, this commit made today in TensorFlow Learn that provides a function get_variable_names in estimator that you can use to retrieve all variable names easily.

Split text file into smaller multiple text file using command line

Here's an example in C# (cause that's what I was searching for). I needed to split a 23 GB csv-file with around 175 million lines to be able to look at the files. I split it into files of one million rows each. This code did it in about 5 minutes on my machine:

var list = new List<string>();
var fileSuffix = 0;

using (var file = File.OpenRead(@"D:\Temp\file.csv"))
using (var reader = new StreamReader(file))
{
    while (!reader.EndOfStream)
    {
        list.Add(reader.ReadLine());

        if (list.Count >= 1000000)
        {
            File.WriteAllLines(@"D:\Temp\split" + (++fileSuffix) + ".csv", list);
            list = new List<string>();
        }
    }
}

File.WriteAllLines(@"D:\Temp\split" + (++fileSuffix) + ".csv", list);

How to cherry pick from 1 branch to another

When you cherry-pick, it creates a new commit with a new SHA. If you do:

git cherry-pick -x <sha>

then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.

Initial bytes incorrect after Java AES/CBC decryption

Online Editor Runnable version:-

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
//import org.apache.commons.codec.binary.Base64;
import java.util.Base64;

public class Encryptor {
    public static String encrypt(String key, String initVector, String value) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));

            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());

            //System.out.println("encrypted string: "
              //      + Base64.encodeBase64String(encrypted));

            //return Base64.encodeBase64String(encrypted);
            String s = new String(Base64.getEncoder().encode(encrypted));
            return s;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String key, String initVector, String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));

            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String key = "Bar12345Bar12345"; // 128 bit key
        String initVector = "RandomInitVector"; // 16 bytes IV

        System.out.println(encrypt(key, initVector, "Hello World"));
        System.out.println(decrypt(key, initVector, encrypt(key, initVector, "Hello World")));
    }
}

What is the easiest way to remove the first character from a string?

We can use slice to do this:

val = "abc"
 => "abc" 
val.slice!(0)
 => "a" 
val
 => "bc" 

Using slice! we can delete any character by specifying its index.

Textarea that can do syntax highlighting on the fly?

It's not possible to achieve the required level of control over presentation in a regular textarea.

If you're OK with that, try CodeMirror or Ace or Monaco (used in MS VSCode).

From the duplicate thread - an obligatory wikipedia link: Comparison of JavaScript-based source code editors

How to start Activity in adapter?

public class MyAdapter extends Adapter {
     private Context context;      


     public MyAdapter(Context context) {
          this.context = context;         
     }


     public View getView(...){  
         View v;  
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                  Intent intent= new Intent(context, ToActivity.class); 
                   intent.putExtra("your_extra","your_class_value");
                 context.startActivity(intent);
             }
         });
     }
}

"RangeError: Maximum call stack size exceeded" Why?

The answer with for is correct, but if you really want to use functional style avoiding for statement - you can use the following instead of your expression:

Array.from(Array(1000000), () => Math.random());

The Array.from() method creates a new Array instance from an array-like or iterable object. The second argument of this method is a map function to call on every element of the array.

Following the same idea you can rewrite it using ES2015 Spread operator:

[...Array(1000000)].map(() => Math.random())

In both examples you can get an index of the iteration if you need, for example:

[...Array(1000000)].map((_, i) => i + Math.random())