Programs & Examples On #Jfreereport

JFreeReport is now Pentaho Classic Reporting Engine, an embeddable Java reporting library.

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

There is no way to identify the charset of a string that is completely accurate. There are ways to try to guess the charset. One of these ways, and probably/currently the best in PHP, is mb_detect_encoding(). This will scan your string and look for occurrences of stuff unique to certain charsets. Depending on your string, there may not be such distinguishable occurrences.

Take the ISO-8859-1 charset vs ISO-8859-15 ( http://en.wikipedia.org/wiki/ISO/IEC_8859-15#Changes_from_ISO-8859-1 )

There's only a handful of different characters, and to make it worse, they're represented by the same bytes. There is no way to detect, being given a string without knowing it's encoding, whether byte 0xA4 is supposed to signify ¤ or € in your string, so there is no way to know it's exact charset.

(Note: you could add a human factor, or an even more advanced scanning technique (e.g. what Oroboros102 suggests), to try to figure out based upon the surrounding context, if the character should be ¤ or €, though this seems like a bridge too far)

There are more distinguishable differences between e.g. UTF-8 and ISO-8859-1, so it's still worth trying to figure it out when you're unsure, though you can and should never rely on it being correct.

Interesting read: http://kore-nordmann.de/blog/php_charset_encoding_FAQ.html#how-do-i-determine-the-charset-encoding-of-a-string

There are other ways of ensuring the correct charset though. Concerning forms, try to enforce UTF-8 as much as possible (check out snowman to make sure yout submission will be UTF-8 in every browser: http://intertwingly.net/blog/2010/07/29/Rails-and-Snowmen ) That being done, at least you're can be sure that every text submitted through your forms is utf_8. Concerning uploaded files, try running the unix 'file -i' command on it through e.g. exec() (if possible on your server) to aid the detection (using the document's BOM.) Concerning scraping data, you could read the HTTP headers, that usually specify the charset. When parsing XML files, see if the XML meta-data contain a charset definition.

Rather than trying to automagically guess the charset, you should first try to ensure a certain charset yourself where possible, or trying to grab a definition from the source you're getting it from (if applicable) before resorting to detection.

How to remove the hash from window.location (URL) with JavaScript without page refresh?

Here is another solution to change the location using href and clear the hash without scrolling.

The magic solution is explained here. Specs here.

const hash = window.location.hash;
history.scrollRestoration = 'manual';
window.location.href = hash;    
history.pushState('', document.title, window.location.pathname);

NOTE: The proposed API is now part of WhatWG HTML Living Standard

How to populate a sub-document in mongoose after creating it?

@user1417684 and @chris-foster are right!

excerpt from working code (without error handling):

var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel    = mongoose.model('items', ItemSchema);

var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {

  var new_item = new ItemModel(new_item);
  new_item.subitem = new_sub_item._id;
  new_item.save(function (error, new_item) {
    // so this is a valid way to populate via the Model
    // as documented in comments above (here @stack overflow):
    ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
      callback(new_item.toObject());
    });
    // or populate directly on the result object
    new_item.populate('subitem', function(error, new_item) {
      callback(new_item.toObject());
    });
  });

});

How to enable CORS in flask

If you want to enable CORS for all routes, then just install flask_cors extension (pip3 install -U flask_cors) and wrap app like this: CORS(app).

That is enough to do it (I tested this with a POST request to upload an image, and it worked for me):

from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # This will enable CORS for all routes

Important note: if there is an error in your route, let us say you try to print a variable that does not exist, you will get a CORS error related message which, in fact, has nothing to do with CORS.

How to disable horizontal scrolling of UIScrollView?

since iOS7 use

self.automaticallyAdjustsScrollViewInsets = NO;

//and create you page scroller with 3 pages

    self.pageView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.pageView setContentSize:CGSizeMake(self.view.frame.size.width*3, self.view.frame.size.height)];
    [self.pageView setShowsVerticalScrollIndicator:NO];
    [self.pageView setPagingEnabled:YES];
    [self.view addSubview:self.pageView];

SQLiteDatabase.query method

Where clause and args work together to form the WHERE statement of the SQL query. So say you looking to express

WHERE Column1 = 'value1' AND Column2 = 'value2'

Then your whereClause and whereArgs will be as follows

String whereClause = "Column1 =? AND Column2 =?";
String[] whereArgs = new String[]{"value1", "value2"};

If you want to select all table columns, i believe a null string passed to tableColumns will suffice.

Understanding The Modulus Operator %

As you say, the % sign is used to take the modulus (division remainder).

In w3schools' JavaScript Arithmetic page we can read in the Remainder section what I think to be a great explanation

In arithmetic, the division of two integers produces a quotient and a remainder.

In mathematics, the result of a modulo operation is the remainder of an arithmetic division.

So, in your specific case, when you try to divide 7 bananas into a group of 5 bananas, you're able to create 1 group of 5 (quotient) and you'll be left with 2 bananas (remainder).

If 5 bananas into a group of 7, you won't be able to and so you're left with again the 5 bananas (remainder).

Get width/height of SVG element

SVG has properties width and height. They return an object SVGAnimatedLength with two properties: animVal and baseVal. This interface is used for animation, where baseVal is the value before animation. From what I can see, this method returns consistent values in both Chrome and Firefox, so I think it can also be used to get calculated size of SVG.

How do I check to see if my array includes an object?

If you want to check if an object is within in array by checking an attribute on the object, you can use any? and pass a block that evaluates to true or false:

unless @suggested_horses.any? {|h| h.id == horse.id }
  @suggested_horses << horse
end

How to trigger an event after using event.preventDefault()

The approach I use is this:

$('a').on('click', function(event){
    if (yourCondition === true) { //Put here the condition you want
        event.preventDefault(); // Here triggering stops
        // Here you can put code relevant when event stops;
        return;
    }
    // Here your event works as expected and continue triggering
    // Here you can put code you want before triggering
});

Java Round up Any Number

Math.ceil() is the correct function to call. I'm guessing a is an int, which would make a / 100 perform integer arithmetic. Try Math.ceil(a / 100.0) instead.

int a = 142;
System.out.println(a / 100);
System.out.println(Math.ceil(a / 100));
System.out.println(a / 100.0);
System.out.println(Math.ceil(a / 100.0));
System.out.println((int) Math.ceil(a / 100.0));

Outputs:

1
1.0
1.42
2.0
2

See http://ideone.com/yhT0l

Where can I find the .apk file on my device, when I download any app and install?

All user installed apks are located in /data/app/, but you can only access this if you are rooted(afaik, you can try without root and if it doesn't work, rooting isn't hard. I suggest you search xda-developers for rooting instructions)

Use Root explorer or ES File Explorer to access /data/app/ (you have to keep going "up" until you reach the root directory /, kind of like C: in windows, before you can see the data directory(folder)). In ES file explorer you must also tick a checkbox in settings to allow going up to the root directory.

When you are in there you will see all your applications apks, though they might be named strangely. Just copy the wanted .apk and paste in the sd card, after that you can copy it to your computer and when you want to install it just open the .apk in a file manager (be sure to have install from unknown sources enabled in android settings). Even if you only want to send over bluetooth I would recommend copying it to the SD first.

PS Note that paid apps probably won't work being copied this way, since they usually check their licence online. PPS Installing an app this way may not link it with google play(you won't see it in my apps and it won't get updates).

Finding the average of a list

If you wanted to get more than just the mean (aka average) you might check out scipy stats

from scipy import stats
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(stats.describe(l))

# DescribeResult(nobs=9, minmax=(2, 78), mean=20.11111111111111, 
# variance=572.3611111111111, skewness=1.7791785448425341, 
# kurtosis=1.9422716419666397)

Java, Simplified check if int array contains int

Here is Java 8 solution

public static boolean contains(final int[] arr, final int key) {
    return Arrays.stream(arr).anyMatch(i -> i == key);
}

Minimum Hardware requirements for Android development

I use an i5 processor with 4Gb RAM. It works very well. I feel this is the minimum configuration required to run both eclipse and android avd simultaneously. Just an old processor with high RAM is not sufficient.

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Perform the following steps:

  1. Start the Registry Editor by typing regedit in the Run window.
  2. Select the following key in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC.
  3. In the Security menu, click Permissions.
  4. Grant Full Permission to the account which is being used for making connections.
  5. Quit the Registry Editor.

Distinct() with lambda?

You can use InlineComparer

public class InlineComparer<T> : IEqualityComparer<T>
{
    //private readonly Func<T, T, bool> equalsMethod;
    //private readonly Func<T, int> getHashCodeMethod;
    public Func<T, T, bool> EqualsMethod { get; private set; }
    public Func<T, int> GetHashCodeMethod { get; private set; }

    public InlineComparer(Func<T, T, bool> equals, Func<T, int> hashCode)
    {
        if (equals == null) throw new ArgumentNullException("equals", "Equals parameter is required for all InlineComparer instances");
        EqualsMethod = equals;
        GetHashCodeMethod = hashCode;
    }

    public bool Equals(T x, T y)
    {
        return EqualsMethod(x, y);
    }

    public int GetHashCode(T obj)
    {
        if (GetHashCodeMethod == null) return obj.GetHashCode();
        return GetHashCodeMethod(obj);
    }
}

Usage sample:

  var comparer = new InlineComparer<DetalleLog>((i1, i2) => i1.PeticionEV == i2.PeticionEV && i1.Etiqueta == i2.Etiqueta, i => i.PeticionEV.GetHashCode() + i.Etiqueta.GetHashCode());
  var peticionesEV = listaLogs.Distinct(comparer).ToList();
  Assert.IsNotNull(peticionesEV);
  Assert.AreNotEqual(0, peticionesEV.Count);

Source: https://stackoverflow.com/a/5969691/206730
Using IEqualityComparer for Union
Can I specify my explicit type comparator inline?

Run local python script on remote server

Although this question isn't quite new and an answer was already chosen, I would like to share another nice approach.

Using the paramiko library - a pure python implementation of SSH2 - your python script can connect to a remote host via SSH, copy itself (!) to that host and then execute that copy on the remote host. Stdin, stdout and stderr of the remote process will be available on your local running script. So this solution is pretty much independent of an IDE.

On my local machine, I run the script with a cmd-line parameter 'deploy', which triggers the remote execution. Without such a parameter, the actual code intended for the remote host is run.

import sys
import os

def main():
    print os.name

if __name__ == '__main__':
    try:
        if sys.argv[1] == 'deploy':
            import paramiko

            # Connect to remote host
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect('remote_hostname_or_IP', username='john', password='secret')

            # Setup sftp connection and transmit this script
            sftp = client.open_sftp()
            sftp.put(__file__, '/tmp/myscript.py')
            sftp.close()

            # Run the transmitted script remotely without args and show its output.
            # SSHClient.exec_command() returns the tuple (stdin,stdout,stderr)
            stdout = client.exec_command('python /tmp/myscript.py')[1]
            for line in stdout:
                # Process each line in the remote output
                print line

            client.close()
            sys.exit(0)
    except IndexError:
        pass

    # No cmd-line args provided, run script normally
    main()

Exception handling is left out to simplify this example. In projects with multiple script files you will probably have to put all those files (and other dependencies) on the remote host.

How to set limits for axes in ggplot2 R plots?

Quick note: if you're also using coord_flip() to flip the x and the y axis, you won't be able to set range limits using coord_cartesian() because those two functions are exclusive (see here).

Fortunately, this is an easy fix; set your limits within coord_flip() like so:

p + coord_flip(ylim = c(3,5), xlim = c(100, 400))

This just alters the visible range (i.e. doesn't remove data points).

Remove style attribute from HTML tags

Here you go:

<?php

$html = '<p style="border: 1px solid red;">Test</p>';
echo preg_replace('/<p style="(.+?)">(.+?)<\/p>/i', "<p>$2</p>", $html);

?>

By the way, as pointed out by others, regex are not suggested for this.

Deprecated meaning?

Deprecated in general means "don't use it".
A deprecated function may or may not work, but it is not guaranteed to work.

Python argparse command line flags without arguments

Here's a quick way to do it, won't require anything besides sys.. though functionality is limited:

flag = "--flag" in sys.argv[1:]

[1:] is in case if the full file name is --flag

How to fix UITableView separator on iOS 7?

UITableView has a property separatorInset. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen.

[tableView setSeparatorInset:UIEdgeInsetsZero];

Note: If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:

if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [tableView setSeparatorInset:UIEdgeInsetsZero];
}

How to programmatically set style attribute in a view

Depending on what style attributes you'd like to change you may be able to use the Paris library:

Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
Paris.style(view).apply(R.style.YourStyle);

Many attributes like background, padding, textSize, textColor, etc. are supported.

Disclaimer: I authored the library.

How to upload a project to Github

Follow these steps to upload your project to Github

1) git init

2) git add .

3) git commit -m "Add all my files"

4) git remote add origin https://github.com/yourusername/your-repo-name.git

Upload of project from scratch require git pull origin master.

5) git pull origin master

6) git push origin master

If any problem occurs in pushing use git push --force origin master

Giving graphs a subtitle in matplotlib

The solution that worked for me is:

  • use suptitle() for the actual title
  • use title() for the subtitle and adjust it using the optional parameter y:
    import matplotlib.pyplot as plt
    """
            some code here
    """
    plt.title('My subtitle',fontsize=16)
    plt.suptitle('My title',fontsize=24, y=1)
    plt.show()

