Programs & Examples On #Ob start

ob_start is a PHP function which turns output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

Palindrome check in Javascript

Some above short anwsers is good, but it's not easy for understand, I suggest one more way:

function checkPalindrome(inputString) {

    if(inputString.length == 1){
        return true;
    }else{
        var i = 0;
        var j = inputString.length -1;
        while(i < j){
            if(inputString[i] != inputString[j]){
                return false;
            }
            i++;
            j--;
        }
    }
    return true;
}

I compare each character, i start form left, j start from right, until their index is not valid (i<j). It's also working in any languages

Proper way to exit iPhone application?

Hm, you may 'have to' quit the application if, say, your application requires an internet connection. You could display an alert and then do something like this:

if ([[UIApplication sharedApplication] respondsToSelector:@selector(terminate)]) {
    [[UIApplication sharedApplication] performSelector:@selector(terminate)];
} else {
    kill(getpid(), SIGINT); 
}

C# Get a control's position on a form

private Point FindLocation(Control ctrl)
{
    if (ctrl.Parent is Form)
        return ctrl.Location;
    else
    {
        Point p = FindLocation(ctrl.Parent);
        p.X += ctrl.Location.X;
        p.Y += ctrl.Location.Y;
        return p;
    }
}

C# How do I click a button by hitting Enter whilst textbox has focus?

Or you can just use this simple 2 liner code :)

if (e.KeyCode == Keys.Enter)
            button1.PerformClick();

How to compile Go program consisting of multiple files?

Since Go 1.11+, GOPATH is no longer recommended, the new way is using Go Modules.

Say you're writing a program called simple:

  1. Create a directory:

    mkdir simple
    cd simple
    
  2. Create a new module:

    go mod init github.com/username/simple
    # Here, the module name is: github.com/username/simple.
    # You're free to choose any module name.
    # It doesn't matter as long as it's unique.
    # It's better to be a URL: so it can be go-gettable.
    
  3. Put all your files in that directory.

  4. Finally, run:

    go run .
    
  5. Alternatively, you can create an executable program by building it:

    go build .
    
    # then:
    ./simple     # if you're on xnix
    
    # or, just:
    simple       # if you're on Windows
    

For more information, you may read this.

Go has included support for versioned modules as proposed here since 1.11. The initial prototype vgo was announced in February 2018. In July 2018, versioned modules landed in the main Go repository. In Go 1.14, module support is considered ready for production use, and all users are encouraged to migrate to modules from other dependency management systems.

Where does Chrome store extensions?

For my Mac, extensions were here:

~/Library/Application Support/Google/Chrome/Default/Extensions/

if you go to chrome://extensions you'll find the "ID" of each extension. That is going to be a directory within Extensions directory. It is there you'll find all of the extension's files.

How to calculate the angle between a line and the horizontal axis?

matlab function:

function [lineAngle] = getLineAngle(x1, y1, x2, y2) 
    deltaY = y2 - y1;
    deltaX = x2 - x1;

    lineAngle = rad2deg(atan2(deltaY, deltaX));

    if deltaY < 0
        lineAngle = lineAngle + 360;
    end
end

How can I calculate the number of years between two dates?

for(var y=birthyear; y <= thisyear; y++){ 

if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) { 
 days = days-366;
 number_of_long_years++; 
} else {
    days=days-365;
}

year++;

}

can you try this way??

Installing a local module using npm?

Missing the main property?

As previous people have answered npm --save ../location-of-your-packages-root-directory. The ../location-of-your-packages-root-directory however must have two things in order for it to work.

1) package.json in that directory pointed towards

2) main property in the package.json must be set and working i.g. "main": "src/index.js", if the entry file for ../location-of-your-packages-root-directory is ../location-of-your-packages-root-directory/src/index.js

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

How do I change TextView Value inside Java Code?

First we need to find a Button:

Button mButton = (Button) findViewById(R.id.my_button);

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});

How to store the hostname in a variable in a .bat file?

Why not so?:

set host=%COMPUTERNAME%
echo %host%

Check if a string is a palindrome

class Program
{
    static void Main(string[] args)
    {

        string s, revs = "";
        Console.WriteLine(" Enter string");
        s = Console.ReadLine();
        for (int i = s.Length - 1; i >= 0; i--) //String Reverse
        {
            Console.WriteLine(i);
            revs += s[i].ToString();
        }
        if (revs == s) // Checking whether string is palindrome or not
        {
            Console.WriteLine("String is Palindrome");
        }
        else
        {
            Console.WriteLine("String is not Palindrome");
        }
        Console.ReadKey();
    }
}

ToList().ForEach in Linq

You can use Array.ForEach()

Array.ForEach(employees, employee => {
   Array.ForEach(employee.Departments, department => department.SomeProperty = null);
   Collection.AddRange(employee.Departments);
});

Javascript checkbox onChange

I know this seems like noob answer but I'm putting it here so that it can help others in the future.

Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.

<!-- Begin Loop-->
<tr>
 <td><?=$criteria?></td>
 <td><?=$indicator?></td>
 <td><?=$target?></td>
 <td>
   <div class="form-check">
    <input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>> 
<!-- mark as 'checked' if checkbox was selected on a previous save -->
   </div>
 </td>
</tr>
<!-- End of Loop -->

You place a button below the table with a hidden input:

<form method="post" action="/goalobj-review" id="goalobj">

 <!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->

 <input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
 <button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>

You can write your script like so:

<script type="text/javascript">
    var checkboxes = document.getElementsByClassName('form-check-input');
    var i;
    var tid = setInterval(function () {
        if (document.readyState !== "complete") {
            return;
        }
        clearInterval(tid);
    for(i=0;i<checkboxes.length;i++){
        checkboxes[i].addEventListener('click',checkBoxValue);
    }
    },100);

    function checkBoxValue(event) {
        var selected = document.querySelector("input[id=selected]");
        var result = 0;
        if(this.checked) {

            if(selected.value.length > 0) {
                result = selected.value + "," + this.value;
                document.querySelector("input[id=selected]").value = result;
            } else {
                result = this.value;
                document.querySelector("input[id=selected]").value = result;
            }
        }
        if(! this.checked) { 

// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.

            var compact = selected.value.split(","); // split string into array
            var index = compact.indexOf(this.value); // return index of our selected checkbox
            compact.splice(index,1); // removes 1 item at specified index
            var newValue = compact.join(",") // returns a new string
            document.querySelector("input[id=selected]").value = newValue;
        }

    }
</script>

The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Basically, you get connections in the Sleep state when :

  • a PHP script connects to MySQL
  • some queries are executed
  • then, the PHP script does some stuff that takes time
    • without disconnecting from the DB
  • and, finally, the PHP script ends
    • which means it disconnects from the MySQL server

So, you generally end up with many processes in a Sleep state when you have a lot of PHP processes that stay connected, without actually doing anything on the database-side.

A basic idea, so : make sure you don't have PHP processes that run for too long -- or force them to disconnect as soon as they don't need to access the database anymore.


Another thing, that I often see when there is some load on the server :

  • There are more and more requests coming to Apache
    • which means many pages to generate
  • Each PHP script, in order to generate a page, connects to the DB and does some queries
  • These queries take more and more time, as the load on the DB server increases
  • Which means more processes keep stacking up

A solution that can help is to reduce the time your queries take -- optimizing the longest ones.

Send request to curl with post data sourced from a file

You're looking for the --data-binary argument:

curl -i -X POST host:port/post-file \
  -H "Content-Type: text/xml" \
  --data-binary "@path/to/file"

In the example above, -i prints out all the headers so that you can see what's going on, and -X POST makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @ symbol, so curl knows to read from a file.

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

make sure you download the x86 SDK instead of only the x64 SDK for visual studio.

Make Frequency Histogram for Factor Variables

Data as factor can be used as input to the plot function.

An answer to a similar question has been given here: https://stat.ethz.ch/pipermail/r-help/2010-December/261873.html

 x=sample(c("Richard", "Minnie", "Albert", "Helen", "Joe", "Kingston"),  
 50, replace=T)
 x=as.factor(x)
 plot(x)

Convert binary to ASCII and vice versa

Convert binary to its equivalent character.

k=7
dec=0
new=[]
item=[x for x in input("Enter 8bit binary number with , seprator").split(",")]
for i in item:
    for j in i:
        if(j=="1"):
            dec=2**k+dec
            k=k-1
        else:
            k=k-1
    new.append(dec)
    dec=0
    k=7
print(new)
for i in new:
    print(chr(i),end="")

How to hide underbar in EditText

You can do it programmatically using setBackgroundResource:

editText.setBackgroundResource(android.R.color.transparent);

Google Maps: how to get country, state/province/region, city given a lat/long value?

I've created a small mapper function:

private getAddressParts(object): Object {
    let address = {};
    const address_components = object.address_components;
    address_components.forEach(element => {
        address[element.types[0]] = element.short_name;
    });
    return address;
}

It's a solution for Angular 4 but I think you'll get the idea.

Usage:

geocoder.geocode({ 'location' : latlng }, (results, status) => {
    if (status === google.maps.GeocoderStatus.OK) {
        const address = {
            formatted_address: results[0].formatted_address,
            address_parts: this.getAddressParts(results[0])
        };
        (....)
    }

This way the address object will be something like this:

address: {
    address_parts: {
        administrative_area_level_1: "NY",
        administrative_area_level_2: "New York County",
        country: "US",
        locality: "New York",
        neighborhood: "Lower Manhattan",
        political: "Manhattan",
        postal_code: "10038",
        route: "Beekman St",
        street_number: "90",
    },
    formatted_address: "90 Beekman St, New York, NY 10038, USA"
}

Hope it helps!

Close Android Application

android.os.Process.killProcess(android.os.Process.myPid());

This code kill the process from OS Using this code disturb the OS. So I would recommend you to use the below code

this.finish();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

SQLAlchemy equivalent to SQL "LIKE" statement

Using PostgreSQL like (see accepted answer above) somehow didn't work for me although cases matched, but ilike (case insensisitive like) does.

Output Django queryset as JSON

You can use JsonResponse with values. Simple example:

from django.http import JsonResponse

def some_view(request):
    data = list(SomeModel.objects.values())  # wrap in list(), because QuerySet is not JSON serializable
    return JsonResponse(data, safe=False)  # or JsonResponse({'data': data})

Or another approach with Django's built-in serializers:

from django.core import serializers
from django.http import HttpResponse

def some_view(request):
    qs = SomeModel.objects.all()
    qs_json = serializers.serialize('json', qs)
    return HttpResponse(qs_json, content_type='application/json')

In this case result is slightly different (without indent by default):

[
    {
        "model": "some_app.some_model",
        "pk": 1,
        "fields": {
            "name": "Elon",
            "age": 48,
            ...
        }
    },
    ...
]

I have to say, it is good practice to use something like marshmallow to serialize queryset.

...and a few notes for better performance:

  • use pagination if your queryset is big;
  • use objects.values() to specify list of required fields to avoid serialization and sending to client unnecessary model's fields (you also can pass fields to serializers.serialize);

Where is Ubuntu storing installed programs?

for some applications, for example google chrome, they store it under /opt. you can follow the above instruction using dpkg -l to get the correct naming then dpkg -L to get the detail.

hope it helps

How to use .htaccess in WAMP Server?

Click on Wamp icon and open Apache/httpd.conf and search "#LoadModule rewrite_module modules/mod_rewrite.so". Remove # as below and save it

LoadModule rewrite_module modules/mod_rewrite.so

and restart all service.

How do I debug a stand-alone VBScript script?

For posterity, here's Microsoft's article KB308364 on the subject. This no longer exists on their website, it is from an archive.

How to debug Windows Script Host, VBScript, and JScript files

SUMMARY

The purpose of this article is to explain how to debug Windows Script Host (WSH) scripts, which can be written in any ActiveX script language (as long as the proper language engine is installed), but which, by default, are written in VBScript and JScript. There are certain flags in the registry and, depending on the debugger used, certain required procedures to enable debugging.

MORE INFORMATION

To debug WSH scripts in Microsoft Visual InterDev, the Microsoft Script Debugger, or any other debugger, use the following command-line syntax to start the script:

wscript.exe //d <path to WSH file>
           This code informs the user when a runtime error has occurred and gives the user a choice to debug the application. Also, the //x flag

can be used, as follows, to throw an immediate exception, which starts the debugger immediately after the script starts running:

wscript.exe //d //x <path to WSH file>
           After a debug condition exists, the following registry key determines which debugger will be used:

HKEY_CLASSES_ROOT\CLSID\{834128A2-51F4-11D0-8F20-00805F2CD064}\LocalServer32

The script debugger should be Msscrdbg.exe, and the Visual InterDev debugger should be Mdm.exe.

If Visual InterDev is the default debugger, make sure that just-in-time (JIT) functionality is enabled. To do this, follow these steps:

  1. Start Visual InterDev.

  2. On the Tools menu, click Options.

  3. Click Debugger, and then ensure that the Just-In-Time options are selected for both the General and Script categories.

Additionally, if you are trying to debug a .wsf file, make sure that the following registry key is set to 1:

HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug

PROPERTIES

Article ID: 308364 - Last Review: June 19, 2014 - Revision: 3.0

Keywords: kbdswmanage2003swept kbinfo KB308364

Simple UDP example to send and receive data from same socket

here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports

    static UdpClient sendClient = new UdpClient();
    static int localPort = 49999;
    static int remotePort = 49000;
    static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
    static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
    static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
    static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);


    private static void initStuff()
    {
      
        fw.AutoFlush = true;
        sendClient.ExclusiveAddressUse = false;
        sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        sendClient.Client.Bind(localEP);
        sendClient.BeginReceive(DataReceived, sendClient);
    }

    private static void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") +  " (" + receivedBytes.Length + " bytes)");

        c.BeginReceive(DataReceived, ar.AsyncState);
    }


    static void Main(string[] args)
    {
        initStuff();
        byte[] emptyByte = {};
        sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
    }

