Programs & Examples On #Logging application block

How to output MySQL query results in CSV format?

This answer uses Python and a popular third party library, PyMySQL. I'm adding it because Python's csv library is powerful enough to correctly handle many different flavors of .csv and no other answers are using Python code to interact with the database.

import contextlib
import csv
import datetime
import os

# https://github.com/PyMySQL/PyMySQL
import pymysql

SQL_QUERY = """
SELECT * FROM my_table WHERE my_attribute = 'my_attribute';
"""

# embedding passwords in code gets nasty when you use version control
# the environment is not much better, but this is an example
# https://stackoverflow.com/questions/12461484
SQL_USER = os.environ['SQL_USER']
SQL_PASS = os.environ['SQL_PASS']

connection = pymysql.connect(host='localhost',
                             user=SQL_USER,
                             password=SQL_PASS,
                             db='dbname')

with contextlib.closing(connection):
    with connection.cursor() as cursor:
        cursor.execute(SQL_QUERY)
        # Hope you have enough memory :)
        results = cursor.fetchall()

output_file = 'my_query-{}.csv'.format(datetime.datetime.today().strftime('%Y-%m-%d'))
with open(output_file, 'w', newline='') as csvfile:
    # http://stackoverflow.com/a/17725590/2958070 about lineterminator
    csv_writer = csv.writer(csvfile, lineterminator='\n')
    csv_writer.writerows(results)

How to wait for the 'end' of 'resize' event and only then perform an action?

One solution is extend jQuery with a function, e.g.: resized

$.fn.resized = function (callback, timeout) {
    $(this).resize(function () {
        var $this = $(this);
        if ($this.data('resizeTimeout')) {
            clearTimeout($this.data('resizeTimeout'));
        }
        $this.data('resizeTimeout', setTimeout(callback, timeout));
    });
};

Sample usage:

$(window).resized(myHandler, 300);

How to configure socket connect timeout

I just wrote an extension class in order to allow timeouts in connections. Use it exactly as you would use the standard Connect() methods, with an extra parameter named timeout.

using System;
using System.Net;
using System.Net.Sockets;

/// <summary>
/// Extensions to Socket class
/// </summary>
public static class SocketExtensions
{
    /// <summary>
    /// Connects the specified socket.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="host">The host.</param>
    /// <param name="port">The port.</param>
    /// <param name="timeout">The timeout.</param>
    public static void Connect(this Socket socket, string host, int port, TimeSpan timeout)
    {
        AsyncConnect(socket, (s, a, o) => s.BeginConnect(host, port, a, o), timeout);
    }

    /// <summary>
    /// Connects the specified socket.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="addresses">The addresses.</param>
    /// <param name="port">The port.</param>
    /// <param name="timeout">The timeout.</param>
    public static void Connect(this Socket socket, IPAddress[] addresses, int port, TimeSpan timeout)
    {
        AsyncConnect(socket, (s, a, o) => s.BeginConnect(addresses, port, a, o), timeout);
    }

    /// <summary>
    /// Asyncs the connect.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="connect">The connect.</param>
    /// <param name="timeout">The timeout.</param>
    private static void AsyncConnect(Socket socket, Func<Socket, AsyncCallback, object, IAsyncResult> connect, TimeSpan timeout)
    {
        var asyncResult = connect(socket, null, null);
        if (!asyncResult.AsyncWaitHandle.WaitOne(timeout))
        {
            try
            {
                socket.EndConnect(asyncResult);
            }
            catch (SocketException)
            { }
            catch (ObjectDisposedException)
            { }
        }
    }

How to read a text file into a string variable and strip newlines?

This works: Change your file to:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

Then:

file = open("file.txt")
line = file.read()
words = line.split()

This creates a list named words that equals:

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

That got rid of the "\n". To answer the part about the brackets getting in your way, just do this:

for word in words: # Assuming words is the list above
    print word # Prints each word in file on a different line

Or:

print words[0] + ",", words[1] # Note that the "+" symbol indicates no spaces
#The comma not in parentheses indicates a space

This returns:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN, GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

System.BadImageFormatException: Could not load file or assembly

It seems that you are using the 64-bit version of the tool to install a 32-bit/x86 architecture application. Look for the 32-bit version of the tool here:

C:\Windows\Microsoft.NET\Framework\v4.0.30319

and it should install your 32-bit application just fine.

How do I get IntelliJ to recognize common Python modules?

This is how i solved my problem (i have imported the project and it was showing there only, newly created files were not showing those errors):

1) Command + alt + R (Control in case of windows

2) Debug window will appear, select your file and press right arrow (->) and choose Edit then press enter (Edit configuration setting window will appear)

3) Under configuration, at the bottom you can see the error (please select a module with a valid python sdk), So in Python Interpreter, check Use Specified Interpreter, then in drop down you select your Python version

(In case python is not there download python plugin for intelliJ using following link https://www.jetbrains.com/help/idea/2016.3/installing-updating-and-uninstalling-repository-plugins.html

4) Click on apply then close it.

Bingo it's done.

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

I have solved this issue as follows:

removed from chrome extension and install ext again. It will work ISA

How to check if C string is empty

The shortest way to do that would be:

do {
    // Something
} while (*url);

Basically, *url will return the char at the first position in the array; since C strings are null-terminated, if the string is empty, its first position will be the character '\0', whose ASCII value is 0; since C logical statements treat every zero value as false, this loop will keep going while the first position of the string is non-null, that is, while the string is not empty.

Recommended readings if you want to understand this better:

Get the correct week number of a given date

Since there doesn't seem to be a .Net-culture that yields the correct ISO-8601 week number, I'd rather bypass the built-in week determination altogether, and do the calculation manually, instead of attempting to correct a partially correct result.

What I ended up with is the following extension method:

/// <summary>
/// Converts a date to a week number.
/// ISO 8601 week 1 is the week that contains the first Thursday that year.
/// </summary>
public static int ToIso8601Weeknumber(this DateTime date)
{
    var thursday = date.AddDays(3 - date.DayOfWeek.DayOffset());
    return (thursday.DayOfYear - 1) / 7 + 1;
}

/// <summary>
/// Converts a week number to a date.
/// Note: Week 1 of a year may start in the previous year.
/// ISO 8601 week 1 is the week that contains the first Thursday that year, so
/// if December 28 is a Monday, December 31 is a Thursday,
/// and week 1 starts January 4.
/// If December 28 is a later day in the week, week 1 starts earlier.
/// If December 28 is a Sunday, it is in the same week as Thursday January 1.
/// </summary>
public static DateTime FromIso8601Weeknumber(int weekNumber, int? year = null, DayOfWeek day = DayOfWeek.Monday)
{
    var dec28 = new DateTime((year ?? DateTime.Today.Year) - 1, 12, 28);
    var monday = dec28.AddDays(7 * weekNumber - dec28.DayOfWeek.DayOffset());
    return monday.AddDays(day.DayOffset());
}

/// <summary>
/// Iso8601 weeks start on Monday. This returns 0 for Monday.
/// </summary>
private static int DayOffset(this DayOfWeek weekDay)
{
    return ((int)weekDay + 6) % 7;
}

First of all, ((int)date.DayOfWeek + 6) % 7) determines the weekday number, 0=monday, 6=sunday.

date.AddDays(-((int)date.DayOfWeek + 6) % 7) determines the date of the monday preceiding the requested week number.

Three days later is the target thursday, which determines what year the week is in.

If you divide the (zero based) day-number within the year by seven (round down), you get the (zero based) week number in the year.

In c#, integer calculation results are round down implicitly.

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

What's the difference between window.location and document.location in JavaScript?

I would say window.location is the more reliable way of getting the current URL. Following is the difference between the window.location and document.url that came in front in one of the scenarios where I was appending hash parameters in the URL and reading it later.

After adding hash parameters in the URL.

In an older browser, I was not able to get the hash parameters from the URL by using document.url, but when I used window.location then I was able to get the hash parameters from the URL.

So it's always better to use window.location.

Load RSA public key from file

Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/

   import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;

    public class Demo {

        public static final String PRIVATE_KEY="/home/user/private.der";
        public static final String PUBLIC_KEY="/home/user/public.der";

        public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
            //get the private key
            File file = new File(PRIVATE_KEY);
            FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);

            byte[] keyBytes = new byte[(int) file.length()];
            dis.readFully(keyBytes);
            dis.close();

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
            System.out.println("Exponent :" + privKey.getPrivateExponent());
            System.out.println("Modulus" + privKey.getModulus());

            //get the public key
            File file1 = new File(PUBLIC_KEY);
            FileInputStream fis1 = new FileInputStream(file1);
            DataInputStream dis1 = new DataInputStream(fis1);
            byte[] keyBytes1 = new byte[(int) file1.length()];
            dis1.readFully(keyBytes1);
            dis1.close();

            X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
            KeyFactory kf1 = KeyFactory.getInstance("RSA");
            RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);

            System.out.println("Exponent :" + pubKey.getPublicExponent());
            System.out.println("Modulus" + pubKey.getModulus());
        }
    }

string in namespace std does not name a type

You need to

#include <string>

<iostream> declares cout, cin, not string.

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

I faced this issue too. I was using jquery.poptrox.min.js for image popping and zooming and I received an error which said:

“Uncaught TypeError: a.indexOf is not a function” error.

This is because indexOf was not supported in 3.3.1/jquery.min.js so a simple fix to this is to change it to an old version 2.1.0/jquery.min.js.

This fixed it for me.

Concatenating variables and strings in React

the best way to concat props/variables:

var sample = "test";    
var result = `this is just a ${sample}`;    
//this is just a test

MySQL select query with multiple conditions

also you can use "AND" instead of "OR" if you want both attributes to be applied.

select * from tickets where (assigned_to='1') and (status='open') order by created_at desc;

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

I had the same problem and I chosed to create my own encoder, which will cope by themself with recursion.

I created classes which implements Symfony\Component\Serializer\Normalizer\NormalizerInterface, and a service which holds every NormalizerInterface.

#This is the NormalizerService

class NormalizerService 
{

   //normalizer are stored in private properties
   private $entityOneNormalizer;
   private $entityTwoNormalizer;

   public function getEntityOneNormalizer()
   {
    //Normalizer are created only if needed
    if ($this->entityOneNormalizer == null)
        $this->entityOneNormalizer = new EntityOneNormalizer($this); //every normalizer keep a reference to this service

    return $this->entityOneNormalizer;
   }

   //create a function for each normalizer



  //the serializer service will also serialize the entities 
  //(i found it easier, but you don't really need it)
   public function serialize($objects, $format)
   {
     $serializer = new Serializer(
            array(
                $this->getEntityOneNormalizer(),
                $this->getEntityTwoNormalizer()
            ),
            array($format => $encoder) );

     return $serializer->serialize($response, $format);
}

An example of a Normalizer :

use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class PlaceNormalizer implements NormalizerInterface {

private $normalizerService;

public function __construct($normalizerService)
{
    $this->service = normalizerService;

}

public function normalize($object, $format = null) {
    $entityTwo = $object->getEntityTwo();
    $entityTwoNormalizer = $this->service->getEntityTwoNormalizer();

    return array(
        'param' => object->getParam(),
        //repeat for every parameter
        //!!!! this is where the entityOneNormalizer dealt with recursivity
        'entityTwo' => $entityTwoNormalizer->normalize($entityTwo, $format.'_without_any_entity_one') //the 'format' parameter is adapted for ignoring entity one - this may be done with different ways (a specific method, etc.)
    );
}

}

In a controller :

$normalizerService = $this->get('normalizer.service'); //you will have to configure services.yml
$json = $normalizerService->serialize($myobject, 'json');
return new Response($json);

The complete code is here : https://github.com/progracqteur/WikiPedale/tree/master/src/Progracqteur/WikipedaleBundle/Resources/Normalizer

FirebaseInstanceIdService is deprecated

firebaser here

Check the reference documentation for FirebaseInstanceIdService:

This class was deprecated.

In favour of overriding onNewToken in FirebaseMessagingService. Once that has been implemented, this service can be safely removed.

Weirdly enough the JavaDoc for FirebaseMessagingService doesn't mention the onNewToken method yet. It looks like not all updated documentation has been published yet. I've filed an internal issue to get the updates to the reference docs published, and to get the samples in the guide updated too.

In the meantime both the old/deprecated calls, and the new ones should work. If you're having trouble with either, post the code and I'll have a look.

What does the ^ (XOR) operator do?

^ is the Python bitwise XOR operator. It is how you spell XOR in python:

>>> 0 ^ 0
0
>>> 0 ^ 1
1
>>> 1 ^ 0
1
>>> 1 ^ 1
0

XOR stands for exclusive OR. It is used in cryptography because it let's you 'flip' the bits using a mask in a reversable operation:

>>> 10 ^ 5
15
>>> 15 ^ 5
10

where 5 is the mask; (input XOR mask) XOR mask gives you the input again.

How to escape special characters of a string with single backslashes

Utilize the output of built-in repr to deal with \r\n\t and process the output of re.escape is what you want:

re.escape(repr(a)[1:-1]).replace('\\\\', '\\')

Iterating over a numpy array

see nditer

import numpy as np
Y = np.array([3,4,5,6])
for y in np.nditer(Y, op_flags=['readwrite']):
    y += 3

Y == np.array([6, 7, 8, 9])

y = 3 would not work, use y *= 0 and y += 3 instead.

SQL Server default character encoding

The default character encoding for a SQL Server database is iso_1, which is ISO 8859-1. Note that the character encoding depends on the data type of a column. You can get an idea of what character encodings are used for the columns in a database as well as the collations using this SQL:

select data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name, count(*) count
from information_schema.columns
group by data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name;

If it's using the default, the character_set_name should be iso_1 for the char and varchar data types. Since nchar and nvarchar store Unicode data in UCS-2 format, the character_set_name for those data types is UNICODE.

How to access the SMS storage on Android?

Do the following, download SQLLite Database Browser from here:

Locate your db. file in your phone.

Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!

You can actually export the data to an excel file or SQL.

Use of Custom Data Types in VBA

It looks like you want to define Truck as a Class with properties NumberOfAxles, AxleWeights & AxleSpacings.

This can be defined in a CLASS MODULE (here named clsTrucks)

Option Explicit

Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double


Public Property Get truckID() As String
    truckID = tID
End Property

Public Property Let truckID(value As String)
    tID = value
End Property

Public Property Get truckNumberOfAxles() As Double
    truckNumberOfAxles = tNumberOfAxles
End Property

Public Property Let truckNumberOfAxles(value As Double)
    tNumberOfAxles = value
End Property

Public Property Get truckAxleSpacings() As Double
    truckAxleSpacings = tAxleSpacings
End Property

Public Property Let truckAxleSpacings(value As Double)
    tAxleSpacings = value
End Property

then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.

Option Explicit

Public TruckCollection As New Collection

Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long