There can be some nasty overlap between the two pieces of text. You can fix this by fiddling with the value of y until you get it right.

How to pass multiple values to single parameter in stored procedure

I spent time finding a proper way. This may be useful for others.

Create a UDF and refer in the query -

http://www.geekzilla.co.uk/view5C09B52C-4600-4B66-9DD7-DCE840D64CBD.htm

How do I create 7-Zip archives with .NET?

Install the NuGet package called SevenZipSharp.Interop

Then:

SevenZipBase.SetLibraryPath(@".\x86\7z.dll");
var compressor = new SevenZip.SevenZipCompressor();
var filesToCompress = Directory.GetFiles(@"D:\data\");
compressor.CompressFiles(@"C:\archive\abc.7z", filesToCompress);

Spring MVC Controller redirect using URL parameters instead of in response

This problem is caused (as others have stated) by model attributes being persisted into the query string - this is usually undesirable and is at risk of creating security holes as well as ridiculous query strings. My usual solution is to never use Strings for redirects in Spring MVC, instead use a RedirectView which can be configured not to expose model attributes (see: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/RedirectView.html)

RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes)

So I tend to have a util method which does a 'safe redirect' like:

public static RedirectView safeRedirect(String url) {
    RedirectView rv = new RedirectView(url);
    rv.setExposeModelAttributes(false);
    return rv;
}

The other option is to use bean configuration XML:

<bean id="myBean" class="org.springframework.web.servlet.view.RedirectView">
   <property name="exposeModelAttributes" value="false" />
   <property name="url" value="/myRedirect"/>
</bean>

Again, you could abstract this into its own class to avoid repetition (e.g. SafeRedirectView).


A note about 'clearing the model' - this is not the same as 'not exposing the model' in all circumstances. One site I worked on had a lot of filters which added things to the model, this meant that clearing the model before redirecting would not prevent a long query string. I would also suggest that 'not exposing model attributes' is a more semantic approach than 'clearing the model before redirecting'.

How to dynamically create generic C# object using reflection?

Check out this article and this simple example. Quick translation of same to your classes ...

var d1 = typeof(Task<>);
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

Per your edit: For that case, you can do this ...

var d1 = Type.GetType("GenericTest.TaskA`1"); // GenericTest was my namespace, add yours
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

To see where I came up with backtick1 for the name of the generic class, see this article.

Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:

Type type = typeof(IReadOnlyDictionary<,>);

Does Git Add have a verbose switch

I was debugging an issue with git and needed some very verbose output to figure out what was going wrong. I ended up setting the GIT_TRACE environment variable:

export GIT_TRACE=1
git add *.txt

You can also use these on the same line:

GIT_TRACE=1 git add *.txt

Output:

14:06:05.508517 git.c:415               trace: built-in: git add test.txt test2.txt
14:06:05.544890 git.c:415               trace: built-in: git config --get oh-my-zsh.hide-dirty

How to print time in format: 2009-08-10 18:17:54.811

The above answers do not fully answer the question (specifically the millisec part). My solution to this is to use gettimeofday before strftime. Note the care to avoid rounding millisec to "1000". This is based on Hamid Nazari's answer.

#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>

int main() {
  char buffer[26];
  int millisec;
  struct tm* tm_info;
  struct timeval tv;

  gettimeofday(&tv, NULL);

  millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
  if (millisec>=1000) { // Allow for rounding up to nearest second
    millisec -=1000;
    tv.tv_sec++;
  }

  tm_info = localtime(&tv.tv_sec);

  strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
  printf("%s.%03d\n", buffer, millisec);

  return 0;
}

exception in initializer error in java when using Netbeans

Retrofit have recently updated to 2.7.1 version. After that Android 4.x clients have crashed. See https://stackoverflow.com/a/60071876/2914140.

Downgrade Retrofit to 2.6.4.

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

Recently I had this same problem on windows 10 - after installing Hyper-V & other windows features like:

Windows Projected File System, Windows Sandbox, Windows Subsystem for Linux, Work Folders Client,

And it stopped working for me;(

  1. Step uninstall Hyper-V -check if ti stared to work for you - no in my case
  2. Step uninstall other windows features mentioned above! - I worked for me;) enter image description here

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

a late answer, but I think this one works as required in the question :)

this one uses z-index and position absolute, and avoid the issue that the container element width doesn't grow in transition.

You can tweak the text's margin and padding to suit your needs, and "+" can be changed to font awesome icons if needed.

_x000D_
_x000D_
body {
  font-size: 16px;
}

.container {
  height: 2.5rem;
  position: relative;
  width: auto;
  display: inline-flex;
  align-items: center;
}

.add {
  font-size: 1.5rem;
  color: #fff;
  cursor: pointer;
  font-size: 1.5rem;
  background: #2794A5;
  border-radius: 20px;
  height: 100%;
  width: 2.5rem;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  z-index: 2;
}

.text {
  white-space: nowrap;
  position: relative;
  z-index: 1;
  height: 100%;
  width: 0;
  color: #fff;
  overflow: hidden;
  transition: 0.3s all ease;
  background: #2794A5;
  height: 100%;
  display: flex;
  align-items: center;
  border-top-right-radius: 20px;
  border-bottom-right-radius: 20px;
  margin-left: 20px;
  padding-left: 20px;
  cursor: pointer;
}

.container:hover .text {
  width: 100%;
  padding-right: 20px;
}
_x000D_
<div class="container">
  <span class="add">+</span>
  <span class="text">Add new client</span>
</div>
_x000D_
_x000D_
_x000D_

How to get the id of the element clicked using jQuery

I wanted to share how you can use this to change a attribute of the button, because it took me some time to figure it out...

For example in order to change it's background to yellow:

$("#"+String(this.id)).css("background-color","yellow");

Capture close event on Bootstrap Modal

Though is answered in another stack overflow question Bind a function to Twitter Bootstrap Modal Close but for visual feel here is more detailed answer.

Source: http://getbootstrap.com/javascript/#modals-events

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

I know this is old, but Google sent me here so I guess others will come too like me.

The answer on 2018 is the selected one here: Pycharm: "unresolved reference" error on the IDE when opening a working project

Just be aware that you can only add one Content Root but you can add several Source Folders. No need to touch __init__.py files.

Using OR operator in a jquery if statement

The logical OR '||' automatically short circuits if it meets a true condition once.

false || false || true || false = true, stops at second condition.

On the other hand, the logical AND '&&' automatically short circuits if it meets a false condition once.

false && true && true && true = false, stops at first condition.

Multiple select in Visual Studio?

Multi cursor edit is natively supported in Visual Studio starting from version 2017 Update 8. The following is an extract of the documentation:

  • Ctrl + Alt + click : Add a secondary caret
  • Ctrl + Alt + double-click : Add a secondary word selection
  • Ctrl + Alt + click + drag : Add a secondary selection
  • Shift + Alt + . : Add the next matching text as a selection
  • Shift + Alt + ; : Add all matching text as selections
  • Shift + Alt + , : Remove last selected occurrence
  • Shift + Alt + / : Skip next matching occurrence
  • Alt + click : Add a box selection
  • Esc or click : Clear all selections

Some of those commands are also available in the Edit menu:

Multiple Carets Menu

Two decimal places using printf( )

For %d part refer to this How does this program work? and for decimal places use %.2f

Strip out HTML and Special Characters

Strip out tags, leave only alphanumeric characters and space:

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($des));

Edit: all credit to DaveRandom for the perfect solution...

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags(html_entity_decode($des)));

How to put spacing between floating divs?

I found a solution, which at least helps in my situation, it probably is not suitable for other situations:

I give all my green child divs a complete margin:

margin: 10px;

And for the surrounding yellow parent div i set a negative margin:

margin: -10px;

I also had to remove any explicit width or height setting for the yellow parent div, otherwise it did not work.

This way, in absolute terms, the child divs are correctly aligned, although the parent yellow div obviously is set off, which in my case is OK, because it will not be visible.

RESTful Authentication via Spring

Why don't you start using OAuth with JSON WebTokens

http://projects.spring.io/spring-security-oauth/

OAuth2 is an standardized authorization protocol/framework. As per Official OAuth2 Specification:

You can find more info here

Passing an array of data as an input parameter to an Oracle procedure

This is one way to do it:

SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
  2  /

Type created

SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
  2  BEGIN
  3    FOR i IN 1..t_in.count LOOP
  4      dbms_output.put_line(t_in(i));
  5    END LOOP;
  6  END;
  7  /

Procedure created

SQL> DECLARE
  2    v_t MyType;
  3  BEGIN
  4    v_t := MyType();
  5    v_t.EXTEND(10);
  6    v_t(1) := 'this is a test';
  7    v_t(2) := 'A second test line';
  8    testing(v_t);
  9  END;
 10  /

this is a test
A second test line

To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:

SQL> CREATE OR REPLACE PACKAGE p IS
  2    TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
  3  
  4    PROCEDURE pp (inp p_type);
  5  END p;
  6  /

Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
  2    PROCEDURE pp (inp p_type) IS
  3    BEGIN
  4      FOR i IN 1..inp.count LOOP
  5        dbms_output.put_line(inp(i));
  6      END LOOP;
  7    END pp;
  8  END p;
  9  /

Package body created
SQL> DECLARE
  2    v_t p.p_type;
  3  BEGIN
  4    v_t(1) := 'this is a test of p';
  5    v_t(2) := 'A second test line for p';
  6    p.pp(v_t);
  7  END;
  8  /

this is a test of p
A second test line for p

PL/SQL procedure successfully completed

SQL> 

This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.

Java - using System.getProperty("user.dir") to get the home directory

Program to get the current working directory=user.dir

public class CurrentDirectoryExample {

    public static void main(String args[]) {

        String current = System.getProperty("user.dir");
        System.out.println("Current working directory in Java : " + current);
    }
}

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