How to push a new folder (containing other folders and files) to an existing git repo?

You can directly go to Web IDE and upload your folder there.

Steps:

  1. Go to Web IDE(Mostly located below the clone option).
  2. Create new directory at your path
  3. Upload your files and folders

In some cases you may not be able to directly upload entire folder containing folders, In such cases, you will have to create directory structure yourself.

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

If you really want to insert this record, remove the `abuse_id` field and the corresponding value from the INSERTstatement :

INSERT INTO  `abuses` (  `user_id` ,  `abuser_username` ,  `comment` ,  `reg_date` , `auction_id` ) 
VALUES ( 100020,  'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;

How to create query parameters in Javascript?

URLSearchParams has increasing browser support.

const data = {
  var1: 'value1',
  var2: 'value2'
};

const searchParams = new URLSearchParams(data);

// searchParams.toString() === 'var1=value1&var2=value2'

Node.js offers the querystring module.

const querystring = require('querystring');

const data = {
  var1: 'value1',
  var2: 'value2'
};

const searchParams = querystring.stringify(data);

// searchParams === 'var1=value1&var2=value2'

How to get child element by ID in JavaScript?

If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.

$('#note').find('#textid');

You can also use jQuery selectors to basically achieve the same thing:

$('#note #textid');

Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.

On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.

Update 2020.03.10

It's a breeze to use native JS for this:

document.querySelector('#note #textid');

If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(

var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;

Get current time in seconds since the Epoch on Linux, Bash

Just to add.

Get the seconds since epoch(Jan 1 1970) for any given date(e.g Oct 21 1973).

date -d "Oct 21 1973" +%s


Convert the number of seconds back to date

date --date @120024000


The command date is pretty versatile. Another cool thing you can do with date(shamelessly copied from date --help). Show the local time for 9AM next Friday on the west coast of the US

date --date='TZ="America/Los_Angeles" 09:00 next Fri'

Better yet, take some time to read the man page http://man7.org/linux/man-pages/man1/date.1.html

jquery's append not working with svg element?

Based on @chris-dolphin 's answer but using helper function:

// Creates svg element, returned as jQuery object
function $s(elem) {
  return $(document.createElementNS('http://www.w3.org/2000/svg', elem));
}

var $svg = $s("svg");
var $circle = $s("circle").attr({...});
$svg.append($circle);

Initializing a struct to 0

I also thought this would work but it's misleading:

myStruct _m1 = {0};

When I tried this:

myStruct _m1 = {0xff};

Only the 1st byte was set to 0xff, the remaining ones were set to 0. So I wouldn't get into the habit of using this.

CSS display:inline property with list-style-image: property on <li> tags

Try using float: left (or right) instead of display: inline. Inline display replaces list-item display, which is what adds the bullet points.

Add new row to excel Table (VBA)

I had the same problem before and i fixed it by creating the same table in a new sheet and deleting all the name ranges associated to the table, i believe whene you're using listobjects you're not alowed to have name ranges contained within your table hope that helps thanks

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

Error: Module not specified (IntelliJ IDEA)

For IntelliJ IDEA 2019.3.4 (Ultimate Edition), the following worked for me:

  1. Find the Environment variables for your project.
  2. Specify, from the dropdowns, the values of "Use class path of module:" and "JRE" as in the attached screenshot.

enter image description here

Get folder name from full file path

Simply use Path.GetFileName

Here - Extract folder name from the full path of a folder:

string folderName = Path.GetFileName(@"c:\projects\root\wsdlproj\devlop\beta2\text");//Return "text"

Here is some extra - Extract folder name from the full path of a file:

string folderName = Path.GetFileName(Path.GetDirectoryName(@"c:\projects\root\wsdlproj\devlop\beta2\text\GTA.exe"));//Return "text"

Get local IP address

To get local Ip Address:

public static string GetLocalIPAddress()
{
    var host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            return ip.ToString();
        }
    }
    throw new Exception("No network adapters with an IPv4 address in the system!");
}

To check if you're connected or not:

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

Set a border around a StackPanel.

You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.

If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)

font awesome icon in select option

Another solution is setting the size attribute on the select box.

Thus taking back control of the styling of the dropdown from the Apple style and displaying Font Awesome Icons correctly.

How to print a date in a regular format?

You can use easy_date to make it easy:

import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')

Get Application Name/ Label via ADB Shell or Terminal

If you know the app id of the package (like org.mozilla.firefox), it is easy. First to get the path of actual package file of the appId,

$  adb shell pm list packages -f com.google.android.apps.inbox
package:/data/app/com.google.android.apps.inbox-1/base.apk=com.google.android.apps.inbox

Now you can do some grep|sed magic to extract the path : /data/app/com.google.android.apps.inbox-1/base.apk

After that aapt tool comes in handy :

$  adb shell aapt dump badging /data/app/com.google.android.apps.inbox-1/base.apk
...
application-label:'Inbox'
application-label-hi:'Inbox'
application-label-ru:'Inbox'
...

Again some grep magic to get the Label.

How can I get the average (mean) of selected columns

Try using rowMeans:

z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)

  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

javascript compare strings without being case sensitive

You can make both arguments lower case, and that way you will always end up with a case insensitive search.

var string1 = "aBc";
var string2 = "AbC";

if (string1.toLowerCase() === string2.toLowerCase())
{
    #stuff
}

video as site background? HTML 5

Take a look at my jquery videoBG plugin

http://syddev.com/jquery.videoBG/

Make any HTML5 video a site background... has an image fallback for browsers that don't support html5

Really easy to use

Let me know if you need any help.

Length of the String without using length() method

You can use a loop to check every character position and catch the IndexOutOfBoundsException when you pass the last character. But why?

public int slowLength(String myString) {
    int i = 0;
    try {
        while (true) {
            myString.charAt(i);
            i++;
        }
    } catch (IndexOutOfBoundsException e) {
       return i;
    }
}

Note: This is very bad programming practice and very inefficient.

You can use reflection to examine the internal variables in the String class, specifically count.

How to set default value for column of new created table from select statement in 11g

You will need to alter table abc modify (salary default 0);

Keep a line of text as a single line - wrap the whole line or none at all

You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

Find the server name for an Oracle database

I use this query in order to retrieve the server name of my Oracle database.

SELECT program FROM v$session WHERE program LIKE '%(PMON)%';

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

I resolved my problem doing this:

  • The .php file is encoded to ANSI. In this file is the function to create the .json file.
  • I use json_encode($array, JSON_UNESCAPED_UNICODE) to encode the data;

The result is a .json file encoded to ANSI as UTF-8.

sed one-liner to convert all uppercase to lowercase?

Here are many solutions :

To upercaser with perl, tr, sed and awk

perl -ne 'print uc'
perl -npe '$_=uc'
perl -npe 'tr/[a-z]/[A-Z]/'
perl -npe 'tr/a-z/A-Z/'
tr '[a-z]' '[A-Z]'
sed y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/
sed 's/\([a-z]\)/\U\1/g'
sed 's/.*/\U&/'
awk '{print toupper($0)}'

To lowercase with perl, tr, sed and awk

perl -ne 'print lc'
perl -npe '$_=lc'
perl -npe 'tr/[A-Z]/[a-z]/'
perl -npe 'tr/A-Z/a-z/'
tr '[A-Z]' '[a-z]'
sed y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
sed 's/\([A-Z]\)/\L\1/g'
sed 's/.*/\L&/'
awk '{print tolower($0)}'

Complicated bash to lowercase :

