Programs & Examples On #Bytearray

Represents an array of bytes

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

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

You just needed to cast the unsigned char into a char as the string class doesn't have a constructor that accepts unsigned char:

unsigned char* uc;
std::string s( reinterpret_cast< char const* >(uc) ) ;

However, you will need to use the length argument in the constructor if your byte array contains nulls, as if you don't, only part of the array will end up in the string (the array up to the first null)

size_t len;
unsigned char* uc;
std::string s( reinterpret_cast<char const*>(uc), len ) ;

Python 3 Building an array of bytes

agf's bytearray solution is workable, but if you find yourself needing to build up more complicated packets using datatypes other than bytes, you can try struct.pack(). http://docs.python.org/release/3.1.3/library/struct.html

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Convert InputStream to byte array in Java

You can try Cactoos:

byte[] array = new BytesOf(stream).bytes();

Put byte array to JSON and vice versa

what about simply this:

byte[] args2 = getByteArry();
String byteStr = new String(args2);

Converting any object to a byte array in java

As i've mentioned in other, similar questions, you may want to consider compressing the data as the default java serialization is a bit verbose. you do this by putting a GZIPInput/OutputStream between the Object streams and the Byte streams.

java.net.URL read stream to byte[]

Just extending Barnards's answer with commons-io. Separate answer because I can not format code in comments.

InputStream is = null;
try {
  is = url.openStream ();
  byte[] imageBytes = IOUtils.toByteArray(is);
}
catch (IOException e) {
  System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
  e.printStackTrace ();
  // Perform any other exception handling that's appropriate.
}
finally {
  if (is != null) { is.close(); }
}

http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toByteArray(java.io.InputStream)

How to convert an Stream into a byte[] in C#?

Byte[] Content = new BinaryReader(file.InputStream).ReadBytes(file.ContentLength);

Converting byte array to String (Java)

public static String readFile(String fn)   throws IOException 
{
    File f = new File(fn);

    byte[] buffer = new byte[(int)f.length()];
    FileInputStream is = new FileInputStream(fn);
    is.read(buffer);
    is.close();

    return  new String(buffer, "UTF-8"); // use desired encoding
}

c# how to add byte to byte array

To prevent recopy the array every time which isn't efficient

What about using Stack

csharp> var i = new Stack<byte>();
csharp> i.Push(1);
csharp> i.Push(2); 
csharp> i.Push(3); 
csharp> i; { 3, 2, 1 }

csharp> foreach(var x in i) {
  >       Console.WriteLine(x);
  >     }

3 2 1

Best way to read a large file into a byte array in C#?

I would think this:

byte[] file = System.IO.File.ReadAllBytes(fileName);

How do I print bytes as hexadecimal?

I don't know of a better way than:

unsigned char byData[xxx]; 

int nLength = sizeof(byData) * 2;
char *pBuffer = new char[nLength + 1];
pBuffer[nLength] = 0;
for (int i = 0; i < sizeof(byData); i++)
{
    sprintf(pBuffer[2 * i], "%02X", byData[i]);
}

You can speed it up by using a Nibble to Hex method

unsigned char byData[xxx];

const char szNibbleToHex = { "0123456789ABCDEF" };

int nLength = sizeof(byData) * 2;
char *pBuffer = new char[nLength + 1];
pBuffer[nLength] = 0;
for (int i = 0; i < sizeof(byData); i++)
{
    // divide by 16
    int nNibble = byData[i] >> 4;
    pBuffer[2 * i]  = pszNibbleToHex[nNibble];

    nNibble = byData[i] & 0x0F;
    pBuffer[2 * i + 1]  = pszNibbleToHex[nNibble];

}

Int to byte array

If you came here from Google

Alternative answer to an older question refers to John Skeet's Library that has tools for letting you write primitive data types directly into a byte[] with an Index offset. Far better than BitConverter if you need performance.

Older thread discussing this issue here

John Skeet's Libraries are here

Just download the source and look at the MiscUtil.Conversion namespace. EndianBitConverter.cs handles everything for you.

How to convert NSData to byte array in iPhone?

Here's what I believe is the Swift equivalent:

if let data = NSData(contentsOfFile: filePath) {
   let length = data.length
   let byteData = malloc(length)
   memcmp(byteData, data.bytes, length)
}

C# 4.0: Convert pdf to byte[] and vice versa

// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);

// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself

// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);

Byte Array to Hex String

hex_string = "".join("%02x" % b for b in array_alpha)

hexadecimal string to byte array in python

Suppose your hex string is something like

>>> hex_string = "deadbeef"

Convert it to a string (Python = 2.7):

>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"

or since Python 2.7 and Python 3.0:

>>> bytes.fromhex(hex_string)  # Python = 3
b'\xde\xad\xbe\xef'

>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')

Note that bytes is an immutable version of bytearray.

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

public static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = new ObjectInputStream(in);
    return is.readObject();
}

How to convert a byte array to its numeric value (Java)?

public static long byteArrayToLong(byte[] bytes) {
    return ((long) (bytes[0]) << 56)
            + (((long) bytes[1] & 0xFF) << 48)
            + ((long) (bytes[2] & 0xFF) << 40)
            + ((long) (bytes[3] & 0xFF) << 32)
            + ((long) (bytes[4] & 0xFF) << 24)
            + ((bytes[5] & 0xFF) << 16)
            + ((bytes[6] & 0xFF) << 8)
            + (bytes[7] & 0xFF);
}

convert bytes array (long is 8 bytes) to long

Java ByteBuffer to String

The answers referring to simply calling array() are not quite correct: when the buffer has been partially consumed, or is referring to a part of an array (you can ByteBuffer.wrap an array at a given offset, not necessarily from the beginning), we have to account for that in our calculations. This is the general solution that works for buffers in all cases (does not cover encoding):

if (myByteBuffer.hasArray()) {
    return new String(myByteBuffer.array(),
        myByteBuffer.arrayOffset() + myByteBuffer.position(),
        myByteBuffer.remaining());
} else {
    final byte[] b = new byte[myByteBuffer.remaining()];
    myByteBuffer.duplicate().get(b);
    return new String(b);
}

For the concerns related to encoding, see Andy Thomas' answer.

Convert python long/int to fixed size byte array

With Python 3.2 and later, you can use int.to_bytes and int.from_bytes: https://docs.python.org/3/library/stdtypes.html#int.to_bytes

Easiest way to convert a Blob into a byte array

the mySql blob class has the following function :

blob.getBytes

use it like this:

//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");

int blobLength = (int) blob.length();  
byte[] blobAsBytes = blob.getBytes(1, blobLength);

//release the blob and free up memory. (since JDBC 4.0)
blob.free();

Gets byte array from a ByteBuffer in java

Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.

I.e.

byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"

Which might not be what you intend to do.

If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.

Fastest way to convert Image to Byte array

public static class HelperExtensions
{
    //Convert Image to byte[] array:
    public static byte[] ToByteArray(this Image imageIn)
    {
        var ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms.ToArray();
    }

    //Convert byte[] array to Image:
    public static Image ToImage(this byte[] byteArrayIn)
    {
        var ms = new MemoryStream(byteArrayIn);
        var returnImage = Image.FromStream(ms);
        return returnImage;
    }
}

How to store a byte array in Javascript

You could store the data in an array of strings of some large fixed size. It should be efficient to access any particular character in that array of strings, and to treat that character as a byte.

It would be interesting to see the operations you want to support, perhaps expressed as an interface, to make the question more concrete.

Hex-encoded String to Byte Array

I know it's late but hope it will help someone else...

This is my code: It takes two by two hex representations contained in String and add those into byte array. It works perfectly for me.

public byte[] stringToByteArray (String s) {
    byte[] byteArray = new byte[s.length()/2];
    String[] strBytes = new String[s.length()/2];
    int k = 0;
    for (int i = 0; i < s.length(); i=i+2) {
        int j = i+2;
        strBytes[k] = s.substring(i,j);
        byteArray[k] = (byte)Integer.parseInt(strBytes[k], 16);
        k++;
    }
    return byteArray;
}

String to byte array in php

PHP has no explicit byte type, but its string is already the equivalent of Java's byte array. You can safely write fputs($connection, "The quick brown fox …"). The only thing you must be aware of is character encoding, they must be the same on both sides. Use mb_convert_encoding() when in doubt.

Appending a byte[] to the end of another byte[]

Perhaps the easiest way:

ByteArrayOutputStream output = new ByteArrayOutputStream();

output.write(ciphertext);
output.write(mac);

byte[] out = output.toByteArray();

how to convert image to byte array in java?

BufferedImage consists of two main classes: Raster & ColorModel. Raster itself consists of two classes, DataBufferByte for image content while the other for pixel color.

if you want the data from DataBufferByte, use:

public byte[] extractBytes (String ImageName) throws IOException {
 // open image
 File imgPath = new File(ImageName);
 BufferedImage bufferedImage = ImageIO.read(imgPath);

 // get DataBufferBytes from Raster
 WritableRaster raster = bufferedImage .getRaster();
 DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

 return ( data.getData() );
}

now you can process these bytes by hiding text in lsb for example, or process it the way you want.

How to convert a Java String to an ASCII byte array?

In my string I have Thai characters (TIS620 encoded) and German umlauts. The answer from agiles put me on the right path. Instead of .getBytes() I use now

  int len = mString.length(); // Length of the string
  byte[] dataset = new byte[len];
  for (int i = 0; i < len; ++i) {
     char c = mString.charAt(i);
     dataset[i]= (byte) c;
  }

Byte[] to InputStream or OutputStream

You create and use byte array I/O streams as follows:

byte[] source = ...;
ByteArrayInputStream bis = new ByteArrayInputStream(source);
// read bytes from bis ...

ByteArrayOutputStream bos = new ByteArrayOutputStream();
// write bytes to bos ...
byte[] sink = bos.toByteArray();

Assuming that you are using a JDBC driver that implements the standard JDBC Blob interface (not all do), you can also connect a InputStream or OutputStream to a blob using the getBinaryStream and setBinaryStream methods1, and you can also get and set the bytes directly.

(In general, you should take appropriate steps to handle any exceptions, and close streams. However, closing bis and bos in the example above is unnecessary, since they aren't associated with any external resources; e.g. file descriptors, sockets, database connections.)

1 - The setBinaryStream method is really a getter. Go figure.

How to create bitmap from byte array?

In addition, you can simply convert byte array to Bitmap.

var bmp = new Bitmap(new MemoryStream(imgByte));

You can also get Bitmap from file Path directly.

Bitmap bmp = new Bitmap(Image.FromFile(filePath));

How to convert a byte array to a hex string in Java?

Use DataTypeConverter classjavax.xml.bind.DataTypeConverter

String hexString = DatatypeConverter.printHexBinary(bytes[] raw);

How to add a filter class in Spring Boot?

This filter will also help you to allow cross origin access

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

            HttpServletResponse response = (HttpServletResponse) res;
            HttpServletRequest request = (HttpServletRequest) req;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "20000");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");

            if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                chain.doFilter(req, res);
            }
    }


    public void destroy() {}

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}

MVC 3 file upload and model binding

For multiple files; note the newer "multiple" attribute for input:

Form:

@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    <label for="files">Filename:</label>
    <input type="file" name="files" multiple="true" id="files" />
    <input type="submit"  />
}

Controller:

[HttpPost]
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files)
{
    return View();
}

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

You don't have the namespace the Login class is in as a reference.

Add the following to the form that uses the Login class:

using FootballLeagueSystem;

When you want to use a class in another namespace, you have to tell the compiler where to find it. In this case, Login is inside the FootballLeagueSystem namespace, or : FootballLeagueSystem.Login is the fully qualified namespace.

As a commenter pointed out, you declare the Login class inside the FootballLeagueSystem namespace, but you're using it in the FootballLeague namespace.

jQuery - hashchange event

A different approach to your problem...

There are 3 ways to bind the hashchange event to a method:

<script>
    window.onhashchange = doThisWhenTheHashChanges;
</script>

Or

<script>
    window.addEventListener("hashchange", doThisWhenTheHashChanges, false);
</script>

Or

<body onhashchange="doThisWhenTheHashChanges();">

These all work with IE 9, FF 5, Safari 5, and Chrome 12 on Win 7.

android listview item height