I recommend: Twisted (http://twistedmatrix.com)

an event-driven networking engine written in Python and licensed under the open source MIT license.

It's cross-platform and was preinstalled on OS X 10.5 to 10.12. Amongst other things you can start up a simple web server in the current directory with:

twistd -no web --path=.

Details

Explanation of Options (see twistd --help for more):

-n, --nodaemon       don't daemonize, don't use default umask of 0077
-o, --no_save        do not save state on shutdown

"web" is a Command that runs a simple web server on top of the Twisted async engine. It also accepts command line options (after the "web" command - see twistd web --help for more):

  --path=             <path> is either a specific file or a directory to be
                      set as the root of the web server. Use this if you
                      have a directory full of HTML, cgi, php3, epy, or rpy
                      files or any other files that you want to be served up
                      raw.

There are also a bunch of other commands such as:

conch            A Conch SSH service.
dns              A domain name server.
ftp              An FTP server.
inetd            An inetd(8) replacement.
mail             An email service
... etc

Installation

Ubuntu

sudo apt-get install python-twisted-web (or python-twisted for the full engine)

Mac OS-X (comes preinstalled on 10.5 - 10.12, or is available in MacPorts and through Pip)

sudo port install py-twisted

Windows

installer available for download at http://twistedmatrix.com/

HTTPS

Twisted can also utilise security certificates to encrypt the connection. Use this with your existing --path and --port (for plain HTTP) options.

twistd -no web -c cert.pem -k privkey.pem --https=4433

Render HTML string as real HTML in a React component

dangerouslySetInnerHTML

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

Why are there no ++ and --? operators in Python?

as i understood it so you won't think the value in memory is changed. in c when you do x++ the value of x in memory changes. but in python all numbers are immutable hence the address that x pointed as still has x not x+1. when you write x++ you would think that x change what really happens is that x refrence is changed to a location in memory where x+1 is stored or recreate this location if doe's not exists.

CSS - center two images in css side by side

You can't have two elements with the same ID.

Aside from that, you are defining them as block elemnts, meaning (in layman's terms) that they are being forced to appear on their own line.

Instead, try something like this:

<div class="link"><a href="..."><img src="..."... /></a></div>
<div class="link"><a href="..."><img src="..."... /></a></div>

CSS:

.link {
    width: 50%;
    float: left;
    text-align: center;
}

JavaScript: Parsing a string Boolean value?

I shamelessly converted Apache Common's toBoolean to JavaScript:

JSFiddle: https://jsfiddle.net/m2efvxLm/1/

Code:

_x000D_
_x000D_
function toBoolean(str) {_x000D_
  if (str == "true") {_x000D_
    return true;_x000D_
  }_x000D_
  if (!str) {_x000D_
    return false;_x000D_
  }_x000D_
  switch (str.length) {_x000D_
    case 1: {_x000D_
      var ch0 = str.charAt(0);_x000D_
      if (ch0 == 'y' || ch0 == 'Y' ||_x000D_
          ch0 == 't' || ch0 == 'T' ||_x000D_
          ch0 == '1') {_x000D_
        return true;_x000D_
      }_x000D_
      if (ch0 == 'n' || ch0 == 'N' ||_x000D_
          ch0 == 'f' || ch0 == 'F' ||_x000D_
          ch0 == '0') {_x000D_
        return false;_x000D_
      }_x000D_
      break;_x000D_
    }_x000D_
    case 2: {_x000D_
      var ch0 = str.charAt(0);_x000D_
      var ch1 = str.charAt(1);_x000D_
      if ((ch0 == 'o' || ch0 == 'O') &&_x000D_
          (ch1 == 'n' || ch1 == 'N') ) {_x000D_
        return true;_x000D_
      }_x000D_
      if ((ch0 == 'n' || ch0 == 'N') &&_x000D_
          (ch1 == 'o' || ch1 == 'O') ) {_x000D_
        return false;_x000D_
      }_x000D_
      break;_x000D_
    }_x000D_
    case 3: {_x000D_
      var ch0 = str.charAt(0);_x000D_
      var ch1 = str.charAt(1);_x000D_
      var ch2 = str.charAt(2);_x000D_
      if ((ch0 == 'y' || ch0 == 'Y') &&_x000D_
          (ch1 == 'e' || ch1 == 'E') &&_x000D_
          (ch2 == 's' || ch2 == 'S') ) {_x000D_
        return true;_x000D_
      }_x000D_
      if ((ch0 == 'o' || ch0 == 'O') &&_x000D_
          (ch1 == 'f' || ch1 == 'F') &&_x000D_
          (ch2 == 'f' || ch2 == 'F') ) {_x000D_
        return false;_x000D_
      }_x000D_
      break;_x000D_
    }_x000D_
    case 4: {_x000D_
      var ch0 = str.charAt(0);_x000D_
      var ch1 = str.charAt(1);_x000D_
      var ch2 = str.charAt(2);_x000D_
      var ch3 = str.charAt(3);_x000D_
      if ((ch0 == 't' || ch0 == 'T') &&_x000D_
          (ch1 == 'r' || ch1 == 'R') &&_x000D_
          (ch2 == 'u' || ch2 == 'U') &&_x000D_
          (ch3 == 'e' || ch3 == 'E') ) {_x000D_
        return true;_x000D_
      }_x000D_
      break;_x000D_
    }_x000D_
    case 5: {_x000D_
      var ch0 = str.charAt(0);_x000D_
      var ch1 = str.charAt(1);_x000D_
      var ch2 = str.charAt(2);_x000D_
      var ch3 = str.charAt(3);_x000D_
      var ch4 = str.charAt(4);_x000D_
      if ((ch0 == 'f' || ch0 == 'F') &&_x000D_
          (ch1 == 'a' || ch1 == 'A') &&_x000D_
          (ch2 == 'l' || ch2 == 'L') &&_x000D_
          (ch3 == 's' || ch3 == 'S') &&_x000D_
          (ch4 == 'e' || ch4 == 'E') ) {_x000D_
        return false;_x000D_
      }_x000D_
      break;_x000D_
    }_x000D_
    default:_x000D_
      break;_x000D_
  }_x000D_
_x000D_
  return false;_x000D_
}_x000D_
console.log(toBoolean("yEs")); // true_x000D_
console.log(toBoolean("yES")); // true_x000D_
console.log(toBoolean("no")); // false_x000D_
console.log(toBoolean("NO")); // false_x000D_
console.log(toBoolean("on")); // true_x000D_
console.log(toBoolean("oFf")); // false
_x000D_
Inspect this element, and view the console output.
_x000D_
_x000D_
_x000D_

Android Split string

String s = "String="

String[] str = s.split("="); //now str[0] is "hello" and str[1] is "goodmorning,2,1"

add this string

Easy way to build Android UI?

This is an old question, that unfortunately even several years on doesn't have a good solution. I've just ported an app from iOS (Obj C) to Android. The biggest problem was not the back end code (for many/most folks, if you can code in Obj C you can code in Java) but porting the native interfaces. What Todd said above, UI layout is still a complete pain. In my experience, the fastest wat to develop a reliable UI that supports multiple formats etc is in good 'ol HTML.

java.nio.file.Path for a classpath resource

Guessing that what you want to do, is call Files.lines(...) on a resource that comes from the classpath - possibly from within a jar.

Since Oracle convoluted the notion of when a Path is a Path by not making getResource return a usable path if it resides in a jar file, what you need to do is something like this:

Stream<String> stream = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("/filename.txt"))).lines();

join on multiple columns

Agree no matches in your example.
If you mean both columns on either then need a query like this or need to re-examine the data design.

    Select TableA.Col1, TableA.Col2, TableB.Val
    FROM TableA
    INNER JOIN TableB
          ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2 
          OR TableA.Col2 = TableB.Col1 OR TableA.Col1 = TableB.Col2

What does 'var that = this;' mean in JavaScript?

This is a hack to make inner functions (functions defined inside other functions) work more like they should. In javascript when you define one function inside another this automatically gets set to the global scope. This can be confusing because you expect this to have the same value as in the outer function.

var car = {};
car.starter = {};

car.start = function(){
    var that = this;

    // you can access car.starter inside this method with 'this'
    this.starter.active = false;

    var activateStarter = function(){
        // 'this' now points to the global scope
        // 'this.starter' is undefined, so we use 'that' instead.
        that.starter.active = true;

        // you could also use car.starter, but using 'that' gives
        // us more consistency and flexibility
    };

    activateStarter();

};

This is specifically a problem when you create a function as a method of an object (like car.start in the example) then create a function inside that method (like activateStarter). In the top level method this points to the object it is a method of (in this case, car) but in the inner function this now points to the global scope. This is a pain.

Creating a variable to use by convention in both scopes is a solution for this very general problem with javascript (though it's useful in jquery functions, too). This is why the very general sounding name that is used. It's an easily recognizable convention for overcoming a shortcoming in the language.

Like El Ronnoco hints at Douglas Crockford thinks this is a good idea.

Convert pandas DataFrame into list of lists

you can do it like this:

map(list, df.values)

How do you create optional arguments in php?

Much like the manual, use an equals (=) sign in your definition of the parameters:

function dosomething($var1, $var2, $var3 = 'somevalue'){
    // Rest of function here...
}

How to find the highest value of a column in a data frame in R?

Try this solution:

Oz<-subset(data, data$Month==5,select=Ozone) # select ozone  value in the month of                 
                                             #May (i.e. Month = 5)
summary(T)                                   #gives caracteristics of table( contains 1 column of Ozone) including max, min ...

PHP, pass array through POST

You could put it in the session:

session_start();
$_SESSION['array_name'] = $array_name;

Or if you want to send it via a form you can serialize it:

<input type='hidden' name='input_name' value="<?php echo htmlentities(serialize($array_name)); ?>" />

$passed_array = unserialize($_POST['input_name']);

Note that to work with serialized arrays, you need to use POST as the form's transmission method, as GET has a size limit somewhere around 1024 characters.

I'd use sessions wherever possible.

How to use "svn export" command to get a single file from the repository?

You don't have to do this locally either. You can do it through a remote repository, for example:

svn export http://<repo>/process/test.txt /path/to/code/

How do I delete an item or object from an array using ng-click?

Building on the accepted answer, this will work with ngRepeat, filterand handle expections better:

Controller:

vm.remove = function(item, array) {
  var index = array.indexOf(item);
  if(index>=0)
    array.splice(index, 1);
}

View:

ng-click="vm.remove(item,$scope.bdays)"

Spring MVC - How to return simple String as JSON in Rest Controller

This issue has driven me mad: Spring is such a potent tool and yet, such a simple thing as writing an output String as JSON seems impossible without ugly hacks.

My solution (in Kotlin) that I find the least intrusive and most transparent is to use a controller advice and check whether the request went to a particular set of endpoints (REST API typically since we most often want to return ALL answers from here as JSON and not make specializations in the frontend based on whether the returned data is a plain string ("Don't do JSON deserialization!") or something else ("Do JSON deserialization!")). The positive aspect of this is that the controller remains the same and without hacks.

The supports method makes sure that all requests that were handled by the StringHttpMessageConverter(e.g. the converter that handles the output of all controllers that return plain strings) are processed and in the beforeBodyWrite method, we control in which cases we want to interrupt and convert the output to JSON (and modify headers accordingly).

@ControllerAdvice
class StringToJsonAdvice(val ob: ObjectMapper) : ResponseBodyAdvice<Any?> {
    
    override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean =
        converterType === StringHttpMessageConverter::class.java

    override fun beforeBodyWrite(
        body: Any?,
        returnType: MethodParameter,
        selectedContentType: MediaType,
        selectedConverterType: Class<out HttpMessageConverter<*>>,
        request: ServerHttpRequest,
        response: ServerHttpResponse
    ): Any? {
        return if (request.uri.path.contains("api")) {
            response.getHeaders().contentType = MediaType.APPLICATION_JSON
            ob.writeValueAsString(body)
        } else body
    }
}

I hope in the future that we will get a simple annotation in which we can override which HttpMessageConverter should be used for the output.

Changing default encoding of Python?

If you get this error when you try to pipe/redirect output of your script

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

Just export PYTHONIOENCODING in console and then run your code.

export PYTHONIOENCODING=utf8

Hidden Columns in jqGrid

To hide the grid column

jQuery("#validGrid").jqGrid('hideCol',str);

Most efficient way to remove special characters from string

public string RemoveSpecial(string evalstr)
{
StringBuilder finalstr = new StringBuilder();
            foreach(char c in evalstr){
            int charassci = Convert.ToInt16(c);
            if (!(charassci >= 33 && charassci <= 47))// special char ???
             finalstr.append(c);
            }
return finalstr.ToString();
}

Setting dropdownlist selecteditem programmatically

ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;

Python regular expressions return true/false

Ignacio Vazquez-Abrams is correct. But to elaborate, re.match() will return either None, which evaluates to False, or a match object, which will always be True as he said. Only if you want information about the part(s) that matched your regular expression do you need to check out the contents of the match object.

Using Linq select list inside list

After my previous answer disaster, I'm going to try something else.

List<Model> usrList  = 
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));

Defining a variable with or without export

To illustrate what the other answers are saying:

$ foo="Hello, World"
$ echo $foo
Hello, World
$ bar="Goodbye"
$ export foo
$ bash
bash-3.2$ echo $foo
Hello, World
bash-3.2$ echo $bar

bash-3.2$ 

What does %>% function mean in R?

My understanding after reading the link offered by G.Grothendieck is that %>% is an operator that pipes functions. This helps readability and productivity as it's easier to follow the flow of multiple functions through these pipes than going backwards when multiple function are nested.

Display/Print one column from a DataFrame of Series in Pandas

Not sure what you are really after but if you want to print exactly what you have you can do:

Option 1

print(df['Item'].to_csv(index=False))

Sweet
Candy
Chocolate

Option 2

for v in df['Item']:
    print(v)

Sweet
Candy
Chocolate

List of all special characters that need to be escaped in a regex

The Pattern.quote(String s) sort of does what you want. However it leaves a little left to be desired; it doesn't actually escape the individual characters, just wraps the string with \Q...\E.

There is not a method that does exactly what you are looking for, but the good news is that it is actually fairly simple to escape all of the special characters in a Java regular expression:

regex.replaceAll("[\\W]", "\\\\$0")

Why does this work? Well, the documentation for Pattern specifically says that its permissible to escape non-alphabetic characters that don't necessarily have to be escaped:

It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.