while read v;do v=${v//A/a};v=${v//B/b};v=${v//C/c};v=${v//D/d};v=${v//E/e};v=${v//F/f};v=${v//G/g};v=${v//H/h};v=${v//I/i};v=${v//J/j};v=${v//K/k};v=${v//L/l};v=${v//M/m};v=${v//N/n};v=${v//O/o};v=${v//P/p};v=${v//Q/q};v=${v//R/r};v=${v//S/s};v=${v//T/t};v=${v//U/u};v=${v//V/v};v=${v//W/w};v=${v//X/x};v=${v//Y/y};v=${v//Z/z};echo "$v";done

Complicated bash to uppercase :

while read v;do v=${v//a/A};v=${v//b/B};v=${v//c/C};v=${v//d/D};v=${v//e/E};v=${v//f/F};v=${v//g/G};v=${v//h/H};v=${v//i/I};v=${v//j/J};v=${v//k/K};v=${v//l/L};v=${v//m/M};v=${v//n/N};v=${v//o/O};v=${v//p/P};v=${v//q/Q};v=${v//r/R};v=${v//s/S};v=${v//t/T};v=${v//u/U};v=${v//v/V};v=${v//w/W};v=${v//x/X};v=${v//y/Y};v=${v//z/Z};echo "$v";done

Simple bash to lowercase :

while read v;do echo "${v,,}"; done

Simple bash to uppercase :

while read v;do echo "${v^^}"; done

Note that ${v,} and ${v^} only change the first letter.

You should use it that way :

(while read v;do echo "${v,,}"; done) < input_file.txt > output_file.txt

How do I run a docker instance from a DockerFile?

Download the file and from the same directory run docker build -t nodebb .

This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb (you can change nodebb to your own name).

Is it better to use "is" or "==" for number comparison in Python?

Use ==.

Sometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is (in CPython implementations for instance). But don't rely on this or use it in real programs.

How to validate phone numbers using regex

Although the answer to strip all whitespace is neat, it doesn't really solve the problem that's posed, which is to find a regex. Take, for instance, my test script that downloads a web page and extracts all phone numbers using the regex. Since you'd need a regex anyway, you might as well have the regex do all the work. I came up with this:

1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?

Here's a perl script to test it. When you match, $1 contains the area code, $2 and $3 contain the phone number, and $5 contains the extension. My test script downloads a file from the internet and prints all the phone numbers in it.

#!/usr/bin/perl

my $us_phone_regex =
        '1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?';


my @tests =
(
"1-234-567-8901",
"1-234-567-8901 x1234",
"1-234-567-8901 ext1234",
"1 (234) 567-8901",
"1.234.567.8901",
"1/234/567/8901",
"12345678901",
"not a phone number"
);

foreach my $num (@tests)
{
        if( $num =~ m/$us_phone_regex/ )
        {
                print "match [$1-$2-$3]\n" if not defined $4;
                print "match [$1-$2-$3 $5]\n" if defined $4;
        }
        else
        {
                print "no match [$num]\n";
        }
}

#
# Extract all phone numbers from an arbitrary file.
#
my $external_filename =
        'http://web.textfiles.com/ezines/PHREAKSANDGEEKS/PnG-spring05.txt';
my @external_file = `curl $external_filename`;
foreach my $line (@external_file)
{
        if( $line =~ m/$us_phone_regex/ )
        {
                print "match $1 $2 $3\n";
        }
}

Edit:

You can change \W* to \s*\W?\s* in the regex to tighten it up a bit. I wasn't thinking of the regex in terms of, say, validating user input on a form when I wrote it, but this change makes it possible to use the regex for that purpose.

'1?\s*\W?\s*([2-9][0-8][0-9])\s*\W?\s*([2-9][0-9]{2})\s*\W?\s*([0-9]{4})(\se?x?t?(\d*))?';

HttpGet with HTTPS : SSLPeerUnverifiedException

Using HttpClient 3.x, you need to do this:

Protocol easyHttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", easyHttps);

An implementation of EasySSLProtocolSocketFactory can be found here.

How to increase number of threads in tomcat thread pool?

Sounds like you should stay with the defaults ;-)

Seriously: The number of maximum parallel connections you should set depends on your expected tomcat usage and also on the number of cores on your server. More cores on your processor => more parallel threads that can be executed.

See here how to configure...

Tomcat 9: https://tomcat.apache.org/tomcat-9.0-doc/config/executor.html

Tomcat 8: https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html

Tomcat 7: https://tomcat.apache.org/tomcat-7.0-doc/config/executor.html

Tomcat 6: https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html

JPA: how do I persist a String into a database field, type MYSQL Text

With @Lob I always end up with a LONGTEXTin MySQL.

To get TEXT I declare it that way (JPA 2.0):

@Column(columnDefinition = "TEXT")
private String text

Find this better, because I can directly choose which Text-Type the column will have in database.

For columnDefinition it is also good to read this.

EDIT: Please pay attention to Adam Siemions comment and check the database engine you are using, before applying columnDefinition = "TEXT".

Python loop for inside lambda

Just in case, if someone is looking for a similar problem...

Most solutions given here are one line and are quite readable and simple. Just wanted to add one more that does not need the use of lambda(I am assuming that you are trying to use lambda just for the sake of making it a one line code). Instead, you can use a simple list comprehension.

[print(i) for i in x]

BTW, the return values will be a list on None s.

Turn a simple socket into an SSL socket

For others like me:

There was once an example in the SSL source in the directory demos/ssl/ with example code in C++. Now it's available only via the history: https://github.com/openssl/openssl/tree/691064c47fd6a7d11189df00a0d1b94d8051cbe0/demos/ssl

You probably will have to find a working version, I originally posted this answer at Nov 6 2015. And I had to edit the source -- not much.

Certificates: .pem in demos/certs/apps/: https://github.com/openssl/openssl/tree/master/demos/certs/apps

How to block until an event is fired in c#

If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.

    TaskCompletionSource<bool> tcs = null;

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        tcs = new TaskCompletionSource<bool>();
        await tcs.Task;
        WelcomeTitle.Text = "Finished work";
    }

    private void Button_Click2(object sender, RoutedEventArgs e)
    {
        tcs?.TrySetResult(true);
    }

This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change

await tcs.Task;

to

await Task.WhenAny(tcs.Task, Task.Delay(25000));
if (tcs.Task.IsCompleted)
    WelcomeTitle.Text = "Task Completed";
else
    WelcomeTitle.Text = "Task Timed Out";

Best practice for Django project working directory structure

As per the Django Project Skeleton, the proper directory structure that could be followed is :

[projectname]/                  <- project root
+-- [projectname]/              <- Django root
¦   +-- __init__.py
¦   +-- settings/
¦   ¦   +-- common.py
¦   ¦   +-- development.py
¦   ¦   +-- i18n.py
¦   ¦   +-- __init__.py
¦   ¦   +-- production.py
¦   +-- urls.py
¦   +-- wsgi.py
+-- apps/
¦   +-- __init__.py
+-- configs/
¦   +-- apache2_vhost.sample
¦   +-- README
+-- doc/
¦   +-- Makefile
¦   +-- source/
¦       +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦   +-- media/
¦   ¦   +-- README
¦   +-- README
¦   +-- static/
¦       +-- README
+-- static/
¦   +-- README
+-- templates/
    +-- base.html
    +-- core
    ¦   +-- login.html
    +-- README

Refer https://django-project-skeleton.readthedocs.io/en/latest/structure.html for the latest directory structure.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

How do I select between the 1st day of the current month and current day in MySQL?

A less orthodox approach might be

SELECT * FROM table_name 
WHERE LEFT(table_name.date, 7) = LEFT(CURDATE(), 7)
  AND table_name.date <= CURDATE();

as a date being between the first of a month and now is equivalent to a date being in this month, and before now. I do feel that this is a bit easier on the eyes than some other approaches, though.

Reference jars inside a jar

Add the jar files to your library(if using netbeans) and modify your manifest's file classpath as follows:

Class-Path: lib/derby.jar lib/derbyclient.jar lib/derbynet.jar lib/derbytools.jar

a similar answer exists here

Experimental decorators warning in TypeScript compilation

Not to belabor the point but be sure to add the following to

  • Workspace Settings not User Settings

under File >> Preferences >> Settings

"javascript.implicitProjectConfig.experimentalDecorators": true

this fixed the issue for me, and i tried quite a few suggestions i found here and other places.

Setting a timeout for socket operations

Use the Socket() constructor, and connect(SocketAddress endpoint, int timeout) method instead.

In your case it would look something like:

Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);

Quoting from the documentation

connect

public void connect(SocketAddress endpoint, int timeout) throws IOException

Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.

Parameters:

endpoint - the SocketAddress
timeout - the timeout value to be used in milliseconds.

Throws:

IOException - if an error occurs during the connection
SocketTimeoutException - if timeout expires before connecting
IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode
IllegalArgumentException - if endpoint is null or is a SocketAddress subclass not supported by this socket

Since: 1.4

Detect if string contains any spaces

var string  = 'hello world';
var arr = string.split(''); // converted the string to an array and then checked: 
if(arr[i] === ' '){
   console.log(i);
}

I know regex can do the trick too!

Java: Calling a super method which calls an overridden method

Since the only way to avoid a method to get overriden is to use the keyword super, I've thought to move up the method2() from SuperClass to another new Base class and then call it from SuperClass:

class Base 
{
    public void method2()
    {
        System.out.println("superclass method2");
    }
}

class SuperClass extends Base
{
    public void method1()
    {
        System.out.println("superclass method1");
        super.method2();
    }
}

class SubClass extends SuperClass
{
    @Override
    public void method1()
    {
        System.out.println("subclass method1");
        super.method1();
    }

    @Override
    public void method2()
    {
        System.out.println("subclass method2");
    }
}

public class Demo 
{
    public static void main(String[] args) 
    {
        SubClass mSubClass = new SubClass();
        mSubClass.method1();
    }
}

Output:

subclass method1
superclass method1
superclass method2

Class file for com.google.android.gms.internal.zzaja not found

Use:

compile 'com.google.firebase:firebase-auth:11.0.4'

This works.

Spring Boot - Handle to Hibernate SessionFactory

If it's really required to access SessionFactory through @Autowire, I'd rather configure another EntityManagerFactory and then use it to configure the SessionFactory bean, like following:

@Configuration
public class SessionFactoryConfig {

@Autowired 
DataSource dataSource;

@Autowired
JpaVendorAdapter jpaVendorAdapter;

@Bean
@Primary
public EntityManagerFactory entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource);
    emf.setJpaVendorAdapter(jpaVendorAdapter);
    emf.setPackagesToScan("com.hibernateLearning");
    emf.setPersistenceUnitName("default");
    emf.afterPropertiesSet();
    return emf.getObject();
}

@Bean
public SessionFactory setSessionFactory(EntityManagerFactory entityManagerFactory) {
    return entityManagerFactory.unwrap(SessionFactory.class);
} }

How to expand a list to function arguments in Python

It exists, but it's hard to search for. I think most people call it the "splat" operator.

It's in the documentation as "Unpacking argument lists".

You'd use it like this: foo(*values). There's also one for dictionaries:

d = {'a': 1, 'b': 2}
def foo(a, b):
    pass
foo(**d)

How do I kill a VMware virtual machine that won't die?

If you're on linux then you can grab the guest processes with

ps axuw | grep vmware-vmx

As @Dubas pointed out, you should be able to pick out the errant process by the path name to the VMD

Is there a way to specify a max height or width for an image?

If you only specify either the height or the width, but not both, most browsers will honor the aspect ratio.

Because you are working with an ASP.NET server control, you may consider executing logic on the server side prior to rendering to decide which (height or width) attribute you want to specify; that is, if you want a fixed height under one condition or a fixed width under another.

Why can templates only be implemented in the header file?

That is exactly correct because the compiler has to know what type it is for allocation. So template classes, functions, enums,etc.. must be implemented as well in the header file if it is to be made public or part of a library (static or dynamic) because header files are NOT compiled unlike the c/cpp files which are. If the compiler doesn't know the type is can't compile it. In .Net it can because all objects derive from the Object class. This is not .Net.

Multiline strings in VB.NET

I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.

You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.

Dim script As String = <code><![CDATA[
  <script type="text/javascript">
    var URL = ']]><%= domain %><![CDATA[/mypage.html';
  </script>]]>
</code>.value

UITableView - scroll to the top