    'Add 5 trucks
    For i = 1 To 5
        Set tempTruck = New clsTrucks
        'Random data
        tempTruck.truckID = "Truck" & i
        tempTruck.truckAxleSpacings = 13.5 + i
        tempTruck.truckNumberOfAxles = 20.5 + i

        'tempTruck.truckID is the collection key
        TruckCollection.Add tempTruck, tempTruck.truckID
    Next i

    'retrieve 5 trucks
    For i = 1 To 5
        'retrieve by collection index
        Debug.Print TruckCollection(i).truckAxleSpacings
        'retrieve by key
        Debug.Print TruckCollection("Truck" & i).truckAxleSpacings

    Next i

End Sub

There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.

numpy matrix vector multiplication

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays. Instead, you could try using numpy.matrix, and * will be treated like matrix multiplication.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you'd expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum('ji,i->j', a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don't use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

How can I dynamically add a directive in AngularJS?

Inspired from many of the previous answers I have came up with the following "stroman" directive that will replace itself with any other directives.

app.directive('stroman', function($compile) {
  return {
    link: function(scope, el, attrName) {
      var newElem = angular.element('<div></div>');
      // Copying all of the attributes
      for (let prop in attrName.$attr) {
        newElem.attr(prop, attrName[prop]);
      }
      el.replaceWith($compile(newElem)(scope)); // Replacing
    }
  };
});

Important: Register the directives that you want to use with restrict: 'C'. Like this:

app.directive('my-directive', function() {
  return {
    restrict: 'C',
    template: 'Hi there',
  };
});

You can use like this:

<stroman class="my-directive other-class" randomProperty="8"></stroman>

To get this:

<div class="my-directive other-class" randomProperty="8">Hi there</div>

Protip. If you don't want to use directives based on classes then you can change '<div></div>' to something what you like. E.g. have a fixed attribute that contains the name of the desired directive instead of class.

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

String dateStr = "2016-09-17T08:14:03+00:00";
String s = dateStr.replace("Z", "+00:00");
s = s.substring(0, 22) + s.substring(23);
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
Timestamp createdOn = new Timestamp(date.getTime());
mcList.setCreated_on(createdOn);

Java 7 added support for time zone descriptors according to ISO 8601. This can be use in Java 7.

Can I have an onclick effect in CSS?

You can use pseudo class :target to mimic on click event, let me give you an example.

_x000D_
_x000D_
#something {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
#something:target {_x000D_
  display: block;_x000D_
}
_x000D_
<a href="#something">Show</a>_x000D_
<div id="something">Bingo!</div>
_x000D_
_x000D_
_x000D_

Here's how it looks like: http://jsfiddle.net/TYhnb/

One thing to note, this is only limited to hyperlink, so if you need to use on other than hyperlink, such as a button, you might want to hack it a little bit, such as styling a hyperlink to look like a button.

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

How can I find WPF controls by name or type?

You can use the VisualTreeHelper to find controls. Below is a method that uses the VisualTreeHelper to find a parent control of a specified type. You can use the VisualTreeHelper to find controls in other ways as well.

public static class UIHelper
{
   /// <summary>
   /// Finds a parent of a given item on the visual tree.
   /// </summary>
   /// <typeparam name="T">The type of the queried item.</typeparam>
   /// <param name="child">A direct or indirect child of the queried item.</param>
   /// <returns>The first parent item that matches the submitted type parameter. 
   /// If not matching item can be found, a null reference is being returned.</returns>
   public static T FindVisualParent<T>(DependencyObject child)
     where T : DependencyObject
   {
      // get parent item
      DependencyObject parentObject = VisualTreeHelper.GetParent(child);

      // we’ve reached the end of the tree
      if (parentObject == null) return null;

      // check if the parent matches the type we’re looking for
      T parent = parentObject as T;
      if (parent != null)
      {
         return parent;
      }
      else
      {
         // use recursion to proceed with next level
         return FindVisualParent<T>(parentObject);
      }
   }
}

Call it like this:

Window owner = UIHelper.FindVisualParent<Window>(myControl);

Get The Current Domain Name With Javascript (Not the path, etc.)

If you want to get domain name in JavaScript, just use the following code:

var domain_name = document.location.hostname;
alert(domain_name);

If you need to web page URL path so you can access web URL path use this example:

var url = document.URL;
alert(url);

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

MySQL Data - Best way to implement paging?

you can also do

SELECT SQL_CALC_FOUND_ROWS * FROM tbl limit 0, 20

The row count of the select statement (without the limit) is captured in the same select statement so that you don't need to query the table size again. You get the row count using SELECT FOUND_ROWS();

how to read a long multiline string line by line in python

What about using .splitlines()?

for line in textData.splitlines():
    print(line)
    lineResult = libLAPFF.parseLine(line)

TypeError: Can't convert 'int' object to str implicitly

You cannot concatenate a string with an int. You would need to convert your int to a string using the str function, or use formatting to format your output.

Change: -

print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")

to: -

print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))

or: -

print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")

or as per the comment, use , to pass different strings to your print function, rather than concatenating using +: -

print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")

How to get the latest tag name in current branch in Git?

if your tags are sortable:

git tag --merged $YOUR_BRANCH_NAME | grep "prefix/" | sort | tail -n 1

How to load a resource from WEB-INF directory of a web archive

The problem I had accessing the sqlite db file I created in my java (jersey) server had solely to due with path. Some of the docs say the jdbc connect url should look like "jdbc:sqlite://path-to-file/sample.db". I thought the double-slash was part of a htt protocol-style path and would map properly when deployed, but in actuality, it's an absolute or relative path. So, when I placed the file at the root of the WebContent folder (tomcat project), a uri like this worked "jdbc:sqlite:sample.db".

The one thing that was throwing me was that when I was stepping through the debugger, I received a message that said "opening db: ... permission denied". I thought it was a matter of file system permissions or perhaps sql user permissions. After finding out that SQLite doesn't have the concept of roles/permissions like MySQL, etc, I did eventually change the file permissions before I came to what I believe was the correct solution, but I think it was just a bad message (i.e. permission denied, instead of File not found).

Hope this helps someone.

MySQL combine two columns into one column

I have used this way and Its a best forever. In this code null also handled

SELECT Title,
FirstName,
lastName, 
ISNULL(Title,'') + ' ' + ISNULL(FirstName,'') + ' ' + ISNULL(LastName,'') as FullName 
FROM Customer

Try this...

grunt: command not found when running from terminal

For windows

npm install -g grunt-cli

npm install load-grunt-tasks

Then run

grunt

How can I match a string with a regex in Bash?

A Function To Do This

extract () {
  if [ -f $1 ] ; then
      case $1 in
          *.tar.bz2)   tar xvjf $1    ;;
          *.tar.gz)    tar xvzf $1    ;;
          *.bz2)       bunzip2 $1     ;;
          *.rar)       rar x $1       ;;
          *.gz)        gunzip $1      ;;
          *.tar)       tar xvf $1     ;;
          *.tbz2)      tar xvjf $1    ;;
          *.tgz)       tar xvzf $1    ;;
          *.zip)       unzip $1       ;;
          *.Z)         uncompress $1  ;;
          *.7z)        7z x $1        ;;
          *)           echo "don't know '$1'..." ;;
      esac
  else
      echo "'$1' is not a valid file!"
  fi
}

Other Note

In response to Aquarius Power in the comment above, We need to store the regex on a var

The variable BASH_REMATCH is set after you match the expression, and ${BASH_REMATCH[n]} will match the nth group wrapped in parentheses ie in the following ${BASH_REMATCH[1]} = "compressed" and ${BASH_REMATCH[2]} = ".gz"

if [[ "compressed.gz" =~ ^(.*)(\.[a-z]{1,5})$ ]]; 
then 
  echo ${BASH_REMATCH[2]} ; 
else 
  echo "Not proper format"; 
fi