For example, ; is not a special character in a regular expression. However, if you escape it, Pattern will still interpret \; as ;. Here are a few more examples:

  • > becomes \> which is equivalent to >
  • [ becomes \[ which is the escaped form of [
  • 8 is still 8.
  • \) becomes \\\) which is the escaped forms of \ and ( concatenated.

Note: The key is is the definition of "non-alphabetic", which in the documentation really means "non-word" characters, or characters outside the character set [a-zA-Z_0-9].

ORACLE IIF Statement

Oracle doesn't provide such IIF Function. Instead, try using one of the following alternatives:

DECODE Function:

SELECT DECODE(EMP_ID, 1, 'True', 'False') from Employee

CASE Function:

SELECT CASE WHEN EMP_ID = 1 THEN 'True' ELSE 'False' END from Employee

Getting a machine's external IP address with Python

I tried most of the other answers on this question here and came to find that most of the services used were defunct except one.

Here is a script that should do the trick and download only a minimal amount of information:

#!/usr/bin/env python

import urllib
import re

def get_external_ip():
    site = urllib.urlopen("http://checkip.dyndns.org/").read()
    grab = re.findall('([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)', site)
    address = grab[0]
    return address

if __name__ == '__main__':
  print( get_external_ip() )

yii2 redirect in controller action does not work?

You can redirect by this method also:

return Yii::$app->response->redirect(['user/index', 'id' => 10]);

If you want to send the Header information immediately use with send().This method adds a Location header to the current response.

return Yii::$app->response->redirect(['user/index', 'id' => 10])->send();

If you want the complete URL then use like Url::to(['user/index', 'id' => 302]) with the header of use yii\helpers\Url;.

For more information check Here. Hope this will help someone.

How to use a wildcard in the classpath to add multiple jars?

If you mean that you have an environment variable named CLASSPATH, I'd say that's your mistake. I don't have such a thing on any machine with which I develop Java. CLASSPATH is so tied to a particular project that it's impossible to have a single, correct CLASSPATH that works for all.

I set CLASSPATH for each project using either an IDE or Ant. I do a lot of web development, so each WAR and EAR uses their own CLASSPATH.

It's ignored by IDEs and app servers. Why do you have it? I'd recommend deleting it.

Java TreeMap Comparator

The comparator should be only for the key, not for the whole entry. It sorts the entries based on the keys.

You should change it to something as follows

SortedMap<String, Double> myMap = 
    new TreeMap<String, Double>(new Comparator<String>()
    {
        public int compare(String o1, String o2)
        {
            return o1.compareTo(o2);
        } 
});

Update

You can do something as follows (create a list of entries in the map and sort the list base on value, but note this not going to sort the map itself) -

List<Map.Entry<String, Double>> entryList = new ArrayList<Map.Entry<String, Double>>(myMap.entrySet());
    Collections.sort(entryList, new Comparator<Map.Entry<String, Double>>() {
        @Override
        public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
    });

Excel - extracting data based on another list

Have you tried Advanced Filter? Using your short list as the 'Criteria' and long list as the 'List Range'. Use the options: 'Filter in Place' and 'Unique Values'.

You should be presented with the list of unique values that only appear in your short list.

Alternatively, you can paste your Unique list to another location (on the same sheet), if you prefer. Choose the option 'Copy to another Location' and in the 'Copy to' box enter the cell reference (say F1) where you want the Unique list.

Note: this will work with the two columns (name/ID) too, if you select the two columns as both 'Criteria' and 'List Range'.

Does Java support structs?

Java doesn't have an analog to C++'s structs, but you can use classes with all public members.

Excel Formula: Count cells where value is date

Here is how I was able to trick Excel to count expired certifications in a list. I didn't have a set date, or date range, just current date. "TODAY()" doesn't work in these for Excel 2013. It sees it as text or condition, not the date value. So these previous didn't work for me. So the word problem/scenario: How many people are expired in this list?

Use: =IFERROR(D5-TODAY(),0) Where D5 is the date to be interrogated.

Then use: =IF(J5>=1,1,0) Where J5 is the cell where the first equation is producing either a positive or negative number. This set, I have hidden on the side of the visible sheet, then I just sum the total for the number of unexpired members.

Unable to establish SSL connection, how do I fix my SSL cert?

This problem happened for me only in special cases, when I called website from some internet providers,

I've configured only ip v4 in VirtualHost configuration of apache, but some of router use ip v6, and when I added ip v6 to apache config the problem solved.

Generate SQL Create Scripts for existing tables with Query

"Easiest way is to use the built-in feature of SQL Management Studio" but... I have resolved it with a function and a couple of procedures. For example, to obtain the create table for a table named 'table_name', you have to execute just the procedure called sp_ppinScriptTabla:

Exec sp_ppinScriptTabla 'table_name'

Here is the tsql script code:

Use Master
GO

Create Function sp_ppinTipoLongitud
(
    @xtype int,
    @length int,
    @isnullable int
)
Returns Varchar(512)
As 
Begin
    -- Función que a partir de un tipo de datos y una logitud, devuelve el texto del tipo.
    -- Por ejemplo: para xtype=varchar y length=10 devolverá "varchar(10)"
    Declare @ret varchar(512)
    Set @ret = ''

    Select @ret = t.name +
    Case When name in ('varchar', 'nvarchar', 'char', 'nchar') Then '(' + Convert(varchar, @length) + ')' Else '' End + ' ' +
    Case @isnullable When 1 Then 'NULL' Else 'NOT NULL' End
    From systypes t 
    Where t.xtype = @xtype

    Return @ret
End
GO

Create Procedure sp_ppinScriptLlavesForaneas
(
    @vchTabla sysname,
    @vchResultado varchar(8000) output
)
AS 
Begin

    DECLARE @tmpFK table(
        TablaF sysname,
        TablaR sysname,
        ColF sysname,
        ColR sysname,
        FKName sysname)

    -- obtengo las llaves foraneas en @vchForeign
    Declare @vchForeign varchar(8000), @FKName sysname, @vchColumnasF varchar(4000), @vchColumnasR varchar(4000), @ColF sysname, @ColR sysname
    Declare @vchTemp varchar(1000), @TablaR sysname

    Insert into @tmpFK
    Select TablaF.name AS TablaF, TablaR.name AS TablaR, ColF.name AS ColF, ColR.name AS ColR, ofk.name AS FKName
    From sysforeignkeys fk, sysobjects ofk, sysobjects TablaF, sysobjects TablaR, 
    syscolumns ColF, syscolumns ColR
    Where TablaF.name = @vchTabla
    And ofk.id = fk.constid
    And TablaF.id = fk.fkeyid
    And TablaR.id = fk.rkeyid
    And ColF.id = TablaF.id And ColF.colid = fk.fkey
    And ColR.id = TablaR.id And ColR.colid = fk.rkey
    order by FKName

    Set @vchForeign = ''
    While Exists ( Select * From @tmpFK )
    Begin
        Select Top 1 @FKName = FKName From @tmpFK
        Set @vchColumnasF = ''
        Set @vchColumnasR = ''
        While Exists ( Select * From @tmpFK Where FKName = @FKName )
        Begin
            Select Top 1 @ColF = ColF, @ColR = ColR, @TablaR = TablaR From @tmpFK Where FKName = @FKName
            Delete From @tmpFK Where ColF = @ColF And ColR = @ColR And TablaR = @TablaR And FKName = @FKName
            Set @vchColumnasF = @vchColumnasF + @ColF + ', '
            Set @vchColumnasR = @vchColumnasR + @ColR + ', '
        End

        Set @vchColumnasF = LEFT(@vchColumnasF, LEN(@vchColumnasF) - 1)
        Set @vchColumnasR = LEFT(@vchColumnasR, LEN(@vchColumnasR) - 1)
        Set @vchTemp = 'Constraint ' + @FKName + ' Foreign Key (' + @vchColumnasF + ') '
        Set @vchTemp = @vchTemp + 'References ' + @TablaR + ' (' + @vchColumnasR + ')'
        Set @vchForeign = @vchForeign + char(9) + @vchTemp + ',' + char(13) 
    End

    Select @vchResultado = Case When Len(@vchForeign) >=2 Then Left(@vchForeign, Len(@vchForeign) - 2) Else @vchForeign End
End
GO

Create Procedure sp_ppinScriptTabla
(
    @vchTabla sysname
)
AS

Set nocount on

-- Obtengo las foreign keys
Declare @foreign varchar(8000)
Exec sp_ppinScriptLlavesForaneas @vchTabla, @foreign output

-- SELECT que devuelve el script de Create Table de la tabla
Select 'Create ' + 
Case o.xtype When 'U' Then 'Table' When 'P' Then 'Procedure' Else '??' End + ' ' +
@vchTabla + char(13) + '('
From sysobjects o
Where o.name = @vchTabla
Union all
-- Campos + identitys + DEFAULTS
select char(9) + c.name + ' ' +                                 -- Nombre
dbo.sp_ppinTipoLongitud(t.xtype, c.length, c.isnullable) +          -- Tipo(longitud)
Case When c.colstat & 1 = 1                                     -- Identity (si aplica)
    Then ' Identity(' + convert(varchar, ident_seed(@vchTabla)) + ',' + Convert(varchar, ident_incr(@vchTabla)) + ')' 
    Else '' 
End + 
Case When not od.name is null                                   -- Defaults (si aplica)
    Then ' Constraint ' + od.name + ' Default ' + replace(replace(cd.text, '((', '('), '))', ')')
    Else ''
End + ', '
from sysobjects o, syscolumns c
LEFT OUTER JOIN sysobjects od On od.id = c.cdefault LEFT OUTER join syscomments cd On cd.id = od.id, 
systypes t
where o.id = object_id(@vchTabla)
and o.id = c.id
and c.xtype = t.xtype
Union all
-- Primary Keys y Unique keys
select char(9) + 'Constraint ' + o.name + ' ' +
Case o.xtype When 'PK' Then 'Primary Key' Else 'Unique' End + ' ' +
dbo.sp_ppinCamposIndice (db_name(), @vchTabla, i.indid) + ', '
from sysobjects o, sysindexes i
where o.parent_obj = object_id(@vchTabla)
and o.xtype in ('PK','UQ')
and i.id = o.parent_obj
and o.name = i.name
Union all
-- Check constraints
select char(9) + 'Constraint ' + o.name + ' Check ' + c.text + ', '
from sysobjects o, syscomments c
where o.parent_obj = object_id(@vchTabla)
and o.xtype in ('C')
and o.id = c.id
Union all
-- Foreign keys
Select @foreign
Union all
Select ')'

Set nocount off
GO

Why is access to the path denied?

I was facing this error because

Sometimes when I Combine the path with File Name and FileName = ""

It become Path Directory not a file which is a problem as mentioned above

so you must check for FileName like this

if(itemUri!="")
        File.Delete(Path.Combine(RemoteDirectoryPath, itemUri));

C# ASP.NET MVC Return to Previous Page

I am assuming (please correct me if I am wrong) that you want to re-display the edit page if the edit fails and to do this you are using a redirect.

You may have more luck by just returning the view again rather than trying to redirect the user, this way you will be able to use the ModelState to output any errors too.

Edit:

Updated based on feedback. You can place the previous URL in the viewModel, add it to a hidden field then use it again in the action that saves the edits.

For instance:

public ActionResult Index()
{
    return View();
}

[HttpGet] // This isn't required
public ActionResult Edit(int id)
{
   // load object and return in view
   ViewModel viewModel = Load(id);

   // get the previous url and store it with view model
   viewModel.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;

   return View(viewModel);
}

[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
   // Attempt to save the posted object if it works, return index if not return the Edit view again

   bool success = Save(viewModel);
   if (success)
   {
       return Redirect(viewModel.PreviousUrl);
   }
   else
   {
      ModelState.AddModelError("There was an error");
      return View(viewModel);
   }
}

The BeginForm method for your view doesn't need to use this return URL either, you should be able to get away with:

@model ViewModel

@using (Html.BeginForm())
{
    ...
    <input type="hidden" name="PreviousUrl" value="@Model.PreviousUrl" />
}

Going back to your form action posting to an incorrect URL, this is because you are passing a URL as the 'id' parameter, so the routing automatically formats your URL with the return path.

This won't work because your form will be posting to an controller action that won't know how to save the edits. You need to post to your save action first, then handle the redirect within it.

How to obfuscate Python code effectively?

Maybe you should look into using something simple like a truecrypt volume for source code storage as that seems to be a concern of yours. You can create an encrypted file on a usb key or just encrypt the whole volume (provided the code will fit) so you can simply take the key with you at the end of the day.

To compile, you could then use something like PyInstaller or py2exe in order to create a stand-alone executable. If you really wanted to go the extra mile, look into a packer or compression utility in order to add more obfuscation. If none of these are an option, you could at least compile the script into bytecode so it isn't immediately readable. Keep in mind that these methods will merely slow someone trying to debug or decompile your program.

How to do SELECT MAX in Django?

Django also has the 'latest(field_name = None)' function that finds the latest (max. value) entry. It not only works with date fields but also with strings and integers.

You can give the field name when calling that function:

max_rated_entry = YourModel.objects.latest('rating')
return max_rated_entry.details

Or you can already give that field name in your models meta data:

from django.db import models

class YourModel(models.Model):
    #your class definition
    class Meta:
        get_latest_by = 'rating'

Now you can call 'latest()' without any parameters:

max_rated_entry = YourModel.objects.latest()
return max_rated_entry.details

JQuery show and hide div on mouse click (animate)

<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $(".click-header").click(function(){
            $(this).next(".hidden-content").slideToggle("slow");
            $(this).toggleClass("expanded-header");
        });
    });
</script>
.demo-container {
    margin:0 auto;
    width: 600px;
    text-align:center;
}
.click-header {
    padding: 5px 10px 5px 60px;
    background: url(images/arrow-down.png) no-repeat 50% 50%;
}
.expanded-header {
    padding: 5px 10px 5px 60px;
    background: url(images/arrow-up.png) no-repeat 50% 50%;
}
.hidden-content {
    display:none;
    border: 1px solid #d7dbd8;
    padding: 20px;
    text-align: center;
}
<div class="demo-container">
    <div class="click-header">&nbsp;</div>
    <div class="hidden-content">Lorem Ipsum.</div>
</div>

JavaScript REST client Library

You don't really need a specific client, it's fairly simple with most libraries. For example in jQuery you can just call the generic $.ajax function with the type of request you want to make:

$.ajax({
    url: 'http://example.com/',
    type: 'PUT',
    data: 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray()
    success: function() { alert('PUT completed'); }
});

You can replace PUT with GET/POST/DELETE or whatever.

Python: import module from another directory at the same level in project hierarchy

From Python 2.5 onwards, you can use

from ..Modules import LDAPManager

The leading period takes you "up" a level in your heirarchy.

See the Python docs on intra-package references for imports.

form serialize javascript (no framework)

I could be crazy but I'm finding these answers seriously bloated. Here's my solution

function serialiseForm(form) {
  var input = form.getElementsByTagName("input");
  var formData = {};
  for (var i = 0; i < input.length; i++) {
    formData[input[i].name] = input[i].value;
  }
  return formData = JSON.stringify(formData);
}

How do I get the AM/PM value from a DateTime?

Here is an easier way you can write the time format (hh:mm:ss tt) and display them separately if you wish.

string time = DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00") + DateTime.Now.ToString(" tt");

or just simply:

 DateTime.Now.ToString("hh:mm:ss tt")

Change private static final field using Java reflection

Even in spite of being final a field can be modified outside of static initializer and (at least JVM HotSpot) will execute the bytecode perfectly fine.