func scrollToTop() {
        NSIndexPath *topItem = [NSIndexPath indexPathForItem:0 inSection:0];
        [tableView scrollToRowAtIndexPath:topItem atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

call this function wherever you want UITableView scroll to top

The application may be doing too much work on its main thread

Optimize your images ... Dont use images larger than 100KB ... Image loading takes too much CPU and cause your app hangs .

How do I upgrade the Python installation in Windows 10?

Every minor version of Python, that is any 3.x and 2.x version, will install side-by-side with other versions on your computer. Only patch versions will upgrade existing installations.

So if you want to keep your installed Python 2.7 around, then just let it and install a new version using the installer. If you want to get rid of Python 2.7, you can uninstall it before or after installing a newer version—there is no difference to this.

Current Python 3 installations come with the py.exe launcher, which by default is installed into the system directory. This makes it available from the PATH, so you can automatically run it from any shell just by using py instead of python as the command. This avoids you having to put the current Python installation into PATH yourself. That way, you can easily have multiple Python installations side-by-side without them interfering with each other. When running, just use py script.py instead of python script.py to use the launcher. You can also specify a version using for example py -3 or py -3.6 to launch a specific version, otherwise the launcher will use the current default (which will usually be the latest 3.x).

Using the launcher, you can also run Python 2 scripts (which are often syntax incompatible to Python 3), if you decide to keep your Python 2.7 installation. Just use py -2 script.py to launch a script.


As for PyPI packages, every Python installation comes with its own folder where modules are installed into. So if you install a new version and you want to use modules you installed for a previous version, you will have to install them first for the new version. Current versions of the installer also offer you to install pip; it’s enabled by default, so you already have pip for every installation. Unless you explicitly add a Python installation to the PATH, you cannot just use pip though. Luckily, you can also simply use the py.exe launcher for this: py -m pip runs pip. So for example to install Beautiful Soup for Python 3.6, you could run py -3.6 -m pip install beautifulsoup4.

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

Go to

Tools > Android > (Uncheck) Enable ADB Integration (if studio hangs/gets stuck end adb process manually)

then,

Tools > Android > (Check) Enable ADB Integration

Safely override C++ virtual functions

As far as I know, can't you just make it abstract?

class parent {
public:
  virtual void handle_event(int something) const = 0 {
    // boring default code
  }
};

I thought I read on www.parashift.com that you can actually implement an abstract method. Which makes sense to me personally, the only thing it does is force subclasses to implement it, no one said anything about it not being allowed to have an implementation itself.

How to convert a string with comma-delimited items to a list in Python?

Example 1

>>> email= "[email protected]"
>>> email.split()
#OUTPUT
["[email protected]"]

Example 2

>>> email= "[email protected], [email protected]"
>>> email.split(',')
#OUTPUT
["[email protected]", "[email protected]"]

Can I change the height of an image in CSS :before/:after pseudo-elements?

Adjusting the background-size is permitted. You still need to specify width and height of the block, however.

.pdflink:after {
    background-image: url('/images/pdf.png');
    background-size: 10px 20px;
    display: inline-block;
    width: 10px; 
    height: 20px;
    content:"";
}

See the full Compatibility Table at the MDN.

Java for loop syntax: "for (T obj : objects)"

yes... This is for each loop in java.

Generally this loop is become useful when you are retrieving data or object from the database.

Syntex :

for(Object obj : Collection obj)
{
     //Code enter code here
}

Example :

for(User user : userList)
{
     System.out.println("USer NAme :" + user.name);
   // etc etc
}

This is for each loop.

it will incremental by automatically. one by one from collection to USer object data has been filled. and working.

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Where can I get a list of Ansible pre-defined variables?

The debug module can be used to analyze variables. Be careful running the following command. In our setup it generates 444709 lines with 16MB:

ansible -m debug -a 'var=hostvars' localhost

I am not sure but it might be necessary to enable facts caching.

If you need just one host use the host name as a key for the hostvars hash:

ansible -m debug -a 'var=hostvars.localhost' localhost

This command will display also group and host variables.

git: Your branch is ahead by X commits

Someone said you might be misreading your message, you aren't. This issue actually has to do with your <project>/.git/config file. In it will be a section similar to this:

[remote "origin"]
    url = <url>
    fetch = +refs/heads/*:refs/remotes/origin/*

If you remove the fetch line from your project's .git/config file you'll stop the "Your branch is ahead of 'origin/master' by N commits." annoyance from occurring.

Or so I hope. :)

How do I redirect to another webpage?

JavaScript is very extensive. If you want to jump to another page you have three options.

 window.location.href='otherpage.com';
 window.location.assign('otherpage.com');
 //and...

 window.location.replace('otherpage.com');

As you want to move to another page, you can use any from these if this is your requirement. However all three options are limited to different situations. Chose wisely according to your requirement.

If you are interested in more knowledge about the concept, you can go through further.

window.location.href; returns the href (URL) of the current page
window.location.hostname; returns the domain name of the web host
window.location.pathname; returns the path and filename of the current page
window.location.protocol; returns the web protocol used (http: or https:)
window.location.assign; loads a new document
window.location.replace; Replace the current location with new one.

Docker - Container is not running

In my case , i changed certain file names and directory names of the parent directory of the Dockerfile . Due to which container not finding the required parameters to start it again.

After renaming it back to the original names, container started like butter.

HTML: Image won't display?

If you put <img src="iwojimaflag.jpg"/> in html code then place iwojimaflag.jpg and html file in same folder.

If you put <img src="images/iwojimaflag.jpg"/> then you must create "images" folder and put image iwojimaflag.jpg in that folder.

How can I remove a substring from a given String?

You can also use guava's CharMatcher.removeFrom function.

Example:

 String s = CharMatcher.is('a').removeFrom("bazaar");

android listview item height

Here is my solutions; It is my getView() in BaseAdapter subclass:

public View getView(int position, View convertView, ViewGroup parent)
{
    if(convertView==null)
    {
        convertView=inflater.inflate(R.layout.list_view, parent,false);
        System.out.println("In");
    }
    convertView.setMinimumHeight(100);
    return convertView;
}

Here i have set ListItem's minimum height to 100;

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

Difference between Hive internal tables and external tables?

For managed tables, Hive controls the lifecycle of their data. Hive stores the data for managed tables in a sub-directory under the directory defined by hive.metastore.warehouse.dir by default.

When we drop a managed table, Hive deletes the data in the table.But managed tables are less convenient for sharing with other tools. For example, lets say we have data that is created and used primarily by Pig , but we want to run some queries against it, but not give Hive ownership of the data.

At that time, external table is defined that points to that data, but doesn’t take ownership of it.

How to get text from each cell of an HTML table?

I have not used Selenium 2. Selenium 1.x has selenium.getTable("tablename".columnNumber.rowNumber) to reach the required cell. May be you can use webdriverbackedselenium and do this.

And you can get the total rows and columns by using

int numOfRows = selenium.getXpathCount("//table[@id='tableid']//tr")

int numOfCols=selenium.getXpathCount("//table[@id='tableid']//tr//td")

What is .htaccess file?

You are allow to use php_value to change php setting in .htaccess file. Same like how php.ini did.

Example:

php_value date.timezone Asia/Kuala_Lumpur

For other php setting, please read http://www.php.net/manual/en/ini.list.php

Show a child form in the centre of Parent form in C#

You can set the StartPosition in the constructor of the child form so that all new instances of the form get centered to it's parent:

public MyForm()
{
    InitializeComponent();

    this.StartPosition = FormStartPosition.CenterParent;
}

Of course, you could also set the StartPosition property in the Designer properties for your child form. When you want to display the child form as a modal dialog, just set the window owner in the parameter for the ShowDialog method:

private void buttonShowMyForm_Click(object sender, EventArgs e)
{
    MyForm form = new MyForm();
    form.ShowDialog(this);
}

How to find the maximum value in an array?

Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

Because it's not actually a dictionary; it's another mapping type that looks like a dictionary. Use type() to verify. Pass it to dict() to get a real dictionary from it.

call a function in success of datatable ajax call

The success option of ajax should not be altered because DataTables uses it internally to execute the table draw when the data load is complete. The recommendation is used "dataSrc" to alter the received data.

Java : Accessing a class within a package, which is the better way?

There is no performance difference between importing the package or using the fully qualified class name. The import directive is not converted to Java byte code, consequently there is no effect on runtime performance. The only difference is that it saves you time in case you are using the imported class multiple times. This is a good read here

How to add element in List while iterating in java?

Just iterate the old-fashion way, because you need explicit index handling:

List myList = ...
...
int length = myList.size();
for(int i = 0; i < length; i++) {
   String s = myList.get(i);
   // add items here, if you want to
}

Box shadow for bottom side only

You have to specify negative spread in the box shadow to remove side shadow

-webkit-box-shadow: 0 10px 10px -10px #000000;
   -moz-box-shadow: 0 10px 10px -10px #000000;
        box-shadow: 0 10px 10px -10px #000000;

Check out http://dabblet.com/gist/9532817 and try changing properties and know how it behaves

jQuery .slideRight effect

If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide(), with additional arguments, as follows:

$(document).ready(
    function(){
        $('#slider').click(
            function(){
                $(this).hide('slide',{direction:'right'},1000);

            });
    });

JS Fiddle demo.


Without using jQuery UI, you could achieve your aim just using animate():

$(document).ready(
    function(){
        $('#slider').click(
            function(){
                $(this)
                    .animate(
                        {
                            'margin-left':'1000px'
                            // to move it towards the right and, probably, off-screen.
                        },1000,
                        function(){
                            $(this).slideUp('fast');
                            // once it's finished moving to the right, just 
                            // removes the the element from the display, you could use
                            // `remove()` instead, or whatever.
                        }
                        );

            });
    });

JS Fiddle demo

If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js

Changing the current working directory in Java?

The other possible answer to this question may depend on the reason you are opening the file. Is this a property file or a file that has some configuration related to your application?

If this is the case you may consider trying to load the file through the classpath loader, this way you can load any file Java has access to.

Using async/await with a forEach loop

This solution is also memory-optimized so you can run it on 10,000's of data items and requests. Some of the other solutions here will crash the server on large data sets.

In TypeScript:

export async function asyncForEach<T>(array: Array<T>, callback: (item: T, index: number) => void) {
        for (let index = 0; index < array.length; index++) {
            await callback(array[index], index);
        }
    }

How to use?

await asyncForEach(receipts, async (eachItem) => {
    await ...
})

What is makeinfo, and how do I get it?

In (at least) Ubuntu when using bash, it tells you what package you need to install if you type in a command and its not found in your path. My terminal says you need to install 'texinfo' package.

sudo apt-get install texinfo

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

How to add a ScrollBar to a Stackpanel

Stackpanel doesn't have built in scrolling mechanism but you can always wrap the StackPanel in a ScrollViewer

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <StackPanel ... />
</ScrollViewer>

How can I present a file for download from an MVC controller?

Return a FileResult or FileStreamResult from your action, depending on whether the file exists or you create it on the fly.

public ActionResult GetPdf(string filename)
{
    return File(filename, "application/pdf", Server.UrlEncode(filename));
}

TS1086: An accessor cannot be declared in ambient context

I got the same issue when adding @angular/flex-layout to my Angular 8 project now with

`npm install @angular/flex-layout --save`.

This since now that command installed the major 9th version of the flex-layout package. Instead of upgrading everything else to the last version, I solved it by installing the last 8th major version of the package instead.

 npm install @angular/[email protected] --save

How to remove carriage return and newline from a variable in shell script

for a pure shell solution without calling external program:

NL=$'\n'    # define a variable to reference 'newline'

testVar=${testVar%$NL}    # removes trailing 'NL' from string

Scrolling to an Anchor using Transition/CSS3

I implemented the answer suggested by @user18490 but ran into two problems:

  • First bouncing when user clicks on several tabs/links multiple times in short succession
  • Second, the undefined error mentioned by @krivar

I developed the following class to get around the mentioned problems, and it works fine:

export class SScroll{
    constructor(){
        this.delay=501      //ms
        this.duration=500   //ms
        this.lastClick=0
    }

    lastClick
    delay
    duration

    scrollTo=(destID)=>{
        /* To prevent "bounce" */
        /* https://stackoverflow.com/a/28610565/3405291 */
        if(this.lastClick>=(Date.now()-this.delay)){return}
        this.lastClick=Date.now()

        const dest=document.getElementById(destID)
        const to=dest.offsetTop
        if(document.body.scrollTop==to){return}
        const diff=to-document.body.scrollTop
        const scrollStep=Math.PI / (this.duration/10)
        let count=0
        let currPos
        const start=window.pageYOffset
        const scrollInterval=setInterval(()=>{
            if(document.body.scrollTop!=to){
                count++
                currPos=start+diff*(.5-.5*Math.cos(count*scrollStep))
                document.body.scrollTop=currPos
            }else{clearInterval(scrollInterval)}
        },10)
    }
}

UPDATE

There is a problem with Firefox as mentioned here. Therefore, to make it work on Firefox, I implemented the following code. It works fine on Chromium-based browsers and also Firefox.

