Programs & Examples On #Fully qualified naming

Using Position Relative/Absolute within a TD?

Contents of table cell, variable height, could be more than 60px;

<div style="position: absolute; bottom: 0px;">
    Notice
</div>

CSS: background-color only inside the margin

I needed something similar, and came up with using the :before (or :after) pseudoclasses:

#mydiv {
   background-color: #fbb;
   margin-top: 100px;
   position: relative;
}
#mydiv:before {
   content: "";
   background-color: #bfb;
   top: -100px;
   height: 100px;
   width: 100%;
   position: absolute;
}

JSFiddle

Can we convert a byte array into an InputStream in Java?

If you use Robert Harder's Base64 utility, then you can do:

InputStream is = new Base64.InputStream(cph);

Or with sun's JRE, you can do:

InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)

However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.

There are other Stack Overflow questions about Base64 decoding, such as this one.

Command not found error in Bash variable assignment

Drop the spaces around the = sign:

#!/bin/bash 
STR="Hello World" 
echo $STR 

How to submit an HTML form without redirection

Place a hidden iFrame at the bottom of your page and target it in your form:

<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>

<form action="/Car/Edit/17" id="myForm" method="post" name="myForm" target="hiddenFrame"> ... </form>

Quick and easy. Keep in mind that while the target attribute is still widely supported (and supported in HTML5), it was deprecated in HTML 4.01.

So you really should be using Ajax to future-proof.

Converting an int to std::string

Non-standard function, but its implemented on most common compilers:

int input = MY_VALUE;
char buffer[100] = {0};
int number_base = 10;
std::string output = itoa(input, buffer, number_base);

Update

C++11 introduced several std::to_string overloads (note that it defaults to base-10).

Python csv string to array

https://docs.python.org/2/library/csv.html?highlight=csv#csv.reader

csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called

Thus, a StringIO.StringIO(), str.splitlines() or even a generator are all good.

Formatting numbers (decimal places, thousands separators, etc) with CSS

If it helps...

I use the PHP function number_format() and the Narrow No-break Space (&#8239;). It is often used as an unambiguous thousands separator.

echo number_format(200000, 0, "", "&#8239;");

Because IE8 has some problems to render the Narrow No-break Space, I changed it for a SPAN

echo "<span class='number'>".number_format(200000, 0, "", "<span></span>")."</span>";
.number SPAN{
    padding: 0 1px; 
}

VS 2017 Metadata file '.dll could not be found

This issue happens when you renamed your solution and the .net framework cannot find the old solution.

To resolve this, you need to find and replace the old name of solution and all dependencies on it with the new name. If you need to browse the physical file through file explorer do so.

The files that are normally affected are AssemblyInfo.cs, .sln an Properties > Application > Assembly name and Default namespace. Make sure to update them with the new name.

Open the file explorer, if the folder with the old name still exists, you need to delete it. Then clean and build the solution until the error is gone. (If needed clean and build the project one by one especially the affected project.)

How can I escape square brackets in a LIKE clause?

Use Following.

For user input to search as it is, use escape, in that it will require following replacement for all special characters (below covers all of SQL Server).

Here single quote "'" is not taken as it does not affect like clause as It is a matter of string concatenation.

"-" & "^" & "]" replace is not required as we are escaping "[".

String FormattedString = "UserString".Replace("ð","ðð").Replace("_", "ð_").Replace("%", "ð%").Replace("[", "ð[");

Then, in SQL Query it should be as following. (In parameterised query, string can be added with patterns after above replacement).

To search exact string.

like 'FormattedString' ESCAPE 'ð'

To search start with string

like '%FormattedString' ESCAPE 'ð'

To search end with string

like 'FormattedString%' ESCAPE 'ð'

To search contain with string

like '%FormattedString%' ESCAPE 'ð'

and so on for other pattern matching. But direct user input needs to format as mentioned above.

Bold & Non-Bold Text In A Single UILabel?

Swift 4:

// attribute with color red and Bold
var attrs1 = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedStringKey.foregroundColor: UIColor.red]

// attribute with color black and Non Bold
var attrs2 = [NSAttributedStringKey.font: UIFont(name: "Roboto-Regular", size: 20), NSAttributedStringKey.foregroundColor: UIColor.black]  

var color1 = NSAttributedString(string: "RED", attributes: attrs1)

var color2 = NSAttributedString(string: " BLACK", attributes: attrs2)

var string = NSMutableAttributedString()

string.append(color1)

string.append(color2)

// print the text with **RED** BLACK
print("Final String : \(string)")

Boxplot show the value of mean

You can use the output value from stat_summary()

ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) 
+ geom_boxplot() 
+ stat_summary(fun.y=mean, colour="darkred", geom="point", hape=18, size=3,show_guide = FALSE)
+ stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE, 
               vjust=-0.7, aes( label=round(..y.., digits=1)))

Why doesn't indexOf work on an array IE8?

Versions of IE before IE9 don't have an .indexOf() function for Array, to define the exact spec version, run this before trying to use it:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

This is the version from MDN, used in Firefox/SpiderMonkey. In other cases such as IE, it'll add .indexOf() in the case it's missing... basically IE8 or below at this point.

Converting an int to a binary string representation in Java?

public class Main  {

   public static String toBinary(int n, int l ) throws Exception {
       double pow =  Math.pow(2, l);
       StringBuilder binary = new StringBuilder();
        if ( pow < n ) {
            throw new Exception("The length must be big from number ");
        }
       int shift = l- 1;
       for (; shift >= 0 ; shift--) {
           int bit = (n >> shift) & 1;
           if (bit == 1) {
               binary.append("1");
           } else {
               binary.append("0");
           }
       }
       return binary.toString();
   }

    public static void main(String[] args) throws Exception {
        System.out.println(" binary = " + toBinary(7, 4));
        System.out.println(" binary = " + Integer.toString(7,2));
    }
}

How to determine previous page URL in Angular?

You can use Location as mentioned here.

Here's my code if the link opened on new tab

navBack() {
    let cur_path = this.location.path();
    this.location.back();
    if (cur_path === this.location.path())
     this.router.navigate(['/default-route']);    
  }

Required imports

import { Router } from '@angular/router';
import { Location } from '@angular/common';

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Here is an official answer to this:

If Git prompts you for a username and password every time you try to interact with GitHub, you're probably using the HTTPS clone URL for your repository.

Using an HTTPS remote URL has some advantages: it's easier to set up than SSH, and usually works through strict firewalls and proxies. However, it also prompts you to enter your GitHub credentials every time you pull or push a repository.

You can configure Git to store your password for you. If you'd like to set that up, read all about setting up password caching.

Form/JavaScript not working on IE 11 with error DOM7011

This error occurred for me when using window.location.reload(). Replacing with window.location = window.location.href solved the problem.

How to get current relative directory of your Makefile?

If you are using GNU make, $(CURDIR) is actually a built-in variable. It is the location where the Makefile resides the current working directory, which is probably where the Makefile is, but not always.

OUTPUT_PATH = /project1/bin/$(notdir $(CURDIR))

See Appendix A Quick Reference in http://www.gnu.org/software/make/manual/make.html

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

you can also use Recursion

Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method.

How to make node.js require absolute? (instead of relative)

You could define something like this in your app.js:

requireFromRoot = (function(root) {
    return function(resource) {
        return require(root+"/"+resource);
    }
})(__dirname);

and then anytime you want to require something from the root, no matter where you are, you just use requireFromRoot instead of the vanilla require. Works pretty well for me so far.

Media Queries - In between two widths

You need to switch your values:

/* No greater than 900px, no less than 400px */
@media (max-width:900px) and (min-width:400px) {
    .foo {
        display:none;
    }
}?

Demo: http://jsfiddle.net/xf6gA/ (using background color, so it's easier to confirm)

Writing handler for UIAlertAction

Instead of self in your handler, put (alert: UIAlertAction!). This should make your code look like this

    alert.addAction(UIAlertAction(title: "Okay",
                          style: UIAlertActionStyle.Default,
                        handler: {(alert: UIAlertAction!) in println("Foo")}))

this is the proper way to define handlers in Swift.

As Brian pointed out below, there are also easier ways to define these handlers. Using his methods is discussed in the book, look at the section titled Closures

What is the equivalent of 'describe table' in SQL Server?

The problem with those answers is that you're missing the key info. While this is a bit messy this is a quick version I came up with to make sure it contains the same info the MySQL Describe displays.

Select SC.name AS 'Field', ISC.DATA_TYPE AS 'Type', ISC.CHARACTER_MAXIMUM_LENGTH AS 'Length', SC.IS_NULLABLE AS 'Null', I.is_primary_key AS 'Key', SC.is_identity AS 'Identity'
From sys.columns AS SC 
LEFT JOIN sys.index_columns AS IC
ON IC.object_id = OBJECT_ID('dbo.Expenses') AND 
IC.column_id = SC.column_id
LEFT JOIN sys.indexes AS I 
ON I.object_id = OBJECT_ID('dbo.Expenses') AND 
IC.index_id = I.index_id
LEFT JOIN information_schema.columns ISC
ON ISC.TABLE_NAME = 'Expenses'
AND ISC.COLUMN_NAME = SC.name
WHERE SC.object_id = OBJECT_ID('dbo.Expenses')

How to delete an array element based on key?

this looks like PHP to me. I'll delete if it's some other language.

Simply unset($arr[1]);

how to check the jdk version used to compile a .class file

You're looking for this on the command line (for a class called MyClass):

On Unix/Linux:

javap -verbose MyClass | grep "major"

On Windows:

javap -verbose MyClass | findstr "major"

You want the major version from the results. Here are some example values:

  • Java 1.2 uses major version 46
  • Java 1.3 uses major version 47
  • Java 1.4 uses major version 48
  • Java 5 uses major version 49
  • Java 6 uses major version 50
  • Java 7 uses major version 51
  • Java 8 uses major version 52
  • Java 9 uses major version 53
  • Java 10 uses major version 54
  • Java 11 uses major version 55

Getting msbuild.exe without installing Visual Studio

Download MSBuild with the link from @Nicodemeus answer was OK, yet the installation was broken until I've added these keys into a register:

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\12.0]
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))" 

How do the major C# DI/IoC frameworks compare?

See for a comparison of net-ioc-frameworks on google code including linfu and spring.net that are not on your list while i write this text.

I worked with spring.net: It has many features (aop, libraries , docu, ...) and there is a lot of experience with it in the dotnet and the java-world. The features are modularized so you donot have to take all features. The features are abstractions of common issues like databaseabstraction, loggingabstraction. however it is difficuilt to do and debug the IoC-configuration.

From what i have read so far: If i had to chooseh for a small or medium project i would use ninject since ioc-configuration is done and debuggable in c#. But i havent worked with it yet. for large modular system i would stay with spring.net because of abstraction-libraries.

Install a Nuget package in Visual Studio Code

The answers above are good, but insufficient if you have more than 1 project (.csproj) in the same folder.

First, you easily add the "PackageReference" tag to the .csproj file (either manually, by using the nuget package manager or by using the dotnet add package command).

But then, you need to run the "restore" command manually so you can tell it which project you are trying to restore (if I just clicked the restore button that popped up, nothing happened). You can do that by running:

dotnet restore Project-File-Name.csproj

And that installs the package

Use a normal link to submit a form

You are using images to submit.. so you can simply use an type="image" input "button":

<input type="image" src="yourimage.png" name="yourinputname" value="yourinputvalue" />

Virtualbox "port forward" from Guest to Host

Network communication Host -> Guest

Connect to the Guest and find out the ip address:

ifconfig 

example of result (ip address is 10.0.2.15):

eth0      Link encap:Ethernet  HWaddr 08:00:27:AE:36:99
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0

Go to Vbox instance window -> Menu -> Network adapters:

  • adapter should be NAT
  • click on "port forwarding"
  • insert new record (+ icon)
    • for host ip enter 127.0.0.1, and for guest ip address you got from prev. step (in my case it is 10.0.2.15)
    • in your case port is 8000 - put it on both, but you can change host port if you prefer

Go to host system and try it in browser:

http://127.0.0.1:8000

or your network ip address (find out on the host machine by running: ipconfig).

Network communication Guest -> Host

In this case port forwarding is not needed, the communication goes over the LAN back to the host.

On the host machine - find out your netw ip address:

ipconfig

example of result:

IP Address. . . . . . . . . . . . : 192.168.5.1

On the guest machine you can communicate directly with the host, e.g. check it with ping:

# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...

Firewall issues?

@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):

sudo ufw allow 8000 

Could not insert new outlet connection: Could not find any information for the class named