The problem is that Java compiler does not allow this, but this can be easily bypassed using objectweb.asm. Here is p?e?r?f?e?c?t?l?y? ?v?a?l?i?d? ?c?l?a?s?s?f?i?l?e? an invalid classfile from the JVMS specification standpoint, but it passes bytecode verification and then is successfully loaded and initialized under JVM HotSpot OpenJDK12:

ClassWriter cw = new ClassWriter(0);
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "Cl", null, "java/lang/Object", null);
{
    FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, "fld", "I", null, null);
    fv.visitEnd();
}
{
    // public void setFinalField1() { //... }
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "setFinalField1", "()V", null, null);
    mv.visitMaxs(2, 1);
    mv.visitInsn(Opcodes.ICONST_5);
    mv.visitFieldInsn(Opcodes.PUTSTATIC, "Cl", "fld", "I");
    mv.visitInsn(Opcodes.RETURN);
    mv.visitEnd();
}
{
    // public void setFinalField2() { //... }
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "setFinalField2", "()V", null, null);
    mv.visitMaxs(2, 1);
    mv.visitInsn(Opcodes.ICONST_2);
    mv.visitFieldInsn(Opcodes.PUTSTATIC, "Cl", "fld", "I");
    mv.visitInsn(Opcodes.RETURN);
    mv.visitEnd();
}
cw.visitEnd();

In Java, the class looks roughly speaking as follows:

public class Cl{
    private static final int fld;

    public static void setFinalField1(){
        fld = 5;
    }

    public static void setFinalField2(){
        fld = 2;
    }
}

which cannot be compiled with javac, but can be loaded and executed by JVM.

JVM HotSpot has special treatment of such classes in the sense that it prevents such "constants" from participating in constant folding. This check is done on the bytecode rewriting phase of class initialization:

// Check if any final field of the class given as parameter is modified
// outside of initializer methods of the class. Fields that are modified
// are marked with a flag. For marked fields, the compilers do not perform
// constant folding (as the field can be changed after initialization).
//
// The check is performed after verification and only if verification has
// succeeded. Therefore, the class is guaranteed to be well-formed.
InstanceKlass* klass = method->method_holder();
u2 bc_index = Bytes::get_Java_u2(bcp + prefix_length + 1);
constantPoolHandle cp(method->constants());
Symbol* ref_class_name = cp->klass_name_at(cp->klass_ref_index_at(bc_index));
if (klass->name() == ref_class_name) {
   Symbol* field_name = cp->name_ref_at(bc_index);
   Symbol* field_sig = cp->signature_ref_at(bc_index);

   fieldDescriptor fd;
   if (klass->find_field(field_name, field_sig, &fd) != NULL) {
      if (fd.access_flags().is_final()) {
         if (fd.access_flags().is_static()) {
            if (!method->is_static_initializer()) {
               fd.set_has_initialized_final_update(true);
            }
          } else {
            if (!method->is_object_initializer()) {
              fd.set_has_initialized_final_update(true);
            }
          }
        }
      }
    }
}

The only restriction that JVM HotSpot checks is that the final field should not be modified outside of the class that the final field is declared at.

Make header and footer files to be included in multiple html pages

Save the HTML you want to include in an .html file:

Content.html

<a href="howto_google_maps.asp">Google Maps</a><br>
<a href="howto_css_animate_buttons.asp">Animated Buttons</a><br>
<a href="howto_css_modals.asp">Modal Boxes</a><br>
<a href="howto_js_animate.asp">Animations</a><br>
<a href="howto_js_progressbar.asp">Progress Bars</a><br>
<a href="howto_css_dropdown.asp">Hover Dropdowns</a><br>
<a href="howto_js_dropdown.asp">Click Dropdowns</a><br>
<a href="howto_css_table_responsive.asp">Responsive Tables</a><br>

Include the HTML

Including HTML is done by using a w3-include-html attribute:

Example

    <div w3-include-html="content.html"></div>

Add the JavaScript

HTML includes are done by JavaScript.

    <script>
    function includeHTML() {
      var z, i, elmnt, file, xhttp;
      /*loop through a collection of all HTML elements:*/
      z = document.getElementsByTagName("*");
      for (i = 0; i < z.length; i++) {
        elmnt = z[i];
        /*search for elements with a certain atrribute:*/
        file = elmnt.getAttribute("w3-include-html");
        if (file) {
          /*make an HTTP request using the attribute value as the file name:*/
          xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4) {
              if (this.status == 200) {elmnt.innerHTML = this.responseText;}
              if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
              /*remove the attribute, and call this function once more:*/
              elmnt.removeAttribute("w3-include-html");
              includeHTML();
            }
          } 
          xhttp.open("GET", file, true);
          xhttp.send();
          /*exit the function:*/
          return;
        }
      }
    }
    </script>

Call includeHTML() at the bottom of the page:

Example

<!DOCTYPE html>
<html>
<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      }      
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
};
</script>
<body>

<div w3-include-html="h1.html"></div> 
<div w3-include-html="content.html"></div> 

<script>
includeHTML();
</script>

</body>
</html>

What is the difference between Python and IPython?

IPython is basically the "recommended" Python shell, which provides extra features. There is no language called IPython.

Google Maps API v3: How to remove all markers?

I found simple solution (I think) :

var marker = new google.maps.Marker();

function Clear(){
     marker.setMap(null);
}

Can Flask have optional URL parameters?

Almost the same as skornos, but with variable declarations for a more explicit answer. It can work with Flask-RESTful extension:

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class UserAPI(Resource):
    def show(userId, username=None):
    pass

api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint='user')

if __name__ == '__main__':
    app.run()

The add_resource method allows pass multiples URLs. Each one will be routed to your Resource.

How to create Android Facebook Key Hash?

I ran into the same problem and here's how I was able to fix it

keytool -list -alias androiddebugkey -keystore <project_file\android\app\debug.keystore>

.war vs .ear file

From GeekInterview:

In J2EE application, modules are packaged as EAR, JAR, and WAR based on their functionality

JAR: EJB modules which contain enterprise java beans (class files) and EJB deployment descriptor are packed as JAR files with .jar extension

WAR: Web modules which contain Servlet class files, JSP Files, supporting files, GIF and HTML files are packaged as a JAR file with .war (web archive) extension

EAR: All the above files (.jar and .war) are packaged as a JAR file with .ear (enterprise archive) extension and deployed into Application Server.

Get escaped URL parameter

Just in case you guys have the url like localhost/index.xsp?a=1#something and you need to get the param not the hash.

var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
    q = q.split('&');
    for(var i = 0; i < q.length; i++){
        hash = q[i].split('=');
        anchor = hash[1].split('#');
        vars.push(anchor[0]);
        vars[hash[0]] = anchor[0];
    }
}

JavaScript regex for alphanumeric string with length of 3-5 chars

add {3,5} to your expression which means length between 3 to 5

/^([a-zA-Z0-9_-]){3,5}$/

UNC path to a folder on my local computer

On Windows, you can also use the Win32 File Namespace prefixed with \\?\ to refer to your local directories:

\\?\C:\my_dir

See this answer for description.

How do I change the IntelliJ IDEA default JDK?

Download and unpack a JDK archive file (.tar.gz) and add it as a SDK in the 'Project Structure' dialog box ( Ctrl+Alt+Shift+S )

jdk 9 intellij click on the gif to enlarge

Make sure to set the 'Project language level' as well.

Button Listener for button in fragment in android

    //sure run it i will also test it
//we make a class that extends with the fragment
    public class Example_3_1 extends Fragment  implements OnClickListener
    {
       View vi;
        EditText t;
        EditText t1;
        Button bu;
 // that are by defult function of fragment extend class
     @Override
       public View onCreateView(LayoutInflater inflater,ViewGroup container,BundlesavedInstanceState) 
       {        
           vi=inflater.inflate(R.layout.example_3_1, container, false);// load the xml file 
           bu=(Button) vi.findViewById(R.id.button1);// get button id from example_3_1 xml file
           bu.setOnClickListener(this); //on button appay click listner
           t=(EditText) vi.findViewById(R.id.editText1);// id get from example_3_1 xml file
           t1=(EditText) vi.findViewById(R.id.editText2);
          return vi; // return the view object,that set the xml file  example_3_1 xml file
       }
       @Override
       public void onClick(View v)//on button click that called
       {

          switch(v.getId())// on run time get id what button os click and get id
          {
          case R.id.button1:        // it mean if button1 click then this work
           t.setText("UMTien");     //set text 
           t1.setText("programming");
           break;
          }
    }     }

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

I found to delete this section from the project file fix the problem.

<ItemGroup>
<Reference Include="Newtonsoft.Json">
  <HintPath>..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>

Javascript Array.sort implementation?

As of V8 v7.0 / Chrome 70, V8 uses TimSort, Python's sorting algorithm. Chrome 70 was released on September 13, 2018.

See the the post on the V8 dev blog for details about this change. You can also read the source code or patch 1186801.

Generate ER Diagram from existing MySQL database, created for CakePHP

CakePHP was intended to be used as Ruby on Rails framework clone, done in PHP, so any reverse-engineering of underlying database is pointless. EER diagrams should be reverse-engineered from Model layer.

Such tools do exist for Ruby Here you can see Redmine database EER diagrams reverse-engineered from Models. Not from database. http://redminecookbook.com/Redmine-erd-diagrams.html

With following tools: http://rails-erd.rubyforge.org/ http://railroady.prestonlee.com/

Sort ArrayList of custom Objects by property

JAVA 8 lambda expression

Collections.sort(studList, (Student s1, Student s2) ->{
        return s1.getFirstName().compareToIgnoreCase(s2.getFirstName());
});

OR

Comparator<Student> c = (s1, s2) -> s1.firstName.compareTo(s2.firstName);
studList.sort(c)

How to validate date with format "mm/dd/yyyy" in JavaScript?

The function will return true if the given string is in the right format('MM/DD/YYYY') else it will return false. (I found this code online & modified it a little)

_x000D_
_x000D_
function isValidDate(date) {_x000D_
    var temp = date.split('/');_x000D_
    var d = new Date(temp[2] + '/' + temp[0] + '/' + temp[1]);_x000D_
    return (d && (d.getMonth() + 1) == temp[0] && d.getDate() == Number(temp[1]) && d.getFullYear() == Number(temp[2]));_x000D_
}_x000D_
_x000D_
console.log(isValidDate('02/28/2015'));_x000D_
            
_x000D_
_x000D_
_x000D_

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Do HttpClient and HttpClientHandler have to be disposed between requests?

Using dependency injection in your constructor makes managing the lifetime of your HttpClient easier - taking the lifetime managemant outside of the code that needs it and making it easily changable at a later date.

My current preference is to create a seperate http client class that inherits from HttpClient once per target endpoint domain and then make it a singleton using dependency injection. public class ExampleHttpClient : HttpClient { ... }

Then I take a constructor dependency on the custom http client in the service classes where I need access to that API. This solves the lifetime problem and has advantages when it comes to connection pooling.

You can see a worked example in related answer at https://stackoverflow.com/a/50238944/3140853

How to Split Image Into Multiple Pieces in Python

  1. crop would be a more reusable function if you separate the cropping code from the image saving code. It would also make the call signature simpler.
  2. im.crop returns a Image._ImageCrop instance. Such instances do not have a save method. Instead, you must paste the Image._ImageCrop instance onto a new Image.Image
  3. Your ranges do not have the right step sizes. (Why height-2 and not height? for example. Why stop at imgheight-(height/2)?).

So, you might try instead something like this:

import Image
import os