export class SScroll{
    constructor(){
        this.delay=501      //ms
        this.duration=500   //ms
        this.lastClick=0
    }
    lastClick
    delay
    duration
    scrollTo=(destID)=>{
        /* To prevent "bounce" */
        /* https://stackoverflow.com/a/28610565/3405291 */
        if(this.lastClick>=(Date.now()-this.delay)){return}

        this.lastClick=Date.now()
        const dest=document.getElementById(destID)
        const to=dest.offsetTop
        if((document.body.scrollTop || document.documentElement.scrollTop || 0)==to){return}

        const diff=to-(document.body.scrollTop || document.documentElement.scrollTop || 0)
        const scrollStep=Math.PI / (this.duration/10)
        let count=0
        let currPos
        const start=window.pageYOffset
        const scrollInterval=setInterval(()=>{
            if((document.body.scrollTop || document.documentElement.scrollTop || 0)!=to){
                count++
                currPos=start+diff*(.5-.5*Math.cos(count*scrollStep))
                /* https://stackoverflow.com/q/28633221/3405291 */
                /* To support both Chromium-based and Firefox */
                document.body.scrollTop=currPos
                document.documentElement.scrollTop=currPos
            }else{clearInterval(scrollInterval)}
        },10)
    }
}

Autoreload of modules in IPython

You can use:

  import ipy_autoreload
  %autoreload 2 
  %aimport your_mod

Add context path to Spring Boot application

please note that the "server.context-path" or "server.servlet.context-path" [starting from springboot 2.0.x] properties will only work if you are deploying to an embedded container e.g., embedded tomcat. These properties will have no effect if you are deploying your application as a war to an external tomcat for example.

see this answer here: https://stackoverflow.com/a/43856300/4449859

With ng-bind-html-unsafe removed, how do I inject HTML?

You indicated that you're using Angular 1.2.0... as one of the other comments indicated, ng-bind-html-unsafe has been deprecated.

Instead, you'll want to do something like this:

<div ng-bind-html="preview_data.preview.embed.htmlSafe"></div>

In your controller, inject the $sce service, and mark the HTML as "trusted":

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
  // ...
  $scope.preview_data.preview.embed.htmlSafe = 
     $sce.trustAsHtml(preview_data.preview.embed.html);
}

Note that you'll want to be using 1.2.0-rc3 or newer. (They fixed a bug in rc3 that prevented "watchers" from working properly on trusted HTML.)

How do I find which process is leaking memory?

I suggest the use of htop, as a better alternative to top.

Amazon AWS Filezilla transfer permission denied

In my case, after 30 minutes changing permissions, got into account that the XLSX file I was trying to transfer was still open in Excel.

Bootstrap dropdown not working

I had a similar issue only to observe that i had added the bootstrap script twice and the second bootstrap script was after above the jquery script.

Solution:

  • Ensure that bootstrap.min.js and jquery.min.js are only included once in your file.
  • The bootstrap.min.js script should be included after jquery.min.js

Using CMake with GNU Make: How can I see the exact commands?

cmake --build . --verbose

On Linux and with Makefile generation, this is likely just calling make VERBOSE=1 under the hood, but cmake --build can be more portable for your build system, e.g. working across OSes or if you decide to do e.g. Ninja builds later on:

mkdir build
cd build
cmake ..
cmake --build . --verbose

Its documentation also suggests that it is equivalent to VERBOSE=1:

--verbose, -v

Enable verbose output - if supported - including the build commands to be executed.

This option can be omitted if VERBOSE environment variable or CMAKE_VERBOSE_MAKEFILE cached variable is set.

Can I convert a C# string value to an escaped string literal

I submit my own implementation, which handles null values and should be more performant on account of using array lookup tables, manual hex conversion, and avoiding switch statements.

using System;
using System.Text;
using System.Linq;

public static class StringLiteralEncoding {
  private static readonly char[] HEX_DIGIT_LOWER = "0123456789abcdef".ToCharArray();
  private static readonly char[] LITERALENCODE_ESCAPE_CHARS;

  static StringLiteralEncoding() {
    // Per http://msdn.microsoft.com/en-us/library/h21280bw.aspx
    var escapes = new string[] { "\aa", "\bb", "\ff", "\nn", "\rr", "\tt", "\vv", "\"\"", "\\\\", "??", "\00" };
    LITERALENCODE_ESCAPE_CHARS = new char[escapes.Max(e => e[0]) + 1];
    foreach(var escape in escapes)
      LITERALENCODE_ESCAPE_CHARS[escape[0]] = escape[1];
  }

  /// <summary>
  /// Convert the string to the equivalent C# string literal, enclosing the string in double quotes and inserting
  /// escape sequences as necessary.
  /// </summary>
  /// <param name="s">The string to be converted to a C# string literal.</param>
  /// <returns><paramref name="s"/> represented as a C# string literal.</returns>
  public static string Encode(string s) {
    if(null == s) return "null";

    var sb = new StringBuilder(s.Length + 2).Append('"');
    for(var rp = 0; rp < s.Length; rp++) {
      var c = s[rp];
      if(c < LITERALENCODE_ESCAPE_CHARS.Length && '\0' != LITERALENCODE_ESCAPE_CHARS[c])
        sb.Append('\\').Append(LITERALENCODE_ESCAPE_CHARS[c]);
      else if('~' >= c && c >= ' ')
        sb.Append(c);
      else
        sb.Append(@"\x")
          .Append(HEX_DIGIT_LOWER[c >> 12 & 0x0F])
          .Append(HEX_DIGIT_LOWER[c >>  8 & 0x0F])
          .Append(HEX_DIGIT_LOWER[c >>  4 & 0x0F])
          .Append(HEX_DIGIT_LOWER[c       & 0x0F]);
    }

    return sb.Append('"').ToString();
  }
}

Get domain name from given url

I wrote a method (see below) which extracts a url's domain name and which uses simple String matching. What it actually does is extract the bit between the first "://" (or index 0 if there's no "://" contained) and the first subsequent "/" (or index String.length() if there's no subsequent "/"). The remaining, preceding "www(_)*." bit is chopped off. I'm sure there'll be cases where this won't be good enough but it should be good enough in most cases!

Mike Samuel's post above says that the java.net.URI class could do this (and was preferred to the java.net.URL class) but I encountered problems with the URI class. Notably, URI.getHost() gives a null value if the url does not include the scheme, i.e. the "http(s)" bit.

/**
 * Extracts the domain name from {@code url}
 * by means of String manipulation
 * rather than using the {@link URI} or {@link URL} class.
 *
 * @param url is non-null.
 * @return the domain name within {@code url}.
 */
public String getUrlDomainName(String url) {
  String domainName = new String(url);

  int index = domainName.indexOf("://");

  if (index != -1) {
    // keep everything after the "://"
    domainName = domainName.substring(index + 3);
  }

  index = domainName.indexOf('/');

  if (index != -1) {
    // keep everything before the '/'
    domainName = domainName.substring(0, index);
  }

  // check for and remove a preceding 'www'
  // followed by any sequence of characters (non-greedy)
  // followed by a '.'
  // from the beginning of the string
  domainName = domainName.replaceFirst("^www.*?\\.", "");

  return domainName;
}

Regex how to match an optional character

You have to mark the single letter as optional too:

([A-Z]{1})? +.*? +

or make the whole part optional

(([A-Z]{1}) +.*? +)?

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

JavaScript editor within Eclipse

Eclipse HTML Editor Plugin

I too have struggled with this totally obvious question. It seemed crazy that this wasn't an extremely easy-to-find feature with all the web development happening in Eclipse these days.

I was very turned off by Aptana because of how bloated it is, and the fact that it starts up a local web server (by default on port 8000) everytime you start Eclipse and you can't disable this functionality. Adobe's port of JSEclipse is now a 400Mb plugin, which is equally insane.

However, I just found a super-lightweight JavaScript editor called Eclipse HTML Editor Plugin, made by Amateras, which was exactly what I was looking for.

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

Put the code that you want executed after the delay within the setTimeout callback:

console.log('Welcome to My Console,');
setTimeout(function() {
    console.log('Blah blah blah blah extra-blah');
}, 3000);

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

Does Visual Studio have code coverage for unit tests?

As already mentioned you can use Fine Code Coverage that visualize coverlet output. If you create a xunit test project (dotnet new xunit) you'll find coverlet reference already present in csproj file because Coverlet is the default coverage tool for every .NET Core and >= .NET 5 applications.

Microsoft has an example using ReportGenerator that converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.

Example report:

enter image description here

While the article focuses on C# and xUnit as the test framework, both MSTest and NUnit would also work.

Guide:

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports

If you want code coverage in .xml files you can run any of these commands:

dotnet test --collect:"XPlat Code Coverage"

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

It is not possible to restore a preventDefault() but what you can do is trick it :)

<div id="t1">Toggle</div>
<script type="javascript">
$('#t1').click(function (e){
   if($(this).hasClass('prevented')){
       e.preventDefault();
       $(this).removeClass('prevented');
   }else{
       $(this).addClass('prevented');
   }
});
</script>

If you want to go a step further you can even use the trigger button to trigger an event.

How to place the ~/.composer/vendor/bin directory in your PATH?

I did this and it works on osx:

lunch your terminal

 nano ~/.bash_profile 

And paste

 export PATH=~/.composer/vendor/bin:$PATH

press control + x

press the y key

press the return / enter key

How to locate the Path of the current project directory in Java (IDE)?

This is the new way to do it:

Path root = FileSystems.getDefault().getPath("").toAbsolutePath();
Path filePath = Paths.get(root.toString(),"src", "main", "resources", fileName);

Or even better:

Path root = Paths.get(".").normalize().toAbsolutePath();

But I would take it one step further:

public String getUsersProjectRootDirectory() {
    String envRootDir = System.getProperty("user.dir");
    Path rootDIr = Paths.get(".").normalize().toAbsolutePath();
    if ( rootDir.startsWith(envRootDir) ) {
        return rootDir;
    } else {
        throw new RuntimeException("Root dir not found in user directory.");
    }
}

Python Git Module experiences?

For the sake of completeness, http://github.com/alex/pyvcs/ is an abstraction layer for all dvcs's. It uses dulwich, but provides interop with the other dvcs's.

jQuery get specific option tag text

If you'd like to get the option with a value of 2, use

$("#list option[value='2']").text();

If you'd like to get whichever option is currently selected, use

$("#list option:selected").text();

Python Decimals format

Here's a function that will do the trick:

def myformat(x):
    return ('%.2f' % x).rstrip('0').rstrip('.')

And here are your examples:

>>> myformat(1.00)
'1'
>>> myformat(1.20)
'1.2'
>>> myformat(1.23)
'1.23'
>>> myformat(1.234)
'1.23'
>>> myformat(1.2345)
'1.23'

Edit:

From looking at other people's answers and experimenting, I found that g does all of the stripping stuff for you. So,

'%.3g' % x

works splendidly too and is slightly different from what other people are suggesting (using '{0:.3}'.format() stuff). I guess take your pick.

Applying styles to tables with Twitter Bootstrap

Just another good looking table. I added "table-hover" class because it gives a nice hovering effect.

   <h3>NATO Phonetic Alphabet</h3>    
   <table class="table table-striped table-bordered table-condensed table-hover">
   <thead>
    <tr> 
        <th>Letter</th>
        <th>Phonetic Letter</th>

    </tr>
    </thead>
  <tr>
    <th>A</th>
    <th>Alpha</th>

  </tr>
  <tr>
    <td>B</td>
    <td>Bravo</td>

  </tr>
  <tr>
    <td>C</td>
    <td>Charlie</td>

  </tr>

</table>