(The regex above isn't meant to be a valid one for file naming and extensions, but it works for the example)

How to check 'undefined' value in jQuery

You can use shorthand technique to check whether it is undefined or null

 function A(val)
 {
   if(val || "") 
   //do this
 else
 //do this
 }

hope this will help you

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

I think no one has given the correct answer to the question. My working solution is : 1. Just declare another class along with container-fluid class example(.maxx):

_x000D_
_x000D_
 <div class="container-fluid maxx">_x000D_
   <div class="row">_x000D_
     <div class="col-sm-12">_x000D_
     <p>Hello</p>_x000D_
     </div>_x000D_
   </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

  1. Then using specificity in the css part do this:

_x000D_
_x000D_
.container-fluid.maxx {_x000D_
  padding-left: 0px;_x000D_
  padding-right: 0px; }
_x000D_
_x000D_
_x000D_

This will work 100% and will remove the padding from left and right. I hope this helps.

Warning: Found conflicts between different versions of the same dependent assembly

I had such issue when my project had reference to NETStandardLibrary and one of referenced assemblies was published for netcore. Just published it as netstandard and problem was gone

(SC) DeleteService FAILED 1072

I had the same error due to a typo in the service name, i was trying to delete the service display name instead of the service name. Once I used the right service name it worked fine

jQuery OR Selector?

Using a comma may not be sufficient if you have multiple jQuery objects that need to be joined.

The .add() method adds the selected elements to the result set:

// classA OR classB
jQuery('.classA').add('.classB');

It's more verbose than '.classA, .classB', but lets you build more complex selectors like the following:

// (classA which has <p> descendant) OR (<div> ancestors of classB)
jQuery('.classA').has('p').add(jQuery('.classB').parents('div'));

Removing duplicates from a list of lists

Doing it manually, creating a new k list and adding entries not found so far:

k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
new_k = []
for elem in k:
    if elem not in new_k:
        new_k.append(elem)
k = new_k
print k
# prints [[1, 2], [4], [5, 6, 2], [3]]

Simple to comprehend, and you preserve the order of the first occurrence of each element should that be useful, but I guess it's quadratic in complexity as you're searching the whole of new_k for each element.

How do I fetch only one branch of a remote Git repository?

One way to do it:

in .git/config fetch for the remote repo should be set to fetch any branch:

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

to fetch the remote branch:

git fetch origin branch-name

to create a local branch 'branch-name' set up to track remote branch 'branch-name' from origin.

git checkout -b branch-name origin/branch-name

to list all branches

git branch -a

.htaccess - how to force "www." in a generic way?

If you want to redirect all non-www requests to your site to the www version, all you need to do is add the following code to your .htaccess file:

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

Notice: Trying to get property of non-object error

The response is an array.

var_dump($pjs[0]->{'player_name'});

How to start an Intent by passing some parameters to it?

I think you want something like this:

Intent foo = new Intent(this, viewContacts.class);
foo.putExtra("myFirstKey", "myFirstValue");
foo.putExtra("mySecondKey", "mySecondValue");
startActivity(foo);

or you can combine them into a bundle first. Corresponding getExtra() routines exist for the other side. See the intent topic in the dev guide for more information.

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.

In contrast, JSTL works entirely with scoped attributes, either at page, request or session scope. You need to rework your scriptlet to fish test out as an attribute:

<c:set var="test" value="test1"/>
<%
  String resp = "abc";
  String test = pageContext.getAttribute("test");
  resp = resp + test;
  pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>

If you look at the docs for <c:set>, you'll see you can specify scope as page, request or session, and it defaults to page.

Better yet, don't use scriptlets at all: they make the baby jesus cry.

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

Finaly, my service provider answered :

This is a limitation of the virtualization system we use (OpenVZ), basic iptables rules are possible but not those who use the nat table.

If this really is a problem, we can offer you to migrate to a other system virtualization (KVM) as we begin to offer our customers.

SO I had to migrate my server to the new system...

Automatic creation date for Django model form objects?

You can use the auto_now and auto_now_add options for updated_at and created_at respectively.

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

how to convert from int to char*?

This might be a bit late, but i also had the same issue. Converting to char was addressed in C++17 with the "charconv" library.

https://en.cppreference.com/w/cpp/utility/to_chars

How to specify a min but no max decimal using the range data annotation attribute?

You can use custom validation:

    [CustomValidation(typeof(ValidationMethods), "ValidateGreaterOrEqualToZero")]
    public int IntValue { get; set; }

    [CustomValidation(typeof(ValidationMethods), "ValidateGreaterOrEqualToZero")]
    public decimal DecValue { get; set; }

Validation methods type:

public class ValidationMethods
{
    public static ValidationResult ValidateGreaterOrEqualToZero(decimal value, ValidationContext context)
    {
        bool isValid = true;

        if (value < decimal.Zero)
        {
            isValid = false;
        }

        if (isValid)
        {
            return ValidationResult.Success;
        }
        else
        {
            return new ValidationResult(
                string.Format("The field {0} must be greater than or equal to 0.", context.MemberName),
                new List<string>() { context.MemberName });
        }
    }
}

Twitter Bootstrap dropdown menu

It's also possible to customise your bootstrap build by using:

http://twitter.github.com/bootstrap/customize.html

All the plugins are included by default.

Understanding colors on Android (six characters)

On Android, colors are can be specified as RGB or ARGB.

http://en.wikipedia.org/wiki/ARGB

In RGB you have two characters for every color (red, green, blue), and in ARGB you have two additional chars for the alpha channel.

So, if you have 8 characters, it's ARGB, with the first two characters specifying the alpha channel. If you remove the leading two characters it's only RGB (solid colors, no alpha/transparency). If you want to specify a color in your Java source code, you have to use:

int Color.argb (int alpha, int red, int green, int blue)

alpha  Alpha component [0..255] of the color
red    Red component [0..255] of the color
green  Green component [0..255] of the color
blue   Blue component [0..255] of the color

Reference: argb

How to execute a stored procedure within C# program

using (SqlConnection sqlConnection1 = new SqlConnection("Your Connection String")) {
using (SqlCommand cmd = new SqlCommand()) {
  Int32 rowsAffected;

  cmd.CommandText = "StoredProcedureName";
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Connection = sqlConnection1;

  sqlConnection1.Open();

  rowsAffected = cmd.ExecuteNonQuery();

}}

Java switch statement: Constant expression required, but it IS constant

You get Constant expression required because you left the values off your constants. Try:

public abstract class Foo {
    ...
    public static final int BAR=0;
    public static final int BAZ=1;
    public static final int BAM=2;
    ...
}

Inserting a Python datetime.datetime object into MySQL

when iserting into t-sql

this fails:

select CONVERT(datetime,'2019-09-13 09:04:35.823312',21)

this works:

select CONVERT(datetime,'2019-09-13 09:04:35.823',21)

easy way:

regexp = re.compile(r'\.(\d{6})')
def to_splunk_iso(dt):
    """Converts the datetime object to Splunk isoformat string."""
    # 6-digits string.
    microseconds = regexp.search(dt).group(1)
    return regexp.sub('.%d' % round(float(microseconds) / 1000), dt)

PHP Accessing Parent Class Variable

all the properties and methods of the parent class is inherited in the child class so theoretically you can access them in the child class but beware using the protected keyword in your class because it throws a fatal error when used in the child class.
as mentioned in php.net

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

Create a pointer to two-dimensional array

To fully understand this, you must grasp the following concepts:

Arrays are not pointers!

First of all (And it's been preached enough), arrays are not pointers. Instead, in most uses, they 'decay' to the address to their first element, which can be assigned to a pointer:

int a[] = {1, 2, 3};

int *p = a; // p now points to a[0]

I assume it works this way so that the array's contents can be accessed without copying all of them. That's just a behavior of array types and is not meant to imply that they are same thing.



Multidimensional arrays

Multidimensional arrays are just a way to 'partition' memory in a way that the compiler/machine can understand and operate on.

For instance, int a[4][3][5] = an array containing 4*3*5 (60) 'chunks' of integer-sized memory.

The advantage over using int a[4][3][5] vs plain int b[60] is that they're now 'partitioned' (Easier to work with their 'chunks', if needed), and the program can now perform bound checking.

In fact, int a[4][3][5] is stored exactly like int b[60] in memory - The only difference is that the program now manages it as if they're separate entities of certain sizes (Specifically, four groups of three groups of five).

Keep in mind: Both int a[4][3][5] and int b[60] are the same in memory, and the only difference is how they're handled by the application/compiler

{
  {1, 2, 3, 4, 5}
  {6, 7, 8, 9, 10}
  {11, 12, 13, 14, 15}
}
{
  {16, 17, 18, 19, 20}
  {21, 22, 23, 24, 25}
  {26, 27, 28, 29, 30}
}
{
  {31, 32, 33, 34, 35}
  {36, 37, 38, 39, 40}
  {41, 42, 43, 44, 45}
}
{
  {46, 47, 48, 49, 50}
  {51, 52, 53, 54, 55}
  {56, 57, 58, 59, 60}
}

From this, you can clearly see that each "partition" is just an array that the program keeps track of.



Syntax

Now, arrays are syntactically different from pointers. Specifically, this means the compiler/machine will treat them differently. This may seem like a no brainer, but take a look at this:

int a[3][3];

printf("%p %p", a, a[0]);

The above example prints the same memory address twice, like this:

0x7eb5a3b4 0x7eb5a3b4

However, only one can be assigned to a pointer so directly:

int *p1 = a[0]; // RIGHT !

int *p2 = a; // WRONG !

Why can't a be assigned to a pointer but a[0] can?

This, simply, is a consequence of multidimensional arrays, and I'll explain why:

At the level of 'a', we still see that we have another 'dimension' to look forward to. At the level of 'a[0]', however, we're already in the top dimension, so as far as the program is concerned we're just looking at a normal array.

You may be asking:

Why does it matter if the array is multidimensional in regards to making a pointer for it?

It's best to think this way:

A 'decay' from a multidimensional array is not just an address, but an address with partition data (AKA it still understands that its underlying data is made of other arrays), which consists of boundaries set by the array beyond the first dimension.

This 'partition' logic cannot exist within a pointer unless we specify it:

int a[4][5][95][8];

int (*p)[5][95][8];

p = a; // p = *a[0] // p = a+0

Otherwise, the meaning of the array's sorting properties are lost.

Also note the use of parenthesis around *p: int (*p)[5][95][8] - That's to specify that we're making a pointer with these bounds, not an array of pointers with these bounds: int *p[5][95][8]



Conclusion

Let's review:

  • Arrays decay to addresses if they have no other purpose in the used context
  • Multidimensional arrays are just arrays of arrays - Hence, the 'decayed' address will carry the burden of "I have sub dimensions"
  • Dimension data cannot exist in a pointer unless you give it to it.

In brief: multidimensional arrays decay to addresses that carry the ability to understand their contents.

Nginx: stat() failed (13: permission denied)

By default the static data, when you install the nginx, will be in /var/www/html. So you can just copy your static folder into /var/html/ and set the

root /var/www/<your static folder>

in ngix.conf (or /etc/nginx/sites-available/default)

This worked for me on ubuntu but I guess it should not be much different for other distros.

Hope it helps.

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

After an hour ,i found best approach. we should save result of dialog in variable, after that call close method of variable.

Like this:

var dd= $("#divDialog")
.dialog({
   height: 600,
   width: 600,
   modal: true,
   draggable: false,
   resizable: false
});

// . . .

dd.dialog('close');

What's the difference between HTML 'hidden' and 'aria-hidden' attributes?

ARIA (Accessible Rich Internet Applications) defines a way to make Web content and Web applications more accessible to people with disabilities.

The hidden attribute is new in HTML5 and tells browsers not to display the element. The aria-hidden property tells screen-readers if they should ignore the element. Have a look at the w3 docs for more details:

https://www.w3.org/WAI/PF/aria/states_and_properties#aria-hidden

Using these standards can make it easier for disabled people to use the web.

Android "hello world" pushnotification example

Overview of gcm: You send a request to google server from your android phone. You receive a registration id as a response. You will then have to send this registration id to the server from where you wish to send notifications to the mobile. Using this registration id you can then send notification to the device.

Answer:

  1. To send a notification you send the data(message) with the registration id of the device to https://android.googleapis.com/gcm/send. (use curl in php).
  2. To receive notification and registration etc, thats all you will be requiring.
  3. You will have to store the registration id on the device as well as on server. If you use GCM.jar the registration id is stored in preferences. If you wish you can save it in your local database as well.

Run a command over SSH with JSch

I am using JSCH since about 2000 and still find it a good library to use. I agree it is not documented well enough but the provided examples seem good enough to understand that is required in several minutes, and user friendly Swing, while this is quite original approach, allows to test the example quickly to make sure it actually works. It is not always true that every good project needs three times more documentation than the amount of code written, and even when such is present, this not always helps to write faster a working prototype of your concept.

Error C1083: Cannot open include file: 'stdafx.h'

Just include windows.h instead of stdfax or create a clean project without template.

Measure the time it takes to execute a t-sql query

even better, this will measure the average of n iterations of your query! Great for a more accurate reading.

declare @tTOTAL int = 0
declare @i integer = 0
declare @itrs integer = 100

while @i < @itrs
begin
declare @t0 datetime = GETDATE()

--your query here

declare @t1 datetime = GETDATE()

set @tTotal = @tTotal + DATEDIFF(MICROSECOND,@t0,@t1)

set @i = @i + 1
end

select @tTotal/@itrs

What is the Simplest Way to Reverse an ArrayList?

The trick here is defining "reverse". One can modify the list in place, create a copy in reverse order, or create a view in reversed order.

The simplest way, intuitively speaking, is Collections.reverse:

Collections.reverse(myList);

This method modifies the list in place. That is, Collections.reverse takes the list and overwrites its elements, leaving no unreversed copy behind. This is suitable for some use cases, but not for others; furthermore, it assumes the list is modifiable. If this is acceptable, we're good.


If not, one could create a copy in reverse order:

static <T> List<T> reverse(final List<T> list) {
    final List<T> result = new ArrayList<>(list);
    Collections.reverse(result);
    return result;
}

This approach works, but requires iterating over the list twice. The copy constructor (new ArrayList<>(list)) iterates over the list, and so does Collections.reverse. We can rewrite this method to iterate only once, if we're so inclined:

static <T> List<T> reverse(final List<T> list) {
    final int size = list.size();
    final int last = size - 1;

    // create a new list, with exactly enough initial capacity to hold the (reversed) list
    final List<T> result = new ArrayList<>(size);

    // iterate through the list in reverse order and append to the result
    for (int i = last; i >= 0; --i) {
        final T element = list.get(i);
        result.add(element);
    }

    // result now holds a reversed copy of the original list
    return result;
}

This is more efficient, but also more verbose.

Alternatively, we can rewrite the above to use Java 8's stream API, which some people find more concise and legible than the above:

static <T> List<T> reverse(final List<T> list) {
    final int last = list.size() - 1;
    return IntStream.rangeClosed(0, last) // a stream of all valid indexes into the list
        .map(i -> (last - i))             // reverse order
        .mapToObj(list::get)              // map each index to a list element
        .collect(Collectors.toList());    // wrap them up in a list
}

nb. that Collectors.toList() makes very few guarantees about the result list. If you want to ensure the result comes back as an ArrayList, use Collectors.toCollection(ArrayList::new) instead.


The third option is to create a view in reversed order. This is a more complicated solution, and worthy of further reading/its own question. Guava's Lists#reverse method is a viable starting point.

Choosing a "simplest" implementation is left as an exercise for the reader.

executing shell command in background from script

Leave off the quotes

$cmd &
$othercmd &

eg:

nicholas@nick-win7 /tmp
$ cat test
#!/bin/bash

cmd="ls -la"

$cmd &


nicholas@nick-win7 /tmp
$ ./test

nicholas@nick-win7 /tmp
$ total 6
drwxrwxrwt+ 1 nicholas root    0 2010-09-10 20:44 .
drwxr-xr-x+ 1 nicholas root 4096 2010-09-10 14:40 ..
-rwxrwxrwx  1 nicholas None   35 2010-09-10 20:44 test
-rwxr-xr-x  1 nicholas None   41 2010-09-10 20:43 test~

Twitter Bootstrap Responsive Background-Image inside Div

You might also try:

background-size: cover;

There are some good articles to read about using this CSS3 property: Perfect Full Page Background Image by CSS-Tricks and CSS Background-Size by David Walsh.

PLEASE NOTE - This will not work with IE8-. However, it will work on most versions of Chrome, Firefox and Safari.

How to manually install a pypi module without pip/easy_install?

To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.

Download

Click the Clone or download button and choose your method. I placed these into a dev/py/libs directory in my user home directory. It does not matter where they are saved, because they will not be installed there.

Installing setup-tools

You will need to run the following inside the setup-tools directory.

python bootstrap.py
python setup.py install

General dependencies installation

Now you can navigate to the more-itertools direcotry and install it as normal.

  1. Download the package
  2. Unpackage it if it's an archive
  3. Navigate (cd ...) into the directory containing setup.py
  4. If there are any installation instructions contained in the documentation contained herein, read and follow the instructions OTHERWISE
  5. Type in: python setup.py install

Response Content type as CSV

MIME type of the CSV is text/csv according to RFC 4180.

Setting a spinner onClickListener() in Android

Here is a working solution:

Instead of setting the spinner's OnClickListener, we are setting OnTouchListener and OnKeyListener.

spinner.setOnTouchListener(Spinner_OnTouch);
spinner.setOnKeyListener(Spinner_OnKey);

and the listeners:

private View.OnTouchListener Spinner_OnTouch = new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            doWhatYouWantHere();
        }
        return true;
    }
};
private static View.OnKeyListener Spinner_OnKey = new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
            doWhatYouWantHere();
            return true;
        } else {
            return false;
        }
    }
};

newline in <td title="">

This should be OK, but is Internet Explorer specific:

<td title="lineone
linetwo 
etc...">

As others have mentioned, the only other way is to use an HTML + JavaScript based tooltip if you're only interested in the tooltip. If this is for accessibility then you will probably need to stick to just single lines for consistency.

Populate data table from data reader

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

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

Click in OK button inside an Alert (Selenium IDE)

Try Selenium 2.0b1. It has different core than the first version. It should support popup dialogs according to documentation:

Popup Dialogs

Starting with Selenium 2.0 beta 1, there is built in support for handling popup dialog boxes. After you’ve triggered and action that would open a popup, you can access the alert with the following:

Java

Alert alert = driver.switchTo().alert();

Ruby

driver.switch_to.alert