I had the same problem. I realised than in X-Code Manual item was selected when I tried to create an outlet by control-drag

enter image description here

After I set it to automatic it worked

enter image description here

List<T> OrderBy Alphabetical Order

This is a generic sorter. Called with the switch below.

dvm.PagePermissions is a property on my ViewModel of type List T in this case T is a EF6 model class called page_permission.

dvm.UserNameSortDir is a string property on the viewmodel that holds the next sort direction. The one that is actaully used in the view.

switch (sortColumn)
{
    case "user_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.user_name, ref sortDir);
        dvm.UserNameSortDir = sortDir;
        break;
    case "role_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.role_name, ref sortDir);
        dvm.RoleNameSortDir = sortDir;
        break;
    case "page_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.page_name, ref sortDir);
        dvm.PageNameSortDir = sortDir;
        break;
}                 


public List<T> Sort<T,TKey>(List<T> list, Func<T, TKey> sorter, ref string direction)
    {
        if (direction == "asc")
        {
            list = list.OrderBy(sorter).ToList();
            direction = "desc";
        }
        else
        {
            list = list.OrderByDescending(sorter).ToList();
            direction = "asc";
        }
        return list;
    }

How do I fix MSB3073 error in my post-build event?

I had the same problem for my Test project. I found out why my post build event wasn't working and that's because I was copying files before running the $(ProjectName).exe command and some of these files were required for Test project itself. Hence, by just moving $(ProjectName).exe as the first command fix the issue.

Apply Calibri (Body) font to text

There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).

So use just font-family: Calibri or, better, font-family: Calibri, sans-serif. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)

Initializing a list to a known number of elements in Python

The first thing that comes to mind for me is:

verts = [None]*1000

But do you really need to preinitialize it?

Save bitmap to location

You should use the Bitmap.compress() method to save a Bitmap as a file. It will compress (if the format used allows it) your picture and push it into an OutputStream.

Here is an example of a Bitmap instance obtained through getImageBitmap(myurl) that can be compressed as a JPEG with a compression rate of 85% :

// Assume block needs to be inside a Try/Catch block.
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
Integer counter = 0;
File file = new File(path, "FitnessGirl"+counter+".jpg"); // the File to save , append increasing numeric counter to prevent files from getting overwritten.
fOut = new FileOutputStream(file);

Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush(); // Not really required
fOut.close(); // do not forget to close the stream

MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());

How to prevent caching of my Javascript file?

You can append a queryString to your src and change it only when you will release an updated version:

<script src="test.js?v=1"></script>

In this way the browser will use the cached version until a new version will be specified (v=2, v=3...)

Why Would I Ever Need to Use C# Nested Classes

what I don't get is why I would ever need to do this

I think you never need to do this. Given a nested class like this ...

class A
{
  //B is used to help implement A
  class B
  {
    ...etc...
  }
  ...etc...
}

... you can always move the inner/nested class to global scope, like this ...

class A
{
  ...etc...
}

//B is used to help implement A
class B
{
  ...etc...
}

However, when B is only used to help implement A, then making B an inner/nested class has two advantages:

  • It doesn't pollute the global scope (e.g. client code which can see A doesn't know that the B class even exists)
  • The methods of B implicitly have access to private members of A; whereas if B weren't nested inside A, B wouldn't be able to access members of A unless those members were internal or public; but then making those members internal or public would expose them to other classes too (not just B); so instead, keep those methods of A private and let B access them by declaring B as a nested class. If you know C++, this is like saying that in C# all nested classes are automatically a 'friend' of the class in which they're contained (and, that declaring a class as nested is the only way to declare friendship in C#, since C# doesn't have a friend keyword).

When I say that B can access private members of A, that's assuming that B has a reference to A; which it often does, since nested classes are often declared like this ...

class A
{
  //used to help implement A
  class B
  {
    A m_a;
    internal B(A a) { m_a = a; }
    ...methods of B can access private members of the m_a instance...
  }
  ...etc...
}

... and constructed from a method of A using code like this ...

//create an instance of B, whose implementation can access members of self
B b = new B(this);

You can see an example in Mehrdad's reply.

Generating UML from C++ code?

StarUML does just that and it is free. Unfortunately it hasn't been updated for a while. There were a couple of offshoot projects (as the project admins wouldn't allow it to be taken over) but they too have died a death.

How do I convert a float number to a whole number in JavaScript?

var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue ); 
var intvalue = Math.round( floatvalue );

// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );

Math object reference


Examples

Positive
// value=x        //  x=5          5<x<5.5      5.5<=x<6  

Math.floor(value) //  5            5            5
Math.ceil(value)  //  5            6            6
Math.round(value) //  5            5            6
Math.trunc(value) //  5            5            5
parseInt(value)   //  5            5            5
~~value           //  5            5            5
value | 0         //  5            5            5
value >> 0        //  5            5            5
value >>> 0       //  5            5            5
value - value % 1 //  5            5            5
Negative
// value=x        // x=-5         -5>x>=-5.5   -5.5>x>-6

Math.floor(value) // -5           -6           -6
Math.ceil(value)  // -5           -5           -5
Math.round(value) // -5           -5           -6
Math.trunc(value) // -5           -5           -5
parseInt(value)   // -5           -5           -5
value | 0         // -5           -5           -5
~~value           // -5           -5           -5
value >> 0        // -5           -5           -5
value >>> 0       // 4294967291   4294967291   4294967291
value - value % 1 // -5           -5           -5
Positive - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1

// value=x            x=900719925474099    x=900719925474099.4  x=900719925474099.5
           
Math.floor(value) //  900719925474099      900719925474099      900719925474099
Math.ceil(value)  //  900719925474099      900719925474100      900719925474100
Math.round(value) //  900719925474099      900719925474099      900719925474100
Math.trunc(value) //  900719925474099      900719925474099      900719925474099
parseInt(value)   //  900719925474099      900719925474099      900719925474099
value | 0         //  858993459            858993459            858993459
~~value           //  858993459            858993459            858993459
value >> 0        //  858993459            858993459            858993459
value >>> 0       //  858993459            858993459            858993459
value - value % 1 //  900719925474099      900719925474099      900719925474099
Negative - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1

// value = x      // x=-900719925474099   x=-900719925474099.5 x=-900719925474099.6

Math.floor(value) // -900719925474099     -900719925474100     -900719925474100
Math.ceil(value)  // -900719925474099     -900719925474099     -900719925474099
Math.round(value) // -900719925474099     -900719925474099     -900719925474100
Math.trunc(value) // -900719925474099     -900719925474099     -900719925474099
parseInt(value)   // -900719925474099     -900719925474099     -900719925474099
value | 0         // -858993459           -858993459           -858993459
~~value           // -858993459           -858993459           -858993459
value >> 0        // -858993459           -858993459           -858993459
value >>> 0       //  3435973837           3435973837           3435973837
value - value % 1 // -900719925474099     -900719925474099     -900719925474099

Convert js Array() to JSon object for use with JQuery .ajax

If the array is already defined, you can create a json object by looping through the elements of the array which you can then post to the server, but if you are creating the array as for the case above, just create a json object instead as sugested by Paolo Bergantino

    var saveData = Array();
    saveData["a"] = 2;
    saveData["c"] = 1;
    
    //creating a json object
    var jObject={};
    for(i in saveData)
    {
        jObject[i] = saveData[i];
    }

    //Stringify this object and send it to the server
    
    jObject= YAHOO.lang.JSON.stringify(jObject);
    $.ajax({
            type:'post',
           cache:false,
             url:"salvaPreventivo.php",
            data:{jObject:  jObject}
    });
    
    // reading the data at the server
    <?php
    $data = json_decode($_POST['jObject'], true);
    print_r($data);
    ?>

    //for jObject= YAHOO.lang.JSON.stringify(jObject); to work,
    //include the follwing files

    //<!-- Dependencies -->
    //<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>

    //<!-- Source file -->
    //<script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script>

Hope this helps

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.

Make a div into a link

To make thepeer's answer work in IE 7 and forward, it needs a few tweaks.

  1. IE will not honour z-index if the element is has no background-color, so the link will not overlap parts of the containig div that has content, only the blank parts. To fix this a background is added with opacity 0.

  2. For some reason IE7 and various compatibility modes completely fail when using the span in a link approach. However if the link itself is given the style it works just fine.

.blockLink  
{  
    position:absolute;  
    top:0;  
    left: 0;  
    width:100%;  
    height:100%;  
    z-index: 1;  
    background-color:#ffffff;   
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";  
    filter: alpha(opacity=0);  
    opacity:0;  
}
<div style="position:relative">  
    <some content>  
    <a href="somepage" class="blockLink" />  
<div>

jQuery Keypress Arrow Keys

You can check wether an arrow key is pressed by:

$(document).keydown(function(e){
    if (e.keyCode > 36 && e.keyCode < 41) 
      alert( "arrowkey pressed" );          
});

jsfiddle demo

Get the decimal part from a double

var decPlaces = (int)(((decimal)number % 1) * 100);

This presumes your number only has two decimal places.

android set button background programmatically

The answer you're looking for in 2020 and beyond:

  • setColorFilter(color, mode) is deprecated since API 29 (as discussed here)
  • button.setBackgroundColor(color) messes with the button style

Now the proper way to set a buttons color is using BlendModeColorFilter() (see documentation).

Usage:

btn.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)

If you work with older APIs too:

fun setButtonColor(btn: Button, color: Int) {
    if (Build.VERSION.SDK_INT >= 29)
        btn.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)
    else
        btn.background.setColorFilter(color, PorterDuff.Mode.MULTIPLY)
}

Please vote to help others finding this answer - it took me quite a while figuring this out ^^

Smooth scroll without the use of jQuery

I've made an example without jQuery here : http://codepen.io/sorinnn/pen/ovzdq

/**
    by Nemes Ioan Sorin - not an jQuery big fan 
    therefore this script is for those who love the old clean coding style  
    @id = the id of the element who need to bring  into view

    Note : this demo scrolls about 12.700 pixels from Link1 to Link3
*/
(function()
{
      window.setTimeout = window.setTimeout; //
})();

      var smoothScr = {
      iterr : 30, // set timeout miliseconds ..decreased with 1ms for each iteration
        tm : null, //timeout local variable
      stopShow: function()
      {
        clearTimeout(this.tm); // stopp the timeout
        this.iterr = 30; // reset milisec iterator to original value
      },
      getRealTop : function (el) // helper function instead of jQuery
      {
        var elm = el; 
        var realTop = 0;
        do
        {
          realTop += elm.offsetTop;
          elm = elm.offsetParent;
        }
        while(elm);
        return realTop;
      },
      getPageScroll : function()  // helper function instead of jQuery
      {
        var pgYoff = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
        return pgYoff;
      },
      anim : function (id) // the main func
      {
        this.stopShow(); // for click on another button or link
        var eOff, pOff, tOff, scrVal, pos, dir, step;

        eOff = document.getElementById(id).offsetTop; // element offsetTop

        tOff =  this.getRealTop(document.getElementById(id).parentNode); // terminus point 

        pOff = this.getPageScroll(); // page offsetTop

        if (pOff === null || isNaN(pOff) || pOff === 'undefined') pOff = 0;

        scrVal = eOff - pOff; // actual scroll value;

        if (scrVal > tOff) 
        {
          pos = (eOff - tOff - pOff); 
          dir = 1;
        }
        if (scrVal < tOff)
        {
          pos = (pOff + tOff) - eOff;
          dir = -1; 
        }
        if(scrVal !== tOff) 
        {
          step = ~~((pos / 4) +1) * dir;

          if(this.iterr > 1) this.iterr -= 1; 
          else this.itter = 0; // decrease the timeout timer value but not below 0
          window.scrollBy(0, step);
          this.tm = window.setTimeout(function()
          {
             smoothScr.anim(id);  
          }, this.iterr); 
        }  
        if(scrVal === tOff) 
        { 
          this.stopShow(); // reset function values
          return;
        }
    }
 }

Jquery UI datepicker. Disable array of Dates

beforeShowDate didn't work for me, so I went ahead and developed my own solution:

$('#embeded_calendar').datepicker({
               minDate: date,
                localToday:datePlusOne,
               changeDate: true,
               changeMonth: true,
               changeYear: true,
               yearRange: "-120:+1",
               onSelect: function(selectedDateFormatted){

                     var selectedDate = $("#embeded_calendar").datepicker('getDate');

                    deactivateDates(selectedDate);
                   }

           });


              var excludedDates = [ "10-20-2017","10-21-2016", "11-21-2016"];

              deactivateDates(new Date());

            function deactivateDates(selectedDate){
                setTimeout(function(){ 
                      var thisMonthExcludedDates = thisMonthDates(selectedDate);
                      thisMonthExcludedDates = getDaysfromDate(thisMonthExcludedDates);
                       var excludedTDs = page.find('td[data-handler="selectDay"]').filter(function(){
                           return $.inArray( $(this).text(), thisMonthExcludedDates) >= 0
                       });

                       excludedTDs.unbind('click').addClass('ui-datepicker-unselectable');
                   }, 10);
            }

            function thisMonthDates(date){
              return $.grep( excludedDates, function( n){
                var dateParts = n.split("-");
                return dateParts[0] == date.getMonth() + 1  && dateParts[2] == date.getYear() + 1900;
            });
            }

            function getDaysfromDate(datesArray){
                  return  $.map( datesArray, function( n){
                    return n.split("-")[1]; 
                });
             }

jQuery: how to find first visible input/select/textarea excluding buttons?

Why not just target the ones you want (demo)?

$('form').find('input[type=text],textarea,select').filter(':visible:first');

Edit

Or use jQuery :input selector to filter form descendants.

$('form').find('*').filter(':input:visible:first');

Create a <ul> and fill it based on a passed array

First of all, don't create HTML elements by string concatenation. Use DOM manipulation. It's faster, cleaner, and less error-prone. This alone solves one of your problems. Then, just let it accept any array as an argument:

var options = [
        set0 = ['Option 1','Option 2'],
        set1 = ['First Option','Second Option','Third Option']
    ];