Creating your own header file in C

header files contain prototypes for functions you define in a .c or .cpp/.cxx file (depending if you're using c or c++). You want to place #ifndef/#defines around your .h code so that if you include the same .h twice in different parts of your programs, the prototypes are only included once.

client.h

#ifndef CLIENT_H
#define CLIENT_H

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);


#endif /** CLIENT_H */

Then you'd implement the .h in a .c file like so:

client.c

#include "client.h"

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
 short ret = -1;
 //some implementation here
 return ret;
}

What is the C# version of VB.net's InputDialog?

Returns the string the user entered; empty string if they hit Cancel:

    public static String InputBox(String caption, String prompt, String defaultText)
    {
        String localInputText = defaultText;
        if (InputQuery(caption, prompt, ref localInputText))
        {
            return localInputText;
        }
        else
        {
            return "";
        }
    }

Returns the String as a ref parameter, returning true if they hit OK, or false if they hit Cancel:

    public static Boolean InputQuery(String caption, String prompt, ref String value)
    {
        Form form;
        form = new Form();
        form.AutoScaleMode = AutoScaleMode.Font;
        form.Font = SystemFonts.IconTitleFont;

        SizeF dialogUnits;
        dialogUnits = form.AutoScaleDimensions;

        form.FormBorderStyle = FormBorderStyle.FixedDialog;
        form.MinimizeBox = false;
        form.MaximizeBox = false;
        form.Text = caption;

        form.ClientSize = new Size(
                    Toolkit.MulDiv(180, dialogUnits.Width, 4),
                    Toolkit.MulDiv(63, dialogUnits.Height, 8));

        form.StartPosition = FormStartPosition.CenterScreen;

        System.Windows.Forms.Label lblPrompt;
        lblPrompt = new System.Windows.Forms.Label();
        lblPrompt.Parent = form;
        lblPrompt.AutoSize = true;
        lblPrompt.Left = Toolkit.MulDiv(8, dialogUnits.Width, 4);
        lblPrompt.Top = Toolkit.MulDiv(8, dialogUnits.Height, 8);
        lblPrompt.Text = prompt;

        System.Windows.Forms.TextBox edInput;
        edInput = new System.Windows.Forms.TextBox();
        edInput.Parent = form;
        edInput.Left = lblPrompt.Left;
        edInput.Top = Toolkit.MulDiv(19, dialogUnits.Height, 8);
        edInput.Width = Toolkit.MulDiv(164, dialogUnits.Width, 4);
        edInput.Text = value;
        edInput.SelectAll();


        int buttonTop = Toolkit.MulDiv(41, dialogUnits.Height, 8);
        //Command buttons should be 50x14 dlus
        Size buttonSize = Toolkit.ScaleSize(new Size(50, 14), dialogUnits.Width / 4, dialogUnits.Height / 8);

        System.Windows.Forms.Button bbOk = new System.Windows.Forms.Button();
        bbOk.Parent = form;
        bbOk.Text = "OK";
        bbOk.DialogResult = DialogResult.OK;
        form.AcceptButton = bbOk;
        bbOk.Location = new Point(Toolkit.MulDiv(38, dialogUnits.Width, 4), buttonTop);
        bbOk.Size = buttonSize;

        System.Windows.Forms.Button bbCancel = new System.Windows.Forms.Button();
        bbCancel.Parent = form;
        bbCancel.Text = "Cancel";
        bbCancel.DialogResult = DialogResult.Cancel;
        form.CancelButton = bbCancel;
        bbCancel.Location = new Point(Toolkit.MulDiv(92, dialogUnits.Width, 4), buttonTop);
        bbCancel.Size = buttonSize;

        if (form.ShowDialog() == DialogResult.OK)
        {
            value = edInput.Text;
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// Multiplies two 32-bit values and then divides the 64-bit result by a 
    /// third 32-bit value. The final result is rounded to the nearest integer.
    /// </summary>
    public static int MulDiv(int nNumber, int nNumerator, int nDenominator)
    {
        return (int)Math.Round((float)nNumber * nNumerator / nDenominator);
    }

Note: Any code is released into the public domain. No attribution required.

Get selected value/text from Select on change

_x000D_
_x000D_
function test(a) {_x000D_
    var x = (a.value || a.options[a.selectedIndex].value);  //crossbrowser solution =)_x000D_
    alert(x);_x000D_
}
_x000D_
<select onchange="test(this)" id="select_id">_x000D_
    <option value="0">-Select-</option>_x000D_
    <option value="1">Communication</option>_x000D_
    <option value="2">Communication</option>_x000D_
    <option value="3">Communication</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Visual Studio Expand/Collapse keyboard shortcuts

Go to Tools->Options->Text Editor->c#->Advanced and uncheck the first checkbox Enter outlining mode when files open.

This will solve this problem forever

What is http multipart request?

A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.

How to achieve ripple animation using support library?

sometimes will b usable this line on any layout or components.

 android:background="?attr/selectableItemBackground"

Like as.

 <RelativeLayout
                android:id="@+id/relative_ticket_checkin"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="?attr/selectableItemBackground">

How to get all child inputs of a div element (jQuery)

The 'find' method can be used to get all child inputs of a container that has already been cached to save looking it up again (whereas the 'children' method will only get the immediate children). e.g.

var panel= $("#panel");
var inputs = panel.find("input");

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

I needed to have an ImageView and an Bitmap, so the Bitmap is scaled to ImageView size, and size of the ImageView is the same of the scaled Bitmap :).

I was looking through this post for how to do it, and finally did what I want, not the way described here though.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/acpt_frag_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/imageBackground"
android:orientation="vertical">

<ImageView
    android:id="@+id/acpt_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:adjustViewBounds="true"
    android:layout_margin="@dimen/document_editor_image_margin"
    android:background="@color/imageBackground"
    android:elevation="@dimen/document_image_elevation" />

and then in onCreateView method

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_scanner_acpt, null);

    progress = view.findViewById(R.id.progress);

    imageView = view.findViewById(R.id.acpt_image);
    imageView.setImageBitmap( bitmap );

    imageView.getViewTreeObserver().addOnGlobalLayoutListener(()->
        layoutImageView()
    );

    return view;
}

and then layoutImageView() code

private void layoutImageView(){

    float[] matrixv = new float[ 9 ];

    imageView.getImageMatrix().getValues(matrixv);

    int w = (int) ( matrixv[Matrix.MSCALE_X] * bitmap.getWidth() );
    int h = (int) ( matrixv[Matrix.MSCALE_Y] * bitmap.getHeight() );

    imageView.setMaxHeight(h);
    imageView.setMaxWidth(w);

}

And the result is that image fits inside perfectly, keeping aspect ratio, and doesn't have extra leftover pixels from ImageView when the Bitmap is inside.

Result

It's important ImageView to have wrap_content and adjustViewBounds to true, then setMaxWidth and setMaxHeight will work, this is written in the source code of ImageView,

/*An optional argument to supply a maximum height for this view. Only valid if
 * {@link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a
 * maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
 * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width
 * layout params to WRAP_CONTENT. */

java.lang.OutOfMemoryError: Java heap space in Maven

I have solved this problem on my side by 2 ways:

  1. Adding this configuration in pom.xml

    <configuration><argLine>-Xmx1024m</argLine></configuration>
    
  2. Switch to used JDK 1.7 instead of 1.6

How to show current user name in a cell?

if you don't want to create a UDF in VBA or you can't, this could be an alternative.

=Cell("Filename",A1) this will give you the full file name, and from this you could get the user name with something like this:

=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)


This Formula runs only from a workbook saved earlier.

You must start from 4th position because of the first slash from the drive.

Getting the current Fragment instance in the viewpager

I tried the following:

 int index = mViewPager.getCurrentItem();
 List<Fragment> fragments = getSupportFragmentManager().getFragments();
 View rootView = fragments.get(index).getView();

Cleanest way to toggle a boolean variable in Java?

theBoolean ^= true;

Fewer keystrokes if your variable is longer than four letters

Edit: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's bitwise XOR as described here.

What is the difference between <html lang="en"> and <html lang="en-US">?

This should help : http://www.w3.org/International/articles/language-tags/

The golden rule when creating language tags is to keep the tag as short as possible. Avoid region, script or other subtags except where they add useful distinguishing information. For instance, use ja for Japanese and not ja-JP, unless there is a particular reason that you need to say that this is Japanese as spoken in Japan, rather than elsewhere.

The list below shows the various types of subtag that are available. We will work our way through these and how they are used in the sections that follow.

language-extlang-script-region-variant-extension-privateuse

Eclipse reported "Failed to load JNI shared library"

Yep, in Windows 7 64 bit you have C:\Program Files and C:\Program Files (x86). You can find Java folders in both of them, but you must add C:\Program Files\Java\jre7\bin to environment variable PATH.

Jmeter - Run .jmx file through command line and get the summary report in a excel

This worked for me on mac os High sierra 10.13.6, java 8 64-bit, jmeter 4.0

$  jmeter -n --testfile /path/to/Test_Plan.jmx

Sample output:

Creating summariser <summary>
Created the tree successfully using ./src/test/jmeter/Test_Plan.jmx
Starting the test @ Fri Aug 24 17:18:18 PDT 2018 (1535156298333)
Waiting for possible Shutdown/StopTestNow/Heapdump message on port 4445
summary =     10 in 00:00:09 =    1.1/s Avg:  6666 Min:  1000 Max:  8950 Err:     
0 (0.00%)
Tidying up ...    @ Fri Aug 24 17:18:28 PDT 2018 (1535156308049)
... end of run

Posting a File and Associated Data to a RESTful WebService preferably as JSON

FormData Objects: Upload Files Using Ajax

XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.

function AjaxFileUpload() {
    var file = document.getElementById("files");
    //var file = fileInput;
    var fd = new FormData();
    fd.append("imageFileData", file);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", '/ws/fileUpload.do');
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
             alert('success');
        }
        else if (uploadResult == 'success')
             alert('error');
    };
    xhr.send(fd);
}

https://developer.mozilla.org/en-US/docs/Web/API/FormData

SQL Server: how to create a stored procedure

T-SQL