This will return the currently open alert object. With this object you can now accept, dismiss, read it’s contents or even type into a prompt. This interface works equally well on alerts, confirms, prompts. Refer to the JavaDocs for more information.

How to convert the following json string to java object?

Gson is also good for it: http://code.google.com/p/google-gson/

" Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. "

Check the API examples: https://sites.google.com/site/gson/gson-user-guide#TOC-Overview More examples: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

Remove "whitespace" between div element

Add line-height: 0px; to your parent div

jsfiddle: http://jsfiddle.net/majZt/

Android layout replacing a view with another view on run time

it work in my case, oldSensor and newSnsor - oldView and newView:

private void replaceSensors(View oldSensor, View newSensor) {
            ViewGroup parent = (ViewGroup) oldSensor.getParent();

            if (parent == null) {
                return;
            }

            int indexOldSensor = parent.indexOfChild(oldSensor);
            int indexNewSensor = parent.indexOfChild(newSensor);
            parent.removeView(oldSensor);
            parent.addView(oldSensor, indexNewSensor);
            parent.removeView(newSensor);
            parent.addView(newSensor, indexOldSensor);
        }

"Continue" (to next iteration) on VBScript

Try use While/Wend and Do While / Loop statements...

i = 1
While i < N + 1
Do While true
    [Code]
    If Condition1 Then
       Exit Do
    End If

    [MoreCode]
    If Condition2 Then
       Exit Do
    End If

    [...]

    Exit Do
Loop
Wend

Use Expect in a Bash script to provide a password to an SSH command

Mixing Bash and Expect is not a good way to achieve the desired effect. I'd try to use only Expect:

#!/usr/bin/expect
eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com

# Use the correct prompt
set prompt ":|#|\\\$"
interact -o -nobuffer -re $prompt return
send "my_password\r"
interact -o -nobuffer -re $prompt return
send "my_command1\r"
interact -o -nobuffer -re $prompt return
send "my_command2\r"
interact

Sample solution for bash could be:

#!/bin/bash
/usr/bin/expect -c 'expect "\n" { eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com; interact }'

This will wait for Enter and then return to (for a moment) the interactive session.

python multithreading wait till all threads finished

I just came across the same problem where I needed to wait for all the threads which were created using the for loop.I just tried out the following piece of code.It may not be the perfect solution but I thought it would be a simple solution to test:

for t in threading.enumerate():
    try:
        t.join()
    except RuntimeError as err:
        if 'cannot join current thread' in err:
            continue
        else:
            raise

C++: Rounding up to the nearest multiple of a number

Round to Power of Two:

Just in case anyone needs a solution for positive numbers rounded to the nearest multiple of a power of two (because that's how I ended up here):

// number: the number to be rounded (ex: 5, 123, 98345, etc.)
// pow2:   the power to be rounded to (ex: to round to 16, use '4')
int roundPow2 (int number, int pow2) {
    pow2--;                     // because (2 exp x) == (1 << (x -1))
    pow2 = 0x01 << pow2;

    pow2--;                     // because for any
                                //
                                // (x = 2 exp x)
                                //
                                // subtracting one will
                                // yield a field of ones
                                // which we can use in a
                                // bitwise OR

    number--;                   // yield a similar field for
                                // bitwise OR
    number = number | pow2;
    number++;                   // restore value by adding one back

    return number;
}

The input number will stay the same if it is already a multiple.

Here is the x86_64 output that GCC gives with -O2 or -Os (9Sep2013 Build - godbolt GCC online):

roundPow2(int, int):
    lea ecx, [rsi-1]
    mov eax, 1
    sub edi, 1
    sal eax, cl
    sub eax, 1
    or  eax, edi
    add eax, 1
    ret

Each C line of code corresponds perfectly with its line in the assembly: http://goo.gl/DZigfX

Each of those instructions are extremely fast, so the function is extremely fast too. Since the code is so small and quick, it might be useful to inline the function when using it.


Credit:

Git push won't do anything (everything up-to-date)

Thanks to Sam Stokes. According to his answer you can solve the problem with different way (I used this way). After updating your develop directory you should reinitialize it

git init

Then you can commit and push updates to master

MySQL query to select events between start/end date

In PHP and phpMyAdmin

$tb = tableDataName; //Table name
$now = date('Y-m-d'); //Current date

//start and end is the fields of tabla with date format value (yyyy-m-d)

$query = "SELECT * FROM $tb WHERE start <= '".$now."' AND end >= '".$now."'";

Java integer list

Let's use some java 8 feature:

IntStream.iterate(10, x -> x + 10).limit(5)
  .forEach(System.out::println);

If you need to store the numbers you can collect them into a collection eg:

List numbers = IntStream.iterate(10, x -> x + 10).limit(5)
  .boxed()
  .collect(Collectors.toList());

And some delay added:

IntStream.iterate(10, x -> x + 10).limit(5)
  .forEach(x -> {
    System.out.println(x);
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      // Do something with the exception
    }  
  });

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

I found another way without setting proxy. I'm currently using an antivirus which has a firewall program. Then, I turn off this firewall and now I can fetch that URL.

If still doesn't work, try to turn off Firewall on your PC, such as Windows Firewall.

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

For anyone using VSTO, the problem for me was a missing reference to the office assembly. It would also appear if you were trying to instantiate certain VSTO objects manually.

How to create a temporary directory?

For a more robust solution i use something like the following. That way the temp dir will always be deleted after the script exits.

The cleanup function is executed on the EXIT signal. That guarantees that the cleanup function is always called, even if the script aborts somewhere.

#!/bin/bash    

# the directory of the script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# the temp directory used, within $DIR
# omit the -p parameter to create a temporal directory in the default location
WORK_DIR=`mktemp -d -p "$DIR"`

# check if tmp dir was created
if [[ ! "$WORK_DIR" || ! -d "$WORK_DIR" ]]; then
  echo "Could not create temp dir"
  exit 1
fi

# deletes the temp directory
function cleanup {      
  rm -rf "$WORK_DIR"
  echo "Deleted temp working directory $WORK_DIR"
}

# register the cleanup function to be called on the EXIT signal
trap cleanup EXIT

# implementation of script starts here
...

Directory of bash script from here.

Bash traps.

How to force a line break on a Javascript concatenated string?

You need to use \n inside quotes.

document.getElementById("address_box").value = (title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4)

\n is called a EOL or line-break, \n is a common EOL marker and is commonly refereed to as LF or line-feed, it is a special ASCII character

Overcoming "Display forbidden by X-Frame-Options"

If you are getting this error for a YouTube video, rather than using the full url use the embed url from the share options. It will look like http://www.youtube.com/embed/eCfDxZxTBW4

You may also replace watch?v= with embed/ so http://www.youtube.com/watch?v=eCfDxZxTBW4 becomes http://www.youtube.com/embed/eCfDxZxTBW4

IF a == true OR b == true statement

Comparison expressions should each be in their own brackets:

{% if (a == 'foo') or (b == 'bar') %}
    ...
{% endif %}

Alternative if you are inspecting a single variable and a number of possible values:

{% if a in ['foo', 'bar', 'qux'] %}
    ...
{% endif %}

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

Try this:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

zzz is the timezone offset.

How to get the day name from a selected date?

DateTime now = DateTime.Now
string s = now.DayOfWeek.ToString();

how to use json file in html code

You can use JavaScript like... Just give the proper path of your json file...

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
        <script type="text/javascript" >
            function load() {
                var mydata = JSON.parse(data);
                alert(mydata.length);

                var div = document.getElementById('data');

                for(var i = 0;i < mydata.length; i++)
                {
                    div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                }
            }
        </script>
    </head>
    <body onload="load()">
        <div id="data">

        </div>
    </body>
</html>

Simply getting the data and appending it to a div... Initially printing the length in alert.

Here is my Json file: abc.json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';

jQuery datepicker, onSelect won't work

datePicker's onSelect equivalent is the dateSelected event.

$(function() {
    $('.date-pick').datePicker( {
        selectWeek: true,
        inline: true,
        startDate: '01/01/2000',
        firstDay: 1,
    }).bind('dateSelected', function(e, selectedDate, $td) {
        alert(selectedDate);
    });
});

This page has a good example showing the dateSelected event and other events being bound.

LINQ Inner-Join vs Left-Join

If you actually have a database, this is the most-simple way:

var lsPetOwners = ( from person in context.People
                    from pets in context.Pets
                        .Where(mypet => mypet.Owner == person.ID) 
                        .DefaultIfEmpty()
                     select new { OwnerName = person.Name, Pet = pets.Name }
                   ).ToList();

Xcode 6.1 Missing required architecture X86_64 in file

Here's a response to your latest question about the difference between x86_64 and arm64:

  • x86_64 architecture is required for running the 64bit simulator.

  • arm64 architecture is required for running the 64bit device (iPhone 5s, iPhone 6, iPhone 6 Plus, iPad Air, iPad mini with Retina display).

Generate sql insert script from excel worksheet

I had to make SQL scripts often and add them to source control and send them to DBA. I used this ExcelIntoSQL App from windows store https://www.microsoft.com/store/apps/9NH0W51XXQRM It creates complete script with "CREATE TABLE" and INSERTS.

Passing in class names to react components

As other have stated, use an interpreted expression with curly braces.

But do not forget to set a default.
Others has suggested using a OR statement to set a empty string if undefined.

But it would be even better to declare your Props.

Full example:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Pill extends Component {

  render() {

    return (
      <button className={`pill ${ this.props.className }`}>{this.props.children}</button>
    );
  }

}

Pill.propTypes = {
  className: PropTypes.string,
};

Pill.defaultProps = {
  className: '',
};

ngFor with index as value in attribute

with laravel pagination

file.component.ts file

    datasource: any = {
        data: []
    }

    loadData() {
        this.service.find(this.params).subscribe((res: any) => {
            this.datasource = res;
        });
    }

html file

   <tr *ngFor="let item of datasource.data; let i = index">
       <th>{{ datasource.from + i }}</th>
   </tr>

Read file content from S3 bucket with boto3

boto3 offers a resource model that makes tasks like iterating through objects easier. Unfortunately, StreamingBody doesn't provide readline or readlines.

s3 = boto3.resource('s3')
bucket = s3.Bucket('test-bucket')
# Iterates through all the objects, doing the pagination for you. Each obj
# is an ObjectSummary, so it doesn't contain the body. You'll need to call
# get to get the whole body.
for obj in bucket.objects.all():
    key = obj.key
    body = obj.get()['Body'].read()

How do I redirect with JavaScript?

Compared to window.location="url"; it is much easyer to do just location="url"; I always use that

java.lang.IllegalStateException: Fragment not attached to Activity

this happen when the fragment does not have a context ,thus the getActivity()method return null. check if you use the context before you get it,or if the Activity is not exist anymore . use context in fragment.onCreate and after api response usually case this problem

Get single listView SelectedItem

If you want to select single listview item no mouse click over it try this.

private void timeTable_listView_MouseUp(object sender, MouseEventArgs e)
        {
            Point mousePos = timeTable_listView.PointToClient(Control.MousePosition);
            ListViewHitTestInfo hitTest = timeTable_listView.HitTest(mousePos);



            try
            {
            int columnIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);
            edit_textBox.Text = timeTable_listView.SelectedItems[0].SubItems[columnIndex].Text;
            }
            catch(Exception)
            {

            }



        }

Dynamic array in C#

Sometimes plain arrays are preferred to Generic Lists, since they are more convenient (Better performance for costly computation -Numerical Algebra Applications for example, or for exchanging Data with Statistics software like R or Matlab)

In this case you may use the ToArray() method after initiating your List dynamically

List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");

string[] array = list.ToArray();

Of course, this has sense only if the size of the array is never known nor fixed ex-ante. if you already know the size of your array at some point of the program it is better to initiate it as a fixed length array. (If you retrieve data from a ResultSet for example, you could count its size and initiate an array of that size, dynamically)

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

Use NetworkService as Identity value in the application pool advanced settings when you are debugging in Visual Studio. ApplicationPoolIdentity is working if you open the site directly from the browser (or go to virtual directory in IIS and use Browse option at right).

Dynamically change bootstrap progress bar value when checkboxes checked

Try this maybe :

Bootply : http://www.bootply.com/106527

Js :

$('input').on('click', function(){
  var valeur = 0;
  $('input:checked').each(function(){
       if ( $(this).attr('value') > valeur )
       {
           valeur =  $(this).attr('value');
       }
  });
  $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    
});

HTML :

 <div class="progress progress-striped active">
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
        </div>
    </div>
<div class="row tasks">
        <div class="col-md-6">
          <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>
        </div>
        <div class="col-md-2">
          <label>2014-01-29</label>
        </div>
        <div class="col-md-2">
          <input name="progress" class="progress" type="checkbox" value="10">
        </div>
        <div class="col-md-2">
          <input name="done" class="done" type="checkbox" value="20">
        </div>
      </div><!-- tasks -->

<div class="row tasks">
        <div class="col-md-6">
          <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be
sure that you’ll have tangible results to share with the world (or your
boss) at the end of your campaign.</p>
        </div>
        <div class="col-md-2">
          <label>2014-01-25</label>
        </div>
        <div class="col-md-2">
          <input name="progress" class="progress" type="checkbox" value="30">
        </div>
        <div class="col-md-2">
          <input name="done" class="done" type="checkbox" value="40">
        </div>
      </div><!-- tasks -->

Css

.tasks{
    background-color: #F6F8F8;
    padding: 10px;
    border-radius: 5px;
    margin-top: 10px;
}
.tasks span{
    font-weight: bold;
}
.tasks input{
    display: block;
    margin: 0 auto;
    margin-top: 10px;
}
.tasks a{
    color: #000;
    text-decoration: none;
    border:none;
}
.tasks a:hover{
    border-bottom: dashed 1px #0088cc;
}
.tasks label{
    display: block;
    text-align: center;
}