def crop(infile,height,width):
    im = Image.open(infile)
    imgwidth, imgheight = im.size
    for i in range(imgheight//height):
        for j in range(imgwidth//width):
            box = (j*width, i*height, (j+1)*width, (i+1)*height)
            yield im.crop(box)

if __name__=='__main__':
    infile=...
    height=...
    width=...
    start_num=...
    for k,piece in enumerate(crop(infile,height,width),start_num):
        img=Image.new('RGB', (height,width), 255)
        img.paste(piece)
        path=os.path.join('/tmp',"IMG-%s.png" % k)
        img.save(path)

JBoss debugging in Eclipse

If you set up a JBoss server using the Eclipse WebTools, you can simply start the server in debug mode (debug button in the servers view). This will allow you to set breakpoints in the application that is running inside the JBoss.

Including a .js file within a .js file

I use @gnarf's method, though I fall back on document.writelning a <script> tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:

if (horus.script.broken) {
    document.writeln('<script type="text/javascript" src="'+script+'"></script>');   
    horus.script.loaded(script);
} else {
    var s=document.createElement('script');
    s.type='text/javascript';
    s.src=script;
    s.async=true;

    if (horus.brokenDOM){
        s.onreadystatechange=
            function () {
                if (this.readyState=='loaded' || this.readyState=='complete'){
                    horus.script.loaded(script);
                }
        }
    }else{
        s.onload=function () { horus.script.loaded(script) };
    }

    document.head.appendChild(s);
}

where horus.script.loaded() notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).

ClassCastException, casting Integer to Double

The code posted in the question is obviously not a a complete example (it's not adding anything to the arraylist, it's not defining i anywhere).

First as others have said you need to understand the difference between primitive types and the class types that box them. E.g. Integer boxes int, Double boxes double, Long boxes long and so-on. Java automatically boxes and unboxes in various scenarios (it used to be you had to box and unbox manually with library calls but that was deemed an ugly PITA).

http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

You can mostly cast from one primitive type to another (the exception being boolean) but you can't do the same for boxed types. To convert one boxed type to another is a bit more complex. Especially if you don't know the box type in advance. Usually it will involve converting via one or more primitive types.

So the answer to your question depends on what is in your arraylist, if it's just objects of type Integer you can do.

sum = ((double)(int)marks.get(i));

The cast to int will behind the scenes first cast the result of marks.get to Integer, then it will unbox that integer. We then use another cast to convert the primitive int to a primitive double. Finally the result will be autoboxed back into a Double when it is assigned to the sum variable. (asside, it would probablly make more sense for sum to be of type double rather than Double in most cases).

If your arraylist contains a mixture of types but they all implement the Number interface (Integer, Short, Long, Float and Double all do but Character and Boolean do not) then you can do.

sum = ((Number)marks.get(i)).doubleValue();

If there are other types in the mix too then you might need to consider using the instanceof operator to identify them and take appropriate action.

There was no endpoint listening at (url) that could accept the message

I had this problem when I was trying to call a WCF service hosted in a new server from a windows application from my local. I was getting same error message and at end had this "No connection could be made because the target machine actively refused it 127.0.0.1:8888". I donot know whether I am wrong or correct but I feel whenever the server was getting request from my windows application it is routing to something else. So I did some reading and added below in Web.config of service host project. After that everything worked like a magic.

<system.net>
    <defaultProxy enabled="false">
    </defaultProxy>
</system.net>

Alternative to itoa() for converting integer to string C++?

In C++11 you can use std::to_string:

#include <string>

std::string s = std::to_string(5);

If you're working with prior to C++11, you could use C++ streams:

#include <sstream>

int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/

Android selector & text color

Have you tried setOnFocusChangeListener? Within the handler, you could change the text appearance.

For instance:

TextView text = (TextView)findViewById(R.id.text);
text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            ((TextView)v).setXXXX();
        } else {
            ((TextView)v).setXXXX();
        }
    }
});

You can then apply whatever changes you want when it's focused or not. You can also use the ViewTreeObserver to listen for Global focus changes.

For instance:

View all = findViewById(R.id.id_of_top_level_view_on_layout);
ViewTreeObserver vto = all.getViewTreeObserver();
vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
    public void onGlobalFocusChanged(
        View oldFocus, View newFocus) {
        // xxxx
    }
});

I hope this helps or gives you ideas.

How to do if-else in Thymeleaf?

<div th:switch="${user.role}"> 
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p> 
</div>


<div th:with="condition=${potentially_complex_expression}" th:remove="tag">
<h2 th:if="${condition}">Hello!</h2>
<span th:unless="${condition}" class="xxx">Something else</span>
</div>

Grouping into interval of 5 minutes within a time range

This will help exactly what you want

replace dt - your datetime c - call field astro_transit1 - your table 300 refer 5 min so add 300 each time for time gap increase

SELECT FROM_UNIXTIME( 300 * ROUND( UNIX_TIMESTAMP( r.dt ) /300 ) ) AS 5datetime, (
SELECT r.c
FROM astro_transit1 ra
WHERE ra.dt = r.dt
ORDER BY ra.dt DESC
LIMIT 1
) AS first_val FROM astro_transit1 r GROUP BY UNIX_TIMESTAMP( r.dt )
DIV 300
LIMIT 0 , 30

how to pass command line arguments to main method dynamically

Run ---> Debug Configuration ---> YourConfiguration ---> Arguments tab

enter image description here

Render partial from different folder (not shared)

If you are using this other path a lot of the time you can fix this permanently without having to specify the path all of the time. By default, it is checking for partial views in the View folder and in the Shared folder. But say you want to add one.

Add a class to your Models folder:

public class NewViewEngine : RazorViewEngine {

   private static readonly string[] NEW_PARTIAL_VIEW_FORMATS = new[] {
      "~/Views/Foo/{0}.cshtml",
      "~/Views/Shared/Bar/{0}.cshtml"
   };

   public NewViewEngine() {
      // Keep existing locations in sync
      base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NEW_PARTIAL_VIEW_FORMATS).ToArray();
   }
}

Then in your Global.asax.cs file, add the following line:

ViewEngines.Engines.Add(new NewViewEngine());

How to remove error about glyphicons-halflings-regular.woff2 not found

This problem happens because IIS does not know about woff and woff2 file mime types.

Solution 1:

Add these lines in your web.config project:

 <system.webServer>
  ...
  </modules>
    <staticContent>
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
    </staticContent>

Solution 2:

On IIS project page:

Step 1: Go to your project IIS home page and double click on MIME Types button:

Step 1

Step 2: Click on Add button from Actions menu: Step 2

Step 3: In the middle of the screen appears a window and in this window you need to add the two lines from solution 1: Step 3

How to add results of two select commands in same query

If you want to make multiple operation use

select (sel1.s1+sel2+s2)

(select sum(hours) s1 from resource) sel1
join 
(select sum(hours) s2 from projects-time)sel2
on sel1.s1=sel2.s2

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

A simple plugin in Android will help you Step 1. Go to Settings Step 2. Click on Plugin Step 3. Search for Android Drawable Importer Step 4. Install plugin and restart

How to use?

Go to File>New>Batch Drawable Import

Enjoy

Python Requests throwing SSLError

As mentioned by @Rafael Almeida, the problem you are having is caused by an untrusted SSL certificate. In my case, the SSL certificate was untrusted by my server. To get around this without compromising security, I downloaded the certificate, and installed it on the server (by simply double clicking on the .crt file and then Install Certificate...).

Detect if page has finished loading

there are two ways to do this in jquery depending what you are looking for..

using jquery you can do

  • //this will wait for the text assets to be loaded before calling this (the dom.. css.. js)

    $(document).ready(function(){...});
    
  • //this will wait for all the images and text assets to finish loading before executing

    $(window).load(function(){...});
    

Convert python long/int to fixed size byte array

long/int to the byte array looks like exact purpose of struct.pack. For long integers that exceed 4(8) bytes, you can come up with something like the next:

>>> limit = 256*256*256*256 - 1
>>> i = 1234567890987654321
>>> parts = []
>>> while i:
        parts.append(i & limit)
        i >>= 32

>>> struct.pack('>' + 'L'*len(parts), *parts )
'\xb1l\x1c\xb1\x11"\x10\xf4'

>>> struct.unpack('>LL', '\xb1l\x1c\xb1\x11"\x10\xf4')
(2976652465L, 287445236)
>>> (287445236L << 32) + 2976652465L
1234567890987654321L

How to declare a Fixed length Array in TypeScript

The Tuple approach :

This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.

Syntax example :

// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]> 

This is the safest approach, considering it prevents accessing indexes out of the boundaries.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
  Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
  & { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }

Tests :

var myFixedLengthArray: FixedLengthArray< [string, string, string]>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? INVALID INDEX ERROR

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR

(*) This solution requires the noImplicitAny typescript configuration directive to be enabled in order to work (commonly recommended practice)


The Array(ish) approach :

This solution behaves as an augmentation of the Array type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.

Syntax example :

let foo: FixedLengthArray<string, 3> 

Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' |  'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
  Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
  & {
    readonly length: L 
    [ I : number ] : T
    [Symbol.iterator]: () => IterableIterator<T>   
  }

Tests :

var myFixedLengthArray: FixedLengthArray<string,3>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? SHOULD FAIL

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL

Force a screen update in Excel VBA

Put a call to DoEvents in the loop.

This will affect performance, so you might want to only call it on each, say, 10th iteration.
However, if you only have 30, that's hardly an issue.

How can I parse a JSON file with PHP?

I can't believe so many people are posting answers without reading the JSON properly.

If you foreach iterate $json_a alone, you have an object of objects. Even if you pass in true as the second parameter, you have a two-dimensional array. If you're looping through the first dimension you can't just echo the second dimension like that. So this is wrong:

foreach ($json_a as $k => $v) {
   echo $k, ' : ', $v;
}

To echo the statuses of each person, try this:

<?php

$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
    // deal with error...
}

$json_a = json_decode($string, true);
if ($json_a === null) {
    // deal with error...
}

foreach ($json_a as $person_name => $person_a) {
    echo $person_a['status'];
}

?>

Get data from JSON file with PHP

Try:
$data = file_get_contents ("file.json");
        $json = json_decode($data, true);
        foreach ($json as $key => $value) {
            if (!is_array($value)) {
                echo $key . '=>' . $value . '<br/>';
            } else {
                foreach ($value as $key => $val) {
                    echo $key . '=>' . $val . '<br/>';
                }
            }
        }

Calculate business days

I had this same need i started with bobbin's first example and ended up with this

  function add_business_days($startdate,$buisnessdays,$holidays=array(),$dateformat){
    $enddate = strtotime($startdate);
    $day = date('N',$enddate);
    while($buisnessdays > 1){
        $enddate = strtotime(date('Y-m-d',$enddate).' +1 day');
        $day = date('N',$enddate);
        if($day < 6 && !in_array($enddate,$holidays))$buisnessdays--;
    }
    return date($dateformat,$enddate);
  }

hth someone

Removing page title and date when printing web page (with CSS?)

There's a facility to have a separate style sheet for print, using

 <link type="text/css" rel="stylesheet" media="print" href="print.css">

I don't know if it does what you want though.

How can I fill a div with an image while keeping it proportional?

Here is an answer with support to IE using object-fit so you won't lose ratio

Using a simple JS snippet to detect if the object-fit is supported and then replace the img for a svg

_x000D_
_x000D_
//ES6 version
if ('objectFit' in document.documentElement.style === false) {
  document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('img[data-object-fit]').forEach(image => {
      (image.runtimeStyle || image.style).background = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}`
      image.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${image.width}' height='${image.height}'%3E%3C/svg%3E`
    })
  })
}

//ES5 version
if ('objectFit' in document.documentElement.style === false) {
  document.addEventListener('DOMContentLoaded', function() {
    Array.prototype.forEach.call(document.querySelectorAll('img[data-object-fit]').forEach(function(image) {
      (image.runtimeStyle || image.style).background = "url(\"".concat(image.src, "\") no-repeat 50%/").concat(image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit'));
      image.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='".concat(image.width, "' height='").concat(image.height, "'%3E%3C/svg%3E");
    }));
  });
}
_x000D_
img {
  display: inline-flex;
  width: 175px;
  height: 175px;
  margin-right: 10px;
  border: 1px solid red
}


/*for browsers which support object fit */

[data-object-fit='cover'] {
  object-fit: cover
}

[data-object-fit='contain'] {
  object-fit: contain
}
_x000D_
<img data-object-fit='cover' src='//picsum.photos/1200/600' />
<img data-object-fit='contain' src='//picsum.photos/1200/600' />
<img src='//picsum.photos/1200/600' />
_x000D_
_x000D_
_x000D_


Note: There are also a few object-fit polyfills out there that will make object-fit work.

Here are a few examples:

How to save and load cookies using Python + Selenium WebDriver

You can save the current cookies as a Python object using pickle. For example:

import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

And later to add them back:

import pickle
import selenium.webdriver

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

When and Why to use abstract classes/methods?

read the following article http://mycodelines.wordpress.com/2009/09/01/in-which-scenario-we-use-abstract-classes-and-interfaces/

Abstract Classes

–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.

–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.

Use an abstract class

When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.) Use an abstract class to define a common base class for a family of types. Use an abstract class to provide default behavior. Subclass only a base class in a hierarchy to which the class logically belongs.

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

To check if variable is null or empty use this:

IF LEN(ISNULL(@var, '')) = 0
    -- Is empty or NULL
ELSE
    -- Is not empty and is not NULL

How to obtain Certificate Signing Request

To manually generate a Certificate, you need a Certificate Signing Request (CSR) file from your Mac. To create a CSR file, follow the instructions below to create one using Keychain Access.

Create a CSR file. In the Applications folder on your Mac, open the Utilities folder and launch Keychain Access.

Within the Keychain Access drop down menu, select Keychain Access > Certificate Assistant > Request a Certificate from a Certificate Authority.

In the Certificate Information window, enter the following information: In the User Email Address field, enter your email address. In the Common Name field, create a name for your private key (e.g., John Doe Dev Key). The CA Email Address field should be left empty. In the "Request is" group, select the "Saved to disk" option. Click Continue within Keychain Access to complete the CSR generating process.

Excel: VLOOKUP that returns true or false?

You still have to wrap it in an ISERROR, but you could use MATCH() instead of VLOOKUP():

Returns the relative position of an item in an array that matches a specified value in a specified order. Use MATCH instead of one of the LOOKUP functions when you need the position of an item in a range instead of the item itself.

Here's a complete example, assuming you're looking for the word "key" in a range of cells:

=IF(ISERROR(MATCH("key",A5:A16,FALSE)),"missing","found")

The FALSE is necessary to force an exact match, otherwise it will look for the closest value.

How do I get unique elements in this array?