function makeUL(array) {
    // Create the list element:
    var list = document.createElement('ul');

    for (var i = 0; i < array.length; i++) {
        // Create the list item:
        var item = document.createElement('li');

        // Set its contents:
        item.appendChild(document.createTextNode(array[i]));

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:
    return list;
}

// Add the contents of options[0] to #foo:
document.getElementById('foo').appendChild(makeUL(options[0]));

Here's a demo. You might also want to note that set0 and set1 are leaking into the global scope; if you meant to create a sort of associative array, you should use an object:

var options = {
    set0: ['Option 1', 'Option 2'],
    set1: ['First Option', 'Second Option', 'Third Option']
};

And access them like so:

makeUL(options.set0);

How to get the last N rows of a pandas DataFrame?

This is because of using integer indices (ix selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).

*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:

df.iloc[-3:]

see the docs.

As Wes points out, in this specific case you should just use tail!

How to find longest string in the table column data

If column datatype is text you should use DataLength function like:

select top 1 CR, DataLength(CR)
from tbl
order by DataLength(CR) desc

How do I make a list of data frames?

You can also access specific columns and values in each list element with [ and [[. Here are a couple of examples. First, we can access only the first column of each data frame in the list with lapply(ldf, "[", 1), where 1 signifies the column number.

ldf <- list(d1 = d1, d2 = d2)  ## create a named list of your data frames
lapply(ldf, "[", 1)
# $d1
#   y1
# 1  1
# 2  2
# 3  3
#
# $d2
#   y1
# 1  3
# 2  2
# 3  1

Similarly, we can access the first value in the second column with

lapply(ldf, "[", 1, 2)
# $d1
# [1] 4
# 
# $d2
# [1] 6

Then we can also access the column values directly, as a vector, with [[

lapply(ldf, "[[", 1)
# $d1
# [1] 1 2 3
#
# $d2
# [1] 3 2 1

imagecreatefromjpeg and similar functions are not working in PHP

sudo apt-get install phpx.x-gd 
sudo service apache2 restart

x.x is the versión php.

Unit testing with mockito for constructors

You can use PowerMockito

See the example:

Second second = Mockito.mock(Second.class);
whenNew(Second.class).withNoArguments().thenReturn(second);

But re-factoring is better decision.

Changing image on hover with CSS/HTML

You can't use CSS to change image SRC attributes (unless the browser supports it). You may want to use jQuery with the hover event.

$("#Library ").hover(
    function () {
         $(this).attr("src","isHover.jpg");
    },
    function () {
        $(this).attr("src","notHover.jpg");
    }
);

Groovy write to file (newline)

@Comment for ID:14. It's for me rather easier to write:

out.append it

instead of

out.println it

println did on my machine only write the first file of the ArrayList, with append I get the whole List written into the file.

Kindly anyway for the quick-and-dirty-solution.

Remove Primary Key in MySQL

I believe Quassnoi has answered your direct question. Just a side note: Maybe this is just some awkward wording on your part, but you seem to be under the impression that you have three primary keys, one on each field. This is not the case. By definition, you can only have one primary key. What you have here is a primary key that is a composite of three fields. Thus, you cannot "drop the primary key on a column". You can drop the primary key, or not drop the primary key. If you want a primary key that only includes one column, you can drop the existing primary key on 3 columns and create a new primary key on 1 column.

Jaxb, Class has two properties of the same name

I did trial and error and got the conclusion that, you only have to use either of both @XMLElement or @XmlAccessorType(XmlAccessType.FIELD).

When to use which?

case 1 : If your field names and element name you want to use in xml file are different then you have to use @XMLElement(name="elementName"). As this will bind fields with that element name and display in XML file.

case 2 : If fields names and respective element name in xml both are same then you can simply use @XmlAccessorType(XmlAccessType.FIELD)

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

Which version of MVC am I using?

I chose System.web.MVC from reference folder and right clicked on it to go property window where I could see version of MVC. This solution works for me. Thanks

Pandas read_csv low_memory and dtype options

The deprecated low_memory option

The low_memory option is not properly deprecated, but it should be, since it does not actually do anything differently[source]

The reason you get this low_memory warning is because guessing dtypes for each column is very memory demanding. Pandas tries to determine what dtype to set by analyzing the data in each column.

Dtype Guessing (very bad)

Pandas can only determine what dtype a column should have once the whole file is read. This means nothing can really be parsed before the whole file is read unless you risk having to change the dtype of that column when you read the last value.

Consider the example of one file which has a column called user_id. It contains 10 million rows where the user_id is always numbers. Since pandas cannot know it is only numbers, it will probably keep it as the original strings until it has read the whole file.

Specifying dtypes (should always be done)

adding

dtype={'user_id': int}

to the pd.read_csv() call will make pandas know when it starts reading the file, that this is only integers.

Also worth noting is that if the last line in the file would have "foobar" written in the user_id column, the loading would crash if the above dtype was specified.

Example of broken data that breaks when dtypes are defined

import pandas as pd
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO


csvdata = """user_id,username
1,Alice
3,Bob
foobar,Caesar"""
sio = StringIO(csvdata)
pd.read_csv(sio, dtype={"user_id": int, "username": "string"})

ValueError: invalid literal for long() with base 10: 'foobar'

dtypes are typically a numpy thing, read more about them here: http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html

What dtypes exists?

We have access to numpy dtypes: float, int, bool, timedelta64[ns] and datetime64[ns]. Note that the numpy date/time dtypes are not time zone aware.

Pandas extends this set of dtypes with its own:

'datetime64[ns, ]' Which is a time zone aware timestamp.

'category' which is essentially an enum (strings represented by integer keys to save

'period[]' Not to be confused with a timedelta, these objects are actually anchored to specific time periods

'Sparse', 'Sparse[int]', 'Sparse[float]' is for sparse data or 'Data that has a lot of holes in it' Instead of saving the NaN or None in the dataframe it omits the objects, saving space.

'Interval' is a topic of its own but its main use is for indexing. See more here

'Int8', 'Int16', 'Int32', 'Int64', 'UInt8', 'UInt16', 'UInt32', 'UInt64' are all pandas specific integers that are nullable, unlike the numpy variant.

'string' is a specific dtype for working with string data and gives access to the .str attribute on the series.

'boolean' is like the numpy 'bool' but it also supports missing data.

Read the complete reference here:

Pandas dtype reference

Gotchas, caveats, notes

Setting dtype=object will silence the above warning, but will not make it more memory efficient, only process efficient if anything.

Setting dtype=unicode will not do anything, since to numpy, a unicode is represented as object.

Usage of converters

@sparrow correctly points out the usage of converters to avoid pandas blowing up when encountering 'foobar' in a column specified as int. I would like to add that converters are really heavy and inefficient to use in pandas and should be used as a last resort. This is because the read_csv process is a single process.

CSV files can be processed line by line and thus can be processed by multiple converters in parallel more efficiently by simply cutting the file into segments and running multiple processes, something that pandas does not support. But this is a different story.

printf not printing on console

Try setting this before you print:

setvbuf (stdout, NULL, _IONBF, 0);

How do I provide a username and password when running "git clone [email protected]"?

I prefer to use GIT_ASKPASS environment for providing HTTPS credentials to git.
Provided that login and password are exported in USR and PSW variables, the following script does not leave traces of password in history and disk + it is not vulnerable to special characters in the password:

GIT_ASKPASS=$(mktemp) && chmod a+rx $GIT_ASKPASS && export GIT_ASKPASS

cat > $GIT_ASKPASS <<'EOF'
#!/bin/sh
exec echo "$PSW"
EOF

git clone https://${USR}@example.com/repo.git

Note single quotes around heredoc marker 'EOF' which means that temporary script holds literally $PSW characters, not the password

Location of my.cnf file on macOS

rDefault options are read from the following files in the given order: /etc/my.cnf /etc/mysql/my.cnf /usr/local/mysql/etc/my.cnf ~/.my.cnf

How do I lowercase a string in Python?

Also, you can overwrite some variables:

s = input('UPPER CASE')
lower = s.lower()

If you use like this:

s = "Kilometer"
print(s.lower())     - kilometer
print(s)             - Kilometer

It will work just when called.

IFrame: This content cannot be displayed in a frame

Use target="_top" attribute in anchor tag that will really work.

Unable to specify the compiler with CMake

Using with FILEPATH option might work:

set(CMAKE_CXX_COMPILER:FILEPATH C:/MinGW/bin/gcc.exe)

What's the best way to send a signal to all members of a process group?

Killing child process in shell script:

Many time we need to kill child process which are hanged or block for some reason. eg. FTP connection issue.

There are two approaches,

1) To create separate new parent for each child which will monitor and kill child process once timeout reached.

Create test.sh as follows,

#!/bin/bash

declare -a CMDs=("AAA" "BBB" "CCC" "DDD")
for CMD in ${CMDs[*]}; do
    (sleep 10 & PID=$!; echo "Started $CMD => $PID"; sleep 5; echo "Killing $CMD => $PID"; kill $PID; echo "$CMD Completed.") &
done
exit;

and watch processes which are having name as 'test' in other terminal using following command.

watch -n1 'ps x -o "%p %r %c" | grep "test" '

Above script will create 4 new child processes and their parents. Each child process will run for 10sec. But once timeout of 5sec reach, thier respective parent processes will kill those childs. So child won't be able to complete execution(10sec). Play around those timings(switch 10 and 5) to see another behaviour. In that case child will finish execution in 5sec before it reaches timeout of 10sec.

2) Let the current parent monitor and kill child process once timeout reached. This won't create separate parent to monitor each child. Also you can manage all child processes properly within same parent.

Create test.sh as follows,

#!/bin/bash

declare -A CPIDs;
declare -a CMDs=("AAA" "BBB" "CCC" "DDD")

CMD_TIME=15;
for CMD in ${CMDs[*]}; do
    (echo "Started..$CMD"; sleep $CMD_TIME; echo "$CMD Done";) &
    CPIDs[$!]="$RN";
    sleep 1;
done

GPID=$(ps -o pgid= $$);
CNT_TIME_OUT=10;
CNT=0;
while (true); do
    declare -A TMP_CPIDs;

    for PID in "${!CPIDs[@]}"; do
        echo "Checking "${CPIDs[$PID]}"=>"$PID;

        if ps -p $PID > /dev/null ; then
          echo "-->"${CPIDs[$PID]}"=>"$PID" is running..";
          TMP_CPIDs[$PID]=${CPIDs[$PID]};
        else
          echo "-->"${CPIDs[$PID]}"=>"$PID" is completed.";
        fi
    done

    if [ ${#TMP_CPIDs[@]} == 0 ]; then
        echo "All commands completed.";
        break;
    else
        unset CPIDs;
        declare -A CPIDs;
        for PID in "${!TMP_CPIDs[@]}"; do
            CPIDs[$PID]=${TMP_CPIDs[$PID]};
        done
        unset TMP_CPIDs;

        if [ $CNT -gt $CNT_TIME_OUT ]; then
            echo ${CPIDs[@]}"PIDs not reponding. Timeout reached $CNT sec. killing all childern with GPID $GPID..";
            kill -- -$GPID;
        fi
    fi

    CNT=$((CNT+1));
    echo "waiting since $b secs..";
    sleep 1;
done

exit;

and watch processes which are having name as 'test' in other terminal using following command.

watch -n1 'ps x -o "%p %r %c" | grep "test" '

Above script will create 4 new child processes. We are storing pids of all child process and looping over them to check if they are finished their execution or still running. Child process will execution till CMD_TIME time. But if CNT_TIME_OUT timeout reach , All children will get killed by parent process. You can switch timing and play around with script to see behavior. One drawback of this approach is , it is using group id for killing all child tree. But parent process itself belong to same group so it will also get killed.

You may need to assign other group id to parent process if you don’t want parent to be killed.

More details can be found here,

Killing child process in shell script

Convert unsigned int to signed int C

Since converting unsigned values use to represent positive numbers converting it can be done by setting the most significant bit to 0. Therefore a program will not interpret that as a Two`s complement value. One caveat is that this will lose information for numbers that near max of the unsigned type.

template <typename TUnsigned, typename TSinged>
TSinged UnsignedToSigned(TUnsigned val)
{
    return val & ~(1 << ((sizeof(TUnsigned) * 8) - 1));
}

Want to make Font Awesome icons clickable

             <a href="#"><i class="fab fa-facebook-square"></i></a> 
             <a href="#"><i class="fab fa-twitter-square"></i></a> 
             <a href="#"><i class="fas fa-basketball-ball"></i></a> 
             <a href="#"><i class="fab fa-google-plus-square"></i></a>


              All you have to do is wrap your font-awesome icon link in your HTML 
                               with an anchor tag.
        Following this format:
                   <a href="Link here"> <font-awesome icon code> </a>

What does hash do in python?

You can use the Dictionary data type in python. It's very very similar to the hash—and it also supports nesting, similar to the to nested hash.

Example:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

For more information, please reference this tutorial on the dictionary data type.

selecting from multi-index pandas

Understanding how to access multi-indexed pandas DataFrame can help you with all kinds of task like that.

Copy paste this in your code to generate example:

# hierarchical indices and columns
index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]],
                                   names=['year', 'visit'])
columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'Temp']],
                                     names=['subject', 'type'])

# mock some data
data = np.round(np.random.randn(4, 6), 1)
data[:, ::2] *= 10
data += 37

# create the DataFrame
health_data = pd.DataFrame(data, index=index, columns=columns)
health_data

Will give you table like this:

enter image description here

Standard access by column

health_data['Bob']
type       HR   Temp
year visit      
2013    1   22.0    38.6
        2   52.0    38.3
2014    1   30.0    38.9
        2   31.0    37.3


health_data['Bob']['HR']
year  visit
2013  1        22.0
      2        52.0
2014  1        30.0
      2        31.0
Name: HR, dtype: float64

# filtering by column/subcolumn - your case:
health_data['Bob']['HR']==22
year  visit
2013  1         True
      2        False
2014  1        False
      2        False

health_data['Bob']['HR'][2013]    
visit
1    22.0
2    52.0
Name: HR, dtype: float64

health_data['Bob']['HR'][2013][1]
22.0

Access by row

health_data.loc[2013]
subject Bob Guido   Sue
type    HR  Temp    HR  Temp    HR  Temp
visit                       
1   22.0    38.6    40.0    38.9    53.0    37.5
2   52.0    38.3    42.0    34.6    30.0    37.7

health_data.loc[2013,1] 
subject  type
Bob      HR      22.0
         Temp    38.6
Guido    HR      40.0
         Temp    38.9
Sue      HR      53.0
         Temp    37.5
Name: (2013, 1), dtype: float64

health_data.loc[2013,1]['Bob']
type
HR      22.0
Temp    38.6
Name: (2013, 1), dtype: float64

health_data.loc[2013,1]['Bob']['HR']
22.0

Slicing multi-index

idx=pd.IndexSlice
health_data.loc[idx[:,1], idx[:,'HR']]
    subject Bob Guido   Sue
type    HR  HR  HR
year    visit           
2013    1   22.0    40.0    53.0
2014    1   30.0    52.0    45.0

Shell script to set environment variables

I cannot solve it with source ./myscript.sh. It says the source not found error.
Failed also when using . ./myscript.sh. It gives can't open myscript.sh.

So my option is put it in a text file to be called in the next script.

#!/bin/sh
echo "Perform Operation in su mode"
echo "ARCH=arm" >> environment.txt
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export "CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?" >> environment.txt
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...

Tnen call it whenever is needed:

while read -r line; do
    line=$(sed -e 's/[[:space:]]*$//' <<<${line})
    var=`echo $line | cut -d '=' -f1`; test=$(echo $var)
    if [ -z "$(test)" ];then eval export "$line";fi
done <environment.txt

Microsoft Excel ActiveX Controls Disabled?

I'm an Excel developer, and I definitely felt the pain when this happened. Fortunately, I was able to find a workaround by renaming the MSForms.exd files in VBA even when Excel is running, which also can fix the issue. Excel developers who need to distribute their spreadsheets can add the following VBA code to their spreadsheets to make them immune to the MS update.

Place this code in any module.

Public Sub RenameMSFormsFiles() 
  Const tempFileName As String = "MSForms - Copy.exd"  
  Const msFormsFileName As String = "MSForms.exd"  
  On Error Resume Next 

  'Try to rename the C:\Users\[user.name]\AppData\Local\Temp\Excel8.0\MSForms.exd file  
  RenameFile Environ("TEMP") & "\Excel8.0\" & msFormsFileName, Environ("TEMP") & "\Excel8.0\" & tempFileName 
  'Try to rename the C:\Users\[user.name]\AppData\Local\Temp\VBE\MSForms.exd file  
  RenameFile Environ("TEMP") & "\VBE\" & msFormsFileName, Environ("TEMP") & "\VBE\" & tempFileName 
End Sub  

Private Sub RenameFile(fromFilePath As String, toFilePath As String) 
  If CheckFileExist(fromFilePath) Then 
      DeleteFile toFilePath  
      Name fromFilePath As toFilePath  
  End If  
End Sub

Private Function CheckFileExist(path As String) As Boolean 
  CheckFileExist = (Dir(path) <> "")  
End Function  

Private Sub DeleteFile(path As String) 
  If CheckFileExist(path) Then 
      SetAttr path, vbNormal  
      Kill path  
  End If  
End Sub    

The RenameMSFormsFiles subroutine tries to rename the MSForms.exd files in the C:\Users\[user.name]\AppData\Local\Temp\Excel8.0\ and C:\Users\[user.name]\AppData\Local\Temp\VBE\ folders to MSForms - Copy.exd.

Then call the RenameMSFormsFiles subroutine at the very beginning of the Workbook_Open event.

Private Sub Workbook_Open() 
  RenameMSFormsFiles  
End Sub

The spreadsheet will try to rename the MSForms.exd files when it opens. Obviously, this is not a perfect fix:

  1. The affected user will still experience the ActiveX control errors when running the VBA code the very first time opening the spreadsheet. Only after executing the VBA code once and restarting Excel, the issue is fixed. Normally when a user encounters a broken spreadsheet, the knee-jerk reaction is to close Excel and try to open the spreadsheet again. :)
  2. The MSForms.exd files are renamed every time the spreadsheet opens, even when there's no issue with the MSForms.exd files. But the spreadsheet will work just fine.

At least for now, Excel developers can continue to distribute their work with this workaround until Microsoft releases a fix.

I've posted this solution here.

Disabled form inputs do not appear in the request

I'm updating this answer since is very useful. Just add readonly to the input.

So the form will be:

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />
    <input type="textbox" name="Percentage" value="100" readonly/>
</form>

How to make a PHP SOAP call using the SoapClient class

There is an option to generate php5 objects with WsdlInterpreter class. See more here: https://github.com/gkwelding/WSDLInterpreter

for example:

require_once 'WSDLInterpreter-v1.0.0/WSDLInterpreter.php';
$wsdlLocation = '<your wsdl url>?wsdl';
$wsdlInterpreter = new WSDLInterpreter($wsdlLocation);
$wsdlInterpreter->savePHP('.');

How do I get a HttpServletRequest in my spring beans?

Better way is to autowire with a constructor:

private final HttpServletRequest httpServletRequest;

public ClassConstructor(HttpServletRequest httpServletRequest){
      this.httpServletRequest = httpServletRequest;
}

Check image width and height before upload with Javascript

function uploadfile(ctrl) {
    var validate = validateimg(ctrl);

    if (validate) {
        if (window.FormData !== undefined) {
            ShowLoading();
            var fileUpload = $(ctrl).get(0);
            var files = fileUpload.files;


            var fileData = new FormData();


            for (var i = 0; i < files.length; i++) {
                fileData.append(files[i].name, files[i]);
            }


            fileData.append('username', 'Wishes');

            $.ajax({
                url: 'UploadWishesFiles',
                type: "POST",
                contentType: false,
                processData: false,
                data: fileData,
                success: function(result) {
                    var id = $(ctrl).attr('id');
                    $('#' + id.replace('txt', 'hdn')).val(result);

                    $('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();

                    HideLoading();
                },
                error: function(err) {
                    alert(err.statusText);
                    HideLoading();
                }
            });
        } else {
            alert("FormData is not supported.");
        }

    }

Dropdownlist width in IE

@Thad you need to add a blur event handler as well

$(document).ready(function(){
    $("#dropdown").mousedown(function(){
        if($.browser.msie) {
            $(this).css("width","auto");
        }
    });
    $("#dropdown").change(function(){
        if ($.browser.msie) {
            $(this).css("width","175px");
        }
    });
    $("#dropdown").blur(function(){
        if ($.browser.msie) {
            $(this).css("width","175px");
        }
    });
});

However, this will still expand the selectbox on click, instead of just the elements. (and it seems to fail in IE6, but works perfectly in Chrome and IE7)

Delete all but the most recent X files in bash

Ignoring newlines is ignoring security and good coding. wnoise had the only good answer. Here is a variation on his that puts the filenames in an array $x

while IFS= read -rd ''; do 
    x+=("${REPLY#* }"); 
done < <(find . -maxdepth 1 -printf '%T@ %p\0' | sort -r -z -n )

What is the use of style="clear:both"?

clear:both makes the element drop below any floated elements that precede it in the document.

You can also use clear:left or clear:right to make it drop below only those elements that have been floated left or right.

+------------+ +--------------------+
|            | |                    |
| float:left | |   without clear    |
|            | |                    |
|            | +--------------------+
|            | +--------------------+
|            | |                    |
|            | |  with clear:right  |
|            | |  (no effect here,  |
|            | |   as there is no   |
|            | |   float:right      |
|            | |   element)         |
|            | |                    |
|            | +--------------------+
|            |
+------------+
+---------------------+
|                     |
|   with clear:left   |
|    or clear:both    |
|                     |
+---------------------+

Get the latest date from grouped MySQL data

You can try using max() in subquery, something like this :

SELECT model, date  
FROM doc 
WHERE date in (SELECT MAX(date) from doc GROUP BY model);

Key hash for Android-Facebook app

keytool -exportcert -alias androiddebugkey -keystore       C:\Users\pravin\.android\debug.keystore | "H:\OpenSSL\bin\openssl" sha1 -binary | "H:\OpenSSL\bin\openssl" base64

This worked for me ...

Steps:

1) Open command line go to - > java Keytool..... for me C:\Program Files\Java\JDK1.7\bin
2) Download OpenSSL from google
3) paste this with changing your paths -
   keytool -exportcert -alias androiddebugkey -keystore C:\Users\pravin\.android\debug.keystore | "H:\OpenSSL\bin\openssl" sha1 -binary | "H:\OpenSSL\bin\openssl" base64 

    ....................   give proper debug.keystore path and openSSL path .. 

4) Finley it may be ask u password .. so give password -> android   ...
5) you will get 28 characters that will be your has key

Create File If File Does Not Exist

Yes, you need to negate File.Exists(path) if you want to check if the file doesn't exist.

PHP salt and hash SHA256 for login password

These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.

Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php

Save a password hash:

$options = [
    'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];

$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);

// Now insert it (with login or whatever) into your database, use mysqli or pdo!

Get the password hash:

// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

Modulo operator in Python

Same thing you'd expect from normal modulo .. e.g. 7 % 4 = 3, 7.3 % 4.0 = 3.3

Beware of floating point accuracy issues.

how to run a winform from console application?

It´s very simple to do:

Just add following attribute and code to your Main-method:

[STAThread]
void Main(string[] args])
{
   Application.EnableVisualStyles();
   //Do some stuff...
   while(!Exit)
   {
       Application.DoEvents(); //Now if you call "form.Show()" your form won´t be frozen
       //Do your stuff
   }
}

Now you´re fully able to show WinForms :)

Stopping a JavaScript function when a certain condition is met

use return for this

if(i==1) { 
    return; //stop the execution of function
}

//keep on going

How do I 'foreach' through a two-dimensional array?

I try this. I hope to help. It work with

static void Main()
    {
        string[,] matrix = {
                               { "aa", "aaa" },
                               { "bb", "bbb" }
                           };
        int index = 0;
        foreach (string element in matrix)
        {
            if (index < matrix.GetLength(1))
            {
                Console.Write(element);
                if (index < (matrix.GetLength(1) - 1))
                {
                    Console.Write(" ");
                }
                index++;
            }
            if (index == matrix.GetLength(1))
            {
                Console.Write("\n");
                index = 0;
            }
        }

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

Refer to here

write query with named parameter, use simple ListPreparedStatementSetter with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,

ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);

List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
    parameters.add(a.getId());

MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);     
return sql;

Populate data table from data reader

You can load a DataTable directly from a data reader using the Load() method that accepts an IDataReader.

var dataReader = cmd.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(dataReader);

Send POST data via raw json with postman

Just check JSON option from the drop down next to binary; when you click raw. This should do

skill synon pass json to postman

Get current URL/URI without some of $_GET variables

You are definitely searching for this

Yii::app()->request->pathInfo

How to center HTML5 Videos?

I found this page while trying to center align a pair of videos. So, if I enclose both videos in a center div (which I've called central), the margin trick works, but the width is important (2 videos at 400 + padding etc)

<div class=central>
    <video id="vid1" width="400" controls>
        <source src="Carnival01.mp4" type="video/mp4">
    </video> 

    <video id="vid2" width="400" controls>
        <source src="Carnival02.mp4" type="video/mp4">
    </video>
</div>

<style>
div.central { 
  margin: 0 auto;
  width: 880px; <!--this value must be larger than both videos + padding etc-->
}
</style>

Worked for me!

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

This is often caused by an attempt to process a null object. An example, trying to empty a Bindable list that is null will trigger the exception:

public class MyViewModel {
    [BindableProperty]
    public virtual IList<Products> ProductsList{ get; set; }

    public MyViewModel ()
    {
        ProductsList.Clear(); // here is the problem
    }
}

This could easily be fixed by checking for null:

if (ProductsList!= null) ProductsList.Clear();

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

Just a few lines in the /etc/mysql/mariadb.conf.d/50-server.cnf or wherever your config is:

innodb-file-format=barracuda
innodb-file-per-table=ON
innodb-large-prefix=ON
innodb_default_row_format = 'DYNAMIC'

and sudo service mysql restart

https://stackoverflow.com/a/57465235/778234

See the docs: https://dev.mysql.com/doc/refman/5.6/en/innodb-row-format.html

Could someone explain this for me - for (int i = 0; i < 8; i++)

for(<first part>; <second part>; <third part>)
{
    DoStuff();
}

This code is evaluated like this:

  1. Run <first part>
  2. If <second part> is false, skip to the end
  3. DoStuff();
  4. Run <third part>
  5. Goto 2

So for your example:

for (int i = 0; i < 8; i++)
{
    DoStuff();
}
  1. Set i to 0.
  2. If i is not less than 8, skip to the end.
  3. DoStuff();
  4. i++
  5. Goto 2

So the loop runs one time with i set to each value from 0 to 7. Note that i is incremented to 8, but then the loop ends immediately afterwards; it does not run with i set to 8.

Installed Java 7 on Mac OS X but Terminal is still using version 6

I did

export JAVA_HOME=`/usr/libexec/java_home`

and that fixed my Java 8 issue.

before:

java version "1.6.0_31"
Java(TM) SE Runtime Environment (build 1.6.0_31-b04)
Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01, mixed mode)

after:

java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)

What is Scala's yield?

Yield is similar to for loop which has a buffer that we cannot see and for each increment, it keeps adding next item to the buffer. When the for loop finishes running, it would return the collection of all the yielded values. Yield can be used as simple arithmetic operators or even in combination with arrays. Here are two simple examples for your better understanding

scala>for (i <- 1 to 5) yield i * 3

res: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 6, 9, 12, 15)

scala> val nums = Seq(1,2,3)
nums: Seq[Int] = List(1, 2, 3)

scala> val letters = Seq('a', 'b', 'c')
letters: Seq[Char] = List(a, b, c)

scala> val res = for {
     |     n <- nums
     |     c <- letters
     | } yield (n, c)

res: Seq[(Int, Char)] = List((1,a), (1,b), (1,c), (2,a), (2,b), (2,c), (3,a), (3,b), (3,c))

Hope this helps!!

Comparing two integer arrays in Java

You can check array equality with the Apache Commons ArrayUtils#isEquals() method.

How to get info on sent PHP curl request

The request is printed in a request.txt with details

$ch = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt_array($ch, array(
CURLOPT_URL            => $url, 
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE        => 1,
CURLOPT_STDERR         => $f,
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);

You can also use curl_getinfo() function.

Store query result in a variable using in PL/pgSQL

I think you're looking for SELECT INTO:

select test_table.name into name from test_table where id = x;

That will pull the name from test_table where id is your function's argument and leave it in the name variable. Don't leave out the table name prefix on test_table.name or you'll get complaints about an ambiguous reference.

Figure out size of UILabel based on String in Swift

Heres a simple solution thats working for me... similar to some of the others posted, but it doesn't not include the need for calling sizeToFit

Note this is written in Swift 5

let lbl = UILabel()
lbl.numberOfLines = 0
lbl.font = UIFont.systemFont(ofSize: 12) // make sure you set this correctly 
lbl.text = "My text that may or may not wrap lines..."

let width = 100.0 // the width of the view you are constraint to, keep in mind any applied margins here

let height = lbl.systemLayoutSizeFitting(CGSize(width: width, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel).height

This handles line wrapping and such. Not the most elegant code, but it gets the job done.

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

in angular 7, you have to import "ReactiveFormsModule".

import {FormsModule, ReactiveFormsModule} from '@angular/forms';

I solved this issue by this import.It would help you.

How to restart Postgresql

macOS:

  1. On the top left of the MacOS menu bar you have the Postgres Icon
  2. Click on it this opens a drop down menu
  3. Click on Stop -> than click on start

Set a button group's width to 100% and make buttons equal width?

Bootstrap 4 Solution

<div class="btn-group w-100">
    <button type="button" class="btn">One</button>
    <button type="button" class="btn">Two</button>
    <button type="button" class="btn">Three</button>
</div>

You basically tell the btn-group container to have width 100% by adding w-100 class to it. The buttons inside will fill in the whole space automatically.

Using strtok with a std::string

Assuming that by "string" you're talking about std::string in C++, you might have a look at the Tokenizer package in Boost.

passing 2 $index values within nested ng-repeat

Just to help someone who get here... You should not use $parent.$index as it's not really safe. If you add an ng-if inside the loop, you get the $index messed!

Right way

  <table>
    <tr ng-repeat="row in rows track by $index" ng-init="rowIndex = $index">
        <td ng-repeat="column in columns track by $index" ng-init="columnIndex = $index">

          <b ng-if="rowIndex == columnIndex">[{{rowIndex}} - {{columnIndex}}]</b>
          <small ng-if="rowIndex != columnIndex">[{{rowIndex}} - {{columnIndex}}]</small>

        </td>
    </tr>
  </table>

Check: plnkr.co/52oIhLfeXXI9ZAynTuAJ

Android - shadow on text?

If you want to achieve a shadow like the one that Android does in the Launcher, we're managing these values. They're useful if you want to create TextViews that will appear as a Widget, without a background.

android:shadowColor="#94000000"
android:shadowDy="2"
android:shadowRadius="4"

xsl: how to split strings?

I. Plain XSLT 1.0 solution:

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="text()" name="split">
  <xsl:param name="pText" select="."/>
  <xsl:if test="string-length($pText)">
   <xsl:if test="not($pText=.)">
    <br />
   </xsl:if>
   <xsl:value-of select=
    "substring-before(concat($pText,';'),';')"/>
   <xsl:call-template name="split">
    <xsl:with-param name="pText" select=
     "substring-after($pText, ';')"/>
   </xsl:call-template>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

produces the wanted, corrected result:

123 Elm Street<br />PO Box 222<br />c/o James Jones

II. FXSL 1 (for XSLT 1.0):

Here we just use the FXSL template str-map (and do not have to write recursive template for the 999th time):

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/"
xmlns:testmap="testmap"
exclude-result-prefixes="xsl f testmap"
>
   <xsl:import href="str-dvc-map.xsl"/>

   <testmap:testmap/>

   <xsl:output omit-xml-declaration="yes" indent="yes"/>

   <xsl:template match="/">
     <xsl:variable name="vTestMap" select="document('')/*/testmap:*[1]"/>
     <xsl:call-template name="str-map">
       <xsl:with-param name="pFun" select="$vTestMap"/>
       <xsl:with-param name="pStr" select=
       "'123 Elm Street;PO Box 222;c/o James Jones'"/>
     </xsl:call-template>
   </xsl:template>

    <xsl:template name="replace" mode="f:FXSL"
         match="*[namespace-uri() = 'testmap']">
      <xsl:param name="arg1"/>

      <xsl:choose>
       <xsl:when test="not($arg1=';')">
        <xsl:value-of select="$arg1"/>
       </xsl:when>
       <xsl:otherwise><br /></xsl:otherwise>
      </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), the same, wanted correct result is produced:

123 Elm Street<br/>PO Box 222<br/>c/o James Jones

III. Using XSLT 2.0

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="text()">
  <xsl:for-each select="tokenize(.,';')">
   <xsl:sequence select="."/>
   <xsl:if test="not(position() eq last())"><br /></xsl:if>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

the wanted, correct result is produced:

123 Elm Street<br />PO Box 222<br />c/o James Jones

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I know it is an answered question, but I do not see the cause that I faced.

It was that Android Studio placed my drawables in /drawable-V24 My emulator is API 23. So, eventually it can not find it.

The solution was to move all drawables to /drawable folder (no -24).

How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

<?php
    $db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
    <body>
          <?php
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page
                }
          ?>
    </body>
</html>

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

jQuery get the rendered height of an element?

Have you set the height in the css specifically? If you haven't you need to use offsetHeight; rather than height

var h = document.getElementById('someDiv').style.offsetHeight;

How to do a scatter plot with empty circles in Python?

Would these work?

plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')

example image

or using plot()

plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')

example image

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

If you use MVC, tables, it works like this:

<td>@(((DateTime)detalle.fec).ToString("dd'/'MM'/'yyyy"))</td>

SELECT from nothing?

There is another possibility - standalone VALUES():

VALUES ('Hello World');

Output:

column1
Hello World

It is useful when you need to specify multiple values in compact way:

VALUES (1, 'a'), (2, 'b'), (3, 'c');

Output:

column1     column2
      1     a
      2     b
      3     c

DBFiddle Demo

This syntax is supported by SQLite/PostgreSQL/DB LUW/MariaDB 10.3.

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

Laravel Testing with sqlite needs php pdo sqlite drivers

For Ubuntu 14.04

sudo apt-get install php5-sqlite
sudo service apache2 restart

In ubuntu 16.04 there is no php5-sqlite

sudo apt-get install php7.0-sqlite
sudo service apache2 restart

UINavigationBar custom back button without title

I have been using this solution since iOS 5 or so without any problems. I made a utility function that I call in my view controllers. You need to do it either in viewDidLoad or any point after that.

void updateBackButtonTextForViewController(UIViewController *viewController, NSString *text)
{
    if(! viewController.navigationItem.backBarButtonItem)
    {
        viewController.navigationItem.backBarButtonItem =
        [[UIBarButtonItem alloc] initWithTitle:text
                                         style:UIBarButtonItemStylePlain
                                        target:nil action:nil];
    }
    else
    {
        viewController.navigationItem.backBarButtonItem.title = text;
    }
}

In some cases the navigation item may already exist, in other cases it needs to be created. This accounts for both of those cases without messing with the navigation item title. It allows you to remove the title by simply passing in @"".

How can I create a UIColor from a hex string?

There's a nice post on how to tackle the OP's question of extracting a UIColor from a hex string. The solution presented below is different from others because it supports string values that may include '0x' or '#' prefixed to the hex string representation... (see usage)

Here's the main bit...

- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
  // Convert hex string to an integer
  unsigned int hexint = [self intFromHexString:hexStr];

  // Create a color object, specifying alpha as well
  UIColor *color =
    [UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255
    green:((CGFloat) ((hexint & 0xFF00) >> 8))/255
    blue:((CGFloat) (hexint & 0xFF))/255
    alpha:alpha];

  return color;
}

Helper method...

- (unsigned int)intFromHexString:(NSString *)hexStr
{
  unsigned int hexInt = 0;

  // Create scanner
  NSScanner *scanner = [NSScanner scannerWithString:hexStr];

  // Tell scanner to skip the # character
  [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];

  // Scan hex value
  [scanner scanHexInt:&hexInt];

  return hexInt;
}

Usage:

NSString *hexStr1 = @"123ABC";
NSString *hexStr2 = @"#123ABC";
NSString *hexStr3 = @"0x123ABC";

UIColor *color1 = [self getUIColorObjectFromHexString:hexStr1 alpha:.9];
NSLog(@"UIColor: %@", color1);

UIColor *color2 = [self getUIColorObjectFromHexString:hexStr2 alpha:.9];
NSLog(@"UIColor: %@", color2);

UIColor *color3 = [self getUIColorObjectFromHexString:hexStr3 alpha:.9];
NSLog(@"UIColor: %@", color3);

Complete Reference Article

Swift 2+

I've ported this solution to Swift 2.2. Note that I've changed the alpha parameter to use a default set to 1.0. I've also updated the int type to UInt32 as required by the NSScanner class in Swift 2.2.

func colorWithHexString(hexString: String, alpha:CGFloat = 1.0) -> UIColor {

    // Convert hex string to an integer
    let hexint = Int(self.intFromHexString(hexString))
    let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
    let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
    let blue = CGFloat((hexint & 0xff) >> 0) / 255.0 

    // Create color object, specifying alpha as well
    let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
    return color
}

func intFromHexString(hexStr: String) -> UInt32 {
    var hexInt: UInt32 = 0
    // Create scanner
    let scanner: NSScanner = NSScanner(string: hexStr)
    // Tell scanner to skip the # character
    scanner.charactersToBeSkipped = NSCharacterSet(charactersInString: "#")
    // Scan hex value
    scanner.scanHexInt(&hexInt)
    return hexInt
}

Swift 4+

Using the same logic with changes applied for swift 4,

func colorWithHexString(hexString: String, alpha:CGFloat = 1.0) -> UIColor {

    // Convert hex string to an integer
    let hexint = Int(self.intFromHexString(hexStr: hexString))
    let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
    let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
    let blue = CGFloat((hexint & 0xff) >> 0) / 255.0

    // Create color object, specifying alpha as well
    let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
    return color
}

func intFromHexString(hexStr: String) -> UInt32 {
    var hexInt: UInt32 = 0
    // Create scanner
    let scanner: Scanner = Scanner(string: hexStr)
    // Tell scanner to skip the # character
    scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
    // Scan hex value
    scanner.scanHexInt32(&hexInt)
    return hexInt
}

Color Hex References

HTML Color Names and Codes

Color Hex Color Codes

jQuery check/uncheck radio button onclick

Improved version of answer from Jurrie

$('#myRadio').off('click').on('click', function() {
  if ($(this).data('checked')) {
    $(this).removeAttr('checked');
    $(this).data('checked', false);
  } else {
    $(this).data('checked', true);
  }
});

Live Demo

What is the meaning of {...this.props} in Reactjs

It is ES-6 feature. It means you extract all the properties of props in div.{... }

operator is used to extract properties of an object.

How do you make a deep copy of an object?

A few people have mentioned using or overriding Object.clone(). Don't do it. Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone.

The schemes that rely on serialization (XML or otherwise) are kludgy.

There is no easy answer here. If you want to deep copy an object you will have to traverse the object graph and copy each child object explicitly via the object's copy constructor or a static factory method that in turn deep copies the child object. Immutables (e.g. Strings) do not need to be copied. As an aside, you should favor immutability for this reason.

How to use radio buttons in ReactJS?

To build upon ChinKang said for his answer, I have a more dry'er approach and in es6 for those interested:

class RadioExample extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedRadio: 'public'
    };
  }

  handleRadioChange = (event) => {
    this.setState({
      selectedRadio: event.currentTarget.value
    })
  };

  render() {
    return (
      <div className="radio-row">
        <div className="input-row">
          <input
            type="radio"
            name="public"
            value="public"
            checked={this.state.selectedRadio === 'public'}
            onChange={this.handleRadioChange}
          />
          <label htmlFor="public">Public</label>
        </div>
        <div className="input-row">
          <input
            type="radio"
            name="private"
            value="private"
            checked={this.state.selectedRadio === 'private'}
            onChange={this.handleRadioChange}
          />
          <label htmlFor="private">Private</label>
        </div>
      </div>
    )
  }
}

except this one would have a default checked value.

How to print to console in pytest?

By default, py.test captures the result of standard out so that it can control how it prints it out. If it didn't do this, it would spew out a lot of text without the context of what test printed that text.

However, if a test fails, it will include a section in the resulting report that shows what was printed to standard out in that particular test.

For example,

def test_good():
    for i in range(1000):
        print(i)

def test_bad():
    print('this should fail!')
    assert False

Results in the following output:

>>> py.test tmp.py
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items

tmp.py .F

=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________

    def test_bad():
        print('this should fail!')
>       assert False
E       assert False

tmp.py:7: AssertionError
------------------------------- Captured stdout --------------------------------
this should fail!
====================== 1 failed, 1 passed in 0.04 seconds ======================

Note the Captured stdout section.

If you would like to see print statements as they are executed, you can pass the -s flag to py.test. However, note that this can sometimes be difficult to parse.

>>> py.test tmp.py -s
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items

tmp.py 0
1
2
3
... and so on ...
997
998
999
.this should fail!
F

=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________

    def test_bad():
        print('this should fail!')
>       assert False
E       assert False

tmp.py:7: AssertionError
====================== 1 failed, 1 passed in 0.02 seconds ======================

Check if any type of files exist in a directory using BATCH script

For files in a directory, you can use things like:

if exist *.csv echo "csv file found"

or

if not exist *.csv goto nofile

How to store JSON object in SQLite database

There is no data types for that.. You need to store it as VARCHAR or TEXT only.. jsonObject.toString();

How do I get the value of text input field using JavaScript?

Just try this ..

_x000D_
_x000D_
function handleValueChange() {
    var y = document.getElementById('textbox_id').value;
    var x = document.getElementById('result');
    x.innerHTML = y;
}

function changeTextarea() {
  var a = document.getElementById('text-area').value;
  var b = document.getElementById('text-area-result');
  b.innerHTML = a;
}
_x000D_
input {
  padding: 5px;
}

p {
  white-space: pre;
}
_x000D_
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>

<textarea name="" id="text-area" cols="20" rows="5" oninput="changeTextarea()"></textarea>
<p id="text-area-result"></p>
_x000D_
_x000D_
_x000D_

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

Same from above with little modification

_x000D_
_x000D_
function focusMe() {_x000D_
       var rowpos = $('#FocusME').position();_x000D_
        rowpos.top = rowpos.top - 30;_x000D_
        $('#container').scrollTop(rowpos.top);_x000D_
    }
_x000D_
<html>_x000D_
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>_x000D_
<body>_x000D_
    <input type="button" onclick="focusMe()" value="focus">_x000D_
    <div id="container" style="max-height:200px;overflow:scroll;">_x000D_
        <table>_x000D_
            <tr>_x000D_
                <td>1</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>2</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>3</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>4</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>5</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>6</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>7</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>8</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>9</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr id="FocusME">_x000D_
                <td>10</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>11</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>12</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>13</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>14</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>15</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>16</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>17</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>18</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>19</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>20</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
        </table>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Visual Studio Code open tab in new window

On Windows and Linux, press Ctrl+K, then release the keys and press O (the letter O, not Zero).

On macOS, press command+K, then O (without holding command).

This will open the active file tab in a new window/instance.

Passing environment-dependent variables in webpack

Since my Edit on the above post by thevangelist wasn't approved, posting additional information.

If you want to pick value from package.json like a defined version number and access it through DefinePlugin inside Javascript.

{"version": "0.0.1"}

Then, Import package.json inside respective webpack.config, access the attribute using the import variable, then use the attribute in the DefinePlugin.

const PACKAGE = require('../package.json');
const _version = PACKAGE.version;//Picks the version number from package.json

For example certain configuration on webpack.config is using METADATA for DefinePlugin:

const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR,
  RELEASE_VERSION:_version//Version attribute retrieved from package.json
});

new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
          'VERSION': JSON.stringify(METADATA.RELEASE_VERSION)//Setting it for the Scripts usage.
        }
      }),

Access this inside any typescript file:

this.versionNumber = process.env.VERSION;

The smartest way would be like this:

// webpack.config.js
plugins: [
    new webpack.DefinePlugin({
      VERSION: JSON.stringify(require("./package.json").version)
    })
  ]

Thanks to Ross Allen

How to close a Tkinter window by pressing a Button?

from tkinter import *

window = tk()
window.geometry("300x300")

def close_window (): 

    window.destroy()

button = Button ( text = "Good-bye", command = close_window)
button.pack()

window.mainloop()

Postgres: check if array field contains value?

This should work:

select * from mytable where 'Journal'=ANY(pub_types);

i.e. the syntax is <value> = ANY ( <array> ). Also notice that string literals in postresql are written with single quotes.

Get Environment Variable from Docker Container

If by any chance you use VSCode and has installed the docker extension, just right+click on the docker you want to check (within the docker extension), click on Inspect, and there search for env, you will find all your env variables values

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

Changing Vim indentation behavior by file type

Personally, I use these settings in .vimrc:

autocmd FileType python set tabstop=8|set shiftwidth=2|set expandtab
autocmd FileType ruby set tabstop=8|set shiftwidth=2|set expandtab

Angular 2 - innerHTML styling

Use the below method to allow css styles in innerhtml.

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
.
.
.
.
html: SafeHtml;

constructor(protected _sanitizer: DomSanitizer) {
this.html = this._sanitizer.bypassSecurityTrustHtml(`
<html>
  <head></head>
  <body>
    <div style="display:flex; color: blue;">
      <div>
        <h1>Hello World..!!!!!</h1>
      </div>
    </div>
  </body>
</html>`);
}

Example code stackblitz

Or use the below method to write directly in html. https://gist.github.com/klihelp/4dcac910124409fa7bd20f230818c8d1

Content-Disposition:What are the differences between "inline" and "attachment"?

Because when I use one or another I get a window prompt asking me to download the file for both of them.

This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.

For example, if you have a PDF file and Firefox/Adobe Reader, an inline disposition will open the PDF within Firefox, whereas attachment will force it to download.

If you're serving a .ZIP file, browsers won't be able to display it inline, so for inline and attachment dispositions, the file will be downloaded.

passing form data to another HTML page

*first html page*

<form action="display.jsp" >
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />
</form>


*Second html page*
<body>
<p>The serial number is:<%=request.getParameter("serialNumber") %></p>
</body>


you will get the value of the textbox on another page.

What should main() return in C and C++?

Returning 0 should tell the programmer that the program has successfully finished the job.

Drawing circles with System.Drawing

PictureBox circle = new PictureBox();
circle.Paint += new PaintEventHandler(circle_Paint);        

void circle_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawEllipse(Pens.Red, 0, 0, 30, 30);
        }

Byte array to image conversion

One liner:

Image bmp = (Bitmap)((new ImageConverter()).ConvertFrom(imageBytes));

Reloading submodules in IPython

I hate to add yet another answer to a long thread, but I found a solution that enables recursive reloading of submodules on %run() that others might find useful (I have anyway)

del the submodule you wish to reload on run from sys.modules in iPython:

In[1]: from sys import modules
In[2]: del modules["mymodule.mysubmodule"] # tab completion can be used like mymodule.<tab>!

Now your script will recursively reload this submodule:

In[3]: %run myscript.py

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

Add zero-padding to a string

You can use PadLeft

var newString = Your_String.PadLeft(4, '0');

How to serialize SqlAlchemy result to JSON?

You could just output your object as a dictionary:

class User:
   def as_dict(self):
       return {c.name: getattr(self, c.name) for c in self.__table__.columns}

And then you use User.as_dict() to serialize your object.

As explained in Convert sqlalchemy row object to python dict

CSS: Set a background color which is 50% of the width of the window

One way to implement your issue is to add a single line to your div's css:

background-image: linear-gradient(90deg, black 50%, blue 50%);

Here is a demonstration code and more options (horizontal, diagonal, etc.), you can click on "Run code snippet" to see it live.

_x000D_
_x000D_
.abWhiteAndBlack
{
  background-image: linear-gradient(90deg, black 50%, blue 50%);
  height: 300px;
  width: 300px;
  margin-bottom: 80px;
}

.abWhiteAndBlack2
{
  background-image: linear-gradient(180deg, black 50%, blue 50%);
  height: 300px;
  width: 300px;
  margin-bottom: 80px;
}

.abWhiteAndBlack3
{
  background-image: linear-gradient(45deg, black 50%, blue 50%);
  height: 300px;
  width: 300px;
  margin-bottom: 80px;
}
_x000D_
Vertical:

  <div class="abWhiteAndBlack">
  </div>


Horizonal:

  <div class="abWhiteAndBlack2">
    
  </div>


Diagonal:

  <div class="abWhiteAndBlack3">
    
  </div>
_x000D_
_x000D_
_x000D_

Why can't DateTime.Parse parse UTC date

or use the AdjustToUniversal DateTimeStyle in a call to

DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles)

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

How to enable PHP's openssl extension to install Composer?

Wamp works with another php.ini that is in C:\wamp\bin\apache\Apache2.4.4\bin\php.ini. So you need to manualy find the correct file, that is in C:\wamp\bin\php\php5.4.12\php.ini. Uncomment the extension=php_openssl.dll line and just try to install Composer again.

org.apache.jasper.JasperException: Unable to compile class for JSP:

There's no need to manually put class files on Tomcat. Just make sure your package declaration for Member is correctly defined as

package pageNumber;

since, that's the only application package you're importing in your JSP.

<%@ page import="pageNumber.*, java.util.*, java.io.*" %>

How to select a CRAN mirror in R

If you need to set the mirror in a non-interactive way (for example doing an rbundler install in a deploy script) you can do it in this way:

First manually run:

chooseCRANmirror()

Pick the mirror number that is best for you and remember it. Then to automate the selection:

R -e 'chooseCRANmirror(graphics=FALSE, ind=87);library(rbundler);bundle()'

Where 87 is the number of the mirror you would like to use. This snippet also installs the rbundle for you. You can omit that if you like.

SQL: Combine Select count(*) from multiple tables

select 
  (select count(*) from foo) as foo
, (select count(*) from bar) as bar
, ...

<SELECT multiple> - how to allow only one item selected?

Why don't you want to remove the multiple attribute? The entire purpose of that attribute is to specify to the browser that multiple values may be selected from the given select element. If only a single value should be selected, remove the attribute and the browser will know to allow only a single selection.

Use the tools you have, that's what they're for.

Spring MVC - How to get all request params in a map in Spring controller?

While the other answers are correct it certainly is not the "Spring way" to use the HttpServletRequest object directly. The answer is actually quite simple and what you would expect if you're familiar with Spring MVC.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}

Difference between iCalendar (.ics) and the vCalendar (.vcs)

You can try VCS to ICS file converter (Java, works with Windows, Mac, Linux etc.). It has the feature of parsing events and todos. You can convert the VCS generated by your Nokia phone, with bluetooth export or via nbuexplorer.

  • Complete support for UTF-8
  • Quoted-printable encoded strings
  • Completely open source code (GPLv3 and Apache 2.0)
  • Standard iCalendar v2.0 output
  • Encodes multiple files at once (only one event per file)
  • Compatible with Android, iOS, Mozilla Lightning/Sunbird, Google Calendar and others
  • Multiplatform

Getting execute permission to xp_cmdshell

tchester said :

(2) Create a login for the non-sysadmin user that has public access to the master database

I went to my user's database list (server/security/connections/my user name/properties/user mapping, and wanted to check the box for master database. I got an error message telling that the user already exists in the master database. Went to master database, dropped the user, went back to "user mapping" and checked the box for master. Check the "public" box below.

After that, you need to re-issue the grant execute on xp_cmdshell to "my user name"

Yves

Java, Check if integer is multiple of a number

Use modulo

whenever a number x is a multiple of some number y, then always x % y equal to 0, which can be used as a check. So use

if (j % 4 == 0) 

How do you delete all text above a certain line

dgg

will delete everything from your current line to the top of the file.

d is the deletion command, and gg is a movement command that says go to the top of the file, so when used together, it means delete from my current position to the top of the file.

Also

dG

will delete all lines at or below the current one

How can I pass a reference to a function, with parameters?

What you are after is called partial function application.

Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.

Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?

Example:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

Again, see that question for the details.

Getting the inputstream from a classpath resource (XML file)

ClassLoader.class.getResourceAsStream("/path/to/your/xml") and make sure that your compile script is copying the xml file to where in your CLASSPATH.

What is the best (and safest) way to merge a Git branch into master?

This is from GitLab: Just follow the instructions:

enter image description here

cannot import name patterns

Pattern module in not available from django 1.8. So you need to remove pattern from your import and do something similar to the following:

from django.conf.urls import include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = [                 
    # here we are not using pattern module like in previous django versions
    url(r'^admin/', include(admin.site.urls)),
]

What is "overhead"?

You can check Wikipedia. But mainly when more actions or resources are used. Like if you are familiar with .NET there you can have value types and reference types. Reference types have memory overhead as they require more memory than value types.

Declaring a variable and setting its value from a SELECT query in Oracle

One Additional point:

When you are converting from tsql to plsql you have to worry about no_data_found exception

DECLARE
   v_var NUMBER;
BEGIN
   SELECT clmn INTO v_var FROM tbl;
Exception when no_data_found then v_var := null; --what ever handle the exception.
END;

In tsql if no data found then the variable will be null but no exception

How to create a printable Twitter-Bootstrap page

Be sure to have a stylesheet assigned for printing.
It could be a separate stylesheet:

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

or one you share for all devices:

<link rel="stylesheet" type="text/css" href="bootstrap.min.css"> # Note there's no media attribute

Then, you can write your styles for printers in the separate stylesheets or in the shared one using media queries:

@media print {
    /* Your styles here */
}

Is an empty href valid?

Although this question is already answered (tl;dr: yes, an empty href value is valid), none of the existing answers references the relevant specifications.

An empty string can’t be a URI. However, the href attribute doesn’t only take URIs as value, but also URI references. An empty string may be a URI reference.

HTML 4.01

HTML 4.01 uses RFC 2396, where it says in section 4.2. Same-document References (bold emphasis mine):

A URI reference that does not contain a URI is a reference to the current document. In other words, an empty URI reference within a document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference to the identified fragment of that document.

RFC 2396 is obsoleted by RFC 3986 (which is currently IETF’s URI standard), which essentially says the same.

HTML5

HTML5 uses (valid URL potentially surrounded by spaces ? valid URL) W3C’s URL spec, which has been discontinued. WHATWG’s URL Standard should be used instead (see the last section).

HTML 5.1

HTML 5.1 uses (valid URL potentially surrounded by spaces ? valid URL) WHATWG’s URL Standard (see the next section).

WHATWG HTML

WHATWG’s HTML uses (valid URL potentially surrounded by spaces) the definition of valid URL string from WHATWG’s URL Standard, where it says that it can be a relative-URL-with-fragment string, which must at least be a relative-URL string, which can be a path-relative-scheme-less-URL string, which is a path-relative-URL string that doesn’t start with a scheme string followed by :, and its definition says (bold emphasis mine):

A path-relative-URL string must be zero or more URL-path-segment strings, separated from each other by U+002F (/), and not start with U+002F (/).

How to get a variable name as a string in PHP?

I know this is old and already answered but I was actually looking for this. I am posting this answer to save people a little time refining some of the answers.

Option 1:

$data = array('$FooBar');  

$vars = [];  
$vars = preg_replace('/^\\$/', '', $data); 

$varname = key(compact($vars));  
echo $varname;

Prints:

FooBar

For whatever reason you would find yourself in a situation like this, it does actually work.

.
Option 2:

$FooBar = "a string";  

$varname = trim(array_search($FooBar, $GLOBALS), " \t.");  
echo $varname;

If $FooBar holds a unique value, it will print 'FooBar'. If $FooBar is empty or null it will print the name of the first empty or null string it finds.

It could be used as such:

if (isset($FooBar) && !is_null($FooBar) && !empty($FooBar)) {
    $FooBar = "a string";
    $varname = trim(array_search($FooBar, $GLOBALS), " \t.");
}

Fully custom validation error message with Rails

I tried following, worked for me :)

1 job.rb

class Job < ApplicationRecord
    validates :description, presence: true
    validates :title, 
              :presence => true, 
              :length => { :minimum => 5, :message => "Must be at least 5 characters"}
end

2 jobs_controller.rb

def create
      @job = Job.create(job_params)
      if @job.valid?
        redirect_to jobs_path
      else
        render new_job_path
      end     
    end

3 _form.html.erb

<%= form_for @job do |f| %>
  <% if @job.errors.any? %>
    <h2>Errors</h2>
    <ul>
      <% @job.errors.full_messages.each do |message|%>
        <li><%= message %></li>
      <% end %>  
    </ul>
  <% end %>
  <div>
    <%= f.label :title %>
    <%= f.text_field :title %>
  </div>
  <div>
    <%= f.label :description %>
    <%= f.text_area :description, size: '60x6' %>

  </div>
  <div>
    <%= f.submit %>
  </div>
<% end %> 

Cannot change column used in a foreign key constraint

When you set keys (primary or foreign) you are setting constraints on how they can be used, which in turn limits what you can do with them. If you really want to alter the column, you could re-create the table without the constraints, although I'd recommend against it. Generally speaking, if you have a situation in which you want to do something, but it is blocked by a constraint, it's best resolved by changing what you want to do rather than the constraint.

Selecting the first "n" items with jQuery

.slice() isn't always better. In my case, with jQuery 1.7 in Chrome 36, .slice(0, 20) failed with error:

RangeError: Maximum call stack size exceeded

I found that :lt(20) worked without error in this case. I had probably tens of thousands of matching elements.

Table fixed header and scrollable body

_x000D_
_x000D_
table {_x000D_
_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
thead, tbody {_x000D_
    display: block;_x000D_
}_x000D_
tbody {_x000D_
    position: absolute;_x000D_
    height: 150px;_x000D_
    overflow-y: scroll;_x000D_
}_x000D_
td, th {_x000D_
    min-width: 100px !important;_x000D_
    height: 25px !important;_x000D_
    overflow:hidden !important;_x000D_
    text-overflow: ellipsis !important;_x000D_
    max-width: 100px !important;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>_x000D_
_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container" style="position:fixed;height:180px;overflow-x:scroll;overflow-y:hidden">_x000D_
_x000D_
_x000D_
<table>_x000D_
         <thead>_x000D_
        <tr>_x000D_
             <th>Col1</th>_x000D_
            <th>Col2</th>_x000D_
            <th>Username</th>_x000D_
            <th>Password</th>_x000D_
            <th>First Name</th>_x000D_
            <th>Last Name</th>_x000D_
            <th>Col16</th>_x000D_
            <th>Col7</th>_x000D_
            <th>Col8</th>_x000D_
            <th>Col9</th>_x000D_
            <th>Col10</th>_x000D_
            <th>Col11</th>_x000D_
            <th>Col12</th>_x000D_
            <th>Col13</th>_x000D_
            <th>Col14</th>_x000D_
            <th>Col15</th>_x000D_
            <th>Col16</th>_x000D_
            <th>Col17</th>_x000D_
            <th>Col18</th>_x000D_
        </tr>_x000D_
              </thead>_x000D_
         <tbody>_x000D_
         </tbody>_x000D_
          <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
          _x000D_
                    <tr>_x000D_
          <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
            <td>Long Value</td>_x000D_
                      <td>Title</td>_x000D_
          </tr>_x000D_
         </table>_x000D_
_x000D_
_x000D_
_x000D_
</div>`enter code here`
_x000D_
_x000D_
_x000D_

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

It's because the tab is a naming container aswell... your update should be update="Search:insTable:display" What you can do aswell is just place your dialog outside the form and still inside the tab then it would be: update="Search:display"

SQL Server function to return minimum date (January 1, 1753)

It's not January 1, 1753 but select cast('' as datetime) wich reveals: 1900-01-01 00:00:00.000 gives the default value by SQL server. (Looks more uninitialized to me anyway)

What is the correct way to start a mongod service on linux / OS X?

On macOS 10.13.6 with MongoDB 4.0

I was unable to connect to localhost from the mongo shell

I started MongoDB with:

mongod --config /usr/local/etc/mongod.conf

I found that the 'mongod.conf' had:

bindIp: 127.0.0.1

Change my JavaScript connection from localhost to 127.0.0.1 and it worked fine.

The same was occurring with MongoDB Compass too.

g++ undefined reference to typeinfo

The previous answers are correct, but this error can also be caused by attempting to use typeid on an object of a class that has no virtual functions. C++ RTTI requires a vtable, so classes that you wish to perform type identification on require at least one virtual function.

If you want type information to work on a class for which you don't really want any virtual functions, make the destructor virtual.

Convert date to another timezone in JavaScript

there is server issue pick gmt+0000 standard time zone you can change it by using library moment-timezone in javascript

const moment = require("moment-timezone")
const dateNew = new Date()
const changeZone = moment(dateNew);
changeZone.tz("Asia/Karachi").format("ha z");
// here you can paste "your time zone string"

How to close form

You need the actual instance of the WindowSettings that's open, not a new one.

Currently, you are creating a new instance of WindowSettings and calling Close on that. That doesn't do anything because that new instance never has been shown.

Instead, when showing DialogSettingsCancel set the current instance of WindowSettings as the parent.

Something like this:

In WindowSettings:

private void showDialogSettings_Click(object sender, EventArgs e)
{
    var dialogSettingsCancel = new DialogSettingsCancel();
    dialogSettingsCancel.OwningWindowSettings = this;
    dialogSettingsCancel.Show();
}

In DialogSettingsCancel:

public WindowSettings OwningWindowSettings { get; set; }

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
    if(OwningWindowSettings != null)
        OwningWindowSettings.Close();
}

This approach takes into account, that a DialogSettingsCancel could potentially be opened without a WindowsSettings as parent.

If the two are always connected, you should instead use a constructor parameter:

In WindowSettings:

private void showDialogSettings_Click(object sender, EventArgs e)
{
    var dialogSettingsCancel = new DialogSettingsCancel(this);
    dialogSettingsCancel.Show();
}

In DialogSettingsCancel:

WindowSettings _owningWindowSettings;

public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
    if(owningWindowSettings == null)
        throw new ArgumentNullException("owningWindowSettings");

    _owningWindowSettings = owningWindowSettings;
}

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
    _owningWindowSettings.Close();
}

Working copy XXX locked and cleanup failed in SVN

I know this is a really old thread but I maintain that:

The easiest and safest method to fix this is to delete your hidden ".svn" folder and check everything out again.

It fixes most problems when svn screws around should keep local changes (marked as "conflicted") when you check out the head revision again.

Unable to add window -- token null is not valid; is your activity running?

PopupWindow can only be attached to an Activity. In your case you are trying to add PopupWindow to service which is not right.

To solve this problem you can use a blank and transparent Activity. On click of floating icon, launch the Activity and on onCreate of Activity show the PopupWindow.

On dismiss of PopupWindow, you can finish the transparent Activity. Hope this helps you.

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

I just want to add that if you want to somehow store the encrypted byte array as String and then retrieve it and decrypt it (often for obfuscation of database values) you can use this approach:

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES 
{
    public void run() 
    {
        try 
        {
            String text = "Hello World";
            String key = "Bar12345Bar12345"; // 128 bit key
            // Create key and cipher
            Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            // encrypt the text
            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            byte[] encrypted = cipher.doFinal(text.getBytes());

            StringBuilder sb = new StringBuilder();
            for (byte b: encrypted) {
                sb.append((char)b);
            }

            // the encrypted String
            String enc = sb.toString();
            System.out.println("encrypted:" + enc);

            // now convert the string to byte array
            // for decryption
            byte[] bb = new byte[enc.length()];
            for (int i=0; i<enc.length(); i++) {
                bb[i] = (byte) enc.charAt(i);
            }

            // decrypt the text
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            String decrypted = new String(cipher.doFinal(bb));
            System.err.println("decrypted:" + decrypted);

        }
        catch(Exception e) 
        {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) 
    {
        StrongAES app = new StrongAES();
        app.run();
    }
}

How do you get the length of a string?

A somewhat important distinction is if the element is an input or not. If an input you can use:

$('#selector').val().length;

otherwise if the element is a different html element like a paragraph or list item div etc, you must use

$('#selector').text().length;

How to sort a dataFrame in python pandas by two or more columns?

As of the 0.17.0 release, the sort method was deprecated in favor of sort_values. sort was completely removed in the 0.20.0 release. The arguments (and results) remain the same:

df.sort_values(['a', 'b'], ascending=[True, False])

You can use the ascending argument of sort:

df.sort(['a', 'b'], ascending=[True, False])

For example:

In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])

In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
   a  b
2  1  4
7  1  3
1  1  2
3  1  2
4  3  2
6  4  4
0  4  3
9  4  3
5  4  1
8  4  1

As commented by @renadeen

Sort isn't in place by default! So you should assign result of the sort method to a variable or add inplace=True to method call.

that is, if you want to reuse df1 as a sorted DataFrame:

df1 = df1.sort(['a', 'b'], ascending=[True, False])

or

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

how to split the ng-repeat data with three columns using bootstrap

A simple trick with "clearfix" CSS recommended by Bootstrap:

_x000D_
_x000D_
<div class="row">_x000D_
      <div ng-repeat-start="value in values" class="col-md-4">_x000D_
        {{value}}_x000D_
      </div>_x000D_
      <div ng-repeat-end ng-if="$index % 3 == 0" class="clearfix"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Many advantages: Efficient, fast, using Boostrap recommendations, avoiding possible $digest issues, and not altering Angular model.

Moving Git repository content to another repository preserving history

It looks like you're close. Assuming that it's not just a typo in your submission, step 3 should be cd repo2 instead of repo1. And step 6 should be git pull not push. Reworked list:

1. git clone repo1
2. git clone repo2
3. cd repo2
4. git remote rm origin
5. git remote add repo1
6. git pull
7. git remote rm repo1
8. git remote add newremote

How to sort an array in descending order in Ruby

For those folks who like to measure speed in IPS ;)

require 'benchmark/ips'

ary = []
1000.times { 
  ary << {:bar => rand(1000)} 
}

Benchmark.ips do |x|
  x.report("sort")               { ary.sort{ |a,b| b[:bar] <=> a[:bar] } }
  x.report("sort reverse")       { ary.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse }
  x.report("sort_by -a[:bar]")   { ary.sort_by{ |a| -a[:bar] } }
  x.report("sort_by a[:bar]*-1") { ary.sort_by{ |a| a[:bar]*-1 } }
  x.report("sort_by.reverse!")   { ary.sort_by{ |a| a[:bar] }.reverse }
  x.compare!
end

And results:

Warming up --------------------------------------
                sort    93.000  i/100ms
        sort reverse    91.000  i/100ms
    sort_by -a[:bar]   382.000  i/100ms
  sort_by a[:bar]*-1   398.000  i/100ms
    sort_by.reverse!   397.000  i/100ms
Calculating -------------------------------------
                sort    938.530  (± 1.8%) i/s -      4.743k in   5.055290s
        sort reverse    901.157  (± 6.1%) i/s -      4.550k in   5.075351s
    sort_by -a[:bar]      3.814k (± 4.4%) i/s -     19.100k in   5.019260s
  sort_by a[:bar]*-1      3.732k (± 4.3%) i/s -     18.706k in   5.021720s
    sort_by.reverse!      3.928k (± 3.6%) i/s -     19.850k in   5.060202s

Comparison:
    sort_by.reverse!:     3927.8 i/s
    sort_by -a[:bar]:     3813.9 i/s - same-ish: difference falls within error
  sort_by a[:bar]*-1:     3732.3 i/s - same-ish: difference falls within error
                sort:      938.5 i/s - 4.19x  slower
        sort reverse:      901.2 i/s - 4.36x  slower

Increase bootstrap dropdown menu width

Text will never wrap to the next line. The text continues on the same line until a
tag is encountered.

.dropdown-menu {
    white-space: nowrap;
}

How to retrieve Request Payload

If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded data.

You can fetch this data with this snippet:

$request_body = file_get_contents('php://input');

If you are passing json, then you can do:

$data = json_decode($request_body);

$data then contains the json data is php array.

php://input is a so called wrapper.

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

What is the difference between $routeProvider and $stateProvider?

$route: This is used for deep-linking URLs to controllers and views (HTML partials) and watches $location.url() in order to map the path from an existing definition of route.

When we use ngRoute, the route is configured with $routeProvider and when we use ui-router, the route is configured with $stateProvider and $urlRouterProvider.

<div ng-view></div>
    $routeProvider
        .when('/contact/', {
            templateUrl: 'app/views/core/contact/contact.html',
            controller: 'ContactCtrl'
        });


<div ui-view>
    <div ui-view='abc'></div>
    <div ui-view='abc'></div>
   </div>
    $stateProvider
        .state("contact", {
            url: "/contact/",
            templateUrl: '/app/Aisel/Contact/views/contact.html',
            controller: 'ContactCtrl'
        });

Array Length in Java

if you mean by "logical size", the index of array, then simply int arrayLength = arr.length-1; since the the array index starts with "0", so the logical or "array index" will always be less than the actual size by "one".

Get Return Value from Stored procedure in asp.net

you can try this.Add the parameter as output direction and after executing the query get the output parameter value.

  SqlParameter parmOUT = new SqlParameter("@return", SqlDbType.Int);
  parmOUT.Direction = ParameterDirection.Output;
  cmd.Parameters.Add(parmOUT);
  cmd.ExecuteNonQuery();
  int returnVALUE = (int)cmd.Parameters["@return"].Value;

How to count the number of occurrences of an element in a List

Put the elements of the arraylist in the hashMap to count the frequency.

How to check if a String contains another String in a case insensitive manner in Java?

We can use stream with anyMatch and contains of Java 8

public class Test2 {
    public static void main(String[] args) {

        String a = "Gina Gini Protijayi Soudipta";
        String b = "Gini";

        System.out.println(WordPresentOrNot(a, b));
    }// main

    private static boolean WordPresentOrNot(String a, String b) {
    //contains is case sensitive. That's why change it to upper or lower case. Then check
        // Here we are using stream with anyMatch
        boolean match = Arrays.stream(a.toLowerCase().split(" ")).anyMatch(b.toLowerCase()::contains);
        return match;
    }

}

How can I do factory reset using adb in android?

Try :

adb shell
recovery --wipe_data

And here is the list of arguments :

* The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

How to declare std::unique_ptr and what is the use of it?

The constructor of unique_ptr<T> accepts a raw pointer to an object of type T (so, it accepts a T*).

In the first example:

unique_ptr<int> uptr (new int(3));

The pointer is the result of a new expression, while in the second example:

unique_ptr<double> uptr2 (pd);

The pointer is stored in the pd variable.

Conceptually, nothing changes (you are constructing a unique_ptr from a raw pointer), but the second approach is potentially more dangerous, since it would allow you, for instance, to do:

unique_ptr<double> uptr2 (pd);
// ...
unique_ptr<double> uptr3 (pd);

Thus having two unique pointers that effectively encapsulate the same object (thus violating the semantics of a unique pointer).

This is why the first form for creating a unique pointer is better, when possible. Notice, that in C++14 we will be able to do:

unique_ptr<int> p = make_unique<int>(42);

Which is both clearer and safer. Now concerning this doubt of yours:

What is also not clear to me, is how pointers, declared in this way will be different from the pointers declared in a "normal" way.

Smart pointers are supposed to model object ownership, and automatically take care of destroying the pointed object when the last (smart, owning) pointer to that object falls out of scope.

This way you do not have to remember doing delete on objects allocated dynamically - the destructor of the smart pointer will do that for you - nor to worry about whether you won't dereference a (dangling) pointer to an object that has been destroyed already:

{
    unique_ptr<int> p = make_unique<int>(42);
    // Going out of scope...
}
// I did not leak my integer here! The destructor of unique_ptr called delete

Now unique_ptr is a smart pointer that models unique ownership, meaning that at any time in your program there shall be only one (owning) pointer to the pointed object - that's why unique_ptr is non-copyable.

As long as you use smart pointers in a way that does not break the implicit contract they require you to comply with, you will have the guarantee that no memory will be leaked, and the proper ownership policy for your object will be enforced. Raw pointers do not give you this guarantee.

jQuery addClass onClick

Using jQuery:

$('#Button').click(function(){
    $(this).addClass("active");
});

This way, you don't have to pollute your HTML markup with onclick handlers.

CAST to DECIMAL in MySQL

If you need a lot of decimal numbers, in this example 17, I share with you MySql code:

This is the calculate:

=(9/1147)*100

SELECT TRUNCATE(((CAST(9 AS DECIMAL(30,20))/1147)*100),17);