_x000D_
_x000D_
$(function(){_x000D_
$('input').on('click', function(){_x000D_
  var valeur = 0;_x000D_
  $('input:checked').each(function(){_x000D_
       if ( $(this).attr('value') > valeur )_x000D_
       {_x000D_
           valeur =  $(this).attr('value');_x000D_
       }_x000D_
  });_x000D_
  $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    _x000D_
});_x000D_
_x000D_
});
_x000D_
.tasks{_x000D_
 background-color: #F6F8F8;_x000D_
 padding: 10px;_x000D_
 border-radius: 5px;_x000D_
 margin-top: 10px;_x000D_
}_x000D_
.tasks span{_x000D_
 font-weight: bold;_x000D_
}_x000D_
.tasks input{_x000D_
 display: block;_x000D_
 margin: 0 auto;_x000D_
 margin-top: 10px;_x000D_
}_x000D_
.tasks a{_x000D_
 color: #000;_x000D_
 text-decoration: none;_x000D_
 border:none;_x000D_
}_x000D_
.tasks a:hover{_x000D_
 border-bottom: dashed 1px #0088cc;_x000D_
}_x000D_
.tasks label{_x000D_
 display: block;_x000D_
 text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
 <div class="progress progress-striped active">_x000D_
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">_x000D_
        </div>_x000D_
    </div>_x000D_
<div class="row tasks">_x000D_
        <div class="col-md-6">_x000D_
          <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <label>2014-01-29</label>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="progress" class="progress" type="checkbox" value="10">_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="done" class="done" type="checkbox" value="20">_x000D_
        </div>_x000D_
      </div><!-- tasks -->_x000D_
_x000D_
<div class="row tasks">_x000D_
        <div class="col-md-6">_x000D_
          <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be_x000D_
sure that you’ll have tangible results to share with the world (or your_x000D_
boss) at the end of your campaign.</p>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <label>2014-01-25</label>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="progress" class="progress" type="checkbox" value="30">_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="done" class="done" type="checkbox" value="40">_x000D_
        </div>_x000D_
      </div><!-- tasks -->
_x000D_
_x000D_
_x000D_

How to push to History in React Router v4?

If you want to use history while passing a function as a value to a Component's prop, with react-router 4 you can simply destructure the history prop in the render attribute of the <Route/> Component and then use history.push()

    <Route path='/create' render={({history}) => (
      <YourComponent
        YourProp={() => {
          this.YourClassMethod()
          history.push('/')
        }}>
      </YourComponent>
    )} />

Note: For this to work you should wrap React Router's BrowserRouter Component around your root component (eg. which might be in index.js)

Error after upgrading pip: cannot import name 'main'

Use python -m pip install instead of pip install

Example:

python -m pip install --user somepackage
python3 -m pip install --user somepackage

The pip (resp. pip3) executable is provided by your distro (python-pip package on Ubuntu 16.04) and located at /usr/bin/pip.

Therefore, it is not kept up-to date with the pip package itself as you upgrade pip, and may break.

If you just use python -m pip directly, e.g. as in:

python -m pip install --user somepackage
python3 -m pip install --user somepackage

it goes through your Python path, finds the latest version of pip and executes that file.

It relies on the fact that file is executable through import, but that is a very standard type of interface, and therefore less likely to break than the hackier Debian script.

Then I recommend adding the following aliases to your .bashrc:

pip() ( python -m pip "$@" )
pip3() ( python3 -m pip "$@" )

The Ubuntu 18.04 /usr/bin/pip3 file does:

from pip import main

and presumably main was removed from pip at some point which is what broke things.

The breaking pip commit appears to be: 95bcf8c5f6394298035a7332c441868f3b0169f4 "Move all internal APIs to pip._internal" which went into pip 18.0.

Tested in Ubuntu 16.04 after an update from pip3 9.0.1 to 18.0.

pyenv

Ultimately however, for serious Python development I would just recommend that you install your own local Python with pyenv + virtualenv, which would also get around this Ubuntu bug: https://askubuntu.com/questions/682869/how-do-i-install-a-different-python-version-using-apt-get/1195153#1195153

Making text background transparent but not text itself

Don't use opacity for this, set the background to an RGBA-value instead to only make the background semi-transparent. In your case it would be like this.

.content {
    padding:20px;
    width:710px;
    position:relative;
    background: rgb(204, 204, 204); /* Fallback for older browsers without RGBA-support */
    background: rgba(204, 204, 204, 0.5);
}

See http://css-tricks.com/rgba-browser-support/ for more info and samples of rgba-values in css.

Run an OLS regression with Pandas Data Frame

I don't know if this is new in sklearn or pandas, but I'm able to pass the data frame directly to sklearn without converting the data frame to a numpy array or any other data types.

from sklearn import linear_model

reg = linear_model.LinearRegression()
reg.fit(df[['B', 'C']], df['A'])

>>> reg.coef_
array([  4.01182386e-01,   3.51587361e-04])

How to check if input file is empty in jQuery

Questions : how to check File is empty or not?

Ans: I have slove this issue using this Jquery code

_x000D_
_x000D_
//If your file Is Empty :     _x000D_
      if (jQuery('#videoUploadFile').val() == '') {_x000D_
                       $('#message').html("Please Attach File");_x000D_
                   }else {_x000D_
                            alert('not work');_x000D_
                   }_x000D_
_x000D_
    
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" id="videoUploadFile">_x000D_
<br>_x000D_
<br>_x000D_
<div id="message"></div>
_x000D_
_x000D_
_x000D_

'foo' was not declared in this scope c++

In general, in C++ functions have to be declared before you call them. So sometime before the definition of getSkewNormal(), the compiler needs to see the declaration:

double integrate (double start, double stop, int numSteps, Evaluatable evalObj);

Mostly what people do is put all the declarations (only) in the header file, and put the actual code -- the definitions of the functions and methods -- into a separate source (*.cc or *.cpp) file. This neatly solves the problem of needing all the functions to be declared.

How to dynamically set bootstrap-datepicker's date value?

This works for me

$(".datepicker").datepicker("update", new Date());

Running a script inside a docker container using shell script

Assuming that your docker container is up and running, you can run commands as:

docker exec mycontainer /bin/sh -c "cmd1;cmd2;...;cmdn"

ORA-01882: timezone region not found

I ran into this problem with Tomcat. Setting the following in $CATALINA_BASE/bin/setenv.sh solved the issue:

JAVA_OPTS=-Doracle.jdbc.timezoneAsRegion=false

I'm sure that using one of the Java parameter suggestions from the other answers would work in the same way.

Is it possible to use a div as content for Twitter's Popover

here is an another example

<a   data-container = "body" data-toggle = "popover" data-placement = "left" 
    data-content = "&lt;img src='<?php echo baseImgUrl . $row1[2] ?>' width='250' height='100' &gt;&lt;div&gt;&lt;h3&gt; <?php echo $row1['1'] ?>&lt/h3&gt; &lt;p&gt; &lt;span&gt;<?php echo $countsss ?>videos &lt;/span&gt;
&lt;span&gt;<?php echo $countsss1 ?> followers&lt;/span&gt;
&lt;/p&gt;&lt;/div&gt;
<?php echo $row1['4'] ?>   &lt;hr&gt;&lt;div&gt;
&lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt;Follow  &lt;/button&gt;  &lt;/span&gt; &lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt; Go to channel page&lt;/button&gt;   &lt;/span&gt;&lt;span&gt; &lt;button type='button' class='btn btn-default pull-left green'&gt;Close  &lt;/button&gt;  &lt;/span&gt;

 &lt;/div&gt;">

<?php echo $row1['1'] ?>
  </a>

TypeScript enum to object array

Here's the simple function with correct typing I use

/**
 * Helper to produce an array of enum values.
 * @param enumeration Enumeration object.
 */
export function enumToArray<T, G extends keyof T = keyof T>(enumeration: T): T[G][] {
  // tslint:disable: comment-format

  // enum Colors {
  //   WHITE = 0,
  //   BLACK = 1,
  // }
  // Object.values(Colors) will produce ['WHITE', 'BLACK', 0, 1]

  // So, simply slice the second half
  const enumValues = Object.values(enumeration);
  return enumValues.slice(enumValues.length / 2, enumValues.length) as T[G][];
}

Usage example:

enum Colors {
  Red = 1,
  Blue = 2,
}
enumToArray(Colors)

Using scanner.nextLine()

It's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". Primitive data types like int, double etc do not consume "end of line", therefore the "end of line" remains in buffer and When input.next() executes, it consumes the "end of line" from buffer from the first input. That's why, your String sentence = scanner.next() only consumes the "end of line" and does not wait to read from keyboard.

Tip: use scanner.nextLine() instead of scanner.next() because scanner.next() does not read white spaces from the keyboard. (Truncate the string after giving some space from keyboard, only show string before space.)

C char array initialization

The relevant part of C11 standard draft n1570 6.7.9 initialization says:

14 An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

and

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Thus, the '\0' is appended, if there is enough space, and the remaining characters are initialized with the value that a static char c; would be initialized within a function.

Finally,

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

[--]

  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;

[--]

Thus, char being an arithmetic type the remainder of the array is also guaranteed to be initialized with zeroes.

The best way to remove duplicate values from NSMutableArray in Objective-C?

Using Orderedset will do the trick. This will keep the remove duplicates from the array and maintain order which sets normally doesn't do

How to clear Flutter's Build cache?

There are basically 3 alternatives to cleaning everything that you could try:

  • flutter clean will delete the /build folder.
  • Manually delete the /build folder, which is essentially the same as flutter clean.
  • Or, as @Rémi Roudsselet pointed out: restart your IDE, as it might be caching some older error logs and locking everything up.

How to allow <input type="file"> to accept only image files?

If you want to upload multiple images at once you can add multiple attribute to input.

_x000D_
_x000D_
upload multiple files: <input type="file" multiple accept='image/*'>
_x000D_
_x000D_
_x000D_

How to extract extension from filename string in Javascript?

var x = "1.txt";
alert (x.substring(x.indexOf(".")+1));

note 1: this will not work if the filename is of the form file.example.txt
note 2: this will fail if the filename is of the form file

How to resolve git's "not something we can merge" error

For me, the problem was the 'double quotation marks' into merge message. So when I removed the double mark, all magically worked. I hope to help someone. (Sorry for my poor English)

How can I one hot encode in Python?

You can do it with numpy.eye and a using the array element selection mechanism:

import numpy as np
nb_classes = 6
data = [[2, 3, 4, 0]]

def indices_to_one_hot(data, nb_classes):
    """Convert an iterable of indices to one-hot encoded labels."""
    targets = np.array(data).reshape(-1)
    return np.eye(nb_classes)[targets]

The the return value of indices_to_one_hot(nb_classes, data) is now

array([[[ 0.,  0.,  1.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  1.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  1.,  0.],
        [ 1.,  0.,  0.,  0.,  0.,  0.]]])

The .reshape(-1) is there to make sure you have the right labels format (you might also have [[2], [3], [4], [0]]).

How to save user input into a variable in html and js

First, make your markup more portable/reusable. I also set the button's type to 'button' instead of using the onsubmit attribute. You can toggle the type attribute to submit if the form needs to interact with a server.

<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
    <label id='nameLable' for='nameField'>Create a username:</label>
    <input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
    <button id='subButton' type='button'>Print your name!</button>
</div>
</form>

<div>
    <p id='result'></p></div>
</div>

Next write a general function for retrieving the username into a variable. It checks to make sure the variable holding the username has it least three characters in it. You can change this to whatever constant you want.

function getUserName() {
var nameField = document.getElementById('nameField').value;
var result = document.getElementById('result');

if (nameField.length < 3) {
    result.textContent = 'Username must contain at least 3 characters';
    //alert('Username must contain at least 3 characters');
} else {
    result.textContent = 'Your username is: ' + nameField;
    //alert(nameField);
}
}

Next, I created an event listener for the button. It's generally considered the bad practice to have inline js calls.

var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false); 

Here is a working and lightly styled demo:

CodePen demo of this answer.

Join vs. sub-query

Taken from the MySQL manual (13.2.10.11 Rewriting Subqueries as Joins):

A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better—a fact that is not specific to MySQL Server alone.

So subqueries can be slower than LEFT [OUTER] JOIN, but in my opinion their strength is slightly higher readability.

Android Intent Cannot resolve constructor

Or you can simply start the activity as shown below;

startActivity( new Intent(currentactivity.this, Tostartactivity.class));

Laravel 5.4 redirection to custom url after login

Path Customization (tested in laravel 7) When a user is successfully authenticated, they will be redirected to the /home URI. You can customize the post-authentication redirect path using the HOME constant defined in your RouteServiceProvider:

public const HOME = '/home';

Why can I not push_back a unique_ptr into a vector?

std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.

error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
 std::unique_ptr<int>]'

The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

The following works with the new emplace calls.

std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );

See using unique_ptr with standard library containers for further reading.

Convert string to decimal, keeping fractions

this is what you have to do.

decimal d = 1200.00;    
string value = d.ToString(CultureInfo.InvariantCulture);

// value = "1200.00" 

This worked for me. Thanks.