Errr, it's a bit messy in the view. But I think I've gotten it to work with group (http://mongoid.org/docs/querying/)

Controller

@event_attendees = Activity.only(:user_id).where(:action => 'Attend').order_by(:created_at.desc).group

View

<% @event_attendees.each do |event_attendee| %>    
  <%= event_attendee['group'].first.user.first_name %>
<% end %>

How to set HTML Auto Indent format on Sublime Text 3?

This was bugging me too, since this was a standard feature in Sublime Text 2, but somehow automatic indentation no longer worked in Sublime Text 3 for HTML files.

My solution was to find the Miscellaneous.tmPreferences file from Sublime Text 2 (found under %AppData%/Roaming/Sublime Text 2/Packages/HTML) and copy those settings to the same file for ST3.

Now package handling has been made more difficult for ST3, but luckily you can just add the files to your %AppData%/Roaming/Sublime Text 3/Packages folder and they overwrite default settings in the install directory. Just save this file as "%AppData%/Roaming/Sublime Text 3/Packages/HTML/Miscellaneous.tmPreferences" and auto indent works again like it did in ST2.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>name</key>
    <string>Miscellaneous</string>
    <key>scope</key>
    <string>text.html</string>
    <key>settings</key>
    <dict>
        <key>decreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>batchDecreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>increaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>batchIncreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>bracketIndentNextLinePattern</key>
         <string>&lt;!DOCTYPE(?!.*&gt;)</string>
    </dict>
</dict>
</plist>

Add & delete view from Layout

hi if are you new in android use this way Apply your view to make it gone GONE is one way, else, get hold of the parent view, and remove the child from there..... else get the parent layout and use this method an remove all child parentView.remove(child)

I would suggest using the GONE approach...

Count number of matches of a regex in Javascript

('my string'.match(/\s/g) || []).length;

Transparent color of Bootstrap-3 Navbar

The class is .navbar-default. You need to create a class on your custom css .navbar-default.And follow the css code. Also if you don’t want box-shadow on your menu, you can put on the same class.

 .navbar-default {
      background-color:transparent !important;
      border-color:transparent;
      background-image:none;
      box-shadow:none;  
 }

enter image description here

To change font navbar color, the class is to change – .navbar-default .navbar-nav>li>a see the code bellow:

  .navbar-default .navbar-nav>li>a {
     font-size:20px; 
     color:#fff; 
 }

ref : http://twitterbootstrap.org/bootstrap-navbar-background-color-transparent/

How to read file with space separated values in pandas

add delim_whitespace=True argument, it's faster than regex.

mysqldump data only

If you just want the INSERT queries, use the following:

mysqldump --skip-triggers --compact --no-create-info

Hibernate: best practice to pull all lazy collections

if you using jpa repository, set properties.put("hibernate.enable_lazy_load_no_trans",true); to jpaPropertymap

Deleting a pointer in C++

I believe you're not fully understanding how pointers work.
When you have a pointer pointing to some memory there are three different things you must understand:
- there is "what is pointed" by the pointer (the memory)
- this memory address
- not all pointers need to have their memory deleted: you only need to delete memory that was dynamically allocated (used new operator).

Imagine:

int *ptr = new int; 
// ptr has the address of the memory.
// at this point, the actual memory doesn't have anything.
*ptr = 8;
// you're assigning the integer 8 into that memory.
delete ptr;
// you are only deleting the memory.
// at this point the pointer still has the same memory address (as you could
//   notice from your 2nd test) but what inside that memory is gone!

When you did

ptr = NULL;
// you didn't delete the memory
// you're only saying that this pointer is now pointing to "nowhere".
// the memory that was pointed by this pointer is now lost.

C++ allows that you try to delete a pointer that points to null but it doesn't actually do anything, just doesn't give any error.

pandas dataframe groupby datetime month

(update: 2018)

Note that pd.Timegrouper is depreciated and will be removed. Use instead:

 df.groupby(pd.Grouper(freq='M'))

Use -notlike to filter out multiple strings in PowerShell

Yep, but you have to put the array first in the expression:

... | where { @("user1","user2") -notlike $_.username }

-Oisin

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

How to check if iframe is loaded or it has a content?

You can use the iframe's load event to respond when the iframe loads.

document.querySelector('iframe').onload = function(){
    console.log('iframe loaded');
};

This won't tell you whether the correct content loaded: To check that, you can inspect the contentDocument.

document.querySelector('iframe').onload = function(){
    var iframeBody = this.contentDocument.body;
    console.log('iframe loaded, body is: ', body);
};

Checking the contentDocument won't work if the iframe src points to a different domain from where your code is running.

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

I had an issue at work. The oracle server was "patched" and one of the databases I use could not be connect via the TNSNames entry but via Basic connection. The Database was up and admin could see it was up and running.

Addionally any application that used TNS for connecting to the database would not work either.

The problem found was that the database name was not correct in the TNS file but for some reason it's been working for years. Correcting the name fixed it for us. I did find that Oracle SQL Developer kept using the old TNS entry even after I updated it and I don't feel like reinstalling it for just one DB Connection. It appears that when the database was created it was given a smaller name then the others and via some cut and paste action within the TNSNames file it got mixed up. No one is sure how its worked as we're investigating it but the oracle patch ensured that the name had to be correct

An example of the name was it was down as "DBName.Part1.Part2" but in fact the DB name was "DBName"

What is the proper way to re-attach detached objects in Hibernate?

to reattach this object, you must use merge();

this methode accept in parameter your entity detached and return an entity will be attached and reloaded from Database.

Example :
    Lot objAttach = em.merge(oldObjDetached);
    objAttach.setEtat(...);
    em.persist(objAttach);

Creating an array from a text file in Bash

You can do this too:

oldIFS="$IFS"
IFS=$'\n' arr=($(<file))
IFS="$oldIFS"
echo "${arr[1]}" # It will print `A Dog`.

Note:

Filename expansion still occurs. For example, if there's a line with a literal * it will expand to all the files in current folder. So use it only if your file is free of this kind of scenario.

Convert Swift string to array

It is even easier in Swift:

let string : String = "Hello  "
let characters = Array(string)
println(characters)
// [H, e, l, l, o,  , , ,  , ]

This uses the facts that

  • an Array can be created from a SequenceType, and
  • String conforms to the SequenceType protocol, and its sequence generator enumerates the characters.

And since Swift strings have full support for Unicode, this works even with characters outside of the "Basic Multilingual Plane" (such as ) and with extended grapheme clusters (such as , which is actually composed of two Unicode scalars).


Update: As of Swift 2, String does no longer conform to SequenceType, but the characters property provides a sequence of the Unicode characters:

let string = "Hello  "
let characters = Array(string.characters)
print(characters)

This works in Swift 3 as well.


Update: As of Swift 4, String is (again) a collection of its Characters:

let string = "Hello  "
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "", "", " ", ""]

javascript get x and y coordinates on mouse click

It sounds like your printMousePos function should:

  1. Get the X and Y coordinates of the mouse
  2. Add those values to the HTML

Currently, it does this:

  1. Creates (undefined) variables for the X and Y coordinates of the mouse
  2. Attaches a function to the "mousemove" event (which will set those variables to the mouse coordinates when triggered by a mouse move)
  3. Adds the current values of your variables to the HTML

See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.

It seems like you probably don't need that mousemove event at all; I would try something like this:

function printMousePos(e) {
    var cursorX = e.pageX;
    var cursorY = e.pageY;
    document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}

How to get an MD5 checksum in PowerShell

PowerShell One-Liners (string to hash)

MD5

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA1

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA256

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA384

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA384CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

SHA512

([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA512CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")

Comparing two byte arrays in .NET

There's a new built-in solution for this in .NET 4 - IStructuralEquatable

static bool ByteArrayCompare(byte[] a1, byte[] a2) 
{
    return StructuralComparisons.StructuralEqualityComparer.Equals(a1, a2);
}

What does ^M character mean in Vim?

In Unix it is probably easier to use 'tr' command.

cat file1.txt | tr "\r" "\n" > file2.txt

how to check confirm password field in form without reloading page

If you don't want use jQuery:

function check_pass() {
    if (document.getElementById('password').value ==
            document.getElementById('confirm_password').value) {
        document.getElementById('submit').disabled = false;
    } else {
        document.getElementById('submit').disabled = true;
    }
}
<input type="password" name="password" id="password" onchange='check_pass();'/>
<input type="password" name="confirm_password" id="confirm_password" onchange='check_pass();'/>
<input type="submit" name="submit"  value="registration"  id="submit" disabled/>

Check if a String is in an ArrayList of Strings

temp = bankAccNos.contains(no) ? 1 : 2;

Write-back vs Write-Through caching?

Write-back and write-through describe policies when a write hit occurs, that is when the cache has the requested information. In these examples, we assume a single processor is writing to main memory with a cache.

Write-through: The information is written to the cache and memory, and the write finishes when both have finished. This has the advantage of being simpler to implement, and the main memory is always consistent (in sync) with the cache (for the uniprocessor case - if some other device modifies main memory, then this policy is not enough), and a read miss never results in writes to main memory. The obvious disadvantage is that every write hit has to do two writes, one of which accesses slower main memory.

Write-back: The information is written to a block in the cache. The modified cache block is only written to memory when it is replaced (in effect, a lazy write). A special bit for each cache block, the dirty bit, marks whether or not the cache block has been modified while in the cache. If the dirty bit is not set, the cache block is "clean" and a write miss does not have to write the block to memory.

The advantage is that writes can occur at the speed of the cache, and if writing within the same block only one write to main memory is needed (when the previous block is being replaced). The disadvantages are that this protocol is harder to implement, main memory can be not consistent (not in sync) with the cache, and reads that result in replacement may cause writes of dirty blocks to main memory.

The policies for a write miss are detailed in my first link.

These protocols don't take care of the cases with multiple processors and multiple caches, as is common in modern processors. For this, more complicated cache coherence mechanisms are required. Write-through caches have simpler protocols since a write to the cache is immediately reflected in memory.

Good resources:

Array.sort() doesn't sort numbers correctly

I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

array.sort([compareFunction])

Parameters

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:

13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return -1.
19. If Result(16) > Result(17), return 1.
20. Return +0.

Adding an identity to an existing column

I'm a java developer that happened to get on a team without a DBA and one where as a developer, I can't get DBA rights. I was tasked with moving an entire schema between two databases, so without having a DBA, I had to do it and do it by running scripts, not being able to use the GUI in SQL Server 2008 because I didn't have admin privileges.

Everything was moved without issue, however, when running a stored procedure on the new schema.table, I found I lost the identity field in a table. I double checked the script that created the table and it was there, however, SQL Server didn't get it when I ran the script. I was told later by a DBA that he had seen this same problem before.

In any event, for SQL Server 2008, these are the steps I took to get this resolved and they worked, so I'm posting this here in the hopes it will be a help to someone. This is what I did as I had FK dependencies on another table that made this more difficult:

I used this query to verify the identity was indeed missing and to view dependencies on the table.

1.) Find statistics on a table:

exec sp_help 'dbo.table_name_old';

2.) Create a duplicate, identical new table, except add an identity field on the PK field where it had been before.

3.) Disable the identity to move data.

SET IDENTITY_INSERT dbo.table_name ON 

4.) Transfer the data.

INSERT INTO dbo.table_name_new
(
field1, field2, etc...
)
SELECT 
field1, field2, etc...
FROM 
dbo.table_name_old;

5.) Verify the data is there.

SELECT * FROM dbo.table_name_new

6.) Re-enable the identity.

SET IDENTITY_INSERT ToyRecP.ToyAwards.lkpFile_New OFF

7.) This is the best script I found to get all the FK relationships to verify which table(s) the original table references as dependencies and I came across many, so it is a keeper!

SELECT f.name AS ForeignKey,
   OBJECT_NAME(f.parent_object_id) AS TableName,
   COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
   OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
   COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
   ON f.OBJECT_ID = fc.constraint_object_id
   ORDER BY ReferenceTableName;

8.) Make sure you have all the PK and FK scripts for all the tables involved, before this next step.

9.) You can right-click on each key and script this using SQL Server 2008

10.) Drop the FK(s) from the dependency table(s) using this syntax:

ALTER TABLE [dbo].[table_name] DROP CONSTRAINT [Name_of_FK]

11.) Drop the original table:

DROP TABLE dbo.table_name_old;

13.) These next steps rely on the scripts you created in SQL Server 2008 in step 9.

--Add the PK to the new table.

--Add the FK to the new table.

--Add the FK's back to the dependency table.

14.) Verify everything is correct and complete. I used the GUI to look at the tables.

15.) Rename the new table to the original tables name.

exec sp_RENAME '[Schema_Name.OldTableName]' , '[NewTableName]';

Finally, everything worked!

Javascript/DOM: How to remove all events of a DOM object?

One method is to add a new event listener that calls e.stopImmediatePropagation().

How to use particular CSS styles based on screen size / device

I created a little javascript tool to style elements on screen size without using media queries or recompiling bootstrap css:

https://github.com/Heras/Responsive-Breakpoints

Just add class responsive-breakpoints to any element, and it will automagically add xs sm md lg xl classes to those elements.

Demo: https://codepen.io/HerasHackwork/pen/rGGNEK

How to use sed to replace only the first occurrence in a file?

Using FreeBSD ed and avoid ed's "no match" error in case there is no include statement in a file to be processed:

teststr='
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
'

# using FreeBSD ed
# to avoid ed's "no match" error, see
# *emphasized text*http://codesnippets.joyent.com/posts/show/11917 
cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo "$teststr")
   H
   ,g/# *include/u\
   u\
   i\
   #include "newfile.h"\
   .
   ,p
   q
EOF

Enter key in textarea

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