/* 
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/



CREATE  PROCEDURE GetstudentnameInOutputVariable
(

@studentid INT,                   --Input parameter ,  Studentid of the student
@studentname VARCHAR (200) OUT,    -- Output parameter to collect the student name
@StudentEmail VARCHAR (200)OUT     -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname, 
    @StudentEmail=email FROM tbl_Students WHERE studentid=@studentid
END

Fastest way to serialize and deserialize .NET objects

I took the liberty of feeding your classes into the CGbR generator. Because it is in an early stage it doesn't support DateTime yet, so I simply replaced it with long. The generated serialization code looks like this:

public int Size
{
    get 
    { 
        var size = 24;
        // Add size for collections and strings
        size += Cts == null ? 0 : Cts.Count * 4;
        size += Tes == null ? 0 : Tes.Count * 4;
        size += Code == null ? 0 : Code.Length;
        size += Message == null ? 0 : Message.Length;

        return size;              
    }
}

public byte[] ToBytes(byte[] bytes, ref int index)
{
    if (index + Size > bytes.Length)
        throw new ArgumentOutOfRangeException("index", "Object does not fit in array");

    // Convert Cts
    // Two bytes length information for each dimension
    GeneratorByteConverter.Include((ushort)(Cts == null ? 0 : Cts.Count), bytes, ref index);
    if (Cts != null)
    {
        for(var i = 0; i < Cts.Count; i++)
        {
            var value = Cts[i];
            value.ToBytes(bytes, ref index);
        }
    }
    // Convert Tes
    // Two bytes length information for each dimension
    GeneratorByteConverter.Include((ushort)(Tes == null ? 0 : Tes.Count), bytes, ref index);
    if (Tes != null)
    {
        for(var i = 0; i < Tes.Count; i++)
        {
            var value = Tes[i];
            value.ToBytes(bytes, ref index);
        }
    }
    // Convert Code
    GeneratorByteConverter.Include(Code, bytes, ref index);
    // Convert Message
    GeneratorByteConverter.Include(Message, bytes, ref index);
    // Convert StartDate
    GeneratorByteConverter.Include(StartDate.ToBinary(), bytes, ref index);
    // Convert EndDate
    GeneratorByteConverter.Include(EndDate.ToBinary(), bytes, ref index);
    return bytes;
}

public Td FromBytes(byte[] bytes, ref int index)
{
    // Read Cts
    var ctsLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
    var tempCts = new List<Ct>(ctsLength);
    for (var i = 0; i < ctsLength; i++)
    {
        var value = new Ct().FromBytes(bytes, ref index);
        tempCts.Add(value);
    }
    Cts = tempCts;
    // Read Tes
    var tesLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
    var tempTes = new List<Te>(tesLength);
    for (var i = 0; i < tesLength; i++)
    {
        var value = new Te().FromBytes(bytes, ref index);
        tempTes.Add(value);
    }
    Tes = tempTes;
    // Read Code
    Code = GeneratorByteConverter.GetString(bytes, ref index);
    // Read Message
    Message = GeneratorByteConverter.GetString(bytes, ref index);
    // Read StartDate
    StartDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));
    // Read EndDate
    EndDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));

    return this;
}

I created a list of sample objects like this:

var objects = new List<Td>();
for (int i = 0; i < 1000; i++)
{
    var obj = new Td
    {
        Message = "Hello my friend",
        Code = "Some code that can be put here",
        StartDate = DateTime.Now.AddDays(-7),
        EndDate = DateTime.Now.AddDays(2),
        Cts = new List<Ct>(),
        Tes = new List<Te>()
    };
    for (int j = 0; j < 10; j++)
    {
        obj.Cts.Add(new Ct { Foo = i * j });
        obj.Tes.Add(new Te { Bar = i + j });
    }
    objects.Add(obj);
}

Results on my machine in Release build:

var watch = new Stopwatch();
watch.Start();
var bytes = BinarySerializer.SerializeMany(objects);
watch.Stop();

Size: 149000 bytes

Time: 2.059ms 3.13ms

Edit: Starting with CGbR 0.4.3 the binary serializer supports DateTime. Unfortunately the DateTime.ToBinary method is insanely slow. I will replace it with somehting faster soon.

Edit2: When using UTC DateTime by invoking ToUniversalTime() the performance is restored and clocks in at 1.669ms.

ImageView in circular through xml

I use shape = "oval" instead of the "ring" below. It has worked for me. To keep the image within bounds, I use <padding> and set <adjustViewBounds> to true in my <ImageView>. I have tried with images of size between 50 x 50 px upto 200x200 px .

Importing data from a JSON file into R

packages:

  • library(httr)
  • library(jsonlite)

I have had issues converting json to dataframe/csv. For my case I did:

Token <- "245432532532"
source <- "http://......."
header_type <- "applcation/json"
full_token <- paste0("Bearer ", Token)
response <- GET(n_source, add_headers(Authorization = full_token, Accept = h_type), timeout(120), verbose())
text_json <- content(response, type = 'text', encoding = "UTF-8")
jfile <- fromJSON(text_json)
df <- as.data.frame(jfile)

then from df to csv.

In this format it should be easy to convert it to multiple .csvs if needed.

The important part is content function should have type = 'text'.

Skip the headers when editing a csv file using Python

Doing row=1 won't change anything, because you'll just overwrite that with the results of the loop.

You want to do next(reader) to skip one row.

Is there a portable way to get the current username in Python?

For UNIX, at least, this works...

import commands
username = commands.getoutput("echo $(whoami)")
print username

edit: I just looked it up and this works on Windows and UNIX:

import commands
username = commands.getoutput("whoami")

On UNIX it returns your username, but on Windows, it returns your user's group, slash, your username.

--

I.E.

UNIX returns: "username"

Windows returns: "domain/username"

--

It's interesting, but probably not ideal unless you are doing something in the terminal anyway... in which case you would probably be using os.system to begin with. For example, a while ago I needed to add my user to a group, so I did (this is in Linux, mind you)

import os
os.system("sudo usermod -aG \"group_name\" $(whoami)")
print "You have been added to \"group_name\"! Please log out for this to take effect"

I feel like that is easier to read and you don't have to import pwd or getpass.

I also feel like having "domain/user" could be helpful in certain applications in Windows.

modal View controllers - how to display and dismiss

Radu Simionescu - awesome work! and below Your solution for Swift lovers:

@IBAction func showSecondControlerAndCloseCurrentOne(sender: UIButton) {
    let secondViewController = storyboard?.instantiateViewControllerWithIdentifier("ConrollerStoryboardID") as UIViewControllerClass // change it as You need it
    var presentingVC = self.presentingViewController
    self.dismissViewControllerAnimated(false, completion: { () -> Void   in
        presentingVC!.presentViewController(secondViewController, animated: true, completion: nil)
    })
}

How to write UTF-8 in a CSV file

For python2 you can use this code before csv_writer.writerows(rows)
This code will NOT convert integers to utf-8 strings

def encode_rows_to_utf8(rows):
    encoded_rows = []
    for row in rows:
        encoded_row = []
        for value in row:
            if isinstance(value, basestring):
                value = unicode(value).encode("utf-8")
            encoded_row.append(value)
        encoded_rows.append(encoded_row)
    return encoded_rows

Parsing query strings on Android

public static Map<String, List<String>> getUrlParameters(String url)
        throws UnsupportedEncodingException {
    Map<String, List<String>> params = new HashMap<String, List<String>>();
    String[] urlParts = url.split("\\?");
    if (urlParts.length > 1) {
        String query = urlParts[1];
        for (String param : query.split("&")) {
            String pair[] = param.split("=", 2);
            String key = URLDecoder.decode(pair[0], "UTF-8");
            String value = "";
            if (pair.length > 1) {
                value = URLDecoder.decode(pair[1], "UTF-8");
            }
            List<String> values = params.get(key);
            if (values == null) {
                values = new ArrayList<String>();
                params.put(key, values);
            }
            values.add(value);
        }
    }
    return params;
}

How do I programmatically force an onchange event on an input?

Create an Event object and pass it to the dispatchEvent method of the element:

var element = document.getElementById('just_an_example');
var event = new Event('change');
element.dispatchEvent(event);

This will trigger event listeners regardless of whether they were registered by calling the addEventListener method or by setting the onchange property of the element.


If you want the event to bubble, you need to pass a second argument to the Event constructor:

var event = new Event('change', { bubbles: true });

Information about browser compability:

How to delete an element from an array in C#

The code that is written in the question has a bug in it

Your arraylist contains strings of " 1" " 3" " 4" " 9" and " 2" (note the spaces)

So IndexOf(4) will find nothing because 4 is an int, and even "tostring" would convert it to of "4" and not " 4", and nothing will get removed.

An arraylist is the correct way to go to do what you want.

Finding duplicate values in MySQL

I am not seeing any JOIN approaches, which have many uses in terms of duplicates.

This approach gives you actual doubled results.

SELECT t1.* FROM my_table as t1 
LEFT JOIN my_table as t2 
ON t1.name=t2.name and t1.id!=t2.id 
WHERE t2.id IS NOT NULL 
ORDER BY t1.name

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

Set the text in a span

$('.ui-icon-circle-triangle-w').text('<<');

MySQL Cannot Add Foreign Key Constraint

My solution is maybe a little embarrassing and tells the tale of why you should sometimes look at what you have in front of you instead of these posts :)

I had ran a forward engineer before, which failed, so that meant that my database already had a few tables, then i have been sitting trying to fix foreign key contraints failures trying to make sure that everything was perfect, but it ran up against the tables previously created, so it was to no prevail.

import module from string variable

I developed these 3 useful functions:

def loadModule(moduleName):
    module = None
    try:
        import sys
        del sys.modules[moduleName]
    except BaseException as err:
        pass
    try:
        import importlib
        module = importlib.import_module(moduleName)
    except BaseException as err:
        serr = str(err)
        print("Error to load the module '" + moduleName + "': " + serr)
    return module

def reloadModule(moduleName):
    module = loadModule(moduleName)
    moduleName, modulePath = str(module).replace("' from '", "||").replace("<module '", '').replace("'>", '').split("||")
    if (modulePath.endswith(".pyc")):
        import os
        os.remove(modulePath)
        module = loadModule(moduleName)
    return module

def getInstance(moduleName, param1, param2, param3):
    module = reloadModule(moduleName)
    instance = eval("module." + moduleName + "(param1, param2, param3)")
    return instance

And everytime I want to reload a new instance I just have to call getInstance() like this:

myInstance = getInstance("MyModule", myParam1, myParam2, myParam3)

Finally I can call all the functions inside the new Instance:

myInstance.aFunction()

The only specificity here is to customize the params list (param1, param2, param3) of your instance.

SQL JOIN, GROUP BY on three tables to get totals

I have a tip for those, who want to get various aggregated values from the same table.

Lets say I have table with users and table with points the users acquire. So the connection between them is 1:N (one user, many points records).

Now in the table 'points' I also store the information about for what did the user get the points (login, clicking a banner etc.). And I want to list all users ordered by SUM(points) AND then by SUM(points WHERE type = x). That is to say ordered by all the points user has and then by points the user got for a specific action (eg. login).

The SQL would be:

SELECT SUM(points.points) AS points_all, SUM(points.points * (points.type = 7)) AS points_login
FROM user
LEFT JOIN points ON user.id = points.user_id
GROUP BY user.id

The beauty of this is in the SUM(points.points * (points.type = 7)) where the inner parenthesis evaluates to either 0 or 1 thus multiplying the given points value by 0 or 1, depending on wheteher it equals to the the type of points we want.

How to delete a line from a text file in C#?

I'd very simply:

  • Open the file for read/write
  • Read/seek through it until the start of the line you want to delete
  • Set the write pointer to the current read pointer
  • Read through to the end of the line we're deleting and skip the newline delimiters (counting the number of characters as we go, we'll call it nline)
  • Read byte-by-byte and write each byte to the file
  • When finished truncate the file to (orig_length - nline).

HTML/CSS: how to put text both right and left aligned in a paragraph

Ok what you probably want will be provide to you by result of:

  1. in CSS:

    div { column-count: 2; }

  2. in html:

    <div> some text, bla bla bla </div>

In CSS you make div to split your paragraph on to column, you can make them 3, 4...

If you want to have many differend paragraf like that, then put id or class in your div:

removing new line character from incoming stream using sed

This might work for you:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

or:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

or:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}

Set specific precision of a BigDecimal

The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.

Some examples in Clojure.

(.scale     0.00123M) ; 5
(.precision 0.00123M) ; 3

(In Clojure, The M designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)

You can easily increase the scale:

(.setScale 0.00123M 7) ; 0.0012300M

But you can't decrease the scale in the exact same way:

(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary

You'll need to pass a rounding mode too:

(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.

So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!

It is easy to decrease the precision:

(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M

But it is not obvious how to increase the precision:

(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)

For the skeptical, this is not just a matter of trailing zeros not being displayed:

(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6 
; (same as above, still unexpected)

FWIW, Clojure is careful with trailing zeros and will show them:

4.0000M ; 4.0000M
(.precision 4.0000M) ; 5

Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:

(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M

So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?

So, best I can tell, if you want to change precision, you'll need to do these steps:

  1. Lookup the current precision.
  2. Lookup the current scale.
  3. Calculate the scale change.
  4. Set the new scale

These steps, as Clojure code:

(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M

I know, this is a lot of steps just to change the precision!

Why doesn't BigDecimal already provide this? Did I overlook something?

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Handling identity columns in an "Insert Into TABLE Values()" statement?

By default, if you have an identity column, you do not need to specify it in the VALUES section. If your table is:

ID    NAME    ADDRESS

Then you can do:

INSERT INTO MyTbl VALUES ('Joe', '123 State Street, Boston, MA')

This will auto-generate the ID for you, and you don't have to think about it at all. If you SET IDENTITY_INSERT MyTbl ON, you can assign a value to the ID column.

What is an efficient way to implement a singleton pattern in Java?

The best singleton pattern I've ever seen uses the Supplier interface.

  • It's generic and reusable
  • It supports lazy initialization
  • It's only synchronized until it has been initialized, then the blocking supplier is replaced with a non-blocking supplier.

See below:

public class Singleton<T> implements Supplier<T> {

    private boolean initialized;
    private Supplier<T> singletonSupplier;

    public Singleton(T singletonValue) {
        this.singletonSupplier = () -> singletonValue;
    }

    public Singleton(Supplier<T> supplier) {
        this.singletonSupplier = () -> {
            // The initial supplier is temporary; it will be replaced after initialization
            synchronized (supplier) {
                if (!initialized) {
                    T singletonValue = supplier.get();
                    // Now that the singleton value has been initialized,
                    // replace the blocking supplier with a non-blocking supplier
                    singletonSupplier = () -> singletonValue;
                    initialized = true;
                }
                return singletonSupplier.get();
            }
        };
    }

    @Override
    public T get() {
        return singletonSupplier.get();
    }
}

HTTP Ajax Request via HTTPS Page

This is not possible due to the Same Origin Policy.

You will need to switch the Ajax requests to https, too.

is of a type that is invalid for use as a key column in an index

There is a limitation in SQL Server (up till 2008 R2) that varchar(MAX) and nvarchar(MAX) (and several other types like text, ntext ) cannot be used in indices. You have 2 options:
1. Set a limited size on the key field ex. nvarchar(100)
2. Create a check constraint that compares the value with all the keys in the table. The condition is:

([dbo].[CheckKey]([key])=(1))

and [dbo].[CheckKey] is a scalar function defined as:

CREATE FUNCTION [dbo].[CheckKey]
(
    @key nvarchar(max)
)
RETURNS bit
AS
BEGIN
    declare @res bit
    if exists(select * from key_value where [key] = @key)
        set @res = 0
    else
        set @res = 1

    return @res
END

But note that a native index is more performant than a check constraint so unless you really can't specify a length, don't use the check constraint.

Twitter Bootstrap - full width navbar

Put your <nav>element out from the <div class='container-fluid'>. Ex :-

_x000D_
_x000D_
<nav>_x000D_
 ......nav content goes here_x000D_
<nav>_x000D_
_x000D_
<div class="container-fluid">_x000D_
  <div>_x000D_
   ........ other content goes here_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert String to Uri

You can use the parse static method from Uri

//...
import android.net.Uri;
//...

Uri myUri = Uri.parse("http://stackoverflow.com")

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

Then number of columns must match between both parts of the union.

In order to build the full path, you need to "aggregate" all values of the Location column. You still need to select the id and other columns inside the CTE in order to be able to join properly. You get "rid" of them by simply not selecting them in the outer select:

with q as 
(
   select ID, PartOf_LOC_id, Location, ' > ' + Location as path
   from tblLocation 
   where ID = 1 

   union all

   select child.ID, child.PartOf_LOC_id, Location, parent.path + ' > ' + child.Location 
   from tblLocation child
     join q parent on parent.ID = t.LOC_PartOf_ID
)
select path
from q;

Integrating MySQL with Python in Windows

Got sick of the installation troubles with MySQLdb and tried pymysql instead.

Easy setup;

git clone https://github.com/petehunt/PyMySQL.git
python setup.py install

And APIs are pretty much the same.

Laravel - Model Class not found

I was having the same "Class [class name] not found" error message, but it wasn't a namespace issue. All my namespaces were set up correctly. I even tried composer dump-autoload and it didn't help me.

Surprisingly (to me) I then did composer dump-autoload -o which according to Composer's help, "optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production." Somehow doing it that way got composer to behave and include the class correctly in the autoload_classmap.php file.

How do you completely remove Ionic and Cordova installation from mac?

Here the command to remove cordova and ionic from your machine

npm uninstall cordova ionic

Recyclerview inside ScrollView not scrolling smoothly

Replacing ScrollView with NestedScrollView resulted into smooth scrolling to the bottom.

Why doesn't java.util.Set have get(int index)?

java.util.Set is a collection of un-ordered items. It doesn't make any sense if the Set has a get(int index), because Set doesn't has an index and also you only can guess the value.

If you really want this, code a method to get random element from Set.

How to see data from .RData file?

Look at the help page for load. What load returns is the names of the objects created, so you can look at the contents of isfar to see what objects were created. The fact that nothing else is showing up with ls() would indicate that maybe there was nothing stored in your file.

Also note that load will overwrite anything in your global environment that has the same name as something in the file being loaded when used with default behavior. If you mainly want to examine what is in the file, and possibly use something from that file along with other objects in your global environment then it may be better to use the attach function or create a new environment (new.env) and load the file into that environment using the envir argument to load.

Why am I getting this redefinition of class error?

If you are having issues with templates or you are calling the class from another .cpp file

try using '#pragma once' in your header file.

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

For me its solved follow the following steps :

One reason for this occur is if you don't have a start page or wrong start page set under your web project's properties. So do this:

1- Right click on your MVC project

2- Choose "Properties"

3- Select the "Web" tab

4- Select "Specific Page"

Assuming you have a controller called HomeController and an action method called Index, enter "home/index" in to the text box corresponding to the "Specific Page" radio button.

Now, if you launch your web application, it will take you to the view rendered by the HomeController's Index action method.

RuntimeError on windows trying python multiprocessing

Though the earlier answers are correct, there's a small complication it would help to remark on.

In case your main module imports another module in which global variables or class member variables are defined and initialized to (or using) some new objects, you may have to condition that import in the same way:

if __name__ ==  '__main__':
  import my_module

Regular Expression to match every new line character (\n) inside a <content> tag

Actually... you can't use a simple regex here, at least not one. You probably need to worry about comments! Someone may write:

<!-- <content> blah </content> -->

You can take two approaches here:

  1. Strip all comments out first. Then use the regex approach.
  2. Do not use regular expressions and use a context sensitive parsing approach that can keep track of whether or not you are nested in a comment.

Be careful.

I am also not so sure you can match all new lines at once. @Quartz suggested this one:

<content>([^\n]*\n+)+</content>

This will match any content tags that have a newline character RIGHT BEFORE the closing tag... but I'm not sure what you mean by matching all newlines. Do you want to be able to access all the matched newline characters? If so, your best bet is to grab all content tags, and then search for all the newline chars that are nested in between. Something more like this:

<content>.*</content>

BUT THERE IS ONE CAVEAT: regexes are greedy, so this regex will match the first opening tag to the last closing one. Instead, you HAVE to suppress the regex so it is not greedy. In languages like python, you can do this with the "?" regex symbol.

I hope with this you can see some of the pitfalls and figure out how you want to proceed. You are probably better off using an XML parsing library, then iterating over all the content tags.

I know I may not be offering the best solution, but at least I hope you will see the difficulty in this and why other answers may not be right...

UPDATE 1:

Let me summarize a bit more and add some more detail to my response. I am going to use python's regex syntax because it is what I am more used to (forgive me ahead of time... you may need to escape some characters... comment on my post and I will correct it):

To strip out comments, use this regex: Notice the "?" suppresses the .* to make it non-greedy.

Similarly, to search for content tags, use: .*?

Also, You may be able to try this out, and access each newline character with the match objects groups():

<content>(.*?(\n))+.*?</content>

I know my escaping is off, but it captures the idea. This last example probably won't work, but I think it's your best bet at expressing what you want. My suggestion remains: either grab all the content tags and do it yourself, or use a parsing library.

UPDATE 2:

So here is python code that ought to work. I am still unsure what you mean by "find" all newlines. Do you want the entire lines? Or just to count how many newlines. To get the actual lines, try:

#!/usr/bin/python

import re

def FindContentNewlines(xml_text):
    # May want to compile these regexes elsewhere, but I do it here for brevity
    comments = re.compile(r"<!--.*?-->", re.DOTALL)
    content = re.compile(r"<content>(.*?)</content>", re.DOTALL)
    newlines = re.compile(r"^(.*?)$", re.MULTILINE|re.DOTALL)

    # strip comments: this actually may not be reliable for "nested comments"
    # How does xml handle <!--  <!-- --> -->. I am not sure. But that COULD
    # be trouble.
    xml_text = re.sub(comments, "", xml_text)

    result = []
    all_contents = re.findall(content, xml_text)
    for c in all_contents:
        result.extend(re.findall(newlines, c))

    return result

if __name__ == "__main__":
    example = """

<!-- This stuff
ought to be omitted
<content>
  omitted
</content>
-->

This stuff is good
<content>
<p>
  haha!
</p>
</content>

This is not found
"""
    print FindContentNewlines(example)

This program prints the result:

 ['', '<p>', '  haha!', '</p>', '']

The first and last empty strings come from the newline chars immediately preceeding the first <p> and the one coming right after the </p>. All in all this (for the most part) does the trick. Experiment with this code and refine it for your needs. Print out stuff in the middle so you can see what the regexes are matching and not matching.

Hope this helps :-).

PS - I didn't have much luck trying out my regex from my first update to capture all the newlines... let me know if you do.

span with onclick event inside a tag

use onmouseup

try something like this

        <html>
        <head>
        <script type="text/javascript">
        function hide(){
        document.getElementById('span_hide').style.display="none";
        }
        </script>
        </head>

        <body>
        <a href="page" style="text-decoration:none;display:block;">
        <span   onmouseup="hide()" id="span_hide">Hide me</span>
        </a>
        </body>
        </html>

EDIT:

          <html>
        <head>
        <script type="text/javascript">
        $(document).ready(function(){
         $("a").click(function () { 
         $(this).fadeTo("fast", .5).removeAttr("href"); 
        });
        });
        function hide(){
        document.getElementById('span_hide').style.display="none";
        }
        </script>
        </head>

        <body>
        <a href="page.html" style="text-decoration:none;display:block;" onclick="return false" >
        <span   onmouseup="hide()" id="span_hide">Hide me</span>
        </a>
        </body>
        </html>

When to use RabbitMQ over Kafka?

I realize that this is an old question, but one scenario where RabbitMQ might be a better choice is when dealing with data redaction.

With RabbitMQ, by default once the message has been consumed, it's deleted. With Kafka, by default, messages are kept for a week. It's common to set this to a much longer time, or even to never delete them.

While both products can be configured to retain (or not retain) messages, if CCPA or GDPR compliance is a concern, I'd go with RabbitMQ.

Add CSS to <head> with JavaScript?

A simple non-jQuery solution, albeit with a bit of a hack for IE:

var css = ".lightbox { width: 400px; height: 400px; border: 1px solid #333}";

var htmlDiv = document.createElement('div');
htmlDiv.innerHTML = '<p>foo</p><style>' + css + '</style>';
document.getElementsByTagName('head')[0].appendChild(htmlDiv.childNodes[1]);

It seems IE does not allow setting innerText, innerHTML or using appendChild on style elements. Here is a bug report which demonstrates this, although I think it identifies the problem incorrectly. The workaround above is from the comments on the bug report and has been tested in IE6 and IE9.

Whether you use this, document.write or a more complex solution will really depend on your situation.