Android: Create a toggle button with image and no text

  1. Can I replace the toggle text with an image

    No, we can not, although we can hide the text by overiding the default style of the toggle button, but still that won't give us a toggle button you want as we can't replace the text with an image.

  2. How can I make a normal toggle button

    Create a file ic_toggle in your res/drawable folder

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:state_checked="false"
              android:drawable="@drawable/ic_slide_switch_off" />
    
        <item android:state_checked="true"
              android:drawable="@drawable/ic_slide_switch_on" />
    
    </selector>
    

    Here @drawable/ic_slide_switch_on & @drawable/ic_slide_switch_off are images you create.

    Then create another file in the same folder, name it ic_toggle_bg

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:id="@+android:id/background"  
              android:drawable="@android:color/transparent" />
    
        <item android:id="@+android:id/toggle"
              android:drawable="@drawable/ic_toggle" />
    
    </layer-list>
    

    Now add to your custom theme, (if you do not have one create a styles.xml file in your res/values/folder)

    <style name="Widget.Button.Toggle" parent="android:Widget">
       <item name="android:background">@drawable/ic_toggle_bg</item>
       <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
    </style>
    
    <style name="toggleButton"  parent="@android:Theme.Black">
       <item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
       <item name="android:textOn"></item>
       <item name="android:textOff"></item>
    </style>
    

    This creates a custom toggle button for you.

  3. How to use it

    Use the custom style and background in your view.

      <ToggleButton
            android:id="@+id/toggleButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            style="@style/toggleButton"
            android:background="@drawable/ic_toggle_bg"/>
    

Run a Python script from another Python script, passing in arguments

This is inherently the wrong thing to do. If you are running a Python script from another Python script, you should communicate through Python instead of through the OS:

import script1

In an ideal world, you will be able to call a function inside script1 directly:

for i in range(whatever):
    script1.some_function(i)

If necessary, you can hack sys.argv. There's a neat way of doing this using a context manager to ensure that you don't make any permanent changes.

import contextlib
@contextlib.contextmanager
def redirect_argv(num):
    sys._argv = sys.argv[:]
    sys.argv=[str(num)]
    yield
    sys.argv = sys._argv

with redirect_argv(1):
    print(sys.argv)

I think this is preferable to passing all your data to the OS and back; that's just silly.

Import data into Google Colaboratory

Simple way to import data from your googledrive - doing this save people time (don't know why google just doesn't list this step by step explicitly).

INSTALL AND AUTHENTICATE PYDRIVE

     !pip install -U -q PyDrive ## you will have install for every colab session

     from pydrive.auth import GoogleAuth
     from pydrive.drive import GoogleDrive
     from google.colab import auth
     from oauth2client.client import GoogleCredentials

     # 1. Authenticate and create the PyDrive client.
     auth.authenticate_user()
     gauth = GoogleAuth()
     gauth.credentials = GoogleCredentials.get_application_default()
     drive = GoogleDrive(gauth)

UPLOADING

if you need to upload data from local drive:

    from google.colab import files

    uploaded = files.upload()

    for fn in uploaded.keys():
       print('User uploaded file "{name}" with length {length} bytes'.format(name=fn, length=len(uploaded[fn])))

execute and this will display a choose file button - find your upload file - click open

After uploading, it will display:

    sample_file.json(text/plain) - 11733 bytes, last modified: x/xx/2018 - %100 done
    User uploaded file "sample_file.json" with length 11733 bytes

CREATE FILE FOR NOTEBOOK

If your data file is already in your gdrive, you can skip to this step.

Now it is in your google drive. Find the file in your google drive and right click. Click get 'shareable link.' You will get a window with:

    https://drive.google.com/open?id=29PGh8XCts3mlMP6zRphvnIcbv27boawn

Copy - '29PGh8XCts3mlMP6zRphvnIcbv27boawn' - that is the file ID.

In your notebook:

    json_import = drive.CreateFile({'id':'29PGh8XCts3mlMP6zRphvnIcbv27boawn'})

    json_import.GetContentFile('sample.json') - 'sample.json' is the file name that will be accessible in the notebook.

IMPORT DATA INTO NOTEBOOK

To import the data you uploaded into the notebook (a json file in this example - how you load will depend on file/data type - .txt,.csv etc. ):

    sample_uploaded_data = json.load(open('sample.json'))

Now you can print to see the data is there:

    print(sample_uploaded_data)

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

How to find my php-fpm.sock?

I know this is old questions but since I too have the same problem just now and found out the answer, thought I might share it. The problem was due to configuration at pood.d/ directory.

Open

/etc/php5/fpm/pool.d/www.conf

find

listen = 127.0.0.1:9000

change to

listen = /var/run/php5-fpm.sock

Restart both nginx and php5-fpm service afterwards and check if php5-fpm.sock already created.

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

Use datetime.replace:

from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)

how to POST/Submit an Input Checkbox that is disabled?

<input type="checkbox" checked="checked" onclick="this.checked=true" />

I started from the problem: "how to POST/Submit an Input Checkbox that is disabled?" and in my answer I skipped the comment: "If we want to disable a checkbox we surely need to keep a prefixed value (checked or unchecked) and also we want that the user be aware of it (otherwise we should use a hidden type and not a checkbox)". In my answer I supposed that we want to keep always a checkbox checked and that code works in this way. If we click on that ckeckbox it will be forever checked and its value will be POSTED/Submitted! In the same way if I write onclick="this.checked=false" without checked="checked" (note: default is unchecked) it will be forever unchecked and its value will be not POSTED/Submitted!.

SLF4J: Class path contains multiple SLF4J bindings

Seems removing .m2 directory and :

mvn install -DskipTests -T 4 resolved this issue for me.

Using NULL in C++?

The downside of NULL in C++ is that it is a define for 0. This is a value that can be silently converted to pointer, a bool value, a float/double, or an int.

That is not very type safe and has lead to actual bugs in an application I worked on.

Consider this:

void Foo(int i);
void Foo(Bar* b);
void Foo(bool b);


main()
{
     Foo(0);         
     Foo(NULL); // same as Foo(0)
} 

C++11 defines a nullptr that is convertible to a null pointer but not to other scalars. This is supported in all modern C++ compilers, including VC++ as of 2008. In older versions of GCC there is a similar feature, but then it was called __null.

'namespace' but is used like a 'type'

namespace TestApplication // Remove .Controller
{
    public class HomeController : Controller
    {
       public ActionResult Index()
        {
            return View();
        }
    }
}

Remove the controller word from namepsace

Locating child nodes of WebElements in selenium

I also found myself in a similar position a couple of weeks ago. You can also do this by creating a custom ElementLocatorFactory (or simply passing in divA into the DefaultElementLocatorFactory) to see if it's a child of the first div - you would then call the appropriate PageFactory initElements method.

In this case if you did the following:

PageFactory.initElements(new DefaultElementLocatorFactory(divA), pageObjectInstance));
// The Page Object instance would then need a WebElement 
// annotated with something like the xpath above or @FindBy(tagName = "input")

Increase max_execution_time in PHP?

Theres a setting max_input_time (on Apache) for many webservers that defines how long they will wait for post data, regardless of the size. If this time runs out the connection is closed without even touching the php.

So your problem is not necessarily solvable with php only but you will need to change the server settings too.

Store mysql query output into a shell variable

Other way:

Your Script:

#!/bin/sh

# Set these variables
MyUSER="root"   # DB_USERNAME
MyPASS="yourPass"   # DB_PASSWORD
MyHOST="yourHost"    # DB_HOSTNAME
DB_NAME="dbName"
CONTAINER="containerName" #if use docker

# Get data
data=$($MyHOST -u $MyUSER -p$MyPASS $DB_NAME -h $CONTAINER -e "SELECT data1,data2 from table_name LIMIT 1;"  -B --skip-column-names)

# Set data
data1=$(echo $data | awk '{print $1}')
data2=$(echo $data | awk '{print $2}')

# Print data
echo $data1 $data2

How can I verify if a Windows Service is running

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

So many solutions.
But I still think there is room for improvement.

Advantages:

  • very compact code
  • works with any font size
    (no absolute pixel values contained)
  • aligns rows perfectly
    (no slight shift between first line and following lines)

_x000D_
_x000D_
ul {_x000D_
 position: relative;_x000D_
 list-style: none;_x000D_
 margin-left: 0;_x000D_
 padding-left: 1.2em;_x000D_
}_x000D_
ul li:before {_x000D_
 content: "+";_x000D_
 position: absolute;_x000D_
 left: 0;_x000D_
}
_x000D_
<ul>_x000D_
  <li>Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. Pellentesque in ipsum id orci porta dapibus.</li>_x000D_
  <li>Nulla porttitor accumsan tincidunt. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Aliquet quam id dui posuere blandit. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus.</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Failed to connect to mailserver at "localhost" port 25

You need to be running a mail server locally. If this is Unix, enable sendmail If this is Windows install the Simple Mail Transfer Server (not sure if the name is correct) component of IIs. E.g. for windows 2003 follow this: http://msdn.microsoft.com/en-us/library/8b83ac7t.aspx

How to change node.js's console font color?

paint-console

Simple colorable log. Support inspect objects and single line update This package just repaint console.

install

npm install paint-console

usage

require('paint-console');

console.info('console.info();');
console.warn('console.warn();');
console.error('console.error();');
console.log('console.log();');

demo

Retrieve the commit log for a specific line in a file?

In my case the line number had changed a lot over time. I was also on git 1.8.3 which does not support regex in "git blame -L". (RHEL7 still has 1.8.3)

myfile=haproxy.cfg
git rev-list HEAD -- $myfile | while read i
do
    git diff -U0 ${i}^ $i $myfile | sed "s/^/$i /"
done | grep "<sometext>"

Oneliner:

myfile=<myfile> ; git rev-list HEAD -- $myfile | while read i; do     git diff -U0 ${i}^ $i $myfile | sed "s/^/$i /"; done | grep "<sometext>"

This can of course be made into a script or a function.

JavaScript open in a new window, not tab

You shouldn't need to. Allow the user to have whatever preferences they want.

Firefox does that by default because opening a page in a new window is annoying and a page should never be allowed to do so if that is not what is desired by the user. (Firefox does allow you to open tabs in a new window if you set it that way).

How do I look inside a Python object?

In addition if you want to look inside list and dictionaries, you can use pprint()

jQuery animated number counter from zero to value

You can do it with animate function in jQuery.

$({ countNum: $('.code').html() }).animate({ countNum: 4000 }, {
    duration: 8000,
    easing: 'linear',
    step: function () {
        $('.yourelement').html(Math.floor(this.countNum));
    },
    complete: function () {
        $('.code').html(this.countNum);
        //alert('finished');
   }
});

Demo

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Normally, you run IE 32 bit.
However, on 64-bit versions of Windows, there is a separate link in the Start Menu to Internet Explorer (64 bit). There's no real reason to use it, though.

In Help, About, the 64-bit version of IE will say 64-bit Edition (just after the full version string).

The 32-bit and 64-bit versions of IE have separate addons lists (because 32-bit addons cannot be loaded in 64-bit IE, and vice-versa), so you should make sure that Java appears on both lists.

In general, you can tell whether a process is 32-bit or 64-bit by right-clicking the application in Task Manager and clicking Go To Process. 32-bit processes will end with *32.

Find and Replace string in all files recursive using grep and sed

The GNU guys REALLY messed up when they introduced recursive file searching to grep. grep is for finding REs in files and printing the matching line (g/re/p remember?) NOT for finding files. There's a perfectly good tool with a very obvious name for FINDing files. Whatever happened to the UNIX mantra of do one thing and do it well?

Anyway, here's how you'd do what you want using the traditional UNIX approach (untested):

find /path/to/folder -type f -print |
while IFS= read -r file
do
   awk -v old="$oldstring" -v new="$newstring" '
      BEGIN{ rlength = length(old) }
      rstart = index($0,old) { $0 = substr($0,rstart-1) new substr($0,rstart+rlength) }
      { print }
   ' "$file" > tmp &&
   mv tmp "$file"
done

Not that by using awk/index() instead of sed and grep you avoid the need to escape all of the RE metacharacters that might appear in either your old or your new string plus figure out a character to use as your sed delimiter that can't appear in your old or new strings, and that you don't need to run grep since the replacement will only occur for files that do contain the string you want. Having said all of that, if you don't want the file timestamp to change if you don't modify the file, then just do a diff on tmp and the original file before doing the mv or throw in an fgrep -q before the awk.

Caveat: The above won't work for file names that contain newlines. If you have those then let us know and we can show you how to handle them.

Cast IList to List

List<ProjectResources> list = new List<ProjectResources>();        
IList<ProjectResources> obj = `Your Data Will Be Here`;
list = obj.ToList<ProjectResources>();

This Would Convert IList Object to List Object.

Add JsonArray to JsonObject

Your list:

List<MyCustomObject> myCustomObjectList;

Your JSONArray:

// Don't need to loop through it. JSONArray constructor do it for you.
new JSONArray(myCustomObjectList)

Your response:

return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList));

Your post/put http body request would be like this:

    {
        "yourCustomKey: [
           {
               "myCustomObjectProperty": 1
           },
           {
               "myCustomObjectProperty": 2
           }
        ]
    }

Implementing SearchView in action bar

It took a while to put together a solution for this, but have found this is the easiest way to get it to work in the way that you describe. There could be better ways to do this, but since you haven't posted your activity code I will have to improvise and assume you have a list like this at the start of your activity:

private List<String> items = db.getItems();

ExampleActivity.java

private List<String> items;

private Menu menu;

@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.example, menu);

    this.menu = menu;

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

        SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();

        search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));

        search.setOnQueryTextListener(new OnQueryTextListener() { 

            @Override 
            public boolean onQueryTextChange(String query) {

                loadHistory(query);

                return true; 

            } 

        });

    }

    return true;

}

// History
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void loadHistory(String query) {

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

        // Cursor
        String[] columns = new String[] { "_id", "text" };
        Object[] temp = new Object[] { 0, "default" };

        MatrixCursor cursor = new MatrixCursor(columns);

        for(int i = 0; i < items.size(); i++) {

            temp[0] = i;
            temp[1] = items.get(i);

            cursor.addRow(temp);

        }

        // SearchView
        SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        final SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();

        search.setSuggestionsAdapter(new ExampleAdapter(this, cursor, items));

    }

}

Now you need to create an adapter extended from CursorAdapter:

ExampleAdapter.java

public class ExampleAdapter extends CursorAdapter {

    private List<String> items;

    private TextView text;

    public ExampleAdapter(Context context, Cursor cursor, List<String> items) {

        super(context, cursor, false);

        this.items = items;

    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

        text.setText(items.get(cursor.getPosition()));

    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = inflater.inflate(R.layout.item, parent, false);

        text = (TextView) view.findViewById(R.id.text);

        return view;

    }

}

A better way to do this is if your list data is from a database, you can pass the Cursor returned by database functions directly to ExampleAdapter and use the relevant column selector to display the column text in the TextView referenced in the adapter.

Please note: when you import CursorAdapter don't import the Android support version, import the standard android.widget.CursorAdapter instead.

The adapter will also require a custom layout:

res/layout/item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

You can now customize list items by adding additional text or image views to the layout and populating them with data in the adapter.

This should be all, but if you haven't done this already you need a SearchView menu item:

res/menu/example.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/search"
        android:title="@string/search"
        android:showAsAction="ifRoom"
        android:actionViewClass="android.widget.SearchView" />

</menu>

Then create a searchable configuration:

res/xml/searchable.xml

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/search"
    android:hint="@string/search" >
</searchable>

Finally add this inside the relevant activity tag in the manifest file:

AndroidManifest.xml

<intent-filter>
    <action android:name="android.intent.action.SEARCH" />
</intent-filter>

<meta-data
    android:name="android.app.default_searchable"
    android:value="com.example.ExampleActivity" />
<meta-data
    android:name="android.app.searchable"
    android:resource="@xml/searchable" />

Please note: The @string/search string used in the examples should be defined in values/strings.xml, also don't forget to update the reference to com.example for your project.

What are the advantages and disadvantages of recursion?

Some situation would arise where you would have to abandon recursion in a problem where recursion appears to be to your advantage, this is because for problems where your recursion would have to occur thousand of times this would result in a stackoverflow error even though your code did not get stuck in an infinite recursion. Most programming languages limits you to a number of stack calls, so if your recursion goes beyond this limit, then you might consider not using recursion.

Reset C int array to zero : the fastest way?

Here's the function I use:

template<typename T>
static void setValue(T arr[], size_t length, const T& val)
{
    std::fill(arr, arr + length, val);
}

template<typename T, size_t N>
static void setValue(T (&arr)[N], const T& val)
{
    std::fill(arr, arr + N, val);
}

You can call it like this:

//fixed arrays
int a[10];
setValue(a, 0);

//dynamic arrays
int *d = new int[length];
setValue(d, length, 0);

Above is more C++11 way than using memset. Also you get compile time error if you use dynamic array with specifying the size.

Why use double indirection? or Why use pointers to pointers?

If you want to have a list of characters (a word), you can use char *word

If you want a list of words (a sentence), you can use char **sentence

If you want a list of sentences (a monologue), you can use char ***monologue

If you want a list of monologues (a biography), you can use char ****biography

If you want a list of biographies (a bio-library), you can use char *****biolibrary

If you want a list of bio-libraries (a ??lol), you can use char ******lol

... ...

yes, I know these might not be the best data structures


Usage example with a very very very boring lol

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int wordsinsentence(char **x) {
    int w = 0;
    while (*x) {
        w += 1;
        x++;
    }
    return w;
}

int wordsinmono(char ***x) {
    int w = 0;
    while (*x) {
        w += wordsinsentence(*x);
        x++;
    }
    return w;
}

int wordsinbio(char ****x) {
    int w = 0;
    while (*x) {
        w += wordsinmono(*x);
        x++;
    }
    return w;
}

int wordsinlib(char *****x) {
    int w = 0;
    while (*x) {
        w += wordsinbio(*x);
        x++;
    }
    return w;
}

int wordsinlol(char ******x) {
    int w = 0;
    while (*x) {
        w += wordsinlib(*x);
        x++;
    }
    return w;
}

int main(void) {
    char *word;
    char **sentence;
    char ***monologue;
    char ****biography;
    char *****biolibrary;
    char ******lol;

    //fill data structure
    word = malloc(4 * sizeof *word); // assume it worked
    strcpy(word, "foo");

    sentence = malloc(4 * sizeof *sentence); // assume it worked
    sentence[0] = word;
    sentence[1] = word;
    sentence[2] = word;
    sentence[3] = NULL;

    monologue = malloc(4 * sizeof *monologue); // assume it worked
    monologue[0] = sentence;
    monologue[1] = sentence;
    monologue[2] = sentence;
    monologue[3] = NULL;

    biography = malloc(4 * sizeof *biography); // assume it worked
    biography[0] = monologue;
    biography[1] = monologue;
    biography[2] = monologue;
    biography[3] = NULL;

    biolibrary = malloc(4 * sizeof *biolibrary); // assume it worked
    biolibrary[0] = biography;
    biolibrary[1] = biography;
    biolibrary[2] = biography;
    biolibrary[3] = NULL;

    lol = malloc(4 * sizeof *lol); // assume it worked
    lol[0] = biolibrary;
    lol[1] = biolibrary;
    lol[2] = biolibrary;
    lol[3] = NULL;

    printf("total words in my lol: %d\n", wordsinlol(lol));

    free(lol);
    free(biolibrary);
    free(biography);
    free(monologue);
    free(sentence);
    free(word);
}

Output:

total words in my lol: 243

Angular 2 change event - model changes

If this helps you,

<input type="checkbox"  (ngModelChange)="mychange($event)" [ngModel]="mymodel">

mychange(val)
{
   console.log(val); // updated value
}

What does random.sample() method in python do?

random.sample() also works on text

example:

> text = open("textfile.txt").read() 

> random.sample(text, 5)

> ['f', 's', 'y', 'v', '\n']

\n is also seen as a character so that can also be returned

you could use random.sample() to return random words from a text file if you first use the split method

example:

> words = text.split()

> random.sample(words, 5)

> ['the', 'and', 'a', 'her', 'of']

Access a URL and read Data with R

In the simplest case, just do

X <- read.csv(url("http://some.where.net/data/foo.csv"))

plus which ever options read.csv() may need.

Edit in Sep 2020 or 9 years later:

For a few years now R also supports directly passing the URL to read.csv:

X <- read.csv("http://some.where.net/data/foo.csv")

End of 2020 edit. Original post continutes.

Long answer: Yes this can be done and many packages have use that feature for years. E.g. the tseries packages uses exactly this feature to download stock prices from Yahoo! for almost a decade:

R> library(tseries)
Loading required package: quadprog
Loading required package: zoo

    ‘tseries’ version: 0.10-24

    ‘tseries’ is a package for time series analysis and computational finance.

    See ‘library(help="tseries")’ for details.

R> get.hist.quote("IBM")
trying URL 'http://chart.yahoo.com/table.csv?    ## manual linebreak here
  s=IBM&a=0&b=02&c=1991&d=5&e=08&f=2011&g=d&q=q&y=0&z=IBM&x=.csv'
Content type 'text/csv' length unknown
opened URL
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
........
downloaded 258 Kb

             Open   High    Low  Close
1991-01-02 112.87 113.75 112.12 112.12
1991-01-03 112.37 113.87 112.25 112.50
1991-01-04 112.75 113.00 111.87 112.12
1991-01-07 111.37 111.87 110.00 110.25
1991-01-08 110.37 110.37 108.75 109.00
1991-01-09 109.75 110.75 106.75 106.87
[...]

This is all exceedingly well documented in the manual pages for help(connection) and help(url). Also see the manul on 'Data Import/Export' that came with R.

Row names & column names in R

And another expansion:

# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)

If you want to assign new column names you can do following on data.frame:

# an identical effect can be achieved with colnames()   
names(d) <- LETTERS[1:5]
> d
  A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3

If you, however run previous command on matrix, you'll mess things up:

names(m) <- LETTERS[1:5]
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    2    4    3    4
[2,]    2    2    3    1    3
[3,]    3    2    1    2    4
[4,]    4    3    3    3    2
[5,]    1    3    2    4    3
attr(,"names")
 [1] "A" "B" "C" "D" "E" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[20] NA  NA  NA  NA  NA  NA 

Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames().

So there...

Split string with multiple delimiters in Python

Do a str.replace('; ', ', ') and then a str.split(', ')

Read Variable from Web.Config

If you want the basics, you can access the keys via:

string myKey = System.Configuration.ConfigurationManager.AppSettings["myKey"].ToString();
string imageFolder = System.Configuration.ConfigurationManager.AppSettings["imageFolder"].ToString();

To access my web config keys I always make a static class in my application. It means I can access them wherever I require and I'm not using the strings all over my application (if it changes in the web config I'd have to go through all the occurrences changing them). Here's a sample:

using System.Configuration;

public static class AppSettingsGet
{    
    public static string myKey
    {
        get { return ConfigurationManager.AppSettings["myKey"].ToString(); }
    }

    public static string imageFolder
    {
        get { return ConfigurationManager.AppSettings["imageFolder"].ToString(); }
    }

    // I also get my connection string from here
    public static string ConnectionString
    {
       get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
    }
}

How to extract epoch from LocalDate and LocalDateTime?

The conversion you need requires the offset from UTC/Greewich, or a time-zone.

If you have an offset, there is a dedicated method on LocalDateTime for this task:

long epochSec = localDateTime.toEpochSecond(zoneOffset);

If you only have a ZoneId then you can obtain the ZoneOffset from the ZoneId:

ZoneOffset zoneOffset = ZoneId.of("Europe/Oslo").getRules().getOffset(ldt);

But you may find conversion via ZonedDateTime simpler:

long epochSec = ldt.atZone(zoneId).toEpochSecond();

Angular: Can't find Promise, Map, Set and Iterator

I managed to fix this issue without having to add any triple-slash reference to the TS bootstrap file, change to ES6 (which brings a bunch of issues, just as @DatBoi said) update VS2015's NodeJS and/or NPM bundled builds or install typings globally.

Here's what I did in few steps:

  • added typings in the project's package.json file.
  • added a script block in the package.json file to execute/update typings after each NPM action.
  • added a typings.json file in the project's root folder containing a reference to core-js, which is one of the best shim/polyfill packages out there at the moment to fix ES5/ES6 issues.

Here's how the package.json file should look like (relevant lines only):

{
  "version": "1.0.0",
  "name": "YourProject",
  "private": true,
  "dependencies": {
    ...
    "typings": "^1.3.2",
    ...
  },
  "devDependencies": {
    ...
  },
  "scripts": {
      "postinstall": "typings install"
  }
}

And here's the typings.json file:

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160621231320"
  }
}

(Jasmine and Node are not required, but I suggest to keep them in case you'll need to in the future).

This fix is working fine with Angular2 RC1 to RC4, which is what I needed, but I think it will also fix similar issues with other ES6-enabled library packages as well.

AFAIK, I think this is the cleanest possible way of fixing it without messing up the VS2015 default settings.

For more info and a detailed analysis of the issue, I also suggest to read this post on my blog.

Fatal error: [] operator not supported for strings

Solved!

$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';

docker build with --build-arg with multiple arguments

Use --build-arg with each argument.

If you are passing two argument then add --build-arg with each argument like:

docker build \
-t essearch/ess-elasticsearch:1.7.6 \
--build-arg number_of_shards=5 \
--build-arg number_of_replicas=2 \
--no-cache .

PadLeft function in T-SQL

I created a function to do this, where you can specify the desired output character length:

CREATE FUNCTION [dbo].[udfLeadingZero]
(
        @String VARCHAR(MAX)
,       @Len INT
)
RETURNS VARCHAR(MAX)
BEGIN
    SET @String = RIGHT(REPLICATE('0',@Len)+@String,@Len)
RETURN @String
END
GO

Example results

ITSAppUsesNonExemptEncryption export compliance while internal testing?

To select from dropdown please start typing following line:

App Uses Non-Exempt Encryption

When should I use cross apply over inner join?

While most queries which employ CROSS APPLY can be rewritten using an INNER JOIN, CROSS APPLY can yield better execution plan and better performance, since it can limit the set being joined yet before the join occurs.

Stolen from Here

Remove and Replace Printed items

import sys
import time

a = 0  
for x in range (0,3):  
    a = a + 1  
    b = ("Loading" + "." * a)
    # \r prints a carriage return first, so `b` is printed on top of the previous line.
    sys.stdout.write('\r'+b)
    time.sleep(0.5)
print (a)

Note that you might have to run sys.stdout.flush() right after sys.stdout.write('\r'+b) depending on which console you are doing the printing to have the results printed when requested without any buffering.

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Here is a similar solution which I think is more efficient in building up the list of %s strings in the SQL:

Use the list_of_ids directly:

format_strings = ','.join(['%s'] * len(list_of_ids))
cursor.execute("DELETE FROM foo.bar WHERE baz IN (%s)" % format_strings,
                tuple(list_of_ids))

That way you avoid having to quote yourself, and avoid all kinds of sql injection.

Note that the data (list_of_ids) is going directly to mysql's driver, as a parameter (not in the query text) so there is no injection. You can leave any chars you want in the string, no need to remove or quote chars.

What is the use of static synchronized method in java?

In simple words a static synchronized method will lock the class instead of the object, and it will lock the class because the keyword static means: "class instead of instance".

The keyword synchronized means that only one thread can access the method at a time.
And static synchronized mean:

Only one thread can access the class at one time.

Java how to sort a Linked List?

In java8 you no longer need to use Collections.sort method as LinkedList inherits the method sort from java.util.List, so adapting Fido's answer to Java8:

    LinkedList<String>list = new LinkedList<String>();
    list.add("abc");
    list.add("Bcd");
    list.add("aAb");

    list.sort( new Comparator<String>(){
    @Override
        public int compare(String o1,String o2){
            return Collator.getInstance().compare(o1,o2);
        }
    });

References:

http://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html

http://docs.oracle.com/javase/7/docs/api/java/util/List.html

How to expand a list to function arguments in Python

That can be done with:

foo(*values)

How to change Bootstrap's global default font size?

There are several ways but since you are using just the CSS version and not the SASS or LESS versions, your best bet to use Bootstraps own customization tool:

http://getbootstrap.com/customize/

Customize whatever you want on this page and then you can download a custom build with your own font sizes and anything else you want to change.

Altering the CSS file directly (or simply adding new CSS styles that override the Bootstrap CSS) is not recommended because other Bootstrap styles' values are derived from the base font size. For example:

https://github.com/twbs/bootstrap-sass/blob/master/assets/stylesheets/bootstrap/_variables.scss#L52

You can see that the base font size is used to calculate the sizes of the h1, h2, h3 etc. If you just changed the font size in the CSS (or added your own overriding font-size) all the other values that used the font size in calculations would no longer be proportionally accurate according to Bootstrap's design.

As I said, your best bet is to just use their own Customize tool. That is exactly what it's for.

If you are using SASS or LESS, you would change the font size in the variables file before compiling.

Validate a username and password against Active Directory?

If you work on .NET 3.5 or newer, you can use the System.DirectoryServices.AccountManagement namespace and easily verify your credentials:

// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
    // validate the credentials
    bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}