How to check in Javascript if one element is contained within another

I just had to share 'mine'.

Although conceptually the same as Asaph's answer (benefiting from the same cross-browser compatibility, even IE6), it is a lot smaller and comes in handy when size is at a premium and/or when it is not needed so often.

function childOf(/*child node*/c, /*parent node*/p){ //returns boolean
  while((c=c.parentNode)&&c!==p); 
  return !!c; 
}

..or as one-liner (just 64 chars!):

function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}

and jsfiddle here.


Usage:
childOf(child, parent) returns boolean true|false.

Explanation:
while evaluates as long as the while-condition evaluates to true.
The && (AND) operator returns this boolean true/false after evaluating the left-hand side and the right-hand side, but only if the left-hand side was true (left-hand && right-hand).

The left-hand side (of &&) is: (c=c.parentNode).
This will first assign the parentNode of c to c and then the AND operator will evaluate the resulting c as a boolean.
Since parentNode returns null if there is no parent left and null is converted to false, the while-loop will correctly stop when there are no more parents.

The right-hand side (of &&) is: c!==p.
The !== comparison operator is 'not exactly equal to'. So if the child's parent isn't the parent (you specified) it evaluates to true, but if the child's parent is the parent then it evaluates to false.
So if c!==p evaluates to false, then the && operator returns false as the while-condition and the while-loop stops. (Note there is no need for a while-body and the closing ; semicolon is required.)

So when the while-loop ends, c is either a node (not null) when it found a parent OR it is null (when the loop ran through to the end without finding a match).

Thus we simply return that fact (converted as boolean value, instead of the node) with: return !!c;: the ! (NOT operator) inverts a boolean value (true becomes false and vice-versa).
!c converts c (node or null) to a boolean before it can invert that value. So adding a second ! (!!c) converts this false back to true (which is why a double !! is often used to 'convert anything to boolean').


Extra:
The function's body/payload is so small that, depending on case (like when it is not used often and appears just once in the code), one could even omit the function (wrapping) and just use the while-loop:

var a=document.getElementById('child'),
    b=document.getElementById('parent'),
    c;

c=a; while((c=c.parentNode)&&c!==b); //c=!!c;

if(!!c){ //`if(c)` if `c=!!c;` was used after while-loop above
    //do stuff
}

instead of:

var a=document.getElementById('child'),
    b=document.getElementById('parent'),
    c;

function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}

c=childOf(a, b);    

if(c){ 
    //do stuff
}

How to send a “multipart/form-data” POST in Android with Volley

As mentioned in the presentation at the I/O (about 4:05), Volley "is terrible" for large payloads. As I understand it that means not to use Volley for receiving/sending (big) files. Looking at the code it seems that it is not even designed to handle multipart form data (e.g. Request.java has getBodyContentType() with hardcoded "application/x-www-form-urlencoded"; HttpClientStack::createHttpRequest() can handle only byte[], etc...). Probably you will be able to create implementation that can handle multipart but If I were you I will just use HttpClient directly with MultipartEntity like:

    HttpPost req = new HttpPost(composeTargetUrl());
    MultipartEntity entity = new MultipartEntity();
    entity.addPart(POST_IMAGE_VAR_NAME, new FileBody(toUpload));
    try {
        entity.addPart(POST_SESSION_VAR_NAME, new StringBody(uploadSessionId));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    req.setEntity(entity);

You may need newer HttpClient (i.e. not the built-in) or even better, use Volley with newer HttpClient

How to remove all duplicate items from a list

The modern way to do it that maintains the order is:

>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(lseparatedOrbList))

as discussed by Raymond Hettinger (python core dev) in this answer. In python 3.5 and above this is also the fastest way - see the linked answer for details. However the keys must be hashable (as is the case in your list I think)

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

Your method must be static

static void setTextboxText(int result)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result }); 
    }
    else
    {
        SetTextboxTextSafe(result);
    }
}

How to shutdown a Spring Boot Application in a correct way?

SpringApplication implicitly registers a shutdown hook with the JVM to ensure that ApplicationContext is closed gracefully on exit. That will also call all bean methods annotated with @PreDestroy. That means we don't have to explicitly use the registerShutdownHook() method of a ConfigurableApplicationContext in a boot application, like we have to do in spring core application.

@SpringBootConfiguration
public class ExampleMain {
    @Bean
    MyBean myBean() {
        return new MyBean();
    }

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(ExampleMain.class, args);
        MyBean myBean = context.getBean(MyBean.class);
        myBean.doSomething();

        //no need to call context.registerShutdownHook();
    }

    private static class MyBean {

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

        public void doSomething() {
            System.out.println("in doSomething()");
        }

        @PreDestroy
        public void destroy() {
            System.out.println("destroy");
        }
    }
}

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

How to create a List with a dynamic object type

It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.

Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.

DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj

...

The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.

var DyObjectsList = new List<dynamic>; 
if (condition1) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = true; 
    DyObj.Message = "Message 1"; 
    DyObjectsList .Add(DyObj); 
} 
if (condition2) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = false; 
    DyObj.Message = "Message 2"; 
    DyObjectsList .Add(DyObj); 
} 

your resulting List essentially looks like this

DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj

Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.

However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.

How to compile python script to binary executable

# -*- mode: python -*-

block_cipher = None

a = Analysis(['SCRIPT.py'],
             pathex=[
                 'folder path',
                 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_50c6cb8431e7428f',
                 'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_c4f50889467f081d'
             ],
             binaries=[(''C:\\Users\\chromedriver.exe'')],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='NAME OF YOUR EXE',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )

How to grab substring before a specified character jQuery or JavaScript

You can also use shift().

var streetaddress = addy.split(',').shift();

According to MDN Web Docs:

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

I lose my data when the container exits

There are really great answers above to the asked question. There might be no need for another answer but still I want to give my personal opinion on the topic in the simplest words possible.

Here are some points about containers & images that will help us for a conclusion:

  • A docker image can be:
    1. created-from-a-given-container
    2. deleted
    3. used-to-create-any-number-of-containers
  • A docker container can be:
    1. created-from-an-image
    2. started
    3. stopped
    4. restarted
    5. deleted
    6. used-to-create-any-number-of-images
  • A docker run command does this:
    1. Downloads an image or uses a cached image
    2. Creates a new container out of it
    3. Starts the container
  • When a Dockerfile is used to create an image:
    1. It is already well known that the image will eventually be used to run a docker container.
    2. After issuing docker build command, docker behind-the-scenes creates a running container with a base-file-system and follows steps inside the Dockerfile to configure that container as per the developers need.
    3. After the container is configured with specs of the Dockerfile, it will be committed as an image.
    4. The image gets ready to rock & roll!

Conclusion:

As we can see, a docker container is independent of a docker image.

A container can be restarted provided the unique ID of that container [use docker ps --all to get the id].

Any operation like making a new directory, creating files, installing tools, etc. can be done inside the container when it is running. Once the container is stopped, it persists all the changes. Container stopping and restarting is like rebooting a computer system.

An already created container is always available for a restart but when we issue docker run command, a new container is created out of an image and hence it is like a new computer system. The changes made inside the old container - as we can understand now - are not available in this new container.

A final note:

I guess it's now obvious why the data seems to be lost yet it is always there.. but in a different [old] container. So, take a good note of the difference in docker start & docker run command & never get confused in them.

Validate SSL certificates with Python

The following code allows you to benefit from all SSL validation checks (e.g. date validity, CA certificate chain ...) EXCEPT a pluggable verification step e.g. to verify the hostname or do other additional certificate verification steps.

from httplib import HTTPSConnection
import ssl


def create_custom_HTTPSConnection(host):

    def verify_cert(cert, host):
        # Write your code here
        # You can certainly base yourself on ssl.match_hostname
        # Raise ssl.CertificateError if verification fails
        print 'Host:', host
        print 'Peer cert:', cert

    class CustomHTTPSConnection(HTTPSConnection, object):
        def connect(self):
            super(CustomHTTPSConnection, self).connect()
            cert = self.sock.getpeercert()
            verify_cert(cert, host)

    context = ssl.create_default_context()
    context.check_hostname = False
    return CustomHTTPSConnection(host=host, context=context)


if __name__ == '__main__':
    # try expired.badssl.com or self-signed.badssl.com !
    conn = create_custom_HTTPSConnection('badssl.com')
    conn.request('GET', '/')
    conn.getresponse().read()

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

For quick reference of anyone who wants to go to the end of line or start of line in iTerm2, the above link http://hackaddict.blogspot.com/2007/07/skip-to-next-or-previous-word-in-iterm.html notes that in iTerm2:

  • Ctrl+A, jumps to the start of the line, while
  • Ctrl+E, jumps to the end of the line.

Is Google Play Store supported in avd emulators?

If using the command line, you'll need to use one of the packages listed with

sdkmanager --list | grep "playstore"

Once that is installed you can use the appropriate package in

avdmanager create avd --force --name testAVD --abi google_apis_playstore/x86_64 --package "system-images;android-28;google_apis_playstore;x86_64" -d 19

Replace google_apis_playstore;x86_64 with the package you installed

How do you transfer or export SQL Server 2005 data to Excel

you can right click on a grid of results in SQL server, and choose save as CSV. you can then you can import this into Excel.

Excel gives you a import wizard, ensure you select comma delimited. it works fine for me when i needed to import 50k+ records into excel.

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

Maybe your dept_name columns have different charsets.

You could try to alter one or both of them:

ALTER TABLE department MODIFY dept_name VARCHAR(20) CHARACTER SET utf8;
ALTER TABLE course MODIFY dept_name VARCHAR(20) CHARACTER SET utf8;

Git Clone: Just the files, please?

you can create a shallow clone to only get the last few revisions:

 git clone --depth 1 git://url

then either simply delete the .git directory or use git archive to export your tree.

Can a relative sitemap url be used in a robots.txt?

Good technical & logical question my dear friend. No in robots.txt file you can't go with relative URL of the sitemap; you need to go with the complete URL of the sitemap.

It's better to go with "sitemap: https://www.example.com/sitemap_index.xml"

In the above URL after the colon gives space. I also like to support Deepak.

How to force keyboard with numbers in mobile website in Android

This should work. But I have same problems on an Android phone.

<input type="number" /> <input type="tel" />

I found out, that if I didn't include the jquerymobile-framework, the keypad showed correctly on the two types of fields.

But I havn't found a solution to solve that problem, if you really need to use jquerymobile.

UPDATE: I found out, that if the form-tag is stored out of the

<div data-role="page"> 

The number keypad isn't shown. This must be a bug...

Install msi with msiexec in a Specific Directory

This one worked for me too

msiexec /i "msi path" INSTALLDIR="D:\myfolder" /q

I had tried two other iterations and both installed in the default C:\Program Files

INSTALLDIR="D:\myfolder" /q got it installed on the other drive.

What is the iBeacon Bluetooth Profile

For an iBeacon with ProximityUUID E2C56DB5-DFFB-48D2-B060-D0F5A71096E0, major 0, minor 0, and calibrated Tx Power of -59 RSSI, the transmitted BLE advertisement packet looks like this:

d6 be 89 8e 40 24 05 a2 17 6e 3d 71 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 52 ab 8d 38 a5

This packet can be broken down as follows:

d6 be 89 8e # Access address for advertising data (this is always the same fixed value)
40 # Advertising Channel PDU Header byte 0.  Contains: (type = 0), (tx add = 1), (rx add = 0)
24 # Advertising Channel PDU Header byte 1.  Contains:  (length = total bytes of the advertising payload + 6 bytes for the BLE mac address.)
05 a2 17 6e 3d 71 # Bluetooth Mac address (note this is a spoofed address)
02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 # Bluetooth advertisement
52 ab 8d 38 a5 # checksum

The key part of that packet is the Bluetooth Advertisement, which can be broken down like this:

02 # Number of bytes that follow in first AD structure
01 # Flags AD type
1A # Flags value 0x1A = 000011010  
   bit 0 (OFF) LE Limited Discoverable Mode
   bit 1 (ON) LE General Discoverable Mode
   bit 2 (OFF) BR/EDR Not Supported
   bit 3 (ON) Simultaneous LE and BR/EDR to Same Device Capable (controller)
   bit 4 (ON) Simultaneous LE and BR/EDR to Same Device Capable (Host)
1A # Number of bytes that follow in second (and last) AD structure
FF # Manufacturer specific data AD type
4C 00 # Company identifier code (0x004C == Apple)
02 # Byte 0 of iBeacon advertisement indicator
15 # Byte 1 of iBeacon advertisement indicator
e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 # iBeacon proximity uuid
00 00 # major 
00 00 # minor 
c5 # The 2's complement of the calibrated Tx Power

Any Bluetooth LE device that can be configured to send a specific advertisement can generate the above packet. I have configured a Linux computer using Bluez to send this advertisement, and iOS7 devices running Apple's AirLocate test code pick it up as an iBeacon with the fields specified above. See: Use BlueZ Stack As A Peripheral (Advertiser)

This blog has full details about the reverse engineering process.

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can call Stored Procedure like this inside Stored Procedure B.

CREATE PROCEDURE spA
@myDate DATETIME
AS
    EXEC spB @myDate

RETURN 0

Python find elements in one list that are not in the other

I would zip the lists together to compare them element by element.

main_list = [b for a, b in zip(list1, list2) if a!= b]

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.