You need to use padding on the list item layout so space is added on the edges of the item (just increasing the font size won't do that).

<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+id/text1"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:padding="8dp" />

Nth max salary in Oracle

 SELECT sal
    FROM (
                SELECT empno,
                             deptno, sal,
                              dense_rank( ) over ( partition by deptno order by sal desc) NRANK
                FROM emp
            )
    WHERE NRANK = 4

How to set max_connections in MySQL Programmatically

How to change max_connections

You can change max_connections while MySQL is running via SET:

mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 5000  |
+-----------------+-------+
1 row in set (0.00 sec)

To OP

timeout related

I had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.

I suggest that you increase this value to 100k or disable connection pooling Pooling=false

UPDATED

he has two questions.

Q1 - what happens if I disable pooling Slow down making DB connection. connection pooling is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool

Q2 - Can the value of pooling be increased or the maximum is 100?

you can increase but I'm sure what is MAX value, maybe max_connections in my.cnf

My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.

If you have Stress Test tool like JMeter you can test youself.

Using Linq to group a list of objects into a new grouped list of list of objects

Still an old one, but answer from Lee did not give me the group.Key as result. Therefore, I am using the following statement to group a list and return a grouped list:

public IOrderedEnumerable<IGrouping<string, User>> groupedCustomerList;

groupedCustomerList =
        from User in userList
        group User by User.GroupID into newGroup
        orderby newGroup.Key
        select newGroup;

Each group now has a key, but also contains an IGrouping which is a collection that allows you to iterate over the members of the group.

How to get the size of a JavaScript object?

Sorry I could not comment, so I just continue the work from tomwrong. This enhanced version will not count object more than once, thus no infinite loop. Plus, I reckon the key of an object should be also counted, roughly.

function roughSizeOfObject( value, level ) {
    if(level == undefined) level = 0;
    var bytes = 0;

    if ( typeof value === 'boolean' ) {
        bytes = 4;
    }
    else if ( typeof value === 'string' ) {
        bytes = value.length * 2;
    }
    else if ( typeof value === 'number' ) {
        bytes = 8;
    }
    else if ( typeof value === 'object' ) {
        if(value['__visited__']) return 0;
        value['__visited__'] = 1;
        for( i in value ) {
            bytes += i.length * 2;
            bytes+= 8; // an assumed existence overhead
            bytes+= roughSizeOfObject( value[i], 1 )
        }
    }

    if(level == 0){
        clear__visited__(value);
    }
    return bytes;
}

function clear__visited__(value){
    if(typeof value == 'object'){
        delete value['__visited__'];
        for(var i in value){
            clear__visited__(value[i]);
        }
    }
}

roughSizeOfObject(a);

HTML input file selection event not firing upon selecting the same file

Clearing the value of 0th index of input worked for me. Please try the below code, hope this will work (AngularJs).

          scope.onClick = function() {
            input[0].value = "";
                input.click();
            };

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

If the above solutions don't work on ubuntu/linux then you can try this

sudo fuser -k -n tcp port

Run it several times to kill processes on your port of choosing. port could be 3000 for example. You would have killed all the processes if you see no output after running the command

The program can't start because cygwin1.dll is missing... in Eclipse CDT

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

How to force NSLocalizedString to use a specific language

In file .pch to define:

#define currentLanguageBundle [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:[[NSLocale preferredLanguages] objectAtIndex:0] ofType:@"lproj"]]


#define NSLocalizedString(str,nil) NSLocalizedStringFromTableInBundle(str, nil, currentLanguageBundle, @"")

Parse HTML table to Python list?

Hands down the easiest way to parse a HTML table is to use pandas.read_html() - it accepts both URLs and HTML.

import pandas as pd
url = r'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
tables = pd.read_html(url) # Returns list of all tables on page
sp500_table = tables[0] # Select table of interest

Only downside is that read_html() doesn't preserve hyperlinks.

Proper use of 'yield return'

This is what Chris Sells tells about those statements in The C# Programming Language;

I sometimes forget that yield return is not the same as return , in that the code after a yield return can be executed. For example, the code after the first return here can never be executed:

int F() {
    return 1;
    return 2; // Can never be executed
}

In contrast, the code after the first yield return here can be executed:

IEnumerable<int> F() {
    yield return 1;
    yield return 2; // Can be executed
}

This often bites me in an if statement:

IEnumerable<int> F() {
    if(...) {
        yield return 1; // I mean this to be the only thing returned
    }
    yield return 2; // Oops!
}

In these cases, remembering that yield return is not “final” like return is helpful.

How to make HTML code inactive with comments

To comment block with nested comments: substitute inner (block) comments from "--" to "++"

<!-- *********************************************************************
     * IMPORTANT: To uncomment section
     *            sub inner comments "++" -> "--" & remove this comment
     *********************************************************************
<head>
   <title>My document's title</title> <++! My document's title ++>
   <link rel=stylesheet href="mydoc.css" type="text/css">
</head>

<body>
<++! My document's important HTML stuff ++>
...
...
...
</body>

*********************************************************************
* IMPORTANT: To uncomment section
*            sub inner comments "++" -> "--" & remove this comment
*********************************************************************
-->

Thus, the outer most comment ignores all "invalid" inner (block) comments.

Collections.emptyList() returns a List<Object>?

You want to use:

Collections.<String>emptyList();

If you look at the source for what emptyList does you see that it actually just does a

return (List<T>)EMPTY_LIST;

MSVCP120d.dll missing

My problem was with x64 compilations deployed to a remote testing machine. I found the x64 versions of msvp120d.dll and msvcr120d.dll in

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\redist\Debug_NonRedist\x64\Microsoft.VC120.DebugCRT

How to access component methods from “outside” in ReactJS?

React provides an interface for what you are trying to do via the ref attribute. Assign a component a ref, and its current attribute will be your custom component:

class Parent extends React.Class {
    constructor(props) {
        this._child = React.createRef();
    }

    componentDidMount() {
        console.log(this._child.current.someMethod()); // Prints 'bar'
    }

    render() {
        return (
            <div>
                <Child ref={this._child} />
            </div>
        );
    }
}

Note: This will only work if the child component is declared as a class, as per documentation found here: https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component

Update 2019-04-01: Changed example to use a class and createRef per latest React docs.

Update 2016-09-19: Changed example to use ref callback per guidance from the ref String attribute docs.

SQLAlchemy equivalent to SQL "LIKE" statement

Adding to the above answer, whoever looks for a solution, you can also try 'match' operator instead of 'like'. Do not want to be biased but it perfectly worked for me in Postgresql.

Note.query.filter(Note.message.match("%somestr%")).all()

It inherits database functions such as CONTAINS and MATCH. However, it is not available in SQLite.

For more info go Common Filter Operators

How can I make an image transparent on Android?

As setAlpha int has been deprecated, setImageAlpha (int) can be used

ImageView img = (ImageView) findViewById(R.id.img_image);
img.setImageAlpha(127); //value: [0-255]. Where 0 is fully transparent and 255 is fully opaque.

Get current time in milliseconds using C++ and Boost

// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;

int main()
{
     pt::ptime current_date_microseconds = pt::microsec_clock::local_time();

    long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();

    pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);

    pt::ptime current_date_milliseconds(current_date_microseconds.date(), 
                                        current_time_milliseconds);

    std::cout << "Microseconds: " << current_date_microseconds 
              << " Milliseconds: " << current_date_milliseconds << std::endl;

    // Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}

Call function with setInterval in jQuery?

I have written a custom code for setInterval function which can also help

_x000D_
_x000D_
let interval;
      
function startInterval(){
  interval = setInterval(appendDateToBody, 1000);
  console.log(interval);
}

function appendDateToBody() {
    document.body.appendChild(
        document.createTextNode(new Date() + " "));
}

function stopInterval() {
    clearInterval(interval);
  console.log(interval);
}
_x000D_
<!DOCTYPE html>
<html>
<head>
    <title>setInterval</title>
</head>
<body>
    <input type="button" value="Stop" onclick="stopInterval();" />
    <input type="button" value="Start" onclick="startInterval();" />
</body>
</html>
_x000D_
_x000D_
_x000D_

How do I get the command-line for an Eclipse run configuration?

Scan your workspace .metadata directory for files called *.launch. I forget which plugin directory exactly holds these records, but it might even be the most basic org.eclipse.plugins.core one.

How to prevent a double-click using jQuery?

I had a similar issue, but disabling the button didn't fully did the trick. There were some other actions that took place when the button was clicked and, sometimes, button wasn't disabled soon enough and when the user double-clicked, 2 events where fired.
I took Pangui's timeout idea, and combined both techniques, disabling the button and includeding a timeout, just in case. And I created a simple jQuery plugin:

var SINGLECLICK_CLICKED = 'singleClickClicked';
$.fn.singleClick = function () {
    var fncHandler; 
    var eventData;
    var fncSingleClick = function (ev) {
        var $this = $(this);
        if (($this.data(SINGLECLICK_CLICKED)) || ($this.prop('disabled'))) {
            ev.preventDefault();
            ev.stopPropagation();
        }
        else {
            $this.data(SINGLECLICK_CLICKED, true);
            window.setTimeout(function () {
                $this.removeData(SINGLECLICK_CLICKED);
            }, 1500);
            if ($.isFunction(fncHandler)) {
                fncHandler.apply(this, arguments);
            }
        }
    }

    switch (arguments.length) {
        case 0:
            return this.click();
        case 1:
            fncHandler = arguments[0];
            this.click(fncSingleClick);
            break;
        case 2: 
            eventData = arguments[0];
            fncHandler = arguments[1];
            this.click(eventData, fncSingleClick);
            break;
    }
    return this;
}

And then use it like this:

$("#button1").singleClick(function () {
   $(this).prop('disabled', true);
   //...
   $(this).prop('disabled', false);
})

How to extract filename.tar.gz file

As far as I can tell, the command is correct, ASSUMING your input file is a valid gzipped tar file. Your output says that it isn't. If you downloaded the file from the internet, you probably didn't get the entire file, try again.

Without more knowledge of the source of your file, nobody here is going to be able to give you a concrete solution, just educated guesses.

PHP: How to check if a date is today, yesterday or tomorrow

First. You have mistake in using function strtotime see PHP documentation

int strtotime ( string $time [, int $now = time() ] )

You need modify your code to pass integer timestamp into this function.

Second. You use format d.m.Y H:i that includes time part. If you wish to compare only dates, you must remove time part, e.g. `$date = date("d.m.Y");``

Third. I am not sure if it works in the same way for you, but my PHP doesn't understand date format from $timestamp and returns 01.01.1970 02:00 into $match_date

$timestamp = "2014.09.02T13:34";
date('d.m.Y H:i', strtotime($timestamp)) === "01.01.1970 02:00";

You need to check if strtotime($timestamp) returns correct date string. If no, you need to specify format which is used in $timestamp variable. You can do this using one of functions date_parse_from_format or DateTime::createFromFormat

This is a work example:

$timestamp = "2014.09.02T13:34";

$today = new DateTime(); // This object represents current date/time
$today->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison

$match_date = DateTime::createFromFormat( "Y.m.d\\TH:i", $timestamp );
$match_date->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison

$diff = $today->diff( $match_date );
$diffDays = (integer)$diff->format( "%R%a" ); // Extract days count in interval

switch( $diffDays ) {
    case 0:
        echo "//Today";
        break;
    case -1:
        echo "//Yesterday";
        break;
    case +1:
        echo "//Tomorrow";
        break;
    default:
        echo "//Sometime";
}

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The only good use case for recursion mutex is when an object contains multiple methods. When any of the methods modify the content of the object, and therefore must lock the object before the state is consistent again.

If the methods use other methods (ie: addNewArray() calls addNewPoint(), and finalizes with recheckBounds()), but any of those functions by themselves need to lock the mutex, then recursive mutex is a win-win.

For any other case (solving just bad coding, using it even in different objects) is clearly wrong!

Add or change a value of JSON key with jquery or javascript

var temp = data.oldKey; // or data['oldKey']
data.newKey = temp;
delete data.oldKey;

Java Refuses to Start - Could not reserve enough space for object heap

Given that none of the other suggestions have worked (including many things I'd have suggested myself), to help troubleshoot further, could you try running:

sysctl -a

On both the SuSE and RedHat machines to see if there are any differences? I'm guessing the default configurations are different between these two distributions that's causing this.

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

How to get current class name including package name in Java?

use this.getClass().getName() to get packageName.className and use this.getClass().getSimpleName() to get only class name

Multiple aggregations of the same column using pandas GroupBy.agg()

You can simply pass the functions as a list:

In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:         
           mean       sum
dummy                    
1      0.036901  0.369012

or as a dictionary:

In [21]: df.groupby('dummy').agg({'returns':
                                  {'Mean': np.mean, 'Sum': np.sum}})
Out[21]: 
        returns          
           Mean       Sum
dummy                    
1      0.036901  0.369012

How can I remove a button or make it invisible in Android?

use setVisibility in button or imageViwe or .....
To remove button in java code:

Button btn=(Button)findViewById(R.id.btn);
btn.setVisibility(Button.GONE);

To transparent Button in java code

Button btn=(Button)findViewById(R.id.btn);
btn.setVisibility(Button.INVISIBLE);


You should make you button xml code like below:

<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>


hidden:
visibility: gone
show:
visibility: invisible
visibility: visible

Add Keypair to existing EC2 instance

You can actually add a key pair through the elastic beanstalk config page. it then restarts your instance for you and everything works.

Which UUID version to use?

If you want a random number, use a random number library. If you want a unique identifier with effectively 0.00...many more 0s here...001% chance of collision, you should use UUIDv1. See Nick's post for UUIDv3 and v5.

UUIDv1 is NOT secure. It isn't meant to be. It is meant to be UNIQUE, not un-guessable. UUIDv1 uses the current timestamp, plus a machine identifier, plus some random-ish stuff to make a number that will never be generated by that algorithm again. This is appropriate for a transaction ID (even if everyone is doing millions of transactions/s).

To be honest, I don't understand why UUIDv4 exists... from reading RFC4122, it looks like that version does NOT eliminate possibility of collisions. It is just a random number generator. If that is true, than you have a very GOOD chance of two machines in the world eventually creating the same "UUID"v4 (quotes because there isn't a mechanism for guaranteeing U.niversal U.niqueness). In that situation, I don't think that algorithm belongs in a RFC describing methods for generating unique values. It would belong in a RFC about generating randomness. For a set of random numbers:

chance_of_collision = 1 - (set_size! / (set_size - tries)!) / (set_size ^ tries)

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

How to debug Ruby scripts

The mother of all debugger is plain old print screen. Most of the time, you probably only want to inspect some simple objects, a quick and easy way is like this:

@result = fetch_result

p "--------------------------"
p @result

This will print out the contents of @result to STDOUT with a line in front for easy identification.

Bonus if you use a autoload / reload capable framework like Rails, you won't even need to restart your app. (Unless the code you are debugging is not reloaded due to framework specific settings)

I find this works for 90% of the use case for me. You can also use ruby-debug, but I find it overkill most of the time.

change <audio> src with javascript

If you are storing metadata in a tag use data attributes eg.

<li id="song1" data-value="song1.ogg"><button onclick="updateSource()">Item1</button></li>

Now use the attribute to get the name of the song

var audio = document.getElementById('audio');
audio.src='audio/ogg/' + document.getElementById('song1').getAttribute('data-value');
audio.load();

Android EditText delete(backspace) key event

I have found a really simple solution which works with a soft keyboard.

override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {
    text?.let { 
        if(count < before) {
            Toast.makeText(context, "backspace pressed", Toast.LENGTH_SHORT).show()
            // implement your own code
        }
    }
}

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

Issue can be solved using:

kill -9 $(more /home/..name/rprojects/railsapp/tmp/pids/server.pid)

How to go to each directory and execute a command?

I don't get the point with the formating of the file, since you only want to iterate through folders... Are you looking for something like this?

cd parent
find . -type d | while read d; do
   ls $d/
done

Create ArrayList from array

new ArrayList<>(Arrays.asList(array));

How do I find the index of a character within a string in C?

void myFunc(char* str, char c)
{
    char* ptr;
    int index;

    ptr = strchr(str, c);
    if (ptr == NULL)
    {
        printf("Character not found\n");
        return;
    }

    index = ptr - str;

    printf("The index is %d\n", index);
    ASSERT(str[index] == c);  // Verify that the character at index is the one we want.
}

This code is currently untested, but it demonstrates the proper concept.

Split string to equal length substrings in Java

Here is a one liner implementation using Java8 streams:

String input = "Thequickbrownfoxjumps";
final AtomicInteger atomicInteger = new AtomicInteger(0);
Collection<String> result = input.chars()
                                    .mapToObj(c -> String.valueOf((char)c) )
                                    .collect(Collectors.groupingBy(c -> atomicInteger.getAndIncrement() / 4
                                                                ,Collectors.joining()))
                                    .values();

It gives the following output:

[Theq, uick, brow, nfox, jump, s]

VBA (Excel) Initialize Entire Array without Looping

Fancy way to put @rdhs answer in a function:

Function arrayZero(size As Integer)
  arrayZero = Evaluate("=IF(ISERROR(Transpose(A1:A" & size & ")), 0, 0)")
End Function

And use like this:

myArray = arrayZero(15)

How can I see the entire HTTP request that's being sent by my Python application?

If you're using Python 2.x, try installing a urllib2 opener. That should print out your headers, although you may have to combine that with other openers you're using to hit the HTTPS.

import urllib2
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)))
urllib2.urlopen(url)

What does the "no version information available" error from linux dynamic linker mean?

How are you compiling your app? What compiler flags?

In my experience, when targeting the vast realm of Linux systems out there, build your packages on the oldest version you are willing to support, and because more systems tend to be backwards compatible, your app will continue to work. Actually this is the whole reason for library versioning - ensuring backward compatibility.

How to get a tab character?

Posting another alternative to be more complete. When I tried the "pre" based answers, they added extra vertical line breaks as well.

Each tab can be converted to a sequence non-breaking spaces which require no wrapping.

"&nbsp;&nbsp;&nbsp;&nbsp;" 

This is not recommended for repeated/extensive use within a page. A div margin/padding approach would appear much cleaner.

How do I get list of all tables in a database using TSQL?

Well you can use sys.objects to get all database objects.

 GO
 select * from sys.objects where type_desc='USER_TABLE' order by name
 GO

OR

--  For all tables
select * from INFORMATION_SCHEMA.TABLES 
GO 

  --- For user defined tables
select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE'
GO

  --- For Views
select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='VIEW'
GO

Using jquery to get all checked checkboxes with a certain class name

You can use something like this:
HTML:

<div><input class="yourClass" type="checkbox" value="1" checked></div>
<div><input class="yourClass" type="checkbox" value="2"></div>
<div><input class="yourClass" type="checkbox" value="3" checked></div>
<div><input class="yourClass" type="checkbox" value="4"></div>


JQuery:

$(".yourClass:checkbox").filter(":checked")


It will choose values of 1 and 3.

Check if Cookie Exists

public static class CookieHelper
{
    /// <summary>
    /// Checks whether a cookie exists.
    /// </summary>
    /// <param name="cookieCollection">A CookieCollection, such as Response.Cookies.</param>
    /// <param name="name">The cookie name to delete.</param>
    /// <returns>A bool indicating whether a cookie exists.</returns>
    public static bool Exists(this HttpCookieCollection cookieCollection, string name)
    {
        if (cookieCollection == null)
        {
            throw new ArgumentNullException("cookieCollection");
        }

        return cookieCollection[name] != null;
    }
}

Usage:

Request.Cookies.Exists("MyCookie")

Getting raw SQL query string from PDO prepared statements

PDOStatement has a public property $queryString. It should be what you want.

I've just notice that PDOStatement has an undocumented method debugDumpParams() which you may also want to look at.

How to find GCD, LCM on a set of numbers

import java.util.*;
public class lcm {
    public static void main(String args[])
    {
        int lcmresult=1;
        System.out.println("Enter the number1: ");
        Scanner s=new Scanner(System.in);
        int a=s.nextInt();
        System.out.println("Enter the number2: ");
        int b=s.nextInt();
        int max=a>b?a:b;
        for(int i=2;i<=max;i++)
        {
            while(a%i==0||b%i==0)
            {
                lcmresult=lcmresult*i;
                if(a%i==0)
                    a=a/i;
                if(b%i==0)
                    b=b/i;
                if(a==1&&b==1)
                    break;
            }
        }
    System.out.println("lcm: "+lcmresult);
}
}

Rendering an array.map() in React

Dmitry Brin's answer worked for me, with one caveat. In my case, I needed to run a function between the list tags, which requires nested JSX braces. Example JSX below, which worked for me:

{this.props.data().map(function (object, i) { return <li>{JSON.stringify(object)}</li> })}

If you don't use nested JSX braces, for example:

{this.props.data().map(function (object, i) { return <li>JSON.stringify(object)</li>})}

then you get a list of "JSON.stringify(object)" in your HTML output, which probably isn't what you want.

Lining up labels with radio buttons in bootstrap

This may work for you, Please try this.

<form>
  <div class="form-inline">
    <div class="controls-row">
      <label class="control-label">Some label</label>
      <label class="radio inline">
        <input type="radio" value="1" />First
      </label>
      <label class="radio inline">
        <input type="radio" value="2" />Second
      </label>
    </div>
  </div>
</form>

Programmatically obtain the phone number of the Android phone

A little contribution. In my case, the code launched an error exception. I have needed put an annotation that for the code be run and fix that problem. Here I let this code.

public static String getLineNumberPhone(Context scenario) {
    TelephonyManager tMgr = (TelephonyManager) scenario.getSystemService(Context.TELEPHONY_SERVICE);
    @SuppressLint("MissingPermission") String mPhoneNumber = tMgr.getLine1Number();
    return mPhoneNumber;
}

How to implement the Java comparable interface?

Here's the code to implement java comparable interface,

// adding implements comparable to class declaration
public class Animal implements Comparable<Animal>
{
    public String name;
    public int yearDiscovered;
    public String population;

    public Animal(String name, int yearDiscovered, String population)
    {
        this.name = name;
        this.yearDiscovered = yearDiscovered;
        this.population = population; 
    }

    public String toString()
    {
        String s = "Animal name : " + name + "\nYear Discovered : " + yearDiscovered + "\nPopulation: " + population;
        return s;
    }

    @Override
    public int compareTo(Animal other)  // compareTo method performs the comparisons 
    {
        return Integer.compare(this.year_discovered, other.year_discovered);
    }
}

Get HTML inside iframe using jQuery

If you have Div as follows in one Iframe

 <iframe id="ifrmReportViewer" name="ifrmReportViewer" frameborder="0" width="980"

     <div id="EndLetterSequenceNoToShow" runat="server"> 11441551 </div> Or

     <form id="form1" runat="server">        
       <div style="clear: both; width: 998px; margin: 0 auto;" id="divInnerForm">          

            Some Text

        </div>
     </form>
 </iframe>

Then you can find the text of those Div using the following code

var iContentBody = $("#ifrmReportViewer").contents().find("body");
var endLetterSequenceNo = iContentBody.find("#EndLetterSequenceNoToShow").text();

var divInnerFormText = iContentBody.find("#divInnerForm").text();

I hope this will help someone.

Why does git perform fast-forward merges by default?

Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.

Warning: Non-fast-forwarding has potential side effects as well. Please review https://sandofsky.com/blog/git-workflow.html, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master.

alt text
(From nvie.com, Vincent Driessen, post "A successful Git branching model")

Incorporating a finished feature on develop

Finished features may be merged into the develop branch to add them to the upcoming release:

$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.

Jakub Narebski also mentions the config merge.ff:

By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set to false, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the --no-ff option from the command line).
When set to 'only', only such fast-forward merges are allowed (equivalent to giving the --ff-only option from the command line).


The fast-forward is the default because:

  • short-lived branches are very easy to create and use in Git
  • short-lived branches often isolate many commits that can be reorganized freely within that branch
  • those commits are actually part of the main branch: once reorganized, the main branch is fast-forwarded to include them.

But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.

In this case, you can end up setting this kind of config file:

[branch "master"]
# This is the list of cmdline options that should be added to git-merge 
# when I merge commits into the master branch.

# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.

# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.

mergeoptions = --no-commit --no-ff

The OP adds in the comments:

I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?

Jefromi answers:

I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.

To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.

More generally, I add:

it really depends on your development workflow:

  • if it is linear, one branch makes sense.
  • If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.

See "When should you branch?"

Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".

Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.

Datatables - Setting column width

If you ever need to set your datatable column's width using CSS ONLY, following css will help you :-)

HTML

<table class="table table-striped table-bordered table-hover table-checkable" id="datatable">
    <thead>
    <tr role="row" class="heading">
        <th width="2%">
            <label class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
                <input type="checkbox" class="group-checkable" data-set="#sample_2 .checkboxes" />
                <span></span>
            </label>
        </th>
        <th width=""> Col 1 </th>
        <th width=""> Col 2 </th>
        <th width=""> Col 3 </th>
        <th width=""> Actions </th>
    </tr>
    <tr role="row" class="filter">
        <td> </td>
        <td><input type="text" class="form-control form-filter input-sm" name="col_1"></td>
        <td><input type="text" class="form-control form-filter input-sm" name="col_2"></td>
        <td><input type="text" class="form-control form-filter input-sm" name="col_3"></td>
        <td>
            <div class="margin-bottom-5">
                <button class="btn btn-sm btn-success filter-submit margin-bottom"><i class="fa fa-search"></i> Search</button>
            </div>
            <button class="btn btn-sm btn-default filter-cancel"><i class="fa fa-times"></i> Reset</button>
        </td>
    </tr>
    </thead>
    <tbody> </tbody> 
</table>

Using metronic admin theme and my table id is #datatable as above.

CSS

#datatable > thead > tr.heading > th:nth-child(2),
#datatable > thead > tr.heading > th:nth-child(3) { width: 120px; min-width: 120px; }

Spark: Add column to dataframe conditionally

How about something like this?

val newDF = df.filter($"B" === "").take(1) match {
  case Array() => df
  case _ => df.withColumn("D", $"B" === "")
}

Using take(1) should have a minimal hit

How do I install cURL on Windows?

You may find XAMPP at http://www.apachefriends.org/en/xampp.html

http://www.apachefriends.org/en/xampp-windows.html explains XMAPP for Windows.

Yes, there are 3 php.ini files after installation, one is for php4, one is for php5, and one is for apache. Please modify them accordingly.

Open an image using URI in Android's default gallery image viewer

If your app targets Android N (7.0) and above, you should not use the answers above (of the "Uri.fromFile" method), because it won't work for you.

Instead, you should use a ContentProvider.

For example, if your image file is in external folder, you can use this (similar to the code I've made here) :

File file = ...;
final Intent intent = new Intent(Intent.ACTION_VIEW)//
                                    .setDataAndType(VERSION.SDK_INT >= VERSION_CODES.N ?
                                                    FileProvider.getUriForFile(this,getPackageName() + ".provider", file) : Uri.fromFile(file),
                            "image/*").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

manifest:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>

res/xml/provider_paths.xml :

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <!--<external-path name="external_files" path="."/>-->
    <external-path
        name="files_root"
        path="Android/data/${applicationId}"/>
    <external-path
        name="external_storage_root"
        path="."/>
</paths>

If your image is in the private path of the app, you should create your own ContentProvider, as I've created "OpenFileProvider" on the link.

ImportError: No module named apiclient.discovery

This can also happen if the interpreter on your IDE is pointing to the wrong virtual environment. In VSCODE I've set it manually to the correct interpreter and my problem was solved.

Getting coordinates of marker in Google Maps API

One more alternative options

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 1,
    center: new google.maps.LatLng(35.137879, -82.836914),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var myMarker = new google.maps.Marker({
    position: new google.maps.LatLng(47.651968, 9.478485),
    draggable: true
});

google.maps.event.addListener(myMarker, 'dragend', function (evt) {
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});

map.setCenter(myMarker.position);
myMarker.setMap(map);

and html file

<body>
    <section>
        <div id='map_canvas'></div>
        <div id="current">Nothing yet...</div>
    </section>
</body>

Redirect non-www to www in .htaccess

Change your configuration to this (add a slash):

RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L] 

Or the solution outlined below (proposed by @absiddiqueLive) will work for any domain:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

If you need to support http and https and preserve the protocol choice try the following:

RewriteRule ^login\$ https://www.%{HTTP_HOST}/login [R=301,L]

Where you replace login with checkout.php or whatever URL you need to support HTTPS on.

I'd argue this is a bad idea though. For the reasoning please read this answer.

How to change the status bar color in Android?

If you want to set a custom drawable file use this code snippet

fun setCustomStatusBar(){
    if (Build.VERSION.SDK_INT >= 21) {
        val decor = window.decorView
        decor.viewTreeObserver.addOnPreDrawListener(object :
            ViewTreeObserver.OnPreDrawListener {
            override fun onPreDraw(): Boolean {
                decor.viewTreeObserver.removeOnPreDrawListener(this)
                val statusBar = decor.findViewById<View> 
                  (android.R.id.statusBarBackground)
                statusBar.setBackgroundResource(R.drawable.bg_statusbar)
                return true
            }
        })
    }
}

Illegal Escape Character "\"

You can use:

\\

That's ok, for example:

if (invName.substring(j,k).equals("\\")) {
    copyf=invName.substring(0,j);
}

JavaScript: Alert.Show(message) From ASP.NET Code-behind

I use this and it works, as long as the page is not redirect afterwards. Would be nice to have it show, and wait until the user clicks OK, regardless of redirects.

/// <summary>
/// A JavaScript alert class
/// </summary>
public static class webMessageBox
{

/// <summary>
/// Shows a client-side JavaScript alert in the browser.
/// </summary>
/// <param name="message">The message to appear in the alert.</param>
    public static void Show(string message)
    {
       // Cleans the message to allow single quotation marks
       string cleanMessage = message.Replace("'", "\\'");
       string wsScript = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

       // Gets the executing web page
       Page page = HttpContext.Current.CurrentHandler as Page;

       // Checks if the handler is a Page and that the script isn't allready on the Page
       if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
       {
           //ClientScript.RegisterStartupScript(this.GetType(), "MessageBox", wsScript, true);
           page.ClientScript.RegisterClientScriptBlock(typeof(webMessageBox), "alert", wsScript, false);
       }
    }    
}

Scroll event listener javascript

Is there a js listener for when a user scrolls in a certain textbox that can be used?

DOM L3 UI Events spec gave the initial definition but is considered obsolete.

To add a single handler you can do:

  let isTicking;
  const debounce = (callback, evt) => {
    if (isTicking) return;
    requestAnimationFrame(() => {
      callback(evt);
      isTicking = false;
    });
    isTicking = true;
  };
  const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
  document.defaultView.onscroll = evt => debounce(handleScroll, evt);

For multiple handlers or, if preferable for style reasons, you may use addEventListener as opposed to assigning your handler to onscroll as shown above.

If using something like _.debounce from lodash you could probably get away with:

const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
document.defaultView.onscroll = evt => _.debounce(() => handleScroll(evt));

Review browser compatibility and be sure to test on some actual devices before calling it done.

How to get the PYTHONPATH in shell?

Adding to @zzzzzzz answer, I ran the command:python3 -c "import sys; print(sys.path)" and it provided me with different paths comparing to the same command with python. The paths that were displayed with python3 were "python3 oriented".

See the output of the two different commands:

python -c "import sys; print(sys.path)"

['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/local/lib/python2.7/dist-packages/setuptools-39.1.0-py2.7.egg', '/usr/lib/python2.7/dist-packages']

python3 -c "import sys; print(sys.path)"

['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']

Both commands were executed on my Ubuntu 18.04 machine.

Find size of object instance in bytes in c#

Simplest way is: int size = *((int*)type.TypeHandle.Value + 1)

I know this is implementation detail but GC relies on it and it needs to be as close to start of the methodtable for efficiency plus taking into consideration how GC code complex is nobody will dare to change it in future. In fact it works for every minor/major versions of .net framework+.net core. (Currently unable to test for 1.0)
If you want more reliable way, emit a struct in a dynamic assembly with [StructLayout(LayoutKind.Auto)] with exact same fields in same order, take its size with sizeof IL instruction. You may want to emit a static method within struct which simply returns this value. Then add 2*IntPtr.Size for object header. This should give you exact value.
But if your class derives from another class, you need to find each size of base class seperatly and add them + 2*Inptr.Size again for header. You can do this by getting fields with BindingFlags.DeclaredOnly flag.
Arrays and strings just adds that size its length * element size. For cumulative size of aggreagate objects you need to implement more sophisticated solution which involves visiting every field and inspect its contents.

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

For those who's working with latest webpack and has options property on there configuration. You cannot use query and options at the same time. You will get this error if both is present

Error: Provided options and query in use

Instead, add new property to options name generatorOpts, then add the property compact under it.

loaders: [
   { test: /\.js$/, loader: 'babel', option: { generatorOpts: { compact: false } } }
]

And for those who's working with next (like me). You need to do something like this

config.module.rules.filter((rule) => rule.use && rule.use.loader === 'next-babel-loader')
.map((loader) => {
    loader.use.options.generatorOpts = { compact: false };
    return loader;
});

Convert JSON array to Python list

data will return you a string representation of a list, but it is actually still a string. Just check the type of data with type(data). That means if you try using indexing on this string representation of a list as such data['fruits'][0], it will return you "[" as it is the first character of data['fruits']

You can do json.loads(data['fruits']) to convert it back to a Python list so that you can interact with regular list indexing. There are 2 other ways you can convert it back to a Python list suggested here

Format a JavaScript string using placeholders and an object of substitutions?

Just use replace()

var values = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"};
var substitutedString = "My Name is %NAME% and my age is %AGE%.".replace("%NAME%", $values["%NAME%"]).replace("%AGE%", $values["%AGE%"]);

Interview Question: Merge two sorted singly linked lists without creating new nodes

Node MergeLists(Node list1, Node list2) {
  if (list1 == null) return list2;
  if (list2 == null) return list1;

  if (list1.data < list2.data) {
    list1.next = MergeLists(list1.next, list2);
    return list1;
  } else {
    list2.next = MergeLists(list2.next, list1);
    return list2;
  }
}

custom facebook share button

This solution is using javascript to open a new window when a user clicks on your custom share button.

HTML:

<a href="#" onclick="share_fb('http://urlhere.com/test/55d7258b61707022e3050000');return false;" rel="nofollow" share_url="http://urlhere.com/test/55d7258b61707022e3050000" target="_blank">

  //using fontawesome
  <i class="uk-icon-facebook uk-float-left"></i>
    Share
</a>

and in your javascript file. note window.open params are (url, dialogue title, width, height)

function share_fb(url) {
  window.open('https://www.facebook.com/sharer/sharer.php?u='+url,'facebook-share-dialog',"width=626, height=436")
}

Causes of getting a java.lang.VerifyError

This can happen on Android when you're trying to load a library that was compiled against Oracle's JDK.

Here is the problem for Ning Async HTTP client.

Show percent % instead of counts in charts of categorical variables

With ggplot2 version 2.1.0 it is

+ scale_y_continuous(labels = scales::percent)

How do I execute a *.dll file

To Run a .dll file..First find out what are functions it is exporting..Dll files will excecute the functions specified in the Export Category..To know what function it is Exporting refer "filealyzer" Application..It will show you the export function under "PE EXPORT" Category..Notedown the function name-- Then open the command prompt,Type Rundll32 dllname,functionname (dllname--name of your dll) (Functionname-- name of the function you found under the PE Export) Note:Makesure that your command prompt location is your dll file location

Calling another different view from the controller using ASP.NET MVC 4

To return a different view, you can specify the name of the view you want to return and model as follows:

return View("ViewName", yourModel);

if the view is in different folder under Views folder then use below absolute path:

return View("~/Views/FolderName/ViewName.aspx");

What are .tpl files? PHP, web design

.tpl shows there is a smarty! Smarty is a template language to split out PHP code from HTML code. Which gives us to the ability to do design stuff on a page which has not included PHP code.

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

Simply, @Id: This annotation specifies the primary key of the entity. 

@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used. 

GenerationType enum defines four strategies: 
1. Generation Type . TABLE, 
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY   
4. Generation Type. AUTO

GenerationType.SEQUENCE

With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities. 

GenerationType.TABLE

With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities. 

GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used. 

Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

How to split data into trainset and testset randomly?

from sklearn.model_selection import train_test_split
import numpy

with open("datafile.txt", "rb") as f:
   data = f.read().split('\n')
   data = numpy.array(data)  #convert array to numpy type array

   x_train ,x_test = train_test_split(data,test_size=0.5)       #test_size=0.5(whole_data)

Convert array of strings into a string in Java

Use Apache Commons' StringUtils library's join method.

String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");

Preventing an image from being draggable or selectable without using JS

You could set the image as a background image. Since it resides in a div, and the div is undraggable, the image will be undraggable:

<div style="background-image: url("image.jpg");">
</div>

mysql datetime comparison

I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :

[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.

I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...

Paritition array into N chunks with Numpy

I believe that you're looking for numpy.split or possibly numpy.array_split if the number of sections doesn't need to divide the size of the array properly.

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

Delete from two tables in one query

Can't you just separate them by a semicolon?

Delete from messages where messageid = '1';
Delete from usersmessages where messageid = '1'

OR

Just use INNER JOIN as below

DELETE messages , usersmessages  FROM messages  INNER JOIN usersmessages  
WHERE messages.messageid= usersmessages.messageid and messages.messageid = '1'

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

https://cdn.rawgit.com is shutting down. Thus, one of the alternate options can be used. JSDeliver is a free cdn that can be used.

// load any GitHub release, commit, or branch

// note: we recommend using npm for projects that support it

https://cdn.jsdelivr.net/gh/user/repo@version/file

// load jQuery v3.2.1

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

// use a version range instead of a specific version

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

https://cdn.jsdelivr.net/gh/jquery/jquery@3/dist/jquery.min.js

// omit the version completely to get the latest one

// you should NOT use this in production

https://cdn.jsdelivr.net/gh/jquery/jquery/dist/jquery.min.js

// add ".min" to any JS/CSS file to get a minified version

// if one doesn't exist, we'll generate it for you

https://cdn.jsdelivr.net/gh/jquery/[email protected]/src/core.min.js

// add / at the end to get a directory listing

https://cdn.jsdelivr.net/gh/jquery/jquery/

ref - https://www.jsdelivr.com/?docs=gh

Get pixel's RGB using PIL

With numpy :

im = Image.open('image.gif')
im_matrix = np.array(im)
print(im_matrix[0][0])

Give RGB vector of the pixel in position (0,0)

Quantile-Quantile Plot using SciPy

I came up with this. Maybe you can improve it. Especially the method of generating the quantiles of the distribution seems cumbersome to me.

You could replace np.random.normal with any other distribution from np.random to compare data against other distributions.

#!/bin/python

import numpy as np

measurements = np.random.normal(loc = 20, scale = 5, size=100000)

def qq_plot(data, sample_size):
    qq = np.ones([sample_size, 2])
    np.random.shuffle(data)
    qq[:, 0] = np.sort(data[0:sample_size])
    qq[:, 1] = np.sort(np.random.normal(size = sample_size))
    return qq

print qq_plot(measurements, 1000)

LEFT OUTER JOIN in LINQ

Simple solution for the LEFT OUTER JOIN:

var setA = context.SetA;
var setB = context.SetB.Select(st=>st.Id).Distinct().ToList();
var leftOuter  = setA.Where(stA=> !setB.Contains(stA.Id)); 

notes:

  • To improve performance SetB could be converted to a Dictionary (if that is done then you have to change this: !setB.Contains(stA.Id)) or a HashSet
  • When there is more than one field involved this could be achieve using Set operations and a class that implement: IEqualityComparer

How to filter input type="file" dialog by specific file type?

This will give the correct (custom) filter when the file dialog is showing:

<input type="file" accept=".jpg, .png, .jpeg, .gif, .bmp, .tif, .tiff|image/*">

How to convert enum names to string in c

I usually do this:

#define COLOR_STR(color)                            \
    (RED       == color ? "red"    :                \
     (BLUE     == color ? "blue"   :                \
      (GREEN   == color ? "green"  :                \
       (YELLOW == color ? "yellow" : "unknown"))))   

Get git branch name in Jenkins Pipeline/Jenkinsfile

Switching to a multibranch pipeline allowed me to access the branch name. A regular pipeline was not advised.

How can I get the current array index in a foreach loop?

foreach($array as $key=>$value) {
    // do stuff
}

$key is the index of each $array element

The program can't start because MSVCR110.dll is missing from your computer

I was getting a similar issue from the Apache Lounge 32 bit version. After downloading the 64 bit version, the issue was resolved.

Here is an excellent video explain the steps involved: https://www.youtube.com/watch?v=17qhikHv5hY

Rails params explained?

The params come from the user's browser when they request the page. For an HTTP GET request, which is the most common, the params are encoded in the url. For example, if a user's browser requested

http://www.example.com/?foo=1&boo=octopus

then params[:foo] would be "1" and params[:boo] would be "octopus".

In HTTP/HTML, the params are really just a series of key-value pairs where the key and the value are strings, but Ruby on Rails has a special syntax for making the params be a hash with hashes inside. For example, if the user's browser requested

http://www.example.com/?vote[item_id]=1&vote[user_id]=2

then params[:vote] would be a hash, params[:vote][:item_id] would be "1" and params[:vote][:user_id] would be "2".

The Ruby on Rails params are the equivalent of the $_REQUEST array in PHP.

How to write a unit test for a Spring Boot Controller endpoint

Let assume i am having a RestController with GET/POST/PUT/DELETE operations and i have to write unit test using spring boot.I will just share code of RestController class and respective unit test.Wont be sharing any other related code to the controller ,can have assumption on that.

@RestController
@RequestMapping(value = “/myapi/myApp” , produces = {"application/json"})
public class AppController {


    @Autowired
    private AppService service;

    @GetMapping
    public MyAppResponse<AppEntity> get() throws Exception {

        MyAppResponse<AppEntity> response = new MyAppResponse<AppEntity>();
        service.getApp().stream().forEach(x -> response.addData(x));    
        return response;
    }


    @PostMapping
    public ResponseEntity<HttpStatus> create(@RequestBody AppRequest request) throws Exception {
        //Validation code       
        service.createApp(request);

        return ResponseEntity.ok(HttpStatus.OK);
    }

    @PutMapping
    public ResponseEntity<HttpStatus> update(@RequestBody IDMSRequest request) throws Exception {

        //Validation code
        service.updateApp(request);

        return ResponseEntity.ok(HttpStatus.OK);
    }

    @DeleteMapping
    public ResponseEntity<HttpStatus> delete(@RequestBody AppRequest request) throws Exception {

        //Validation        
        service.deleteApp(request.id);

        return ResponseEntity.ok(HttpStatus.OK);
    }

}

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public abstract class BaseTest {
   protected MockMvc mvc;
   @Autowired
   WebApplicationContext webApplicationContext;

   protected void setUp() {
      mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
   }
   protected String mapToJson(Object obj) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(obj);
   }
   protected <T> T mapFromJson(String json, Class<T> clazz)
      throws JsonParseException, JsonMappingException, IOException {

      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(json, clazz);
   }
}

public class AppControllerTest extends BaseTest {

    @MockBean
    private IIdmsService service;

    private static final String URI = "/myapi/myApp";


   @Override
   @Before
   public void setUp() {
      super.setUp();
   }

   @Test
   public void testGet() throws Exception {
       AppEntity entity = new AppEntity();
      List<AppEntity> dataList = new ArrayList<AppEntity>();
      AppResponse<AppEntity> dataResponse = new AppResponse<AppEntity>();
      entity.setId(1);
      entity.setCreated_at("2020-02-21 17:01:38.717863");
      entity.setCreated_by(“Abhinav Kr”);
      entity.setModified_at("2020-02-24 17:01:38.717863");
      entity.setModified_by(“Jyoti”);
            dataList.add(entity);

      dataResponse.setData(dataList);

      Mockito.when(service.getApp()).thenReturn(dataList);

      RequestBuilder requestBuilder =  MockMvcRequestBuilders.get(URI)
                 .accept(MediaType.APPLICATION_JSON);

        MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        String expectedJson = this.mapToJson(dataResponse);
        String outputInJson = mvcResult.getResponse().getContentAsString();

        assertEquals(HttpStatus.OK.value(), response.getStatus());
        assertEquals(expectedJson, outputInJson);
   }

   @Test
   public void testCreate() throws Exception {

       AppRequest request = new AppRequest();
       request.createdBy = 1;
       request.AppFullName = “My App”;
       request.appTimezone = “India”;

       String inputInJson = this.mapToJson(request);
       Mockito.doNothing().when(service).createApp(Mockito.any(AppRequest.class));
       service.createApp(request);
       Mockito.verify(service, Mockito.times(1)).createApp(request);

       RequestBuilder requestBuilder =  MockMvcRequestBuilders.post(URI)
                                                             .accept(MediaType.APPLICATION_JSON).content(inputInJson)
                                                             .contentType(MediaType.APPLICATION_JSON);

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());

   }

   @Test
   public void testUpdate() throws Exception {

       AppRequest request = new AppRequest();
       request.id = 1;
       request.modifiedBy = 1;
        request.AppFullName = “My App”;
       request.appTimezone = “Bharat”;

       String inputInJson = this.mapToJson(request);
       Mockito.doNothing().when(service).updateApp(Mockito.any(AppRequest.class));
       service.updateApp(request);
       Mockito.verify(service, Mockito.times(1)).updateApp(request);

       RequestBuilder requestBuilder =  MockMvcRequestBuilders.put(URI)
                                                             .accept(MediaType.APPLICATION_JSON).content(inputInJson)
                                                             .contentType(MediaType.APPLICATION_JSON);

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());

   }

   @Test
   public void testDelete() throws Exception {

       AppRequest request = new AppRequest();
       request.id = 1;

       String inputInJson = this.mapToJson(request);
       Mockito.doNothing().when(service).deleteApp(Mockito.any(Integer.class));
       service.deleteApp(request.id);
       Mockito.verify(service, Mockito.times(1)).deleteApp(request.id);

       RequestBuilder requestBuilder =  MockMvcRequestBuilders.delete(URI)
                                                             .accept(MediaType.APPLICATION_JSON).content(inputInJson)
                                                             .contentType(MediaType.APPLICATION_JSON);

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());

   }

}

How to Call a Function inside a Render in React/Jsx

_x000D_
_x000D_
class App extends React.Component {_x000D_
  _x000D_
  buttonClick(){_x000D_
    console.log("came here")_x000D_
    _x000D_
  }_x000D_
  _x000D_
  subComponent() {_x000D_
    return (<div>Hello World</div>);_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    return ( _x000D_
      <div className="patient-container">_x000D_
          <button onClick={this.buttonClick.bind(this)}>Click me</button>_x000D_
          {this.subComponent()}_x000D_
       </div>_x000D_
     )_x000D_
  }_x000D_
  _x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App/>, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

it depends on your need, u can use either this.renderIcon() or bind this.renderIcon.bind(this)

UPDATE

This is how you call a method outside the render.

buttonClick(){
    console.log("came here")
}

render() {
   return (
       <div className="patient-container">
          <button onClick={this.buttonClick.bind(this)}>Click me</button>
       </div>
   );
}

The recommended way is to write a separate component and import it.

SQL Server : converting varchar to INT

This is more for someone Searching for a result, than the original post-er. This worked for me...

declare @value varchar(max) = 'sad';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));

returns 0

declare @value varchar(max) = '3';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));

returns 3

What is the difference between String.slice and String.substring?

substr: It's providing us to fetch part of the string based on specified index. syntax of substr- string.substr(start,end) start - start index tells where the fetching start. end - end index tells upto where string fetches. It's optional.

slice: It's providing to fetch part of the string based on the specified index. It's allows us to specify positive and index. syntax of slice - string.slice(start,end) start - start index tells where the fetching start.It's end - end index tells upto where string fetches. It's optional. In 'splice' both start and end index helps to take positive and negative index.

sample code for 'slice' in string

var str="Javascript";
console.log(str.slice(-5,-1));

output: crip

sample code for 'substring' in string

var str="Javascript";
console.log(str.substring(1,5));

output: avas

[*Note: negative indexing starts at the end of the string.]

scipy.misc module has no attribute imread?

Running the following in a Jupyter Notebook, I had a similar error message:

from skimage import data
photo_data = misc.imread('C:/Users/ers.jpg')
type(photo_data)

'error' msg:

D:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\ipykernel_launcher.py:3: DeprecationWarning: imread is deprecated! imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. Use imageio.imread instead. This is separate from the ipykernel package so we can avoid doing imports until

And using the following I got it solved:

import matplotlib.pyplot
photo_data = matplotlib.pyplot.imread('C:/Users/ers.jpg')
type(photo_data)

What's the simplest way to extend a numpy array in 2 dimensions?

Another elegant solution to the first question may be the insert command:

p = np.array([[1,2],[3,4]])
p = np.insert(p, 2, values=0, axis=1) # insert values before column 2

Leads to:

array([[1, 2, 0],
       [3, 4, 0]])

insert may be slower than append but allows you to fill the whole row/column with one value easily.

As for the second question, delete has been suggested before:

p = np.delete(p, 2, axis=1)

Which restores the original array again:

array([[1, 2],
       [3, 4]])

How to get table list in database, using MS SQL 2008?

This should give you a list of all the tables in your database

SELECT Distinct TABLE_NAME FROM information_schema.TABLES

So you can use it similar to your database check.

If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table')
BEGIN
    --CREATE TABLE Your_Table
END
GO

MVC Razor Hidden input and passing values

You are doing it wrong since you try to map WebForms in the MVC application.

There are no server side controlls in MVC. Only the View and the Controller on the back-end. You send the data from server to the client by means of initialization of the View with your model.

This is happening on the HTTP GET request to your resource.

[HttpGet]
public ActionResult Home() 
{
  var model = new HomeModel { Greeatings = "Hi" };
  return View(model);
}

You send data from client to server by means of posting data to server. To make that happen, you create a form inside your view and [HttpPost] handler in your controller.

// View

@using (Html.BeginForm()) {
  @Html.TextBoxFor(m => m.Name)
  @Html.TextBoxFor(m => m.Password)
}

// Controller

[HttpPost]
public ActionResult Home(LoginModel model) 
{
  // do auth.. and stuff
  return Redirect();
}

How can I convert NSDictionary to NSData and vice versa?

NSDictionary -> NSData:

NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:yourDictionary forKey:@"Some Key Value"];
[archiver finishEncoding];
[archiver release];

// Here, data holds the serialized version of your dictionary
// do what you need to do with it before you:
[data release];

NSData -> NSDictionary

NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];

You can do that with any class that conforms to NSCoding.

source

Get all dates between two dates in SQL Server

I listed dates of 2 Weeks later. You can use variable @period OR function datediff(dd, @date_start, @date_end)

declare @period INT, @date_start datetime, @date_end datetime, @i int;

set @period = 14
set @date_start = convert(date,DATEADD(D, -@period, curent_timestamp))
set @date_end = convert(date,current_timestamp)
set @i = 1

create table #datesList(dts datetime)
insert into #datesList values (@date_start)
while @i <= @period
    Begin
        insert into #datesList values (dateadd(d,@i,@date_start))
        set @i = @i + 1
    end
select cast(dts as DATE) from #datesList
Drop Table #datesList

Using :: in C++

One use for the 'Unary Scope Resolution Operator' or 'Colon Colon Operator' is for local and global variable selection of identical names:

    #include <iostream>
    using namespace std;
    
    int variable = 20;
    
    int main()
    {
    float variable = 30;
    
    cout << "This is local to the main function: " << variable << endl;
    cout << "This is global to the main function: " << ::variable << endl;
    
    return 0;
    }

The resulting output would be:

This is local to the main function: 30

This is global to the main function: 20

Other uses could be: Defining a function from outside of a class, to access a static variable within a class or to use multiple inheritance.

What is AF_INET, and why do I need it?

AF_INET is an address family that is used to designate the type of addresses that your socket can communicate with (in this case, Internet Protocol v4 addresses). When you create a socket, you have to specify its address family, and then you can only use addresses of that type with the socket. The Linux kernel, for example, supports 29 other address families such as UNIX (AF_UNIX) sockets and IPX (AF_IPX), and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).

For the most part, sticking with AF_INET for socket programming over a network is the safest option. There is also AF_INET6 for Internet Protocol v6 addresses.

Hope this helps,

Difference between setTimeout with and without quotes and parentheses

What happens in reality in case you pass string as a first parameter of function

setTimeout('string',number)

is value of first param got evaluated when it is time to run (after numberof miliseconds passed). Basically it is equal to

setTimeout(eval('string'), number)

This is

an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.

So samples which you refer are not good samples, and may be given in different context or just simple typo.

If you invoke like this setTimeout(something, number), first parameter is not string, but pointer to a something called something. And again if something is string - then it will be evaluated. But if it is function, then function will be executed. jsbin sample

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

I have found this page

http://schemas.xmlsoap.org/wsdl/soap12/soap12WSDL.htm

which says that Soap 1.2 uses the new namespace http://schemas.xmlsoap.org/wsdl/soap12/

It is in the 'WSDL 1.1 Binding extension for SOAP 1.1'.

Convert LocalDate to LocalDateTime or java.sql.Timestamp

function call asStartOfDay() on java.time.LocalDate object returns a java.time.LocalDateTime object

How to select an option from drop down using Selenium WebDriver C#?

Adding a point to this- I came across a problem that OpenQA.Selenium.Support.UI namespace was not available after installing Selenium.NET binding into the C# project. Later found out that we can easily install latest version of Selenium WebDriver Support Classes by running the command:

Install-Package Selenium.Support

in NuGet Package Manager Console, or install Selenium.Support from NuGet Manager.

The tilde operator in Python

One should note that in the case of array indexing, array[~i] amounts to reversed_array[i]. It can be seen as indexing starting from the end of the array:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
    ^                 ^
    i                ~i

Entity Framework: There is already an open DataReader associated with this Command

In my case the issue had nothing to do with MARS connection string but with json serialization. After upgrading my project from NetCore2 to 3 i got this error.

More information can be found here

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

How I solved my problem.

I had

?useUnicode=true&amp;characterEncoding=UTF-8

In my hibernate jdbc connection url and I changed the string datatype to longtext in database, which was varchar before.

Example of a strong and weak entity types

A weak entity is the entity which can't be fully identified by its own attributes and takes the foreign key as an attribute (generally it takes the primary key of the entity it is related to) in conjunction.

Examples

The existence of rooms is entirely dependent on the existence of a hotel. So room can be seen as the weak entity of the hotel.
Another example is the
bank account of a particular bank has no existence if the bank doesn't exist anymore.

Javascript Object push() function

Objects does not support push property, but you can save it as well using the index as key,

_x000D_
_x000D_
var tempData = {};_x000D_
for ( var index in data ) {_x000D_
  if ( data[index].Status == "Valid" ) { _x000D_
    tempData[index] = data; _x000D_
  } _x000D_
 }_x000D_
data = tempData;
_x000D_
_x000D_
_x000D_

I think this is easier if remove the object if its status is invalid, by doing.

_x000D_
_x000D_
for(var index in data){_x000D_
  if(data[index].Status == "Invalid"){ _x000D_
    delete data[index]; _x000D_
  } _x000D_
}
_x000D_
_x000D_
_x000D_

And finally you don't need to create a var temp –

Difference between Subquery and Correlated Subquery

Correlated Subquery is a sub-query that uses values from the outer query. In this case the inner query has to be executed for every row of outer query.

See example here http://en.wikipedia.org/wiki/Correlated_subquery

Simple subquery doesn't use values from the outer query and is being calculated only once:

SELECT id, first_name 
FROM student_details 
WHERE id IN (SELECT student_id
FROM student_subjects 
WHERE subject= 'Science'); 

CoRelated Subquery Example -

Query To Find all employees whose salary is above average for their department

 SELECT employee_number, name
       FROM employees emp
       WHERE salary > (
         SELECT AVG(salary)
           FROM employees
           WHERE department = emp.department);

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

If you're just looking for a command-line utility (i.e., not something that will get called from other functions), try out this script. It assumes the existence of GNU date (present on pretty much any Linux system):

#! /usr/bin/perl -w

use strict;

$_ = (join ' ', @ARGV);
$_ ||= <STDIN>;

chomp;

if (/^[\d.]+$/) {
    print scalar localtime $_;
    print "\n";
}
else {
    exec "date -d '$_' +%s";
}

Here's how it works:

$ Time now
1221763842

$ Time yesterday
1221677444

$ Time 1221677444
Wed Sep 17 11:50:44 2008

$ Time '12:30pm jan 4 1987'
536790600

$ Time '9am 8 weeks ago'
1216915200

How to Logout of an Application Where I Used OAuth2 To Login With Google?

This works to sign the user out of the application, but not Google.

var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
  console.log('User signed out.');
});

Source: https://developers.google.com/identity/sign-in/web/sign-in

Format Float to n decimal places

public static double roundToDouble(float d, int decimalPlace) {
        BigDecimal bd = new BigDecimal(Float.toString(d));
        bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

How to disable all <input > inside a form with jQuery?

To disable all form, as easy as write:

jQuery 1.6+

$("#form :input").prop("disabled", true);

jQuery 1.5 and below

$("#form :input").attr('disabled','disabled');

Transparent background in JPEG image

You can't make a JPEG image transparent. You should use a format that allows transparency, like GIF or PNG.

Paint will open these files, but AFAIK it'll erase transparency if you edit the file. Use some other application like Paint.NET (it's free).

Edit: since other people have mentioned it: you can convert JPEG images into PNG, in any editor that's capable of working with both types.

How can the error 'Client found response content type of 'text/html'.. be interpreted

I had got this error after changing the web service return type and SoapDocumentMethod.

Initially it was:

[WebMethod]
public int Foo()
{
    return 0;
}

I decided to make it fire and forget type like this:

[SoapDocumentMethod(OneWay = true)]
[WebMethod]
public void Foo()
{
    return;
}

In such cases, updating the web reference helped.

To update a web service reference:

  • Expand solution explorer
  • Locate Web References - this will be visible only if you have added a web service reference in your project
  • Right click and click update web reference

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to run specific test cases in GoogleTest

Finally I got some answer, ::test::GTEST_FLAG(list_tests) = true; //From your program, not w.r.t console.

If you would like to use --gtest_filter =*; /* =*, =xyz*... etc*/ // You need to use them in Console.

So, my requirement is to use them from the program not from the console.

Updated:-

Finally I got the answer for updating the same in from the program.

 ::testing::GTEST_FLAG(filter) = "*Counter*:*IsPrime*:*ListenersTest.DoesNotLeak*";//":-:*Counter*";
      InitGoogleTest(&argc, argv);
RUN_ALL_TEST();

So, Thanks for all the answers.

You people are great.

'readline/readline.h' file not found

This command helped me on linux mint when i had exact same problem

gcc filename.c -L/usr/include -lreadline -o filename

You could use alias if you compile it many times Forexample:

alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'

Selecting multiple classes with jQuery

Have you tried this?

$('.myClass, .myOtherClass').removeClass('theclass');

Android emulator-5554 offline

step 01: Delete current emulator from AVD manager step 02: Add new emulator. select device => select system image, in this step go to x86 images tab and select one which has the target with google APIs. step 03: Finish all steps. Your're good to go ?

How to remove old and unused Docker images

Remove old containers weeks ago.

docker rm $(docker ps -a | grep "weeks" | awk '{ print $1; }')

Remove old images weeks ago. Be careful. This will remove base images which was created weeks ago but which your new images might be using.

docker rmi $(docker images | grep 'weeks' | awk '{ print $3; }')

How can you speed up Eclipse?

Eclipse loads plug-ins lazily, and most common plug-ins, like Subclipse, don't do anything if you don't use them. They don't slow Eclipse down at all during run time, and it won't help you to disable them. In fact, Mylyn was shown to reduce Eclipse's memory footprint when used correctly.

I run Eclipse with tons of plug-ins without any performance penalty at all.

  • Try disabling compiler settings that you perhaps don't need (e.g. the sub-options under "parameter is never read).
  • Which version of Eclipse are you using? Older versions were known to be slow if you upgraded them over and over again, because they got their plug-ins folder inflated with duplicate plug-ins (with different versions). This is not a problem in version 3.4.
  • Use working-sets. They work better than closing projects, particularly if you need to switch between sets of projects all the time.

It's not only the memory that you need to increase with the -Xmx switch, it's also the perm gen size. I think that problem was solved in Eclipse 3.4.

I get exception when using Thread.sleep(x) or wait()

Put your Thread.sleep in a try catch block

try {
    //thread to sleep for the specified number of milliseconds
    Thread.sleep(100);
} catch ( java.lang.InterruptedException ie) {
    System.out.println(ie);
}

Iterating through a golang map

You can make it by one line:

mymap := map[string]interface{}{"foo": map[string]interface{}{"first": 1}, "boo": map[string]interface{}{"second": 2}}
for k, v := range mymap {
    fmt.Println("k:", k, "v:", v)
}

Output is:

k: foo v: map[first:1]
k: boo v: map[second:2]

How do I install a plugin for vim?

Make sure that the actual .vim file is in ~/.vim/plugin/

Difference between null and empty string

When Object variables are initially used in a language like Java, they have absolutely no value at all - not zero, but literally no value - that is null

For instance: String s;

If you were to use s, it would actually have a value of null, because it holds absolute nothing.

An empty string, however, is a value - it is a string of no characters.

String s; //Inits to null
String a =""; //A blank string

Null is essentially 'nothing' - it's the default 'value' (to use the term loosely) that Java assigns to any Object variable that was not initialized.

Null isn't really a value - and as such, doesn't have properties. So, calling anything that is meant to return a value - such as .length(), will invariably return an error, because 'nothing' cannot have properties.

To go into more depth, by creating s1 = ""; you are initializing an object, which can have properties, and takes up relevant space in memory. By using s2; you are designating that variable name to be a String, but are not actually assigning any value at that point.

Handle ModelState Validation in ASP.NET Web API

Add below code in startup.cs file

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = (context) =>
                {
                    var errors = context.ModelState.Values.SelectMany(x => x.Errors.Select(p => new ErrorModel()
                   {
                       ErrorCode = ((int)HttpStatusCode.BadRequest).ToString(CultureInfo.CurrentCulture),
                        ErrorMessage = p.ErrorMessage,
                        ServerErrorMessage = string.Empty
                    })).ToList();
                    var result = new BaseResponse
                    {
                        Error = errors,
                        ResponseCode = (int)HttpStatusCode.BadRequest,
                        ResponseMessage = ResponseMessageConstants.VALIDATIONFAIL,

                    };
                    return new BadRequestObjectResult(result);
                };
           });

Changing the highlight color when selecting text in an HTML text input

this is the code.

/*** Works on common browsers ***/
::selection {
    background-color: #352e7e;
    color: #fff;
}

/*** Mozilla based browsers ***/
::-moz-selection {
    background-color: #352e7e;
    color: #fff;
}

/***For Other Browsers ***/
::-o-selection {
    background-color: #352e7e;
    color: #fff;
}

::-ms-selection {
    background-color: #352e7e;
    color: #fff;
}

/*** For Webkit ***/
::-webkit-selection {
    background-color: #352e7e;
    color: #fff;
}

How to set the action for a UIBarButtonItem in Swift

May this one help a little more

Let suppose if you want to make the bar button in a separate file(for modular approach) and want to give selector back to your viewcontroller, you can do like this :-

your Utility File

class GeneralUtility {

    class func customeNavigationBar(viewController: UIViewController,title:String){
        let add = UIBarButtonItem(title: "Play", style: .plain, target: viewController, action: #selector(SuperViewController.buttonClicked(sender:)));  
      viewController.navigationController?.navigationBar.topItem?.rightBarButtonItems = [add];
    }
}

Then make a SuperviewController class and define the same function on it.

class SuperViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
            // Do any additional setup after loading the view.
    }
    @objc func buttonClicked(sender: UIBarButtonItem) {

    }
}

and In our base viewController(which inherit your SuperviewController class) override the same function

import UIKit

class HomeViewController: SuperViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        GeneralUtility.customeNavigationBar(viewController: self,title:"Event");
    }

    @objc override func buttonClicked(sender: UIBarButtonItem) {
      print("button clicked")    
    } 
}

Now just inherit the SuperViewController in whichever class you want this barbutton.

Thanks for the read

How to use php serialize() and unserialize()

<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b);
print_r($c);

Run this program its echo the output

a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}


here
a=size of array
i=count of array number
s=size of array values

you can use serialize to store array of data in database
and can retrieve and UN-serialize data to use.

How to send password securely over HTTP?

Using https sounds best option here (certificates are not that expensive nowadays). However if http is a requirement, you may use some encription - encript it on server side and decript in users browser (send key separately).

We have used that while implementing safevia.net - encription is done on clients (sender/receiver) sides, so users data are not available on network nor server layer.

How to manipulate arrays. Find the average. Beginner Java

If we want to add numbers of an Array and find the average of them follow this easy way! .....

public class Array {

    public static void main(String[] args) {

        int[]array = {1,3,5,7,9,6,3};
        int i=0;
        int sum=0;
        double average=0;
        for( i=0;i<array.length;i++){
            System.out.println(array[i]);
            sum=sum+array[i];
        }
        System.out.println("sum is:"+sum);
        System.out.println("average is: "+(double)sum/vargu.length);



    }

}

Creating an R dataframe row-by-row

Depending on the format of your new row, you might use tibble::add_row if your new row is simple and can specified in "value-pairs". Or you could use dplyr::bind_rows, "an efficient implementation of the common pattern of do.call(rbind, dfs)".

PHP Pass by reference in foreach

This :

$a = array ('zero','one','two', 'three');

foreach ($a as &$v) {

}

foreach ($a as $v) {
    echo $v.PHP_EOL;
}

is the same as

$a = array ('zero','one','two', 'three');

$v = &$a[3];

for ($i = 0; $i < 4; $i++) {
    $v = $a[$i];
    echo $v.PHP_EOL; 
}

OR

$a = array ('zero','one','two', 'three');

for ($i = 0; $i < 4; $i++) {
    $a[3] = $a[$i];
    echo $a[3].PHP_EOL; 
}

OR

$a = array ('zero','one','two', 'three');

$a[3] = $a[0];
echo $a[3].PHP_EOL;

$a[3] = $a[1]; 
echo $a[3].PHP_EOL;

$a[3] = $a[2];
echo $a[3].PHP_EOL;

$a[3] = $a[3]; 
echo $a[3].PHP_EOL;

Pass values of checkBox to controller action in asp.net mvc4

I hope this somewhat helps.

Create a viewmodel for your view. This will represent the true or false (checked or unchecked) values of your checkboxes.

public class UsersViewModel
{
    public bool IsAdmin { get; set; }
    public bool ManageFiles { get; set; }
    public bool ManageNews { get; set; }
}

Next, create your controller and have it pass the view model to your view.

public IActionResult Users()
{
     var viewModel = new UsersViewModel();
     return View(viewModel);
}

Lastly, create your view and reference your view model. Use @Html.CheckBoxFor(x => x) to display checkboxes and hold their values.

@model Website.Models.UsersViewModel
<div class="form-check">
    @Html.CheckBoxFor(x => x.IsAdmin)
    <label class="form-check-label" for="defaultCheck1">
           Admin
    </label>
</div>
          

When you post/save data from your view, the view model will contain the values of the checkboxes. Be sure to include the viewmodel as a parameter in the method/controller that is called to save your data.

I hope this makes sense and helps. This is my first answer, so apologies if lacking.

Get value (String) of ArrayList<ArrayList<String>>(); in Java

Because the second element is null after you clear the list.

Use:

String s = myList.get(0);

And remember, index 0 is the first element.

How do I change selected value of select2 dropdown with JqGrid?

if you have ajax data source please refer this for bugs free

https://select2.org/programmatic-control/add-select-clear-items

// Set up the Select2 control

$('#mySelect2').select2({
    ajax: {
        url: '/api/students'
    }
});

// Fetch the preselected item, and add to the control

var studentSelect = $('#mySelect2');
$.ajax({
    type: 'GET',
    url: '/api/students/s/' + studentId
}).then(function (data) {
    // create the option and append to Select2
    var option = new Option(data.full_name, data.id, true, true);
    studentSelect.append(option).trigger('change');

    // manually trigger the `select2:select` event
    studentSelect.trigger({
        type: 'select2:select',
        params: {
            data: data
        }
    });
});

Failing to run jar file from command line: “no main manifest attribute”

In Eclipse: right-click on your project -> Export -> JAR file

At last page with options (when there will be no Next button active) you will see settings for Main class:. You need to set here class with main method which should be executed by default (like when JAR file will be double-clicked).

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

Just imagine that the AutoResetEvent executes WaitOne() and Reset() as a single atomic operation.

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

Reload the page after ajax success

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});

Using a .php file to generate a MySQL dump

For security reasons, it's recommended to specify the password in a configuration file and not in the command (a user can execute a ps aux | grep mysqldump and see the password).

//create a temporary file
$file   = tempnam(sys_get_temp_dir(), 'mysqldump');

//store the configuration options
file_put_contents($file, "[mysqldump]
user={$user}
password=\"{$password}\"");

//execute the command and output the result
passthru("mysqldump --defaults-file=$file {$dbname}");

//delete the temporary file
unlink($file);

Google Chrome default opening position and size

You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.

How do you embed binary data in XML?

Base64 is indeed the right answer but CDATA is not, that's basically saying: "this could be anything", however it must not be just anything, it has to be Base64 encoded binary data. XML Schema defines Base 64 binary as a primitive datatype which you can use in your xsd.

Quickest way to find missing number in an array of numbers

I found this beautiful solution here:

http://javaconceptoftheday.com/java-puzzle-interview-program-find-missing-number-in-an-array/

public class MissingNumberInArray
{
    //Method to calculate sum of 'n' numbers

    static int sumOfNnumbers(int n)
    {
        int sum = (n * (n+1))/ 2;

        return sum;
    }

    //Method to calculate sum of all elements of array

    static int sumOfElements(int[] array)
    {
        int sum = 0;

        for (int i = 0; i < array.length; i++)
        {
            sum = sum + array[i];
        }

        return sum;
    }

    public static void main(String[] args)
    {
        int n = 8;

        int[] a = {1, 4, 5, 3, 7, 8, 6};

        //Step 1

        int sumOfNnumbers = sumOfNnumbers(n);

        //Step 2

        int sumOfElements = sumOfElements(a);

        //Step 3

        int missingNumber = sumOfNnumbers - sumOfElements;

        System.out.println("Missing Number is = "+missingNumber);
    }
}

Python function attributes - uses and abuses

I use them sparingly, but they can be pretty convenient:

def log(msg):
   log.logfile.write(msg)

Now I can use log throughout my module, and redirect output simply by setting log.logfile. There are lots and lots of other ways to accomplish that, but this one's lightweight and dirt simple. And while it smelled funny the first time I did it, I've come to believe that it smells better than having a global logfile variable.

Bash Shell Script - Check for a flag and grab its value

Here is a generalized simple command argument interface you can paste to the top of all your scripts.

#!/bin/bash

declare -A flags
declare -A booleans
args=()

while [ "$1" ];
do
    arg=$1
    if [ "${1:0:1}" == "-" ]
    then
      shift
      rev=$(echo "$arg" | rev)
      if [ -z "$1" ] || [ "${1:0:1}" == "-" ] || [ "${rev:0:1}" == ":" ]
      then
        bool=$(echo ${arg:1} | sed s/://g)
        booleans[$bool]=true
        echo \"$bool\" is boolean
      else
        value=$1
        flags[${arg:1}]=$value
        shift
        echo \"$arg\" is flag with value \"$value\"
      fi
    else
      args+=("$arg")
      shift
      echo \"$arg\" is an arg
    fi
done


echo -e "\n"
echo booleans: ${booleans[@]}
echo flags: ${flags[@]}
echo args: ${args[@]}

echo -e "\nBoolean types:\n\tPrecedes Flag(pf): ${booleans[pf]}\n\tFinal Arg(f): ${booleans[f]}\n\tColon Terminated(Ct): ${booleans[Ct]}\n\tNot Mentioned(nm): ${boolean[nm]}"
echo -e "\nFlag: myFlag => ${flags["myFlag"]}"
echo -e "\nArgs: one: ${args[0]}, two: ${args[1]}, three: ${args[2]}"

By running the command:

bashScript.sh firstArg -pf -myFlag "my flag value" secondArg -Ct: thirdArg -f

The output will be this:

"firstArg" is an arg
"pf" is boolean
"-myFlag" is flag with value "my flag value"
"secondArg" is an arg
"Ct" is boolean
"thirdArg" is an arg
"f" is boolean


booleans: true true true
flags: my flag value
args: firstArg secondArg thirdArg

Boolean types:
    Precedes Flag(pf): true
    Final Arg(f): true
    Colon Terminated(Ct): true
    Not Mentioned(nm): 

Flag: myFlag => my flag value

Args: one => firstArg, two => secondArg, three => thirdArg

Basically, the arguments are divided up into flags booleans and generic arguments. By doing it this way a user can put the flags and booleans anywhere as long as he/she keeps the generic arguments (if there are any) in the specified order.

Allowing me and now you to never deal with bash argument parsing again!

You can view an updated script here

This has been enormously useful over the last year. It can now simulate scope by prefixing the variables with a scope parameter.

Just call the script like

replace() (
  source $FUTIL_REL_DIR/commandParser.sh -scope ${FUNCNAME[0]} "$@"
  echo ${replaceFlags[f]}
  echo ${replaceBooleans[b]}
)

Doesn't look like I implemented argument scope, not sure why I guess I haven't needed it yet.

When to throw an exception?

The simple answer is, whenever an operation is impossible (because of either application OR because it would violate business logic). If a method is invoked and it impossible to do what the method was written to do, throw an Exception. A good example is that constructors always throw ArgumentExceptions if an instance cannot be created using the supplied parameters. Another example is InvalidOperationException, which is thrown when an operation cannot be performed because of the state of another member or members of the class.

In your case, if a method like Login(username, password) is invoked, if the username is not valid, it is indeed correct to throw a UserNameNotValidException, or PasswordNotCorrectException if password is incorrect. The user cannot be logged in using the supplied parameter(s) (i.e. it's impossible because it would violate authentication), so throw an Exception. Although I might have your two Exceptions inherit from ArgumentException.

Having said that, if you wish NOT to throw an Exception because a login failure may be very common, one strategy is to instead create a method that returns types that represent different failures. Here's an example:

{ // class
    ...

    public LoginResult Login(string user, string password)
    {
        if (IsInvalidUser(user))
        {
            return new UserInvalidLoginResult(user);
        }
        else if (IsInvalidPassword(user, password))
        {
            return new PasswordInvalidLoginResult(user, password);
        }
        else
        {
            return new SuccessfulLoginResult();
        }
    }

    ...
}

public abstract class LoginResult
{
    public readonly string Message;

    protected LoginResult(string message)
    {
        this.Message = message;
    }
}

public class SuccessfulLoginResult : LoginResult
{
    public SucccessfulLogin(string user)
        : base(string.Format("Login for user '{0}' was successful.", user))
    { }
}

public class UserInvalidLoginResult : LoginResult
{
    public UserInvalidLoginResult(string user)
        : base(string.Format("The username '{0}' is invalid.", user))
    { }
}

public class PasswordInvalidLoginResult : LoginResult
{
    public PasswordInvalidLoginResult(string password, string user)
        : base(string.Format("The password '{0}' for username '{0}' is invalid.", password, user))
    { }
}

Most developers are taught to avoid Exceptions because of the overhead caused by throwing them. It's great to be resource-conscious, but usually not at the expense of your application design. That is probably the reason you were told not to throw your two Exceptions. Whether to use Exceptions or not usually boils down to how frequently the Exception will occur. If it's a fairly common or an fairly expectable result, this is when most developers will avoid Exceptions and instead create another method to indicate failure, because of the supposed consumption of resources.

Here's an example of avoiding using Exceptions in a scenario like just described, using the Try() pattern:

public class ValidatedLogin
{
    public readonly string User;
    public readonly string Password;

    public ValidatedLogin(string user, string password)
    {
        if (IsInvalidUser(user))
        {
            throw new UserInvalidException(user);
        }
        else if (IsInvalidPassword(user, password))
        {
            throw new PasswordInvalidException(password);
        }

        this.User = user;
        this.Password = password;
    }

    public static bool TryCreate(string user, string password, out ValidatedLogin validatedLogin)
    {
        if (IsInvalidUser(user) || 
            IsInvalidPassword(user, password))
        {
            return false;
        }

        validatedLogin = new ValidatedLogin(user, password);

        return true;
    }
}

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

How to save python screen output to a text file

Let me summarize all the answers and add some more.

  • To write to a file from within your script, user file I/O tools that are provided by Python (this is the f=open('file.txt', 'w') stuff.

  • If don't want to modify your program, you can use stream redirection (both on windows and on Unix-like systems). This is the python myscript > output.txt stuff.

  • If you want to see the output both on your screen and in a log file, and if you are on Unix, and you don't want to modify your program, you may use the tee command (windows version also exists, but I have never used it)

  • Even better way to send the desired output to screen, file, e-mail, twitter, whatever is to use the logging module. The learning curve here is the steepest among all the options, but in the long run it will pay for itself.

Split array into two parts without for loop in java

copyOfRange

This does what you want without you having to create a new array as it returns a new array.

int[] original = new int[300000];
int[] firstHalf = Arrays.copyOfRange(original, 0, original.length/2);

How to specify the current directory as path in VBA?

If the path you want is the one to the workbook running the macro, and that workbook has been saved, then

ThisWorkbook.Path

is what you would use.

Set initial value in datepicker with jquery?

From jQuery:

Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

Code examples

Initialize a datepicker with the defaultDate option specified.

$(".selector").datepicker({ defaultDate: +7 });

Get or set the defaultDate option, after init.

//getter
var defaultDate = $(".selector").datepicker("option", "defaultDate");
//setter
$(".selector").datepicker("option", "defaultDate", +7);

After the datepicker is intialized you should also be able to set the date with:

$(/*selector*/).datepicker("setDate" , date)

What is a wrapper class?

Java programming provides wrapper class for each primitive data types, to convert a primitive data types to correspond object of wrapper class.

CSS - Expand float child DIV height to parent's height

<div class="parent" style="height:500px;">
<div class="child-left floatLeft" style="height:100%">
</div>

<div class="child-right floatLeft" style="height:100%">
</div>
</div>

I used inline style just to give idea.

Which MySQL datatype to use for an IP address?

Since IPv4 addresses are 4 byte long, you could use an INT (UNSIGNED) that has exactly 4 bytes:

`ipv4` INT UNSIGNED

And INET_ATON and INET_NTOA to convert them:

INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;

For IPv6 addresses you could use a BINARY instead:

`ipv6` BINARY(16)

And use PHP’s inet_pton and inet_ntop for conversion:

'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);

How to install trusted CA certificate on Android device?

These steps worked for me:

  1. Install Dory Certificate Android app on your mobile device: https://play.google.com/store/apps/details?id=io.tempage.dorycert&hl=en_US
  2. Connect mobile device to laptop with USB Cable.
  3. Create root folder on Internal Phone memory, copy the certificate file in that folder and disconnect cable.
  4. Open Dory Certificate Android app, click the round [+] button and select the right Import File Certificate option.
  5. Select format, provide a name (I typed same as filename), browse the certificate file and click the [OK].
  6. Three cards will list up. I ignored the card that only had the [SIGN CSR] button and proceeded to click the [INSTALL] button on the two other cards.
  7. I refreshed the PWA web app I had opened no my mobile Chrome (it is hosted on a local IIS Web Server) and voala! No chrome warning message. The green lock was there. It was Working.

Alternatively, I found these options which I had no need to try myself but looked easy to follow:

Finally, it may not be relevant but, if you are looking to create and setup a self-signed certificate (with mkcert) for your PWA app (website) hosted on a local IIS Web server, I followed this page:

https://medium.com/@aweber01/locally-trusted-development-certificates-with-mkcert-and-iis-e09410d92031

Thanks and hope it helps!! :)

iTerm2 keyboard shortcut - split pane navigation

Cmd+opt+?/?/?/? navigate similarly to vim's C-w hjkl.

Missing artifact com.sun:tools:jar

I had the same trouble while developing a simple, web service application, in my case I had to add a codehous plug in in order to get jaxws libraries. However, maven pom kept on asking about the tools jar file.

I have to say above comments are correct, you can include the below entry in the pom file:

<dependency>
   <groupId>com.sun</groupId>
   <artifactId>tools</artifactId>
   <version>1.6</version>
   <scope>system</scope>
   <systemPath>C:\Program Files\Java\jdk1.6.0_29\lib\tools.jar</systemPath>
 </dependency>

But, what will it happen when you have to deploy to a production instance? You could replace the path with a reference to a system environment variable but that still does not look good, at least to me.

I found another solution in a StackOverflow comment:

Maven 3 Artifact problem

<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-core</artifactId>
    <version>${struts2.version}</version>
    <exclusions>
        <exclusion>
            <artifactId>tools</artifactId>
            <groupId>com.sun</groupId>
        </exclusion>
    </exclusions>
</dependency>

They suggest including an exclusion statement for tool jar and it works. So summarizing: you can include an exclusion rule within your dependency and avoid having the tool.jar issue:

 <exclusions>
            <exclusion>
                <artifactId>tools</artifactId>
                <groupId>com.sun</groupId>
            </exclusion>
        </exclusions>

How to make modal dialog in WPF?

A lot of these answers are simplistic, and if someone is beginning WPF, they may not know all of the "ins-and-outs", as it is more complicated than just telling someone "Use .ShowDialog()!". But that is the method (not .Show()) that you want to use in order to block use of the underlying window and to keep the code from continuing until the modal window is closed.

First, you need 2 WPF windows. (One will be calling the other.)

From the first window, let's say that was called MainWindow.xaml, in its code-behind will be:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

Then add your button to your XAML:

<Button Name="btnOpenModal" Click="btnOpenModal_Click" Content="Open Modal" />

And right-click the Click routine, select "Go to definition". It will create it for you in MainWindow.xaml.cs:

private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
}

Within that function, you have to specify the other page using its page class. Say you named that other page "ModalWindow", so that becomes its page class and is how you would instantiate (call) it:

private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
    ModalWindow modalWindow = new ModalWindow();
    modalWindow.ShowDialog();
}

Say you have a value you need set on your modal dialog. Create a textbox and a button in the ModalWindow XAML:

<StackPanel Orientation="Horizontal">
    <TextBox Name="txtSomeBox" />
    <Button Name="btnSaveData" Click="btnSaveData_Click" Content="Save" /> 
</StackPanel>

Then create an event handler (another Click event) again and use it to save the textbox value to a public static variable on ModalWindow and call this.Close().

public partial class ModalWindow : Window
{
    public static string myValue = String.Empty;        
    public ModalWindow()
    {
        InitializeComponent();
    }

    private void btnSaveData_Click(object sender, RoutedEventArgs e)
    {
        myValue = txtSomeBox.Text;
        this.Close();
    }
}

Then, after your .ShowDialog() statement, you can grab that value and use it:

private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
    ModalWindow modalWindow = new ModalWindow();
    modalWindow.ShowDialog();

    string valueFromModalTextBox = ModalWindow.myValue;
}

Which characters make a URL invalid?

To add some clarification and directly address the question above, there are several classes of characters that cause problems for URLs and URIs.

There are some characters that are disallowed and should never appear in a URL/URI, reserved characters (described below), and other characters that may cause problems in some cases, but are marked as "unwise" or "unsafe". Explanations for why the characters are restricted are clearly spelled out in RFC-1738 (URLs) and RFC-2396 (URIs). Note the newer RFC-3986 (update to RFC-1738) defines the construction of what characters are allowed in a given context but the older spec offers a simpler and more general description of which characters are not allowed with the following rules.

Excluded US-ASCII Characters disallowed within the URI syntax:

   control     = <US-ASCII coded characters 00-1F and 7F hexadecimal>
   space       = <US-ASCII coded character 20 hexadecimal>
   delims      = "<" | ">" | "#" | "%" | <">

The character "#" is excluded because it is used to delimit a URI from a fragment identifier. The percent character "%" is excluded because it is used for the encoding of escaped characters. In other words, the "#" and "%" are reserved characters that must be used in a specific context.

List of unwise characters are allowed but may cause problems:

   unwise      = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"

Characters that are reserved within a query component and/or have special meaning within a URI/URL:

  reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","

The "reserved" syntax class above refers to those characters that are allowed within a URI, but which may not be allowed within a particular component of the generic URI syntax. Characters in the "reserved" set are not reserved in all contexts. The hostname, for example, can contain an optional username so it could be something like ftp://user@hostname/ where the '@' character has special meaning.

Here is an example of a URL that has invalid and unwise characters (e.g. '$', '[', ']') and should be properly encoded:

http://mw1.google.com/mw-earth-vectordb/kml-samples/gp/seattle/gigapxl/$[level]/r$[y]_c$[x].jpg

Some of the character restrictions for URIs and URLs are programming language-dependent. For example, the '|' (0x7C) character although only marked as "unwise" in the URI spec will throw a URISyntaxException in the Java java.net.URI constructor so a URL like http://api.google.com/q?exp=a|b is not allowed and must be encoded instead as http://api.google.com/q?exp=a%7Cb if using Java with a URI object instance.

WMI "installed" query different from add/remove programs list?

Add/Remove Programs also has to look into this registry key to find installations for the current user:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall

Applications like Google Chrome, Dropbox, or shortcuts installed through JavaWS (web start) JNLPs can be found only here.

Display an image into windows forms

There could be many reasons for this. A few that come up quickly to my mind:

  1. Did you call this routine AFTER InitializeComponent()?
  2. Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
  3. This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.

Replacing a character from a certain index

Strings in Python are immutable meaning you cannot replace parts of them.

You can however create a new string that is modified. Mind that this is not semantically equivalent since other references to the old string will not be updated.

You could for instance write a function:

def replace_str_index(text,index=0,replacement=''):
    return '%s%s%s'%(text[:index],replacement,text[index+1:])

And then for instance call it with:

new_string = replace_str_index(old_string,middle)

If you do not feed a replacement, the new string will not contain the character you want to remove, you can feed it a string of arbitrary length.

For instance:

replace_str_index('hello?bye',5)

will return 'hellobye'; and:

replace_str_index('hello?bye',5,'good')

will return 'hellogoodbye'.

Facebook Javascript SDK Problem: "FB is not defined"

I had the same problem and the only solution I found was putting everything that used the FB statement inside the init script, I also used async loading, so the callback function is after everything that needs FB. I have a common page dinamycally loaded with php so many parts need different facebook functions controlled by php if statements which is making everything a bit messy, but is working!. if I try taking any FB declaration out of the loading script, then firefox shows the "FB is not defined" message. Hope it helps in anything.

jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)

As it is announced in jQuery 1.11.0/2.1.0 Beta 2 Released the source map comment will be removed so the issue will not appear in newer versions of jQuery.

Here is the official announcement:

One of the changes we’ve made in this beta is to remove the sourcemap comment. Sourcemaps have proven to be a very problematic and puzzling thing to developers, generating scores of confused questions on forums like StackOverflow and causing users to think jQuery itself was broken.

Anyway, if you need to use a source map, it still be available:

We’ll still be generating and distributing sourcemaps, but you will need to add the appropriate sourcemap comment at the end of the minified file if the browser does not support manually associating map files (currently, none do). If you generate your own jQuery file using the custom build process, the sourcemap comment will be present in the minified file and the map is generated; you can either leave it in and use sourcemaps or edit it out and ignore the map file entirely.

Here you can find more details about the changes.


Here you can find confirmation that with the jQuery 1.11.0/2.1.0 Released the source-map comment in the minified file is removed.

JavaScript - Get minutes between two dates

The following code worked for me,

function timeDiffCalc(dateNow,dateFuture) {
    var newYear1 = new Date(dateNow);
    var newYear2 = new Date(dateFuture);

        var dif = (newYear2 - newYear1);
        var dif = Math.round((dif/1000)/60);
        console.log(dif);

}

What is the email subject length limit?

I don't believe that there is a formal limit here, and I'm pretty sure there isn't any hard limit specified in the RFC either, as you found.

I think that some pretty common limitations for subject lines in general (not just e-mail) are:

  • 80 Characters
  • 128 Characters
  • 256 Characters

Obviously, you want to come up with something that is reasonable. If you're writing an e-mail client, you may want to go with something like 256 characters, and obviously test thoroughly against big commercial servers out there to make sure they serve your mail correctly.

Hope this helps!

How do I add a new column to a Spark DataFrame (using PySpark)?

To add a column using a UDF:

df = sqlContext.createDataFrame(
    [(1, "a", 23.0), (3, "B", -23.0)], ("x1", "x2", "x3"))

from pyspark.sql.functions import udf
from pyspark.sql.types import *

def valueToCategory(value):
   if   value == 1: return 'cat1'
   elif value == 2: return 'cat2'
   ...
   else: return 'n/a'

# NOTE: it seems that calls to udf() must be after SparkContext() is called
udfValueToCategory = udf(valueToCategory, StringType())
df_with_cat = df.withColumn("category", udfValueToCategory("x1"))
df_with_cat.show()

## +---+---+-----+---------+
## | x1| x2|   x3| category|
## +---+---+-----+---------+
## |  1|  a| 23.0|     cat1|
## |  3|  B|-23.0|      n/a|
## +---+---+-----+---------+

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

For line chart, I use the following codes.

First create custom style

.boxx{
    position: relative;
    width: 20px;
    height: 20px;
    border-radius: 3px;
}

Then add this on your line options

var lineOptions = {
            legendTemplate : '<table>'
                            +'<% for (var i=0; i<datasets.length; i++) { %>'
                            +'<tr><td><div class=\"boxx\" style=\"background-color:<%=datasets[i].fillColor %>\"></div></td>'
                            +'<% if (datasets[i].label) { %><td><%= datasets[i].label %></td><% } %></tr><tr height="5"></tr>'
                            +'<% } %>'
                            +'</table>',
            multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"

var ctx = document.getElementById("lineChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
document.getElementById('legendDiv').innerHTML = myNewChart.generateLegend();

Don't forget to add

<div id="legendDiv"></div>

on your html where do you want to place your legend. That's it!

Get value of Span Text

The accepted answer is close... but no cigar!

Use textContent instead of innerHTML if you strictly want a string to be returned to you.

innerHTML can have the side effect of giving you a node element if there's other dom elements in there. textContent will guard against this possibility.

#pragma mark in Swift?

In Xcode 11 they added minimap which can be activated Editor -> Minimap.

Minimap will show each mark text for fast orientation in code. Each mark is written like // MARK: Variables

enter image description here

How can a web application send push notifications to iOS devices?

ACTUALLY.. This is brand new mind you.. On the newest version of OS X (Mavericks) you CAN send push notifications from a webpage to the desktop. But according to the documentation, NOT iPhones:

Note: This document pertains to OS X only. Notifications for websites do not appear on iOS.

Currently Apple has plans to allow 2 kinds of push notifications: OS X Website Push Notifications and Local Notifications.

The obvious hurdle here is that this will not work on PCs, nor will it allow you to do android push notifications.

Furthermore, you actually can with versions as old as Snow Leapord, send push notifications from a website as long as said website is open and active. The new Mavericks OS will allow push notifications even if the site isnt opened, assuming you have already given permission to said site to send push notifications.

From the mouth of Apple:

In OS X v10.9 and later, you can dispatch OS X Website Push Notifications from your web server directly to OS X users by using the Apple Push Notification service (APNs). Not to be confused with local notifications, push notifications can reach your users regardless of whether your website or their web browser is open…

To integrate push notifications in your website, you first present an interface that allows the user to opt in to receive notifications. If the user consents, Safari contacts your website requesting its credentials in the form of a file called a push package. The push package also contains notification assets used throughout OS X and data used to communicate to a web service you configure. If the push package is valid, you receive a unique identifier for the user on the device known as a device token. The user receives the notification when you send the combination of this device token and your message, or payload, to APNs.

Upon receiving the notification, the user can click on it to open a webpage of your choosing in the user’s default browser.

Note: If you need a refresher on APNs, read the “Apple Push Notification Service” chapter in Local and Push Notification Programming Guide. Although the document is specific to iOS and OS X push notifications, paradigms of the push notification service still apply.

Facebook Architecture

Well Facebook has undergone MANY many changes and it wasn't originally designed to be efficient. It was designed to do it's job. I have absolutely no idea what the code looks like and you probably won't find much info about it (for obvious security and copyright reasons), but just take a look at the API. Look at how often it changes and how much of it doesn't work properly, anymore, or at all.

I think the biggest ace up their sleeve is the Hiphop. http://developers.facebook.com/blog/post/358 You can use HipHop yourself: https://github.com/facebook/hiphop-php/wiki

But if you ask me it's a very ambitious and probably time wasting task. Hiphop only supports so much, it can't simply convert everything to C++. So what does this tell us? Well, it tells us that Facebook is NOT fully taking advantage of the PHP language. It's not using the latest 5.3 and I'm willing to bet there's still a lot that is PHP 4 compatible. Otherwise, they couldn't use HipHop. HipHop IS A GOOD IDEA and needs to grow and expand, but in it's current state it's not really useful for that many people who are building NEW PHP apps.

There's also PHP to JAVA via things like Resin/Quercus. Again, it doesn't support everything...

Another thing to note is that if you use any non-standard PHP module, you aren't going to be able to convert that code to C++ or Java either. However...Let's take a look at PHP modules. They are ARE compiled in C++. So if you can build PHP modules that do things (like parse XML, etc.) then you are basically (minus some interaction) working at the same speed. Of course you can't just make a PHP module for every possible need and your entire app because you would have to recompile and it would be much more difficult to code, etc.

However...There are some handy PHP modules that can help with speed concerns. Though at the end of the day, we have this awesome thing known as "the cloud" and with it, we can scale our applications (PHP included) so it doesn't matter as much anymore. Hardware is becoming cheaper and cheaper. Amazon just lowered it's prices (again) speaking of.

So as long as you code your PHP app around the idea that it will need to one day scale...Then I think you're fine and I'm not really sure I'd even look at Facebook and what they did because when they did it, it was a completely different world and now trying to hold up that infrastructure and maintain it...Well, you get things like HipHop.

Now how is HipHop going to help you? It won't. It can't. You're starting fresh, you can use PHP 5.3. I'd highly recommend looking into PHP 5.3 frameworks and all the new benefits that PHP 5.3 brings to the table along with the SPL libraries and also think about your database too. You're most likely serving up content from a database, so check out MongoDB and other types of databases that are schema-less and document-oriented. They are much much faster and better for the most "common" type of web site/app.

Look at NEW companies like Foursquare and Smugmug and some other companies that are utilizing NEW technology and HOW they are using it. For as successful as Facebook is, I honestly would not look at them for "how" to build an efficient web site/app. I'm not saying they don't have very (very) talented people that work there that are solving (their) problems creatively...I'm also not saying that Facebook isn't a great idea in general and that it's not successful and that you shouldn't get ideas from it....I'm just saying that if you could view their entire source code, you probably wouldn't benefit from it.

How do I get TimeSpan in minutes given two Dates?

I would do it like this:

int totalMinutes = (int)(end - start).TotalMinutes;

How to remove class from all elements jquery

$(".edgetoedge>li").removeClass("highlight");

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

This is called programming to interface. This will be helpful in case if you wish to move to some other implementation of List in the future. If you want some methods in ArrayList then you would need to program to the implementation that is ArrayList a = new ArrayList().

Open files in 'rt' and 'wt' modes

t refers to the text mode. There is no difference between r and rt or w and wt since text mode is the default.

Documented here:

Character   Meaning
'r'     open for reading (default)
'w'     open for writing, truncating the file first
'x'     open for exclusive creation, failing if the file already exists
'a'     open for writing, appending to the end of the file if it exists
'b'     binary mode
't'     text mode (default)
'+'     open a disk file for updating (reading and writing)
'U'     universal newlines mode (deprecated)

The default mode is 'r' (open for reading text, synonym of 'rt').

Sort objects in ArrayList by date?

Use the below approach to identify dates are sort or not

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");

boolean  decendingOrder = true;
    for(int index=0;index<date.size() - 1; index++) {
        if(simpleDateFormat.parse(date.get(index)).getTime() < simpleDateFormat.parse(date.get(index+1)).getTime()) {
            decendingOrder = false;
            break;
        }
    }
    if(decendingOrder) {
        System.out.println("Date are in Decending Order");
    }else {
        System.out.println("Date not in Decending Order");
    }       
}   

Using WGET to run a cronjob PHP

If you want get output only when php fail:

php -r 'echo file_get_contents(http://www.example.com/cronit.php);'

This way you receive an email from cronjob only when the script fails and not whenever the php is called.

jQuery callback for multiple ajax calls

I asked the same question a while ago and got a couple of good answers here: Best way to add a 'callback' after a series of asynchronous XHR calls

Disable vertical scroll bar on div overflow: auto

overflow: auto;
overflow-y: hidden;

For IE8: -ms-overflow-y: hidden;

Or Else :

To hide X:

<div style="height:150x; width:450px; overflow-x:hidden; overflow-y: scroll; padding-bottom:10px;"></div>

To hide Y:

<div style="height:150px; width:450px; overflow-x:scroll ; overflow-y: hidden; padding-bottom:10px;"></div>

Fitting a density curve to a histogram in R

Such thing is easy with ggplot2

library(ggplot2)
dataset <- data.frame(X = c(rep(65, times=5), rep(25, times=5), 
                            rep(35, times=10), rep(45, times=4)))
ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..)) + 
  geom_density()

or to mimic the result from Dirk's solution

ggplot(dataset, aes(x = X)) + 
  geom_histogram(aes(y = ..density..), binwidth = 5) + 
  geom_density()