It's simple, it's reliable, it's 100% C# managed code on your end - what more can you ask for? :-)

Read all about it here:

Update:

As outlined in this other SO question (and its answers), there is an issue with this call possibly returning True for old passwords of a user. Just be aware of this behavior and don't be too surprised if this happens :-) (thanks to @MikeGledhill for pointing this out!)

Add click event on div tag using javascript

Separate function to make adding event handlers much easier.

function addListener(event, obj, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(event, fn, false);   // modern browsers
    } else {
        obj.attachEvent("on"+event, fn);          // older versions of IE
    }
}

element = document.getElementsByClassName('drill_cursor')[0];

addListener('click', element, function () {
    // Do stuff
});

How to get english language word database?

You can find what you need on infochimps.org.

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

Word List - 350,000+ Simple English Words

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

Check if value is in select list with JQuery

Having html collection of selects you can check if every select has option with specific value and filter those which don't match condition:

//get select collection:
let selects = $('select')
//reduce if select hasn't at least one option with value 1
.filter(function () { return [...this.children].some(el => el.value == 1) });

Is <div style="width: ;height: ;background: "> CSS?

For example :

_x000D_
_x000D_
<div style="height:100px; width:100px; background:#000000"></div>
_x000D_
_x000D_
_x000D_

here.

you give css to div of height and width having 100px and background as black.

PS : try to avoid inline-css you can make external CSS and import in your html file.

you can refer here for CSS

hope this helps.

Simple pagination in javascript

A simple client-side pagination example where data is fetched only once at page loading.

_x000D_
_x000D_
// dummy data_x000D_
        const myarr = [{ "req_no": 1, "title": "test1" },_x000D_
        { "req_no": 2, "title": "test2" },_x000D_
        { "req_no": 3, "title": "test3" },_x000D_
        { "req_no": 4, "title": "test4" },_x000D_
        { "req_no": 5, "title": "test5" },_x000D_
        { "req_no": 6, "title": "test6" },_x000D_
        { "req_no": 7, "title": "test7" },_x000D_
        { "req_no": 8, "title": "test8" },_x000D_
        { "req_no": 9, "title": "test9" },_x000D_
        { "req_no": 10, "title": "test10" },_x000D_
        { "req_no": 11, "title": "test11" },_x000D_
        { "req_no": 12, "title": "test12" },_x000D_
        { "req_no": 13, "title": "test13" },_x000D_
        { "req_no": 14, "title": "test14" },_x000D_
        { "req_no": 15, "title": "test15" },_x000D_
        { "req_no": 16, "title": "test16" },_x000D_
        { "req_no": 17, "title": "test17" },_x000D_
        { "req_no": 18, "title": "test18" },_x000D_
        { "req_no": 19, "title": "test19" },_x000D_
        { "req_no": 20, "title": "test20" },_x000D_
        { "req_no": 21, "title": "test21" },_x000D_
        { "req_no": 22, "title": "test22" },_x000D_
        { "req_no": 23, "title": "test23" },_x000D_
        { "req_no": 24, "title": "test24" },_x000D_
        { "req_no": 25, "title": "test25" },_x000D_
        { "req_no": 26, "title": "test26" }];_x000D_
_x000D_
        // on page load collect data to load pagination as well as table_x000D_
        const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
_x000D_
        // At a time maximum allowed pages to be shown in pagination div_x000D_
        const pagination_visible_pages = 4;_x000D_
_x000D_
_x000D_
        // hide pages from pagination from beginning if more than pagination_visible_pages_x000D_
        function hide_from_beginning(element) {_x000D_
            if (element.style.display === "" || element.style.display === "block") {_x000D_
                element.style.display = "none";_x000D_
            } else {_x000D_
                hide_from_beginning(element.nextSibling);_x000D_
            }_x000D_
        }_x000D_
        _x000D_
        // hide pages from pagination ending if more than pagination_visible_pages_x000D_
        function hide_from_end(element) {_x000D_
            if (element.style.display === "" || element.style.display === "block") {_x000D_
                element.style.display = "none";_x000D_
            } else {_x000D_
                hide_from_beginning(element.previousSibling);_x000D_
            }_x000D_
        }_x000D_
        _x000D_
        // load data and style for active page_x000D_
        function active_page(element, rows, req_per_page) {_x000D_
            var current_page = document.getElementsByClassName('active');_x000D_
            var next_link = document.getElementById('next_link');_x000D_
            var prev_link = document.getElementById('prev_link');_x000D_
            var next_tab = current_page[0].nextSibling; _x000D_
            var prev_tab = current_page[0].previousSibling;_x000D_
            current_page[0].className = current_page[0].className.replace("active", "");_x000D_
            if (element === "next") {_x000D_
                if (parseInt(next_tab.text).toString() === 'NaN') {_x000D_
                    next_tab.previousSibling.className += " active";_x000D_
                    next_tab.setAttribute("onclick", "return false");_x000D_
                } else {_x000D_
                    next_tab.className += " active"_x000D_
                    render_table_rows(rows, parseInt(req_per_page), parseInt(next_tab.text));_x000D_
                    if (prev_link.getAttribute("onclick") === "return false") {_x000D_
                        prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
                    }_x000D_
                    if (next_tab.style.display === "none") {_x000D_
                        next_tab.style.display = "block";_x000D_
                        hide_from_beginning(prev_link.nextSibling)_x000D_
                    }_x000D_
                }_x000D_
            } else if (element === "prev") {_x000D_
                if (parseInt(prev_tab.text).toString() === 'NaN') {_x000D_
                    prev_tab.nextSibling.className += " active";_x000D_
                    prev_tab.setAttribute("onclick", "return false");_x000D_
                } else {_x000D_
                    prev_tab.className += " active";_x000D_
                    render_table_rows(rows, parseInt(req_per_page), parseInt(prev_tab.text));_x000D_
                    if (next_link.getAttribute("onclick") === "return false") {_x000D_
                        next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
                    }_x000D_
                    if (prev_tab.style.display === "none") {_x000D_
                        prev_tab.style.display = "block";_x000D_
                        hide_from_end(next_link.previousSibling)_x000D_
                    }_x000D_
                }_x000D_
            } else {_x000D_
                element.className += "active";_x000D_
                render_table_rows(rows, parseInt(req_per_page), parseInt(element.text));_x000D_
                if (prev_link.getAttribute("onclick") === "return false") {_x000D_
                    prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
                }_x000D_
                if (next_link.getAttribute("onclick") === "return false") {_x000D_
                    next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
_x000D_
        // Render the table's row in table request-table_x000D_
        function render_table_rows(rows, req_per_page, page_no) {_x000D_
            const response = JSON.parse(window.atob(rows));_x000D_
            const resp = response.slice(req_per_page * (page_no - 1), req_per_page * page_no)_x000D_
            $('#request-table').empty()_x000D_
            $('#request-table').append('<tr><th>Index</th><th>Request No</th><th>Title</th></tr>');_x000D_
            resp.forEach(function (element, index) {_x000D_
                if (Object.keys(element).length > 0) {_x000D_
                    const { req_no, title } = element;_x000D_
                    const td = `<tr><td>${++index}</td><td>${req_no}</td><td>${title}</td></tr>`;_x000D_
                    $('#request-table').append(td)_x000D_
                }_x000D_
            });_x000D_
        }_x000D_
_x000D_
        // Pagination logic implementation_x000D_
        function pagination(data, myarr) {_x000D_
            const all_data = window.btoa(JSON.stringify(myarr));_x000D_
            $(".pagination").empty();_x000D_
            if (data.req_per_page !== 'ALL') {_x000D_
                let pager = `<a href="#" id="prev_link" onclick=active_page('prev',\"${all_data}\",${data.req_per_page})>&laquo;</a>` +_x000D_
                    `<a href="#" class="active" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>1</a>`;_x000D_
                const total_page = Math.ceil(parseInt(myarr.length) / parseInt(data.req_per_page));_x000D_
                if (total_page < pagination_visible_pages) {_x000D_
                    render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
                    for (let num = 2; num <= total_page; num++) {_x000D_
                        pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
                    }_x000D_
                } else {_x000D_
                    render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
                    for (let num = 2; num <= pagination_visible_pages; num++) {_x000D_
                        pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
                    }_x000D_
                    for (let num = pagination_visible_pages + 1; num <= total_page; num++) {_x000D_
                        pager += `<a href="#" style="display:none;" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
                    }_x000D_
                }_x000D_
                pager += `<a href="#" id="next_link" onclick=active_page('next',\"${all_data}\",${data.req_per_page})>&raquo;</a>`;_x000D_
                $(".pagination").append(pager);_x000D_
            } else {_x000D_
                render_table_rows(all_data, myarr.length, 1);_x000D_
            }_x000D_
        }_x000D_
_x000D_
        //calling pagination function_x000D_
        pagination(data, myarr);_x000D_
_x000D_
_x000D_
        // trigger when requests per page dropdown changes_x000D_
        function filter_requests() {_x000D_
            const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
            pagination(data, myarr);_x000D_
        }
_x000D_
.box {_x000D_
 float: left;_x000D_
 padding: 50px 0px;_x000D_
}_x000D_
_x000D_
.clearfix::after {_x000D_
 clear: both;_x000D_
 display: table;_x000D_
}_x000D_
_x000D_
.options {_x000D_
 margin: 5px 0px 0px 0px;_x000D_
 float: left;_x000D_
}_x000D_
_x000D_
.pagination {_x000D_
 float: right;_x000D_
}_x000D_
_x000D_
.pagination a {_x000D_
 color: black;_x000D_
 float: left;_x000D_
 padding: 8px 16px;_x000D_
 text-decoration: none;_x000D_
 transition: background-color .3s;_x000D_
 border: 1px solid #ddd;_x000D_
 margin: 0 4px;_x000D_
}_x000D_
_x000D_
.pagination a.active {_x000D_
 background-color: #4CAF50;_x000D_
 color: white;_x000D_
 border: 1px solid #4CAF50;_x000D_
}_x000D_
_x000D_
.pagination a:hover:not(.active) {_x000D_
 background-color: #ddd;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>_x000D_
    <table id="request-table">_x000D_
   </table>_x000D_
</div>_x000D_
_x000D_
<div class="clearfix">_x000D_
 <div class="box options">_x000D_
  <label>Requests Per Page: </label>_x000D_
      <select id="req_per_page" onchange="filter_requests()">_x000D_
   <option>5</option>_x000D_
   <option>10</option>_x000D_
   <option>ALL</option>_x000D_
  </select>_x000D_
 </div>_x000D_
 <div class="box pagination">_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

Try this:

<uses-permission android:name="android.permission.INTERNET"/>

And your activity namesmust be like this with capital letters:

<activity android:name=".Addfriend"/>
    <activity android:name=".UpdateDetails"/>
    <activity android:name=".Details"/>
    <activity android:name=".Updateimage"/>

Read remote file with node.js (http.get)

http.get(options).on('response', function (response) {
    var body = '';
    var i = 0;
    response.on('data', function (chunk) {
        i++;
        body += chunk;
        console.log('BODY Part: ' + i);
    });
    response.on('end', function () {

        console.log(body);
        console.log('Finished');
    });
});

Changes to this, which works. Any comments?

How to open existing project in Eclipse

File > Import > General > Existing Projects into workspace. Select the root folder that has your project(s). It lists all the projects available in the selected folder. Select the ones you would like to import and click Finish. This should work just fine.

Is there a conditional ternary operator in VB.NET?

Just for the record, here is the difference between If and IIf:

IIf(condition, true-part, false-part):

  • This is the old VB6/VBA Function
  • The function always returns an Object type, so if you want to use the methods or properties of the chosen object, you have to re-cast it with DirectCast or CType or the Convert.* Functions to its original type
  • Because of this, if true-part and false-part are of different types there is no matter, the result is just an object anyway

If(condition, true-part, false-part):

  • This is the new VB.NET Function
  • The result type is the type of the chosen part, true-part or false-part
  • This doesn't work, if Strict Mode is switched on and the two parts are of different types. In Strict Mode they have to be of the same type, otherwise you will get an Exception
  • If you really need to have two parts of different types, switch off Strict Mode (or use IIf)
  • I didn't try so far if Strict Mode allows objects of different type but inherited from the same base or implementing the same Interface. The Microsoft documentation isn't quite helpful about this issue. Maybe somebody here knows it.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Pass Arraylist as argument to function

Define it as

<return type> AnalyzeArray(ArrayList<Integer> list) {