Programs & Examples On #Widestring

Object cannot be cast from DBNull to other types

For others that arrive on this page from google:

DataRow also has a function .IsNull("ColumnName")

    public DateTime? TestDt; 
    public Parse(DataRow row)
    {
        if (!row.IsNull("TEST_DT"))
            TestDt = Convert.ToDateTime(row["TEST_DT"]);
    }

How to select multiple files with <input type="file">?

You can do it now with HTML5

In essence you use the multiple attribute on the file input.

<input type='file' multiple>

Validate select box

I don't know how was the plugin the time the question was asked (2009), but I faced the same problem today and solved it this way:

  1. Give your select tag a name attribute. For example in this case

    <select name="myselect">

  2. Instead of working with the attribute value="default" in the tag option, disable the default option as suggested by Jeremy Visser or set value=""

    <option disabled="disabled">Choose...</option>

    or

    <option value="">Choose...</option>

  3. Set the plugin validation rule

    $( "#YOUR_FORM_ID" ).validate({ rules: { myselect: { required: true } } });

    or

    <select name="myselect" class="required">

Obs: redsquare's solution works only if you have just one select in your form. If you want his solution to work with more than one select add a name attribute to your select.

Hope it helps! :)

Implicit function declarations in C

To complete the picture, since -Werror might considered too "invasive",
for gcc (and llvm) a more precise solution is to transform just this warning in an error, using the option:

-Werror=implicit-function-declaration

See Make one gcc warning an error?

Regarding general use of -Werror: Of course, having warningless code is recommendable, but in some stage of development it might slow down the prototyping.

vertical-align image in div

you don't need define positioning when you need vertical align center for inline and block elements you can take mentioned below idea:-

inline-elements :- <img style="vertical-align:middle" ...>
                   <span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>  

block-elements :- <td style="vertical-align:middle"> ... </td>
                  <div style="display:table-cell; vertical-align:middle"> ... </div>

see the demo:- http://jsfiddle.net/Ewfkk/2/

What does "to stub" mean in programming?

Layman's terms, it's dummy data (or fake data, test data...etc.) that you can use to test or develop your code against until you (or the other party) is ready to present/receive real data. It's a programmer's "Lorem Ipsum".

Employee database not ready? Make up a simple one with Jane Doe, John Doe...etc. API not ready? Make up a fake one by creating a static .json file containing fake data.

The cast to value type 'Int32' failed because the materialized value is null

I see that this question is already answered. But if you want it to be split into two statements, following may be considered.

var credits = from u in context.User
              join ch in context.CreditHistory 
                  on u.ID equals ch.UserID                                        
              where u.ID == userID
              select ch;

var creditSum= credits.Sum(x => (int?)x.Amount) ?? 0;

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

What worked for me was to pass the activity instead of the context.

I wanted a custom layout for my dialog, but to keep my code separate, I created it in a separate Class, else I would have to copy and paste that chunk of code into every activity where I want to use the dialog.

Solution explains my situation but it gives the core solution:

  1. As I was using a ViewAdapter I initialised the adapter with the Activity (not context ex. ->[kotlin] activity: Activity) as a parameter -> ex. [kotlin] this@MainActivity
  2. Then I passed that parameter to the Viewholder
  3. After which passing it again to the class that will inflate the Dialog.

Use the activity[optional name]: Activity[mandatory type] every where until it gets to the dialog you want to inflate

Its a lot of passing around, but it does make more sense over copy and pasting the same code everywhere

Postgres - Transpose Rows to Columns

If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot

How to call a method after bean initialization is complete?

There are three different approaches to consider, as described in the reference

Use init-method attribute

Pros:

  • Does not require bean to implement an interface.

Cons:

  • No immediate indication this method is required after construction to ensure the bean is correctly configured.

Implement InitializingBean

Pros:

  • No need to specify init-method, or turn on component scanning / annotation processing.
  • Appropriate for beans supplied with a library, where we don't want the application using this library to concern itself with bean lifecycle.

Cons:

  • More invasive than the init-method approach.

Use JSR-250 @PostConstruct lifecyle annotation

Pros:

  • Useful when using component scanning to autodetect beans.
  • Makes it clear that a specific method is to be used for initialisation. Intent is closer to the code.

Cons:

  • Initialisation no longer centrally specified in configuration.
  • You must remember to turn on annotation processing (which can sometimes be forgotten)

Array to String PHP?

json_encode($data) //converts an array to JSON string
json_decode($jsonString) //converts json string to php array

WHY JSON : You can use it with most of the programming languages, string created by serialize() function of php is readable in PHP only, and you will not like to store such things in your databases specially if database is shared among applications written in different programming languages

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

What is the advantage of using REST instead of non-REST HTTP?

IMHO the biggest advantage that REST enables is that of reducing client/server coupling. It is much easier to evolve a REST interface over time without breaking existing clients.

Using Excel OleDb to get sheet names IN SHEET ORDER

Can you not just loop through the sheets from 0 to Count of names -1? that way you should get them in the correct order.

Edit

I noticed through the comments that there are a lot of concerns about using the Interop classes to retrieve the sheet names. Therefore here is an example using OLEDB to retrieve them:

/// <summary>
/// This method retrieves the excel sheet names from 
/// an excel workbook.
/// </summary>
/// <param name="excelFile">The excel file.</param>
/// <returns>String[]</returns>
private String[] GetExcelSheetNames(string excelFile)
{
    OleDbConnection objConn = null;
    System.Data.DataTable dt = null;

    try
    {
        // Connection String. Change the excel file to the file you
        // will search.
        String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
          "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
        // Create connection object by using the preceding connection string.
        objConn = new OleDbConnection(connString);
        // Open connection with the database.
        objConn.Open();
        // Get the data table containg the schema guid.
        dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        if(dt == null)
        {
           return null;
        }

        String[] excelSheets = new String[dt.Rows.Count];
        int i = 0;

        // Add the sheet name to the string array.
        foreach(DataRow row in dt.Rows)
        {
           excelSheets[i] = row["TABLE_NAME"].ToString();
           i++;
        }

        // Loop through all of the sheets if you want too...
        for(int j=0; j < excelSheets.Length; j++)
        {
            // Query each excel sheet.
        }

        return excelSheets;
   }
   catch(Exception ex)
   {
       return null;
   }
   finally
   {
      // Clean up.
      if(objConn != null)
      {
          objConn.Close();
          objConn.Dispose();
      }
      if(dt != null)
      {
          dt.Dispose();
      }
   }
}

Extracted from Article on the CodeProject.

VB.NET Empty String Array

The array you created by Dim s(0) As String IS NOT EMPTY

In VB.Net, the subscript you use in the array is index of the last element. VB.Net by default starts indexing at 0, so you have an array that already has one element.

You should instead try using System.Collections.Specialized.StringCollection or (even better) System.Collections.Generic.List(Of String). They amount to pretty much the same thing as an array of string, except they're loads better for adding and removing items. And let's be honest: you'll rarely create an empty string array without wanting to add at least one element to it.

If you really want an empty string array, declare it like this:

Dim s As String()

or

Dim t() As String

What is an idiomatic way of representing enums in Go?

For a use case like this, it may be useful to use a string constant so it can be marshaled into a JSON string. In the following example, []Base{A,C,G,T} would get marshaled to ["adenine","cytosine","guanine","thymine"].

type Base string

const (
    A Base = "adenine"
    C      = "cytosine"
    G      = "guanine"
    T      = "thymine"
)

When using iota, the values get marshaled into integers. In the following example, []Base{A,C,G,T} would get marshaled to [0,1,2,3].

type Base int

const (
    A Base = iota
    C
    G
    T
)

Here's an example comparing both approaches:

https://play.golang.org/p/VvkcWvv-Tvj

Undefined behavior and sequence points

C++98 and C++03

This answer is for the older versions of the C++ standard. The C++11 and C++14 versions of the standard do not formally contain 'sequence points'; operations are 'sequenced before' or 'unsequenced' or 'indeterminately sequenced' instead. The net effect is essentially the same, but the terminology is different.


Disclaimer : Okay. This answer is a bit long. So have patience while reading it. If you already know these things, reading them again won't make you crazy.

Pre-requisites : An elementary knowledge of C++ Standard


What are Sequence Points?

The Standard says

At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. (§1.9/7)

Side effects? What are side effects?

Evaluation of an expression produces something and if in addition there is a change in the state of the execution environment it is said that the expression (its evaluation) has some side effect(s).

For example:

int x = y++; //where y is also an int

In addition to the initialization operation the value of y gets changed due to the side effect of ++ operator.

So far so good. Moving on to sequence points. An alternation definition of seq-points given by the comp.lang.c author Steve Summit:

Sequence point is a point in time at which the dust has settled and all side effects which have been seen so far are guaranteed to be complete.


What are the common sequence points listed in the C++ Standard ?

Those are:

  • at the end of the evaluation of full expression (§1.9/16) (A full-expression is an expression that is not a subexpression of another expression.)1

    Example :

    int a = 5; // ; is a sequence point here
    
  • in the evaluation of each of the following expressions after the evaluation of the first expression (§1.9/18) 2

    • a && b (§5.14)
    • a || b (§5.15)
    • a ? b : c (§5.16)
    • a , b (§5.18) (here a , b is a comma operator; in func(a,a++) , is not a comma operator, it's merely a separator between the arguments a and a++. Thus the behaviour is undefined in that case (if a is considered to be a primitive type))
  • at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body (§1.9/17).

1 : Note : the evaluation of a full-expression can include the evaluation of subexpressions that are not lexically part of the full-expression. For example, subexpressions involved in evaluating default argument expressions (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument

2 : The operators indicated are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation and the operands form an argument list, without an implied sequence point between them.


What is Undefined Behaviour?

The Standard defines Undefined Behaviour in Section §1.3.12 as

behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements 3.

Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior.

3 : permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or with- out the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant.


What is the relation between Undefined Behaviour and Sequence Points?

Before I get into that you must know the difference(s) between Undefined Behaviour, Unspecified Behaviour and Implementation Defined Behaviour.

You must also know that the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.

For example:

int x = 5, y = 6;

int z = x++ + y++; //it is unspecified whether x++ or y++ will be evaluated first.

Another example here.


Now the Standard in §5/4 says

  • 1) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

What does it mean?

Informally it means that between two sequence points a variable must not be modified more than once. In an expression statement, the next sequence point is usually at the terminating semicolon, and the previous sequence point is at the end of the previous statement. An expression may also contain intermediate sequence points.

From the above sentence the following expressions invoke Undefined Behaviour:

i++ * ++i;   // UB, i is modified more than once btw two SPs
i = ++i;     // UB, same as above
++i = 2;     // UB, same as above
i = ++i + 1; // UB, same as above
++++++i;     // UB, parsed as (++(++(++i)))

i = (i, ++i, ++i); // UB, there's no SP between `++i` (right most) and assignment to `i` (`i` is modified more than once btw two SPs)

But the following expressions are fine:

i = (i, ++i, 1) + 1; // well defined (AFAIK)
i = (++i, i++, i);   // well defined 
int j = i;
j = (++i, i++, j*i); // well defined

  • 2) Furthermore, the prior value shall be accessed only to determine the value to be stored.

What does it mean? It means if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.

For example in i = i + 1 all the access of i (in L.H.S and in R.H.S) are directly involved in computation of the value to be written. So it is fine.

This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification.

Example 1:

std::printf("%d %d", i,++i); // invokes Undefined Behaviour because of Rule no 2

Example 2:

a[i] = i++ // or a[++i] = i or a[i++] = ++i etc

is disallowed because one of the accesses of i (the one in a[i]) has nothing to do with the value which ends up being stored in i (which happens over in i++), and so there's no good way to define--either for our understanding or the compiler's--whether the access should take place before or after the incremented value is stored. So the behaviour is undefined.

Example 3 :

int x = i + i++ ;// Similar to above

Follow up answer for C++11 here.

Get current date in DD-Mon-YYY format in JavaScript/Jquery

//convert DateTime result in jquery mvc 5 using entity fremwork 

const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];


function DateAndTime(date) {

    var value = new Date
        (
        parseInt(date.replace(/(^.*\()|([+-].*$)/g, ''))
    ); 
    var dat = value.getDate() +
        "-" +
        monthNames[value.getMonth()] +
        "-" +
        value.getFullYear();

    var hours = value.getHours();
    var minutes = value.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = hours + ':' + minutes + ' ' + ampm;
    return { Date: dat, Time: strTime };
}
// var getdate = DateAndTime(StartDate);
//var Date = getdate.Date;//here get date
//var time = getdate.Time;//here get Time
//alert(Date)

how to set default culture info for entire c# application

With 4.0, you will need to manage this yourself by setting the culture for each thread as Alexei describes. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.

Adding a rule in iptables in debian to open a new port

About your command line:

root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
  • You are already authenticated as root so sudo is redundant there.

  • You are missing the -j or --jump just before the ACCEPT parameter (just tought that was a typo and you are inserting it correctly).

About yout question:

If you are inserting the iptables rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.

If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:

check your vmachine network settings and:

  • if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.

  • if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.

  • if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.

Hope this helps.

How do I check if there are duplicates in a flat list?

If you are fond of functional programming style, here is a useful function, self-documented and tested code using doctest.

def decompose(a_list):
    """Turns a list into a set of all elements and a set of duplicated elements.

    Returns a pair of sets. The first one contains elements
    that are found at least once in the list. The second one
    contains elements that appear more than once.

    >>> decompose([1,2,3,5,3,2,6])
    (set([1, 2, 3, 5, 6]), set([2, 3]))
    """
    return reduce(
        lambda (u, d), o : (u.union([o]), d.union(u.intersection([o]))),
        a_list,
        (set(), set()))

if __name__ == "__main__":
    import doctest
    doctest.testmod()

From there you can test unicity by checking whether the second element of the returned pair is empty:

def is_set(l):
    """Test if there is no duplicate element in l.

    >>> is_set([1,2,3])
    True
    >>> is_set([1,2,1])
    False
    >>> is_set([])
    True
    """
    return not decompose(l)[1]

Note that this is not efficient since you are explicitly constructing the decomposition. But along the line of using reduce, you can come up to something equivalent (but slightly less efficient) to answer 5:

def is_set(l):
    try:
        def func(s, o):
            if o in s:
                raise Exception
            return s.union([o])
        reduce(func, l, set())
        return True
    except:
        return False

How do I grant myself admin access to a local SQL Server instance?

I adopted a SQL 2012 database where I was not a sysadmin but was an administrator on the machine. I used SSMS with "Run as Administrator", added my NT account as a SQL login and set the server role to sysadmin. No problem.

How do I edit $PATH (.bash_profile) on OSX?

Determine which shell you're using by typing echo $SHELL in Terminal.

Then open/create correct rc file. For Bash it's $HOME/.bash_profile or $HOME/.bashrc. For Z shell it's $HOME/.zshrc.

Add this line to the file end:

export PATH="$PATH:/your/new/path"

To verify, refresh variables by restarting Terminal or typing source $HOME/.<rc file> and then do echo $PATH

Xcode/Simulator: How to run older iOS version?

Open xcode and in the top menu go to xcode > Preferences > Downloads and you will be given the option to download old sdks to use with xcode. You can also download command line tools and Device Debugging Support.

enter image description here

Store query result in a variable using in PL/pgSQL

I think you're looking for SELECT INTO:

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

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

C++ preprocessor __VA_ARGS__ number of arguments

For convenience, here's an implementation that works for 0 to 70 arguments, and works in Visual Studio, GCC, and Clang. I believe it will work in Visual Studio 2010 and later, but have only tested it in VS2013.

#ifdef _MSC_VER // Microsoft compilers

#   define GET_ARG_COUNT(...)  INTERNAL_EXPAND_ARGS_PRIVATE(INTERNAL_ARGS_AUGMENTER(__VA_ARGS__))

#   define INTERNAL_ARGS_AUGMENTER(...) unused, __VA_ARGS__
#   define INTERNAL_EXPAND(x) x
#   define INTERNAL_EXPAND_ARGS_PRIVATE(...) INTERNAL_EXPAND(INTERNAL_GET_ARG_COUNT_PRIVATE(__VA_ARGS__, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
#   define INTERNAL_GET_ARG_COUNT_PRIVATE(_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, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, count, ...) count

#else // Non-Microsoft compilers

#   define GET_ARG_COUNT(...) INTERNAL_GET_ARG_COUNT_PRIVATE(0, ## __VA_ARGS__, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#   define INTERNAL_GET_ARG_COUNT_PRIVATE(_0, _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, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, count, ...) count

#endif

static_assert(GET_ARG_COUNT() == 0, "GET_ARG_COUNT() failed for 0 arguments");
static_assert(GET_ARG_COUNT(1) == 1, "GET_ARG_COUNT() failed for 1 argument");
static_assert(GET_ARG_COUNT(1,2) == 2, "GET_ARG_COUNT() failed for 2 arguments");
static_assert(GET_ARG_COUNT(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, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70) == 70, "GET_ARG_COUNT() failed for 70 arguments");

Group dataframe and get sum AND count?

If you have lots of columns and only one is different you could do:

In[1]: grouper = df.groupby('Company Name')
In[2]: res = grouper.count()
In[3]: res['Amount'] = grouper.Amount.sum()
In[4]: res
Out[4]:
                      Organisation Name   Amount
Company Name                                   
Vifor Pharma UK Ltd                  5  4207.93

Note you can then rename the Organisation Name column as you wish.

Pandas: Looking up the list of sheets in an excel file

I have tried xlrd, pandas, openpyxl and other such libraries and all of them seem to take exponential time as the file size increase as it reads the entire file. The other solutions mentioned above where they used 'on_demand' did not work for me. If you just want to get the sheet names initially, the following function works for xlsx files.

def get_sheet_details(file_path):
    sheets = []
    file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
    # Make a temporary directory with the file name
    directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
    os.mkdir(directory_to_extract_to)

    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(file_path, 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()

    # Open the workbook.xml which is very light and only has meta data, get sheets from it
    path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
    with open(path_to_workbook, 'r') as f:
        xml = f.read()
        dictionary = xmltodict.parse(xml)
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_details = {
                'id': sheet['@sheetId'],
                'name': sheet['@name']
            }
            sheets.append(sheet_details)

    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets

Since all xlsx are basically zipped files, we extract the underlying xml data and read sheet names from the workbook directly which takes a fraction of a second as compared to the library functions.

Benchmarking: (On a 6mb xlsx file with 4 sheets)
Pandas, xlrd: 12 seconds
openpyxl: 24 seconds
Proposed method: 0.4 seconds

Since my requirement was just reading the sheet names, the unnecessary overhead of reading the entire time was bugging me so I took this route instead.

How to get the previous page URL using JavaScript?

You can use the following to get the previous URL.

var oldURL = document.referrer;
alert(oldURL);

Prevent PDF file from downloading and printing

I suggest to modify pdf.js: remove the download button, convert pdf (at backend part) to some intermediate format of pdf.js and put watermark also at server side.

Difference between $(window).load() and $(document).ready() functions

$(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded like CSS, images and frames. One best example is if we want to get the actual image size or to get the details of anything we use it.

$(document).ready() indicates that code in it need to be executed once the DOM got loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.

<script type = "text/javascript">
    //$(window).load was deprecated in 1.8, and removed in jquery 3.0
    // $(window).load(function() {
    //     alert("$(window).load fired");
    // });

    $(document).ready(function() {
        alert("$(document).ready fired");
    });
</script>

$(window).load fired after the $(document).ready().

$(window).load was deprecated in 1.8, and removed in jquery 3.0

Clear text input on click with AngularJS

Try this,

 this.searchAll = element(by.xpath('path here'));
 this.searchAll.sendKeys('');

AndroidStudio gradle proxy

In my case I am behind a proxy with dynamic settings.

I had to download the settings script by picking the script address from internet settings at
Chrome > Settings > Show Advanced Settings > Change proxy Settings > Internet Properties > Connections > LAN Settings > Use automatic configuration script > Address

Opening this URL in a browser downloads a PAC file which I opened in a text editor

  • Look for a PROXY string, it should contain a hostname and port
  • Copy values into gradle.properties

systemProp.https.proxyHost=blabla.domain.com
systemProp.https.proxyPort=8081

  • I didn't have to specify a user not password.

SQL Server 2008- Get table constraints

Here's a script to get foreign keys:

    SELECT TOP(150)
       t.[name] AS [Table],
       cols.[name] AS [Column],
       t2.[name] AS [Referenced Table],
       c2.[name] AS [Referenced Column],
       constr.[name] AS [Constraint]
  FROM sys.tables t
 INNER JOIN sys.foreign_keys constr ON constr.parent_object_id = t.object_id
 INNER JOIN sys.tables t2 ON t2.object_id = constr.referenced_object_id
 INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = constr.object_id
 INNER JOIN sys.columns cols ON cols.object_id = fkc.parent_object_id AND cols.column_id = fkc.parent_column_id
 INNER JOIN sys.columns c2 ON c2.object_id = fkc.referenced_object_id AND c2.column_id = fkc.referenced_column_id
 --WHERE t.[name] IN ('?', '?', ...)
 ORDER BY t.[Name], cols.[name]

How to declare global variables in Android?

Create this subclass

public class MyApp extends Application {
  String foo;
}

In the AndroidManifest.xml add android:name

Example

<application android:name=".MyApp" 
       android:icon="@drawable/icon" 
       android:label="@string/app_name">

Twitter Bootstrap vs jQuery UI?

We have used both and we like Bootstrap for its simplicity and the pace at which it's being developed and enhanced. The problem with jQuery UI is that it's moving at a snail's pace. It's taking years to roll out common features like Menubar, Tree control and DataGrid which are in planning/development stage for ever. We waited waited waited and finally given up and used other libraries like ExtJS for our product http://dblite.com.

Bootstrap has come up with quite a comprehensive set of features in a very short period of time and I am sure it will outpace jQuery UI pretty soon.

So I see no point in using something that will eventually be outdated...

Validate phone number with JavaScript

Just wanted to add a solution specifically for selecting non-local phone numbers(800 and 900 types).

(\+?1[-.(\s]?|\()?(900|8(0|4|5|6|7|8)\3+)[)\s]?[-.\s]?\d{3}[-.\s]?\d{4}

How to automatically update an application without ClickOnce?

This is the code to update the file but not to install This program is made through dos for copying files to the latest date and run your program automatically. may help you

open notepad and save file below with ext .bat

xcopy \\IP address\folder_share_name\*.* /s /y /d /q  
start "label" /b "youraplicationname.exe"

Why isn't my Pandas 'apply' function referencing multiple columns working?

If you just want to compute (column a) % (column b), you don't need apply, just do it directly:

In [7]: df['a'] % df['c']                                                                                                                                                        
Out[7]: 
0   -1.132022                                                                                                                                                                    
1   -0.939493                                                                                                                                                                    
2    0.201931                                                                                                                                                                    
3    0.511374                                                                                                                                                                    
4   -0.694647                                                                                                                                                                    
5   -0.023486                                                                                                                                                                    
Name: a

How to remove numbers from string using Regex.Replace?

Try the following:

var output = Regex.Replace(input, @"[\d-]", string.Empty);

The \d identifier simply matches any digit character.

SoapFault exception: Could not connect to host

A misconfigured service leaves the default namespace with tempuri.org

This means the connection to the wsdl will work, but the function call will fail.

Stacktrace:

SoapClient->__doRequest('http://example.com...', 'http://tempuri.org....', 2, 0)

To remediate this, you must explicitly set the location using __setLocation()

$this->soapClient = new \SoapClient(WS_URL);
$this->soapClient->__setLocation(WS_URL);

How I can print to stderr in C?

The syntax is almost the same as printf. With printf you give the string format and its contents ie:

printf("my %s has %d chars\n", "string format", 30);

With fprintf it is the same, except now you are also specifying the place to print to:

File *myFile;
...
fprintf( myFile, "my %s has %d chars\n", "string format", 30);

Or in your case:

fprintf( stderr, "my %s has %d chars\n", "string format", 30);

How do you extract IP addresses from files using a regex in a linux shell?

You can use some shell helper I made: https://github.com/philpraxis/ipextract

included them here for convenience:

#!/bin/sh
ipextract () 
{ 
egrep --only-matching -E  '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' 
}

ipextractnet ()
{ 
egrep --only-matching -E  '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/[[:digit:]]+' 
}

ipextracttcp ()
{ 
egrep --only-matching -E  '[[:digit:]]+/tcp' 
}

ipextractudp ()
{ 
egrep --only-matching -E  '[[:digit:]]+/udp' 
}

ipextractsctp ()
{ 
egrep --only-matching -E  '[[:digit:]]+/sctp' 
}

ipextractfqdn ()
{ 
egrep --only-matching -E  '[a-zA-Z0-9]+[a-zA-Z0-9\-\.]*\.[a-zA-Z]{2,}' 
}

Load it / source it (when stored in ipextract file) from shell:

$ . ipextract

Use them:

$ ipextract < /etc/hosts
127.0.0.1
255.255.255.255
$

For some example of real use:

ipextractfqdn < /var/log/snort/alert | sort -u
dmesg | ipextractudp

Android emulator failed to allocate memory 8

Update: Starting with Android SDK Manager version 21, the solution is to edit C:\Users\<user>\.android\avd\<avd-profile-name>.avd\config.ini and change the value

hw.ramSize=1024 

to

hw.ramSize=1024MB

Android 4.2 API 17

The emulator is really slow, hope they will release the intel images soon use the new API17 Intel x86 images if you want to change it .. (HAXM, Configuration)


Earlier Android SDK Manager releases:

Had the same problem with the built-in WXGA800 skin. I got it working by editing the virtual device setup to:

  • Target 4.0.3 API 15 / 4.1.0 API 16
  • SD-card 300MiB
  • Resolution 1280 x 800 (set manually -not the built-in ones)
  • Device ram size 1024MB (with MB added to the number)
  • Abstracted LCD 160

Here my tablet config for 4.1.0 API 16 C:\Users\<user>\.android\avd\<avd-profile-name>.avd\config.ini

hw.lcd.density=160
sdcard.size=300M
skin.path=1280x800
skin.name=1280x800
hw.cpu.arch=arm
abi.type=armeabi-v7a
hw.cpu.model=cortex-a8
vm.heapSize=48
hw.ramSize=1024MB
image.sysdir.1=system-images\android-16\armeabi-v7a\

This config shows the software keys too Screenshot Android 4.1 emulator 1280x800@160

Add a column to existing table and uniquely number them on MS SQL Server

And the Postgres equivalent (second line is mandatory only if you want "id" to be a key):

ALTER TABLE tableName ADD id SERIAL;
ALTER TABLE tableName ADD PRIMARY KEY (id);

How to edit default dark theme for Visual Studio Code?

As far as the themes, VS Code is every bit as editable as Sublime. You can edit any of the default themes that come with VS code. You just have to know where to find the theme files.

Side note: I love the Monokai theme. However, all I wanted to change about it was the background. I don't like the dark grayish background. Instead, I think the contrast is WAY better with a solid black background. The code pops out much more.

Anyways, I hunted for the theme file and found it (in windows) at:

c:\Program Files (x86)\Microsoft VS Code\resources\app\extensions\theme-monokai\themes\

In that folder I found the Monokai.tmTheme file and modified the first background key as follows:

<key>background</key>
<string>#000000</string>

There are a few 'background' key in the theme file, make sure you edit the correct one. The one I edited was at the very top. Line 12 I think.

Get current clipboard content?

window.clipboardData.getData('Text') will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.

How to compare 2 dataTables

The OP, MAW74656, originally posted this answer in the question body in response to the accepted answer, as explained in this comment:

I used this and wrote a public method to call the code and return the boolean.

The OP's answer:

Code Used:

public bool tablesAreTheSame(DataTable table1, DataTable table2)
{
    DataTable dt;
    dt = getDifferentRecords(table1, table2);

    if (dt.Rows.Count == 0)
        return true;
    else
        return false;
}

//Found at http://canlu.blogspot.com/2009/05/how-to-compare-two-datatables-in-adonet.html
private DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)
{
    //Create Empty Table     
    DataTable ResultDataTable = new DataTable("ResultDataTable");

    //use a Dataset to make use of a DataRelation object     
    using (DataSet ds = new DataSet())
    {
        //Add tables     
        ds.Tables.AddRange(new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() });

        //Get Columns for DataRelation     
        DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count];
        for (int i = 0; i < firstColumns.Length; i++)
        {
            firstColumns[i] = ds.Tables[0].Columns[i];
        }

        DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count];
        for (int i = 0; i < secondColumns.Length; i++)
        {
            secondColumns[i] = ds.Tables[1].Columns[i];
        }

        //Create DataRelation     
        DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
        ds.Relations.Add(r1);

        DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
        ds.Relations.Add(r2);

        //Create columns for return table     
        for (int i = 0; i < FirstDataTable.Columns.Count; i++)
        {
            ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType);
        }

        //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.     
        ResultDataTable.BeginLoadData();
        foreach (DataRow parentrow in ds.Tables[0].Rows)
        {
            DataRow[] childrows = parentrow.GetChildRows(r1);
            if (childrows == null || childrows.Length == 0)
                ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
        }

        //If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.     
        foreach (DataRow parentrow in ds.Tables[1].Rows)
        {
            DataRow[] childrows = parentrow.GetChildRows(r2);
            if (childrows == null || childrows.Length == 0)
                ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
        }
        ResultDataTable.EndLoadData();
    }

    return ResultDataTable;
}

Linux Command History with date and time

In case you are using zsh you can use for example the -E or -i switch:

history -E

If you do a man zshoptions or man zshbuiltins you can find out more information about these switches as well as other info related to history:

Also when listing,
 -d     prints timestamps for each event
 -f     prints full time-date stamps in the US `MM/DD/YY hh:mm' format
 -E     prints full time-date stamps in the European `dd.mm.yyyy hh:mm' format
 -i     prints full time-date stamps in ISO8601 `yyyy-mm-dd hh:mm' format
 -t fmt prints time and date stamps in the given format; fmt is formatted with the strftime function with the zsh extensions  described  for  the  %D{string} prompt format in the section EXPANSION OF PROMPT SEQUENCES in zshmisc(1).  The resulting formatted string must be no more than 256 characters or will not be printed
 -D     prints elapsed times; may be combined with one of the options above

Creating a file only if it doesn't exist in Node.js

Todo this in a single system call you can use the fs-extra npm module. After this the file will have been created as well as the directory it is to be placed in.

const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFile(file, err => {
    console.log(err) // => null
});

Another way is to use ensureFileSync which will do the same thing but synchronous.

const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFileSync(file)

Is try-catch like error handling possible in ASP Classic?

the statement On Error Resume Next should be placed on top of what we want to validate.

  On Error Resume Next
  'Your code logic is here

Then end with statement like:

  If Err.Number <> 0 then

  'Your error message goes here'

  End if

How to export query result to csv in Oracle SQL Developer?

CSV Export does not escape your data. Watch out for strings which end in \ because the resulting \" will look like an escaped " and not a \. Then you have the wrong number of " and your entire row is broken.

Powershell send-mailmessage - email to multiple recipients

to send a .NET / C# powershell eMail use such a structure:

for best behaviour create a class with a method like this

 using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddCommand("Send-MailMessage")
                                  .AddParameter("SMTPServer", "smtp.xxx.com")
                                  .AddParameter("From", "[email protected]")
                                  .AddParameter("Subject", "xxx Notification")
                                  .AddParameter("Body", body_msg)
                                  .AddParameter("BodyAsHtml")
                                  .AddParameter("To", recipients);

                // invoke execution on the pipeline (ignore output) --> nothing will be displayed
                PowerShellInstance.Invoke();
            }              

Whereby these instance is called in a function like:

        public void sendEMailPowerShell(string body_msg, string[] recipients)

Never forget to use a string array for the recepients, which can be look like this:

string[] reportRecipient = { 
                        "xxx <[email protected]>",
                        "xxx <[email protected]>"
                        };

body_msg

this message can be overgiven as parameter to the method itself, HTML coding enabled!!

recipients

never forget to use a string array in case of multiple recipients, otherwise only the last address in the string will be used!!!

calling the function can look like this:

        mail reportMail = new mail(); //instantiate from class
        reportMail.sendEMailPowerShell(reportMessage, reportRecipient); //msg + email addresses

ThumbUp

What is the relative performance difference of if/else versus switch statement in Java?

I remember reading that there are 2 kinds of Switch statements in Java bytecode. (I think it was in 'Java Performance Tuning' One is a very fast implementation which uses the switch statement's integer values to know the offset of the code to be executed. This would require all integers to be consecutive and in a well-defined range. I'm guessing that using all the values of an Enum would fall in that category too.

I agree with many other posters though... it may be premature to worry about this, unless this is very very hot code.

How to "z-index" to make a menu always on top of the content

you could put the style in container div menu with:

<div style="position:relative; z-index:10">
   ...
   <!--html menu-->
   ...
</div>

before enter image description here

after

enter image description here

List all of the possible goals in Maven 2?

Is it possible to list all of the possible goals (including, say, all the plugins) that it is possible to run?

Maven doesn't have anything built-in for that, although the list of phases is finite (the list of plugin goals isn't since the list of plugins isn't).

But you can make things easier and leverage the power of bash completion (using cygwin if you're under Windows) as described in the Guide to Maven 2.x auto completion using BASH (but before to choose the script from this guide, read further).

To get things working, first follow this guide to setup bash completion on your computer. Then, it's time to get a script for Maven2 and:

  • While you could use the one from the mini guide
  • While you use an improved version attached to MNG-3928
  • While you could use a random scripts found around the net (see the resources if you're curious)
  • I personally use the Bash Completion script from Ludovic Claude's PPA (which is bundled into the packaged version of maven in Ubuntu) that you can download from the HEAD. It's simply the best one.

Below, here is what I get just to illustrate the result:

$ mvn [tab][tab]
Display all 377 possibilities? (y or n)
ant:ant 
ant:clean 
ant:help 
antrun:help 
antrun:run 
archetype:crawl 
archetype:create 
archetype:create-from-project 
archetype:generate 
archetype:help 
assembly:assembly 
assembly:directory 
assembly:directory-single 
assembly:help 
assembly:single  
... 

Of course, I never browse the 377 possibilities, I use completion. But this gives you an idea about the size of "a" list :)

Resources

How to make bootstrap column height to 100% row height?

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

How to force JS to do math instead of putting two strings together

Number()

dots = document.getElementById("txt").value;
dots = Number(dots) + 5;

// from MDN
Number('123')     // 123
Number('123') === 123 /// true
Number('12.3')    // 12.3
Number('12.00')   // 12
Number('123e-1')  // 12.3
Number('')        // 0
Number(null)      // 0
Number('0x11')    // 17
Number('0b11')    // 3
Number('0o11')    // 9
Number('foo')     // NaN
Number('100a')    // NaN
Number('-Infinity') //-Infinity

How to get the previous url using PHP

$_SERVER['HTTP_REFERER'] will give you incomplete url.

If you want http://bawse.3owl.com/jayz__magna_carta_holy_grail.php, $_SERVER['HTTP_REFERER'] will give you http://bawse.3owl.com/ only.

Write and read a list from file

As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:

with open('my_file.txt', 'rU') as in_file:
    data = in_file.read().split('\n')

That will store your data file as a list of items, one per line. To then put it into a file, you would do the opposite:

with open('new_file.txt', 'w') as out_file:
    out_file.write('\n'.join(data)) # This will create a string with all of the items in data separated by new-line characters

Hopefully that fits what you're looking for.

CSS show div background image on top of other contained elements

How about making the <div id="mainWrapperDivWithBGImage"> as three divs, where the two outside divs hold the rounded corners images, and the middle div simply has a background-color to match the rounded corner images. Then you could simply place the other elements inside the middle div, or:

#outside_left{width:10px; float:left;}
#outside_right{width:10px; float:right;}
#middle{background-color:#color of rnd_crnrs_foo.gif; float:left;}

Then

HTML:

<div id="mainWrapperDivWithBGImage">
  <div id="outside_left><img src="rnd_crnrs_left.gif" /></div>
  <div id="middle">
    <div id="another_div"><img src="foo.gif" /></div>
  <div id="outside_right><img src="rnd_crnrs_right.gif" /></div>
</div>

You may have to do position:relative; and such.

Getting Hour and Minute in PHP

Another way to address the timezone issue if you want to set the default timezone for the entire script to a certian timezone is to use date_default_timezone_set() then use one of the supported timezones.

How do I ignore a directory with SVN?

I had problems getting nested directories to be ignored; the top directory I wanted to ignore wouldn't show with 'svn status' but all the subdirs did. This is probably self-evident to everyone else, but I thought I'd share it:

EXAMPLE:

/trunk

/trunk/cache

/trunk/cache/subdir1

/trunk/cache/subdir2

cd /trunk
svn ps svn:ignore . /cache
cd /trunk/cache
svn ps svn:ignore . *
svn ci

Python, compute list difference

In case of a list of dictionaries, the full list comprehension solution works while the set solution raises

TypeError: unhashable type: 'dict'

Test Case

def diff(a, b):
    return [aa for aa in a if aa not in b]

d1 = {"a":1, "b":1}
d2 = {"a":2, "b":2}
d3 = {"a":3, "b":3}

>>> diff([d1, d2, d3], [d2, d3])
[{'a': 1, 'b': 1}]
>>> diff([d1, d2, d3], [d1])
[{'a': 2, 'b': 2}, {'a': 3, 'b': 3}]

Angular 5 Reactive Forms - Radio Button Group

IF you want to derive usg Boolean true False need to add "[]" around value

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female
</form>

Twitter API - Display all tweets with a certain hashtag?

The answer here worked better for me as it isolates the search on the hashtag, not just returning results that contain the search string. In the answer above you would still need to parse the JSON response to see if the entities.hashtags array is not empty.

Left Outer Join using + sign in Oracle 11g

LEFT OUTER JOIN

SELECT * FROM A, B WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT * FROM A, B WHERE A.column (+)= B.column

How to copy Docker images from one host to another without using a repository

First save the Docker image to a zip file:

docker save <docker image name> | gzip > <docker image name>.tar.gz

Then load the exported image to Docker using the below command:

zcat <docker image name>.tar.gz | docker load

How to terminate a Python script

While you should generally prefer sys.exit because it is more "friendly" to other code, all it actually does is raise an exception.

If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch SystemExit, there is another function - os._exit - which terminates immediately at the C level and does not perform any of the normal tear-down of the interpreter; for example, hooks registered with the "atexit" module are not executed.

Create an ArrayList with multiple object types?

It depends on the use case. Can you, please, describe it more?

  • If you want to be able to add both at one time, than you can do the which is nicely described by @Sanket Parikh. Put Integer and String into a new class and use that.

  • If you want to add the list either a String or an int, but only one of these at a time, then sure it is the List<Object>

    which looks good but only for first sight! This is not a good pattern. You'll have to check what type of object you have each time you get an object from your list. Also This type of list can contain any other types as well.. So no, not a nice solution. Although maybe for a beginner it can be used. If you choose this, i would recommend to check what is "instanceof" in Java.

  • I would strongly advise to reconsider your needs and think about maybe your real nead is to encapsulate Integers to a List<Integer> and Strings to a separate List<String>

Can i tell you a metaphor for what you want to do now? I would say you want to make a List wich can contain coffee beans and coffee shops. These to type of objects are totally different! Why are these put onto the same shelf? :)

Or do you have maybe data which can be a word or a number? Yepp! This would make sense, both of them is data! Then try to use one object for that which contains the data as String and if needed, can be translated to integer value.

public class MyDataObj {
String info;
boolean isNumeric;

public MyDataObj(String info){
    setInfo(info);
}

public MyDataObj(Integer info){
    setInfo(info);
}

public String getInfo() {
    return info;
}

public void setInfo(String info) {
    this.info = info;
    this.isNumeric = false;
}

public void setInfo(Integer info) {
    this.info = Integer.toString(info);
    this.isNumeric = true;
}

public boolean isNumeric() {
    return isNumeric;
}
}

This way you can use List<MyDataObj> for your needs. Again, this depends on your needs! :)

Some edition: What about using inharitance? This is better then then List<Object> solution, because you can not have other types in the list then Strings or Integers: Interface:

public interface IMyDataObj {
public String getInfo();
}

For String:

public class MyStringDataObj implements IMyDataObj {

final String info;

public MyStringDataObj(String info){
    this.info = info;
}

@Override
public String getInfo() {
    return info;
}
}

For Integer:

public class MyIntegerDataObj implements IMyDataObj {

final Integer info;

public MyIntegerDataObj(Integer info) {
    this.info = info;
}

@Override
public String getInfo() {
    return Integer.toString(info);
}
}

Finally the list will be: List<IMyDataObj>

PHP, get file name without file extension

As an alternative to pathinfo(), you can use

  • basename() — Returns filename component of path

Example from PHP manual

$path = "/home/httpd/html/index.php";
$file = basename($path);         // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"

You have to know the extension to remove it in advance though.

However, since your question suggests you have the need for getting the extension and the basename, I'd vote Pekka's answer as the most useful one, because it will give you any info you'd want about the path and file with one single native function.

Find out whether radio button is checked with JQuery?

$('#element').click(function() {
   if($('#radio_button').is(':checked')) { alert("it's checked"); }
});

How do I define global variables in CoffeeScript?

Since coffeescript is rarely used on it's own, you can use global variable supplied by either node.js or browserify (and any descendants like coffeeify, gulp build scripts, etc).

In node.js global is global namespace.

In browserify global is equal to window.

So, just:

somefunc = ->
  global.variable = 123

Using sudo with Python script

To pass the password to sudo's stdin:

#!/usr/bin/env python
from subprocess import Popen, PIPE

sudo_password = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'.split()

p = Popen(['sudo', '-S'] + command, stdin=PIPE, stderr=PIPE,
          universal_newlines=True)
sudo_prompt = p.communicate(sudo_password + '\n')[1]

Note: you could probably configure passwordless sudo or SUDO_ASKPASS command instead of hardcoding your password in the source code.

Remove quotes from String in Python

You can use eval() for this purpose

>>> url = "'http address'"
>>> eval(url)
'http address'

while eval() poses risk , i think in this context it is safe.

C++ templates that accept only certain types

C++20 concept usage

https://en.cppreference.com/w/cpp/language/constraints cppreference is giving the inheritance use case as an explicit concept example:

template <class T, class U>
concept Derived = std::is_base_of<U, T>::value;
 
template<Derived<Base> T>
void f(T);  // T is constrained by Derived<T, Base>

For multiple bases I'm guessing the syntax will be:

template <class T, class U, class V>
concept Derived = std::is_base_of<U, T>::value || std::is_base_of<V, T>::value;
 
template<Derived<Base1, Base2> T>
void f(T);

GCC 10 appears to have implemented it: https://gcc.gnu.org/gcc-10/changes.html and you can get it as a PPA on Ubuntu 20.04. https://godbolt.org/ My local GCC 10.1 did not recognize concept yet, so not sure what is going on.

SQL select max(date) and corresponding value

Each MAX function is evaluated individually. So MAX(CompletedDate) will return the value of the latest CompletedDate column and MAX(Notes) will return the maximum (i.e. alphabeticaly highest) value.

You need to structure your query differently to get what you want. This question had actually already been asked and answered several times, so I won't repeat it:

How to find the record in a table that contains the maximum value?

Finding the record with maximum value in SQL

How do I copy the contents of a String to the clipboard in C#?

You can use System.Windows.Forms.Clipboard.SetText(...).

Tomcat 8 Maven Plugin for Java 8

Since November 2017, one can use tomcat8-maven-plugin:

<!-- https://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat8-maven-plugin -->
<dependency>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat8-maven-plugin</artifactId>
    <version>2.2</version>
</dependency>

Note that this plugin resides in ICM repo (not in Maven Central), hence you should add the repo to your pluginsRepositories in your pom.xml:

<pluginRepositories>
    <pluginRepository>
        <id>icm</id>
        <name>Spring Framework Milestone Repository</name>
        <url>http://maven.icm.edu.pl/artifactory/repo</url>
    </pluginRepository>
</pluginRepositories>

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

In my case, this error happened because my HTML had a trailing linebreak.

var myHtml = '<p>\
    This should work.\
    But does not.\
</p>\
';

jQuery('.something').append(myHtml); // this causes the error

To avoid the error, you just need to trim the HTML.

jQuery('.something').append(jQuery.trim(myHtml)); // this works

How can I create directory tree in C++/Linux?

This is similar to the previous but works forward through the string instead of recursively backwards. Leaves errno with the right value for last failure. If there's a leading slash, there's an extra time through the loop which could have been avoided via one find_first_of() outside the loop or by detecting the leading / and setting pre to 1. The efficiency is the same whether we get set up by a first loop or a pre loop call, and the complexity would be (slightly) higher when using the pre-loop call.

#include <iostream>
#include <string>
#include <sys/stat.h>

int
mkpath(std::string s,mode_t mode)
{
    size_t pos=0;
    std::string dir;
    int mdret;

    if(s[s.size()-1]!='/'){
        // force trailing / so we can handle everything in loop
        s+='/';
    }

    while((pos=s.find_first_of('/',pos))!=std::string::npos){
        dir=s.substr(0,pos++);
        if(dir.size()==0) continue; // if leading / first time is 0 length
        if((mdret=mkdir(dir.c_str(),mode)) && errno!=EEXIST){
            return mdret;
        }
    }
    return mdret;
}

int main()
{
    int mkdirretval;
    mkdirretval=mkpath("./foo/bar",0755);
    std::cout << mkdirretval << '\n';

}

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

Parsing ISO 8601 date in Javascript

datejs could parse following, you might want to try out.

Date.parse('1997-07-16T19:20:15')           // ISO 8601 Formats
Date.parse('1997-07-16T19:20:30+01:00')     // ISO 8601 with Timezone offset

Edit: Regex version

x = "2011-01-28T19:30:00EST"

MM = ["January", "February","March","April","May","June","July","August","September","October","November", "December"]

xx = x.replace(
    /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):\d{2}(\w{3})/,
    function($0,$1,$2,$3,$4,$5,$6){
        return MM[$2-1]+" "+$3+", "+$1+" - "+$4%12+":"+$5+(+$4>12?"PM":"AM")+" "+$6
    }
)

Result

January 28, 2011 - 7:30PM EST

Edit2: I changed my timezone to EST and now I got following

x = "2011-01-28T19:30:00-05:00"

MM = {Jan:"January", Feb:"February", Mar:"March", Apr:"April", May:"May", Jun:"June", Jul:"July", Aug:"August", Sep:"September", Oct:"October", Nov:"November", Dec:"December"}

xx = String(new Date(x)).replace(
    /\w{3} (\w{3}) (\d{2}) (\d{4}) (\d{2}):(\d{2}):[^(]+\(([A-Z]{3})\)/,
    function($0,$1,$2,$3,$4,$5,$6){
        return MM[$1]+" "+$2+", "+$3+" - "+$4%12+":"+$5+(+$4>12?"PM":"AM")+" "+$6 
    }
)

return

January 28, 2011 - 7:30PM EST

Basically

String(new Date(x))

return

Fri Jan 28 2011 19:30:00 GMT-0500 (EST)

regex parts just converting above string to your required format.

January 28, 2011 - 7:30PM EST

Setting value of active workbook in Excel VBA

This is all you need

Set wbOOR = ActiveWorkbook

How to view AndroidManifest.xml from APK file?

There is an online tool that lets you upload an APK It decompiles it and finally lets you to download a zip with all sources, manifest XML file and so on decompiled, all of that without having to install any program on your computer: http://www.javadecompilers.com/apk

Also if you wish just to check on some params you can, by their UI

How to assign an exec result to a sql variable?

I always use the return value to pass back error status. If you need to pass back one value I'd use an output parameter.

sample stored procedure, with an OUTPUT parameter:

CREATE PROCEDURE YourStoredProcedure 
(
    @Param1    int
   ,@Param2    varchar(5)
   ,@Param3    datetime OUTPUT
)
AS
IF ISNULL(@Param1,0)>5
BEGIN
    SET @Param3=GETDATE()
END
ELSE
BEGIN
    SET @Param3='1/1/2010'
END
RETURN 0
GO

call to the stored procedure, with an OUTPUT parameter:

DECLARE @OutputParameter  datetime
       ,@ReturnValue      int

EXEC @ReturnValue=YourStoredProcedure 1,null, @OutputParameter OUTPUT
PRINT @ReturnValue
PRINT CONVERT(char(23),@OutputParameter ,121)

OUTPUT:

0
2010-01-01 00:00:00.000

How to show a running progress bar while page is loading

It’s a chicken-and-egg problem. You won’t be able to do it because you need to load the assets to display the progress bar widget, by which time your page will be either fully or partially downloaded. Also, you need to know the total size of the page prior to the user requesting in order to calculate a percentage.

It’s more hassle than it’s worth.

Performing a query on a result from another query?

I don't know if you even need to wrap it. Won't this work?

SELECT COUNT(*), SUM(DATEDIFF(now(),availables.updated_at))
FROM availables
INNER JOIN rooms    ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' 
  AND date_add('2009-06-25', INTERVAL 4 DAY)
  AND rooms.hostel_id = 5094
GROUP BY availables.bookdate);

If your goal is to return both result sets then you'll need to store it some place temporarily.

MySQL Database won't start in XAMPP Manager-osx

  1. close XAMPP control
  2. sudo killall mysqld
  3. sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start

check null,empty or undefined angularjs

A very simple check that you can do:

Explanation 1:

if (value) {
 // it will come inside
 // If value is either undefined, null or ''(empty string)
}

Explanation 2:

(!value) ? "Case 1" : "Case 2"

If the value is either undefined , null or '' then Case 1 otherwise for any other value of value Case 2.

Adding rows to tbody of a table using jQuery

("#tblEntAttributes tbody")

needs to be

$("#tblEntAttributes tbody").

You are not selecting the element with the correct syntax

Here's an example of both

$(newRowContent).appendTo($("#tblEntAttributes"));

and

$("#tblEntAttributes tbody").append(newRowContent);

working http://jsfiddle.net/xW4NZ/

Listview Scroll to the end of the list after updating the list

The transcript mode is what you want and is used by Google Talk and the SMS/MMS application. Are you correctly calling notifyDatasetChanged() on your adapter when you add items?

Is it possible to read from a InputStream with a timeout?

As jt said, NIO is the best (and correct) solution. If you really are stuck with an InputStream though, you could either

  1. Spawn a thread who's exclusive job is to read from the InputStream and put the result into a buffer which can be read from your original thread without blocking. This should work well if you only ever have one instance of the stream. Otherwise you may be able to kill the thread using the deprecated methods in the Thread class, though this may cause resource leaks.

  2. Rely on isAvailable to indicate data that can be read without blocking. However in some cases (such as with Sockets) it can take a potentially blocking read for isAvailable to report something other than 0.

How to run only one unit test class using Gradle

Below is the command to run a single test class using gradlew command line option:

gradlew.bat Connected**your bundleVariant**AndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.example.TestClass

Below example to run class com.example.TestClass with variant Variant_1:

gradlew.bat ConnectedVariant_1AndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.example.TestClass 

Check object empty

You should check it against null.

If you want to check if object x is null or not, you can do:

    if(x != null)

But if it is not null, it can have properties which are null or empty. You will check those explicitly:

    if(x.getProperty() != null)

For "empty" check, it depends on what type is involved. For a Java String, you usually do:

    if(str != null && !str.isEmpty())

As you haven't mentioned about any specific problem with this, difficult to tell.

How do you get the contextPath from JavaScript, the right way?

I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:

<html>
    <head>
        <link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
    <body>
        <script src="main.js" type="text/javascript"></script>
    </body>
</html>

main.js

var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});

If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string

How to read a line from a text file in c/c++?

In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.

If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.

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

void handle_line(char *line) {
  printf("%s", line);
}

int main(int argc, char *argv[]) {
    int size = 1024, pos;
    int c;
    char *buffer = (char *)malloc(size);

    FILE *f = fopen("myfile.txt", "r");
    if(f) {
      do { // read all lines in file
        pos = 0;
        do{ // read one line
          c = fgetc(f);
          if(c != EOF) buffer[pos++] = (char)c;
          if(pos >= size - 1) { // increase buffer length - leave room for 0
            size *=2;
            buffer = (char*)realloc(buffer, size);
          }
        }while(c != EOF && c != '\n');
        buffer[pos] = 0;
        // line is now in buffer
        handle_line(buffer);
      } while(c != EOF); 
      fclose(f);           
    }
    free(buffer);
    return 0;
}

Angular 2.0 router not working on reloading the browser

For those of us struggling through life in IIS: use the following PowerShell code to fix this issue based on the official Angular 2 docs (that someone posted in this thread? http://blog.angular-university.io/angular2-router/)

Import-WebAdministration
# Grab the 404 handler and update it to redirect to index.html.
$redirect = Get-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS 
$redirect.path = "/index.html"
$redirect.responseMode = 1
# shove the updated config back into IIS
Set-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS -value $redirect

This redirects the 404 to the /index.html file as per the suggestion in the Angular 2 docs (link above).

Convert Object to JSON string

jQuery does only make some regexp checking before calling the native browser method window.JSON.parse(). If that is not available, it uses eval() or more exactly new Function() to create a Javascript object.

The opposite of JSON.parse() is JSON.stringify() which serializes a Javascript object into a string. jQuery does not have functionality of its own for that, you have to use the browser built-in version or json2.js from http://www.json.org

JSON.stringify() is available in all major browsers, but to be compatible with older browsers you still need that fallback.

Specifying content of an iframe instead of the src attribute to a page

In combination with what Guffa described, you could use the technique described in Explanation of <script type = "text/template"> ... </script> to store the HTML document in a special script element (see the link for an explanation on how this works). That's a lot easier than storing the HTML document in a string.

Format output string, right alignment

To do it by using f-string and with control of the number of trailing digits:

print(f'A number -> {my_number:>20.5f}')

Retrieving subfolders names in S3 bucket from boto3

Below piece of code returns ONLY the 'subfolders' in a 'folder' from s3 bucket.

import boto3
bucket = 'my-bucket'
#Make sure you provide / in the end
prefix = 'prefix-name-with-slash/'  

client = boto3.client('s3')
result = client.list_objects(Bucket=bucket, Prefix=prefix, Delimiter='/')
for o in result.get('CommonPrefixes'):
    print 'sub folder : ', o.get('Prefix')

For more details, you can refer to https://github.com/boto/boto3/issues/134

How do I convert between ISO-8859-1 and UTF-8 in Java?

If you have a String, you can do that:

String s = "test";
try {
    s.getBytes("UTF-8");
} catch(UnsupportedEncodingException uee) {
    uee.printStackTrace();
}

If you have a 'broken' String, you did something wrong, converting a String to a String in another encoding is defenetely not the way to go! You can convert a String to a byte[] and vice-versa (given an encoding). In Java Strings are AFAIK encoded with UTF-16 but that's an implementation detail.

Say you have a InputStream, you can read in a byte[] and then convert that to a String using

byte[] bs = ...;
String s;
try {
    s = new String(bs, encoding);
} catch(UnsupportedEncodingException uee) {
    uee.printStackTrace();
}

or even better (thanks to erickson) use InputStreamReader like that:

InputStreamReader isr;
try {
     isr = new InputStreamReader(inputStream, encoding);
} catch(UnsupportedEncodingException uee) {
    uee.printStackTrace();
}

Difference between static, auto, global and local variable in the context of c and c++

There are two separate concepts here:

  • scope, which determines where a name can be accessed, and
  • storage duration, which determines when a variable is created and destroyed.

Local variables (pedantically, variables with block scope) are only accessible within the block of code in which they are declared:

void f() {
    int i;
    i = 1; // OK: in scope
}
void g() {
    i = 2; // Error: not in scope
}

Global variables (pedantically, variables with file scope (in C) or namespace scope (in C++)) are accessible at any point after their declaration:

int i;
void f() {
    i = 1; // OK: in scope
}
void g() {
    i = 2; // OK: still in scope
}

(In C++, the situation is more complicated since namespaces can be closed and reopened, and scopes other than the current one can be accessed, and names can also have class scope. But that's getting very off-topic.)

Automatic variables (pedantically, variables with automatic storage duration) are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.

for (int i = 0; i < 5; ++i) {
    int n = 0;
    printf("%d ", ++n);  // prints 1 1 1 1 1  - the previous value is lost
}

Static variables (pedantically, variables with static storage duration) have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope.

for (int i = 0; i < 5; ++i) {
    static int n = 0;
    printf("%d ", ++n);  // prints 1 2 3 4 5  - the value persists
}

Note that the static keyword has various meanings apart from static storage duration. On a global variable or function, it gives it internal linkage so that it's not accessible from other translation units; on a C++ class member, it means there's one instance per class rather than one per object. Also, in C++ the auto keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initialiser.

How to use a table type in a SELECT FROM statement?

Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:

CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);


CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;

In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.

Is the order of elements in a JSON list preserved?

Some JavaScript engines keep keys in insertion order. V8, for instance, keeps all keys in insertion order except for keys that can be parsed as unsigned 32-bit integers.

This means that if you run either of the following:

var animals = {};
animals['dog'] = true;
animals['bear'] = true;
animals['monkey'] = true;
for (var animal in animals) {
  if (animals.hasOwnProperty(animal)) {
    $('<li>').text(animal).appendTo('#animals');
  }
}
var animals = JSON.parse('{ "dog": true, "bear": true, "monkey": true }');
for (var animal in animals) {
  $('<li>').text(animal).appendTo('#animals');
}

You'll consistently get dog, bear, and monkey in that order, on Chrome, which uses V8. Node.js also uses V8. This will hold true even if you have thousands of items. YMMV with other JavaScript engines.

Demo here and here.

How to test if a file is a directory in a batch script?

Based on this article titled "How can a batch file test existence of a directory" it's "not entirely reliable".

BUT I just tested this:

@echo off
IF EXIST %1\NUL goto print
ECHO not dir
pause
exit
:print
ECHO It's a directory
pause

and it seems to work

How do I get ruby to print a full backtrace instead of a truncated one?

IRB has a setting for this awful "feature", which you can customize.

Create a file called ~/.irbrc that includes the following line:

IRB.conf[:BACK_TRACE_LIMIT] = 100

This will allow you to see 100 stack frames in irb, at least. I haven't been able to find an equivalent setting for the non-interactive runtime.

Detailed information about IRB customization can be found in the Pickaxe book.

Error installing mysql2: Failed to build gem native extension

On Ubuntu/Debian and other distributions using aptitude:

sudo apt-get install libmysql-ruby libmysqlclient-dev

Package libmysql-ruby has been phased out and replaced by ruby-mysql. This is where I found the solution.

If the above command doesn't work because libmysql-ruby cannot be found, the following should be sufficient:

sudo apt-get install libmysqlclient-dev

On Red Hat/CentOS and other distributions using yum:

sudo yum install mysql-devel

On Mac OS X with Homebrew:

brew install mysql

How to test whether a service is running from the command line

if you don't mind to combine the net command with grep you can use the following script.

@echo off
net start | grep -x "Service"
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo trouble
goto end
:started
echo started
goto end
:stopped
echo stopped
goto end
:end

Search for a string in Enum and return the Enum

I marked OregonGhost's answer +1, then I tried to use the iteration and realised it wasn't quite right because Enum.GetNames returns strings. You want Enum.GetValues:

public MyColours GetColours(string colour)
{  
   foreach (MyColours mc in Enum.GetValues(typeof(MyColours))) 
   if (mc.ToString() == surveySystem) 
      return mc;

   return MyColors.Default;
}

Subscript out of range error in this Excel VBA script

Private Sub CommandButton1_Click()

    Dim Data As Object, Employee As Object

    Application.ScreenUpdating = False

    Set Data = ThisWorkbook.Sheets("Data")

    Set Employee = ThisWorkbook.Sheets("Employee Names")

    Data.Range("AK1").Value = "Lookup"

    Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Formula = "=VLOOKUP(E2,'Employee Names'!$A:$A,1,0)"

    Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value = Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=5, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=37, Criteria1:="#N/A"

    Application.DisplayAlerts = False

    Data.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)

    Data.Range("AK:AK").Delete

    Data.AutoFilterMode = False

    'Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=7, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"

    Worksheets("Data").Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DrfeeRequested"

    Set Dr = ThisWorkbook.Worksheets("DrfeeRequested")

    Dr.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    'DrfeeRequested.AutoFilterMode = False

    Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "RateLockfollowup"
    Set Ratefolup = ThisWorkbook.Worksheets("RateLockfollowup")

    Ratefolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Lockedlefollowup"
    Set Lockfolup = ThisWorkbook.Worksheets("Lockedlefollowup")

    Lockfolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Hoifollowup"

    Set Hoifolup = ThisWorkbook.Worksheets("Hoifollowup")

    Hoifolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Selection.AutoFilter

    TodayDT = Format(Now())

    Weekdy = Weekday(Now())

    If Weekdy = 2 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 3 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 4 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 5 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 6 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    Else
       MsgBox "Today Satuarday OR Sunday Data is not Available"
    End If

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:=" TodayDT", Operator:=xlAnd, Criteria2:="LastTwoDays"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DRfeefollowup"

    Set Drfreefolup = ThisWorkbook.Worksheets("DRfeefollowup")

    Drfreefolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=15, Criteria1:="yes"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="x"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"

    'Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=14, criterial:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Drworkblefiles"

    Set Drworkblefiles = ThisWorkbook.Worksheets("Drworkblefiles")

    Drworkblefiles.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.Range("A1").AutoFilter

   End Sub

 Private Sub CommandButton2_Click()


    Sheets("Data").Range("A1:AJ" & Sheets("Data").Range("A1").End(xlDown).Row).Clear

    MsgBox "Please paste new data in data sheet"


End Sub

Is there a "do ... while" loop in Ruby?

Like this:

people = []

begin
  info = gets.chomp
  people += [Person.new(info)] if not info.empty?
end while not info.empty?

Reference: Ruby's Hidden do {} while () Loop

How to get date in BAT file

%date% will give you the date.

%time% will give you the time.

The date and time /t commands may give you more detail.

How to show Page Loading div until the page has finished loading?

I've needed this and after some research I came up with this (jQuery needed):

First, right after the <body> tag add this:

<div id="loading">
  <img id="loading-image" src="images/ajax-loader.gif" alt="Loading..." />
</div>

Then add the style class for the div and image to your CSS:

#loading {
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  position: fixed;
  display: block;
  opacity: 0.7;
  background-color: #fff;
  z-index: 99;
  text-align: center;
}

#loading-image {
  position: absolute;
  top: 100px;
  left: 240px;
  z-index: 100;
}

Then, add this javascript to your page (preferably at the end of your page, before your closing </body> tag, of course):

<script>
  $(window).load(function() {
    $('#loading').hide();
  });
</script>

Finally, adjust the position of the loading image and the background-colour of the loading div with the style class.

This is it, should work just fine. But of course you have to have an ajax-loader.gif somewhere. Freebies here. (Right-click > Save Image As...)

Display Two <div>s Side-by-Side

I removed the float from the second div to make it work.

http://jsfiddle.net/rhEyM/2/

Remove and Replace Printed items

Just use CR to go to beginning of the line.

import time
for x in range (0,5):  
    b = "Loading" + "." * x
    print (b, end="\r")
    time.sleep(1)

Android getting value from selected radiobutton

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
       @Override
       public void onCheckedChanged(RadioGroup group, int checkedId)
       {
           radioButton = (RadioButton) findViewById(checkedId);
           Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
       }
   }
   );

CSS text-overflow in a table cell?

If you just want the table to auto-layout

Without using max-width, or percentage column widths, or table-layout: fixed etc.

https://jsfiddle.net/tturadqq/

How it works:


Step 1: Just let the table auto-layout do its thing.

When there's one or more columns with a lot of text, it will shrink the other columns as much as possible, then wrap the text of the long columns:

enter image description here


Step 2: Wrap cell contents in a div, then set that div to max-height: 1.1em

(the extra 0.1em is for characters which render a bit below the text base, like the tail of 'g' and 'y')

enter image description here


Step 3: Set title on the divs

This is good for accessibility, and is necessary for the little trick we'll use in a moment.

enter image description here


Step 4: Add a CSS ::after on the div

This is the tricky bit. We set a CSS ::after, with content: attr(title), then position that on top of the div and set text-overflow: ellipsis. I've coloured it red here to make it clear.

(Note how the long column now has a tailing ellipsis)

enter image description here


Step 5: Set the colour of the div text to transparent

And we're done!

enter image description here

Meaning of *& and **& in C++

First is a reference to a pointer, second is a reference to a pointer to a pointer. See also FAQ on how pointers and references differ.

void foo(int*& x, int**& y) {
    // modifying x or y here will modify a or b in main
}

int main() {
    int val = 42;
    int *a  = &val;
    int **b = &a;

    foo(a, b);
    return 0;
}

Convert .pfx to .cer

PFX files are PKCS#12 Personal Information Exchange Syntax Standard bundles. They can include arbitrary number of private keys with accompanying X.509 certificates and a certificate authority chain (set certificates).

If you want to extract client certificates, you can use OpenSSL's PKCS12 tool.

openssl pkcs12 -in input.pfx -out mycerts.crt -nokeys -clcerts

The command above will output certificate(s) in PEM format. The ".crt" file extension is handled by both macOS and Window.

You mention ".cer" extension in the question which is conventionally used for the DER encoded files. A binary encoding. Try the ".crt" file first and if it's not accepted, easy to convert from PEM to DER:

openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer

In javascript, how do you search an array for a substring match

For a fascinating examination of some of the alternatives and their efficiency, see John Resig's recent posts:

(The problem discussed there is slightly different, with the haystack elements being prefixes of the needle and not the other way around, but most solutions are easy to adapt.)

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Use the latest supportLibrary, version 27.1.1 to solve the problem. worked for me. (many bug fixes included - see changelog)

How do I abort/cancel TPL Tasks?

You can use a CancellationToken to control whether the task gets cancelled. Are you talking about aborting it before it's started ("nevermind, I already did this"), or actually interrupting it in middle? If the former, the CancellationToken can be helpful; if the latter, you will probably need to implement your own "bail out" mechanism and check at appropriate points in the task execution whether you should fail fast (you can still use the CancellationToken to help you, but it's a little more manual).

MSDN has an article about cancelling Tasks: http://msdn.microsoft.com/en-us/library/dd997396.aspx

intl extension: installing php_intl.dll

For the php_intl.dll extension to work correctly, you need to have the following files in a folder in your PATH:

  • icudt36.dll
  • icuin36.dll
  • icuio36.dll
  • icule36.dll
  • iculx36.dll
  • icutu36.dll
  • icuuc36.dll

By default they're sitting in your PHP directory, but that directory isn't necessarily in your PATH (it wasn't for me, using xampp)

This has to be in your global path, not just your user's path. To set the global path, go to system info (windows key + PAUSE), then Advanced System Settings (Vista+) or Advanced (XP) and click the "Environment Variables" button and add the appropriate directory to the PATH variable in the System Variables list.

How to print a list of symbols exported from a dynamic library

Use nm -a your.dylib

It will print all the symbols including globals

Python match a string with regex

As everyone else has mentioned it is better to use the "in" operator, it can also act on lists:

line = "This,is,a,sample,string"
lst = ['This', 'sample']
for i in lst:
     i in line

>> True
>> True

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

comdlg32.dll is not a COM DLL and cannot be registered.

One way to confirm this for yourself is to run this command:

dumpbin /exports comdlg32.dll

You'll see that comdlg32.dll doesn't contain a DllRegisterServer method. Hence RegSvr32.exe won't work.

That's your answer.


ComDlg32.dll is a a system component. (exists in both c:\windows\system32 and c:\windows\syswow64) Trying to replace it or override any registration with an older version could corrupt the rest of Windows.


I can help more, but I need to know what MSComDlg.CommonDialog is. What does it do and how is it supposed to work? And what version of ComDlg32.dll are you trying to register (and where did you get it)?

How to get only the last part of a path in Python?

I like the parts method of Path for this:

grandparent_directory, parent_directory, filename = Path(export_filename).parts[-3:]
log.info(f'{t: <30}: {num_rows: >7} Rows exported to {grandparent_directory}/{parent_directory}/{filename}')

How do I purge a linux mail box with huge number of emails?

Rather than use "d", why not "p". I am not sure if the "p *" will work. I didn't try that. You can; however use the following script"

#!/bin/bash
#

MAIL_INDEX=$(printf 'h a\nq\n' | mail | egrep -o '[0-9]* unread' | awk '{print $1}')

markAllRead=
for (( i=1; i<=$MAIL_INDEX; i++ ))
do
   markAllRead=$markAllRead"p $i\n"
done
markAllRead=$markAllRead"q\n"
printf "$markAllRead" | mail

How to encode a string in JavaScript for displaying in HTML?

If you want to use a library rather than doing it yourself:

The most commonly used way is using jQuery for this purpose:

var safestring = $('<div>').text(unsafestring).html();

If you want to to encode all the HTML entities you will have to use a library or write it yourself.

You can use a more compact library than jQuery, like HTML Encoder and Decode

*ngIf and *ngFor on same element causing error

You can also use ng-template (instead of template. See the note for the caveat of using template tag) for applying both *ngFor and ngIf on the same HTML element. Here is an example where you can use both *ngIf and *ngFor for the same tr element in the angular table.

<tr *ngFor = "let fruit of fruiArray">
    <ng-template [ngIf] = "fruit=='apple'>
        <td> I love apples!</td>
    </ng-template>
</tr>

where fruiArray = ['apple', 'banana', 'mango', 'pineapple'].

Note:

The caveat of using just the template tag instead of ng-template tag is that it throws StaticInjectionError in some places.

How to iterate over each string in a list of strings and operate on it's elements

Use range() instead, like the following :

for i in range(len(words)):
    ...

Tomcat is web server or application server?

Tomcat is a web server (can handle HTTP requests/responses) and web container (implements Java Servlet API, also called servletcontainer) in one. Some may call it an application server, but it is definitely not an fullfledged Java EE application server (it does not implement the whole Java EE API).

See also:

How do I convert from a money datatype in SQL server?

I had this issue as well, and was tripped up for a while on it. I wanted to display 0.00 as 0 and otherwise keep the decimal point. The following didn't work:

CASE WHEN Amount= 0 THEN CONVERT(VARCHAR(30), Amount, 1) ELSE Amount END

Because the resulting column was forced to be a MONEY column. To resolve it, the following worked

CASE WHEN Amount= 0 THEN CONVERT(VARCHAR(30), '0', 1) ELSE CONVERT (VARCHAR(30), Amount, 1) END

This mattered because my final destination column was a VARCHAR(30), and the consumers of that column would error out if an amount was '0.00' instead of '0'.

What's a .sh file?

What is a file with extension .sh?

It is a Bourne shell script. They are used in many variations of UNIX-like operating systems. They have no "language" and are interpreted by your shell (interpreter of terminal commands) or if the first line is in the form

#!/path/to/interpreter

they will use that particular interpreter. Your file has the first line:

#!/bin/bash

and that means that it uses Bourne Again Shell, so called bash. It is for all practical purposes a replacement for good old sh.

Depending upon the interpreter you will have different language in which the file is written.

Keep in mind, that in UNIX world, it is not the extension of the file that determines what the file is (see How to execute a shell script).

If you come from the world of DOS/Windows, you will be familiar with files that have .bat or .cmd extensions (batch files). They are not similar in content, but are akin in design.

How to execute a shell script

Unlike some silly operating systems, *nix does not rely exclusively on extensions to determine what to do with a file. Permissions are also used. This means that if you attempt to run the shell script after downloading it, it will be the same as trying to "run" any text file. The ".sh" extension is there only for your convenience to recognize that file.

You will need to make the file executable. Let's assume that you have downloaded your file as file.sh, you can then run in your terminal:

chmod +x file.sh

chmod is a command for changing file's permissions, +x sets execute permissions (in this case for everybody) and finally you have your file name.

You can also do it in GUI. Most of the time you can right click on the file and select properties, in XUbuntu the permissions options look like this:

File permissions in XUbuntu

If you do not wish to change the permissions. You can also force the shell to run the command. In the terminal you can run:

bash file.sh

The shell should be the same as in the first line of your script.

How safe is it?

You may find it weird that you must perform another task manually in order to execute a file. But this is partially because of strong need for security.

Basically when you download and run a bash script, it is the same thing as somebody telling you "run all these commands in sequence on your computer, I promise that the results will be good and safe". Ask yourself if you trust the party that has supplied this file, ask yourself if you are sure that have downloaded the file from the same place as you thought, maybe even have a glance inside to see if something looks out of place (although that requires that you know something about *nix commands and bash programming).

Unfortunately apart from the warning above I cannot give a step-by-step description of what you should do to prevent evil things from happening with your computer; so just keep in mind that any time you get and run an executable file from someone you're actually saying, "Sure, you can use my computer to do something".

Get value from hashmap based on key to JSTL

I had issue with the solutions mentioned above as specifying the string key would give me javax.el.PropertyNotFoundException. The code shown below worked for me. In this I used status to count the index of for each loop and displayed the value of index I am interested on

<c:forEach items="${requestScope.key}"  var="map" varStatus="status" >
    <c:if test="${status.index eq 1}">
        <option><c:out value=${map.value}/></option>
    </c:if>
</c:forEach>    

Spring Data and Native Query with pagination

Using "ORDER BY id DESC \n-- #pageable\n " instead of "ORDER BY id \n#pageable\n" worked for me with MS SQL SERVER

Codeigniter displays a blank page instead of error messages

please check either error folder is in application folder of not in my case i replace error folder in application folder

Are parameters in strings.xml possible?

If you need two variables in the XML, you can use:

%1$d text... %2$d or %1$s text... %2$s for string variables.

Example :

strings.xml

<string name="notyet">Website %1$s isn\'t yet available, I\'m working on it, please wait %2$s more days</string>

activity.java

String site = "site.tld";
String days = "11";

//Toast example
String notyet = getString(R.string.notyet, site, days);
Toast.makeText(getApplicationContext(), notyet, Toast.LENGTH_LONG).show();

Select SQL results grouped by weeks

Declare @DatePeriod datetime
Set @DatePeriod = '2011-05-30'

Select  ProductName,
        IsNull([1],0) as 'Week 1',
        IsNull([2],0) as 'Week 2',
        IsNull([3],0) as 'Week 3',
        IsNull([4],0) as 'Week 4',
        IsNull([5], 0) as 'Week 5'
From 
(
Select  ProductName,
        DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, '2011-05-30'), 0), '2011-05-30') +1 as [Weeks],
        Sale as 'Sale'
From dbo.WeekReport

-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, '2011-05-30')= DatePart(Month, @DatePeriod)
)p 
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv

OUTPUT LOOK LIKE THIS

a   0   0   0   0   20
b   0   0   0   0   4
c   0   0   0   0   3

How to hide a View programmatically?

Kotlin Solution

view.isVisible = true
view.isInvisible = true
view.isGone = true

// For these to work, you need to use androidx and import:
import androidx.core.view.isVisible // or isInvisible/isGone

Kotlin Extension Solution

If you'd like them to be more consistent length, work for nullable views, and lower the chance of writing the wrong boolean, try using these custom extensions:

// Example
view.hide()

fun View?.show() {
    if (this == null) return
    if (!isVisible) isVisible = true
}

fun View?.hide() {
    if (this == null) return
    if (!isInvisible) isInvisible = true
}

fun View?.gone() {
    if (this == null) return
    if (!isGone) isGone = true
}

To make conditional visibility simple, also add these:

fun View?.show(visible: Boolean) {
    if (visible) show() else gone()
}

fun View?.hide(hide: Boolean) {
    if (hide) hide() else show()
}

fun View?.gone(gone: Boolean = true) {
    if (gone) gone() else show()
}

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

Did you implement the main() function?

int main(int argc, char **argv) {
    ... code ...
    return 0;
}

[edit]

You have your main() in another source file so you've probably forgotten to add it to your project.

To add an existing source file: In Solution Explorer, right-click the Source Files folder, point to Add, and then click Existing Item. Now select the source file containing the main()

How to close jQuery Dialog within the dialog?


        $(document).ready(function () {
            $("#form-dialog").dialog({
                autoOpen: true,
                modal: true,
                width: 200,
                draggable: true,
                resizable: true,
                buttons: {
                    "Close": function () {
                        $("#idDialog").dialog("close");
                    }
                }
            });
        });

This will make you a button to close. you can also call the function close

$("#idDialog").dialog("close");

in some function to do this. or even in a button/a

< a href="javascript:void(0);" id="btnDone"   
                              onClick="$("#idDialog").dialog("close");">CLOSE</a>

EDIT: you need this to include your dialog into form:

open: function (type, data) {
            $(this).parent().appendTo($("form:first"));
        }

How do I join two SQLite tables in my Android application?

In addition to @pawelzieba's answer, which definitely is correct, to join two tables, while you can use an INNER JOIN like this

SELECT * FROM expense INNER JOIN refuel
ON exp_id = expense_id
WHERE refuel_id = 1

via raw query like this -

String rawQuery = "SELECT * FROM " + RefuelTable.TABLE_NAME + " INNER JOIN " + ExpenseTable.TABLE_NAME
        + " ON " + RefuelTable.EXP_ID + " = " + ExpenseTable.ID
        + " WHERE " + RefuelTable.ID + " = " +  id;
Cursor c = db.rawQuery(
        rawQuery,
        null
);

because of SQLite's backward compatible support of the primitive way of querying, we turn that command into this -

SELECT *
FROM expense, refuel
WHERE exp_id = expense_id AND refuel_id = 1

and hence be able to take advanatage of the SQLiteDatabase.query() helper method

Cursor c = db.query(
        RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
        Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
        RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " +  id,
        null,
        null,
        null,
        null
);

For a detailed blog post check this http://blog.championswimmer.in/2015/12/doing-a-table-join-in-android-without-using-rawquery

Skipping Incompatible Libraries at compile

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.

Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)

It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

  1. Just to check: usually you would add flags to CFLAGS rather than CTAGS - are you sure this is correct? (What you have may be correct - this will depend on your build system!)
  2. Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

Javascript array sort and unique

You can now achieve the result in just one line of code.

Using new Set to reduce the array to unique set of values. Apply the sort method after to order the string values.

var myData=['237','124','255','124','366','255']

var uniqueAndSorted = [...new Set(myData)].sort() 

UPDATED for newer methods introduced in JavaScript since time of question.

CSS transition shorthand with multiple properties?

If you have several specific properties that you want to transition in the same way (because you also have some properties you specifically don't want to transition, say opacity), another option is to do something like this (prefixes omitted for brevity):

.myclass {
    transition: all 200ms ease;
    transition-property: box-shadow, height, width, background, font-size;
}

The second declaration overrides the all in the shorthand declaration above it and makes for (occasionally) more concise code.

_x000D_
_x000D_
/* prefixes omitted for brevity */_x000D_
.box {_x000D_
    height: 100px;_x000D_
    width: 100px;_x000D_
    background: red;_x000D_
    box-shadow: red 0 0 5px 1px;_x000D_
    transition: all 500ms ease;_x000D_
    /*note: not transitioning width */_x000D_
    transition-property: height, background, box-shadow;_x000D_
}_x000D_
_x000D_
.box:hover {_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
  box-shadow: blue 0 0 10px 3px;_x000D_
  background: blue;_x000D_
}
_x000D_
<p>Hover box for demo</p>_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

Demo

How do I check my gcc C++ compiler version for my Eclipse?

you can also use gcc -v command that works like gcc --version and if you would like to now where gcc is you can use whereis gcc command

I hope it'll be usefull

A div with auto resize when changing window width\height

Code Snippet:

div{height: calc(100vh - 10vmax)}

Custom Authentication in ASP.Net-Core

From what I learned after several days of research, Here is the Guide for ASP .Net Core MVC 2.x Custom User Authentication

In Startup.cs :

Add below lines to ConfigureServices method :

public void ConfigureServices(IServiceCollection services)
{

services.AddAuthentication(
    CookieAuthenticationDefaults.AuthenticationScheme
).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
    options =>
    {
        options.LoginPath = "/Account/Login";
        options.LogoutPath = "/Account/Logout";
    });

    services.AddMvc();

    // authentication 
    services.AddAuthentication(options =>
    {
       options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    });

    services.AddTransient(
        m => new UserManager(
            Configuration
                .GetValue<string>(
                    DEFAULT_CONNECTIONSTRING //this is a string constant
                )
            )
        );
     services.AddDistributedMemoryCache();
}

keep in mind that in above code we said that if any unauthenticated user requests an action which is annotated with [Authorize] , they well force redirect to /Account/Login url.

Add below lines to Configure method :

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler(ERROR_URL);
    }
     app.UseStaticFiles();
     app.UseAuthentication();
     app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: DEFAULT_ROUTING);
    });
}

Create your UserManager class that will also manage login and logout. it should look like below snippet (note that i'm using dapper):

public class UserManager
{
    string _connectionString;

    public UserManager(string connectionString)
    {
        _connectionString = connectionString;
    }

    public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
    {
        using (var con = new SqlConnection(_connectionString))
        {
            var queryString = "sp_user_login";
            var dbUserData = con.Query<UserDbModel>(
                queryString,
                new
                {
                    UserEmail = user.UserEmail,
                    UserPassword = user.UserPassword,
                    UserCellphone = user.UserCellphone
                },
                commandType: CommandType.StoredProcedure
            ).FirstOrDefault();

            ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

            await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        }
    }

    public async void SignOut(HttpContext httpContext)
    {
        await httpContext.SignOutAsync();
    }

    private IEnumerable<Claim> GetUserClaims(UserDbModel user)
    {
        List<Claim> claims = new List<Claim>();

        claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
        claims.Add(new Claim(ClaimTypes.Name, user.UserFirstName));
        claims.Add(new Claim(ClaimTypes.Email, user.UserEmail));
        claims.AddRange(this.GetUserRoleClaims(user));
        return claims;
    }

    private IEnumerable<Claim> GetUserRoleClaims(UserDbModel user)
    {
        List<Claim> claims = new List<Claim>();

        claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
        claims.Add(new Claim(ClaimTypes.Role, user.UserPermissionType.ToString()));
        return claims;
    }
}

Then maybe you have an AccountController which has a Login Action that should look like below :

public class AccountController : Controller
{
    UserManager _userManager;

    public AccountController(UserManager userManager)
    {
        _userManager = userManager;
    }

    [HttpPost]
    public IActionResult LogIn(LogInViewModel form)
    {
        if (!ModelState.IsValid)
            return View(form);
         try
        {
            //authenticate
            var user = new UserDbModel()
            {
                UserEmail = form.Email,
                UserCellphone = form.Cellphone,
                UserPassword = form.Password
            };
            _userManager.SignIn(this.HttpContext, user);
             return RedirectToAction("Search", "Home", null);
         }
         catch (Exception ex)
         {
            ModelState.AddModelError("summary", ex.Message);
            return View(form);
         }
    }
}

Now you are able to use [Authorize] annotation on any Action or Controller.

Feel free to comment any questions or bug's.

Difference between const reference and normal parameter

Firstly, there is no concept of cv-qualified references. So the terminology 'const reference' is not correct and is usually used to describle 'reference to const'. It is better to start talking about what is meant.

$8.3.2/1- "Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef (7.1.3) or of a template type argument (14.3), in which case the cv-qualifiers are ignored."

Here are the differences

$13.1 - "Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations.112). In particular, for any type T, “pointer to T,” “pointer to const T,” and “pointer to volatile T” are considered distinct parameter types, as are “reference to T,” “reference to const T,” and “reference to volatile T.”

void f(int &n){
   cout << 1; 
   n++;
}

void f(int const &n){
   cout << 2;
   //n++; // Error!, Non modifiable lvalue
}

int main(){
   int x = 2;

   f(x);        // Calls overload 1, after the call x is 3
   f(2);        // Calls overload 2
   f(2.2);      // Calls overload 2, a temporary of double is created $8.5/3
}

Automatic creation date for Django model form objects?

Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

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

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I also have the same problem, and the solution is I didn't bind the event in my onClick. so when it renders for the first time and the data is more, which ends up calling the state setter again, which triggers React to call your function again and so on.

export default function Component(props) {

function clickEvent (event, variable){
    console.log(variable);
}

return (
    <div>
        <IconButton
            key="close"
            aria-label="Close"
            color="inherit"
            onClick={e => clickEvent(e, 10)} // or you can call like this:onClick={() => clickEvent(10)} 
        >
    </div>
)
}

How can I truncate a datetime in SQL Server?

CONVERT(DATE, <yourdatetime>) or CONVERT(DATE, GetDate()) or CONVERT(DATE, CURRENT_TIMESTAMP)

sql try/catch rollback/commit - preventing erroneous commit after rollback

Transaction counter

--@@TRANCOUNT = 0
begin try
--@@TRANCOUNT = 0
BEGIN TRANSACTION tran1
 --@@TRANCOUNT = 1

        --your code
        -- if failed  @@TRANCOUNT = 1
        -- if success @@TRANCOUNT = 0

COMMIT TRANSACTION tran1

end try

begin catch
    print 'FAILED'
end catch

What's the actual use of 'fail' in JUnit test case?

I think the usual use case is to call it when no exception was thrown in a negative test.

Something like the following pseudo-code:

test_addNilThrowsNullPointerException()
{
    try {
        foo.add(NIL);                      // we expect a NullPointerException here
        fail("No NullPointerException");   // cause the test to fail if we reach this            
     } catch (NullNullPointerException e) {
        // OK got the expected exception
    }
}

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The general approach to write to any stream (not only MemoryStream) is to use BinaryWriter:

static void Write(Stream s, Byte[] bytes)
{
    using (var writer = new BinaryWriter(s))
    {
        writer.Write(bytes);
    }
}

Create SQL identity as primary key?

If you're using T-SQL, the only thing wrong with your code is that you used braces {} instead of parentheses ().

PS: Both IDENTITY and PRIMARY KEY imply NOT NULL, so you can omit that if you wish.

Adding image inside table cell in HTML

You have a TH floating at the top of your table which isn't within a TR. Fix that.

With regards to your image problem you;re referencing the image absolutely from your computer's hard drive. Don't do that.

You also have a closing tag which shouldn't be there.

It should be:

<img src="h.gif" alt="" border="3" height="100" width="100" />

Also this:

<table border = 5 bordercolor = red align = center>

Your colspans are also messed up. You only seem to have three columns but have colspans of 14 and 4 in your code.

Should be:

<table border="5" bordercolor="red" align="center">

Also you have no DOCTYPE declared. You should at least add:

<!DOCTYPE html> 

How to get main div container to align to centre?

Do not use the * selector as that will apply to all elements on the page. Suppose you have a structure like this:

...
<body>
    <div id="content">
        <b>This is the main container.</b>
    </div>
</body>
</html>

You can then center the #content div using:

#content {
    width: 400px;
    margin: 0 auto;
    background-color: #66ffff;
}

Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; } snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.

Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:

Bootstrap 4 card-deck with number of columns based on viewport

I got this to work by adding a min-width to the cards:

<div class="card mb-3" style="min-width: 18rem;">
  <p>Card content</p>
</div>

The cards don't go below this width, but still properly fill each row and have equal heights.

How to change int into int64?

This is probably obvious, but simplest:

i64 := int64(23)

How do I install cURL on cygwin?

On the Windows system where you want to install Cygwin with cURL download and run the Cygwin installer

64-bit: cygwin.com/setup-x86_64.exe 32-bit: cygwin.com/setup-x86.exe (if already installed, go to the setup file existed path)

D:\cygwin\setup (where the Cygwin is existed)

Click on the setup (setup-x86_64)

Follow the prompts in the Cygwin Setup wizard.

You can leave most settings at their default values. Pay specific attention to the following:

In the Select Your Internet Connectioin screen, select "Install from Internet".

In the Choose a download site screen, choose a site from the list, or add your own sites to the list, I have Chosen a: “mirrors.xmission.com”

The Select Packages screen displays a list of all the available packages and lets you select those you want to install. By default, only the packages in the "Base" category are marked for installation. The "Base" category does not include tools like cURL. You should select those explicitly.

By default, the packages are grouped by category. Click the View button to toggle to the Full view

Select all the curl packages by clicking the "Skip" button for each package once. Note how the "Skip" label changes to show the version number of the selected package.

the Select Packages screen should look like

Click Next through the rest of the wizard. The selected packages are downloaded and installed.

It worked for me and it resolved the issue : bash curl command not found cygwin

How to print a specific row of a pandas DataFrame?

Sounds like you're calling df.plot(). That error indicates that you're trying to plot a frame that has no numeric data. The data types shouldn't affect what you print().

Use print(df.iloc[159220])

What is the max size of localStorage values?

Don't assume 5MB is available - localStorage capacity varies by browser, with 2.5MB, 5MB and unlimited being the most common values. Source: http://dev-test.nemikor.com/web-storage/support-test/

Closing a file after File.Create

The function returns a FileStream object. So you could use it's return value to open your StreamWriter or close it using the proper method of the object:

File.Create(myPath).Close();

Python-equivalent of short-form "if" in C++

My cryptic version...

a = ['123', '456'][b == True]

LocalDate to java.util.Date and vice versa simplest conversion?

Actually there is. There is a static method valueOf in the java.sql.Date object which does exactly that. So we have

java.util.Date date = java.sql.Date.valueOf(localDate);

and that's it. No explicit setting of time zones because the local time zone is taken implicitly.

From docs:

The provided LocalDate is interpreted as the local date in the local time zone.

The java.sql.Date subclasses java.util.Date so the result is a java.util.Date also.

And for the reverse operation there is a toLocalDate method in the java.sql.Date class. So we have:

LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();

alert() not working in Chrome

I had the same issue recently on my test server. After searching for reasons this might be happening and testing the solutions I found here, I recalled that I had clicked the "Stop this page from creating pop-ups" option a few hours before when the script I was working on was wildly popping up alerts.

The solution was as simple as closing the tab and opening a fresh one!

Is it possible to break a long line to multiple lines in Python?

DB related code looks easier on the eyes in multiple lines, enclosed by a pair of triple quotes:

SQL = """SELECT
            id, 
            fld_1, 
            fld_2, 
            fld_3, 
            ...... 
         FROM some_tbl"""

than the following one giant long line:

SQL = "SELECT id, fld_1, fld_2, fld_3, .................................... FROM some_tbl"

jQuery show/hide not working

if (grid.selectedKeyNames().length > 0) {
            $('#btnRemoveFromList').show();
        } else {
            $('#btnRemoveFromList').hide();
        }

}

() - calls the method

no parentheses - returns the property

Difference between == and ===

In short:

== operator checks if their instance values are equal, "equal to"

=== operator checks if the references point the same instance, "identical to"

Long Answer:

Classes are reference types, it is possible for multiple constants and variables to refer to the same single instance of a class behind the scenes. Class references stay in Run Time Stack (RTS) and their instances stay in Heap area of Memory. When you control equality with == it means if their instances are equal to each other. It doesn't need to be same instance to be equal. For this you need to provide a equality criteria to your custom class. By default, custom classes and structures do not receive a default implementation of the equivalence operators, known as the “equal to” operator == and “not equal to” operator != . To do this your custom class needs to conform Equatable protocol and it's static func == (lhs:, rhs:) -> Bool function

Let's look at example:

class Person : Equatable {
    let ssn: Int
    let name: String

    init(ssn: Int, name: String) {
        self.ssn = ssn
        self.name = name
    }

    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.ssn == rhs.ssn
    }
}

P.S.: Since ssn(social security number) is a unique number, you don't need to compare if their name are equal or not.

let person1 = Person(ssn: 5, name: "Bob")
let person2 = Person(ssn: 5, name: "Bob")

if person1 == person2 {
   print("the two instances are equal!")
}

Although person1 and person2 references point two different instances in Heap area, their instances are equal because their ssn numbers are equal. So the output will be the two instance are equal!

if person1 === person2 {
   //It does not enter here
} else {
   print("the two instances are not identical!")
}

=== operator checks if the references point the same instance, "identical to". Since person1 and person2 have two different instance in Heap area, they are not identical and the output the two instance are not identical!

let person3 = person1

P.S: Classes are reference types and person1's reference is copied to person3 with this assignment operation, thus both references point the same instance in Heap area.

if person3 === person1 {
   print("the two instances are identical!")
}

They are identical and the output will be the two instances are identical!

How to create a density plot in matplotlib?

You can do something like:

s = np.random.normal(2, 3, 1000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 30, density=True)
plt.plot(bins, 1/(3 * np.sqrt(2 * np.pi)) * np.exp( - (bins - 2)**2 / (2 * 3**2) ), 
linewidth=2, color='r')
plt.show()

How to make a JTable non-editable

I used this and it worked : it is very simple and works fine.

JTable myTable = new JTable();
myTable.setEnabled(false);

jQuery Validation using the class instead of the name value

Another way you can do it, is using addClassRules. It's specific for classes, while the option using selector and .rules is more a generic way.

Before calling

$(form).validate()

Use like this:

jQuery.validator.addClassRules('myClassName', {
        required: true /*,
        other rules */
    });

Ref: http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules

I prefer this syntax for a case like this.

How to get the file path from HTML input form in Firefox 3

Simply you cannot do it with FF3.

The other option could be using applet or other controls to select and upload files.

How can I use pointers in Java?

All java objects are pointer because a variable which holds address is called pointer and object hold address.so object is pointer variable.

Sublime 3 - Set Key map for function Goto Definition

On a mac you have to set keybinding yourself. Simply go to

Sublime --> Preference --> Key Binding - User  

and input the following:

{ "keys": ["shift+command+m"], "command": "goto_definition" }

This will enable keybinding of Shift + Command + M to enable goto definition. You can set the keybinding to anything you would like of course.

Mod of negative number is melting my brain

Just add your modulus (arrayLength) to the negative result of % and you'll be fine.

How to style an asp.net menu with CSS

You can try styling with LevelSubMenuStyles

            <asp:Menu ID="mainMenu" runat="server" Orientation="Horizontal" 
                StaticEnableDefaultPopOutImage="False">
                <StaticMenuStyle CssClass="test" />
                <LevelSubMenuStyles>
                    <asp:SubMenuStyle BackColor="#33CCFF" BorderColor="#FF9999" 
                        Font-Underline="False" />
                    <asp:SubMenuStyle BackColor="#FF99FF" Font-Underline="False" />
                </LevelSubMenuStyles>
                <StaticMenuItemStyle CssClass="main-nav-item" />
            </asp:Menu>

Node update a specific package

Most of the time you can just npm update (or yarn upgrade) a module to get the latest non breaking changes (respecting the semver specified in your package.json) (<-- read that last part again).

npm update browser-sync
-------
yarn upgrade browser-sync
  • Use npm|yarn outdated to see which modules have newer versions
  • Use npm update|yarn upgrade (without a package name) to update all modules
  • Include --save-dev|--dev if you want to save the newer version numbers to your package.json. (NOTE: as of npm v5.0 this is only necessary for devDependencies).

Major version upgrades:

In your case, it looks like you want the next major version (v2.x.x), which is likely to have breaking changes and you will need to update your app to accommodate those changes. You can install/save the latest 2.x.x by doing:

npm install browser-sync@2 --save-dev
-------
yarn add browser-sync@2 --dev

...or the latest 2.1.x by doing:

npm install [email protected] --save-dev
-------
yarn add [email protected] --dev

...or the latest and greatest by doing:

npm install browser-sync@latest --save-dev
-------
yarn add browser-sync@latest --dev

Note: the last one is no different than doing this:

npm uninstall browser-sync --save-dev
npm install browser-sync --save-dev
-------
yarn remove browser-sync --dev
yarn add browser-sync --dev

The --save-dev part is important. This will uninstall it, remove the value from your package.json, and then reinstall the latest version and save the new value to your package.json.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The string you're trying to parse as a JSON is not encoded in UTF-8. Most likely it is encoded in ISO-8859-1. Try the following:

json.loads(unicode(opener.open(...), "ISO-8859-1"))

That will handle any umlauts that might get in the JSON message.

You should read Joel Spolsky's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!). I hope that it will clarify some issues you're having around Unicode.

surface plots in matplotlib

Just to chime in, Emanuel had the answer that I (and probably many others) are looking for. If you have 3d scattered data in 3 separate arrays, pandas is an incredible help and works much better than the other options. To elaborate, suppose your x,y,z are some arbitrary variables. In my case these were c,gamma, and errors because I was testing a support vector machine. There are many potential choices to plot the data:

  • scatter3D(cParams, gammas, avg_errors_array) - this works but is overly simplistic
  • plot_wireframe(cParams, gammas, avg_errors_array) - this works, but will look ugly if your data isn't sorted nicely, as is potentially the case with massive chunks of real scientific data
  • ax.plot3D(cParams, gammas, avg_errors_array) - similar to wireframe

Wireframe plot of the data

Wireframe plot of the data

3d scatter of the data

3d scatter of the data

The code looks like this:

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.set_xlabel('c parameter')
    ax.set_ylabel('gamma parameter')
    ax.set_zlabel('Error rate')
    #ax.plot_wireframe(cParams, gammas, avg_errors_array)
    #ax.plot3D(cParams, gammas, avg_errors_array)
    #ax.scatter3D(cParams, gammas, avg_errors_array, zdir='z',cmap='viridis')

    df = pd.DataFrame({'x': cParams, 'y': gammas, 'z': avg_errors_array})
    surf = ax.plot_trisurf(df.x, df.y, df.z, cmap=cm.jet, linewidth=0.1)
    fig.colorbar(surf, shrink=0.5, aspect=5)    
    plt.savefig('./plots/avgErrs_vs_C_andgamma_type_%s.png'%(k))
    plt.show()

Here is the final output:

plot_trisurf of xyz data

HTTP error 403 in Python 3 Web Scraping

Based on previous answers this has worked for me with Python 3.7

from urllib.request import Request, urlopen

req = Request('Url_Link', headers={'User-Agent': 'XYZ/3.0'})
webpage = urlopen(req, timeout=10).read()

print(webpage)

how to run the command mvn eclipse:eclipse

The m2e plugin uses it's own distribution of Maven, packaged with the plugin.

In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows

Once Maven is properly installed (i.e. be sure that MAVEN_HOME, JAVA_HOME and PATH variables are set correctly): you must run mvn eclipse:eclipse from the directory containing the pom.xml.

How to set time to midnight for current day?

Using some of the above recommendations, the following function and code is working for search a date range:

Set date with the time component set to 00:00:00

public static DateTime GetDateZeroTime(DateTime date)
{
    return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}

Usage

var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);

var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));

Open soft keyboard programmatically

I like to do it as an extension to Context so you can call it anywhere

fun Context.showKeyboard(editText: EditText) {
    val inputMethodManager: InputMethodManager =
        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.toggleSoftInputFromWindow(
        editText.applicationWindowToken,
        InputMethodManager.SHOW_IMPLICIT, 0
    )
    editText.requestFocus()
    editText.setSelection(editText.text.length)
}

fun Context.hideKeyboard(editText: EditText) {
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(editText.windowToken, 0)
}

Convert bytes to a string

From sys — System-specific parameters and functions:

To write or read binary data from/to the standard streams, use the underlying binary buffer. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc').

Can't push to remote branch, cannot be resolved to branch

I had the same problem but was resolved. I realized branch name is case sensitive. The main branch in GitHub is 'master', while in my gitbash command it's 'Master'. I renamed Master in local repository to master and it worked!

Reading inputStream using BufferedReader.readLine() is too slow

I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader's fault. Try measuring this:

InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing

I think you'll find it's almost exactly the same time as when you're parsing the text.

Note that you should also give InputStreamReader an appropriate encoding - the platform default encoding is almost certainly not what you should be using.

JavaScript file not updating no matter what I do

Are you 100% sure your browser is even loading the script? Go to your page in Firefox and use the console in Firebug to check if the script has been loaded or not.

Filtering DataSet

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

Regex: matching up to the first occurrence of a character

This was very helpful for me as I was trying to figure out how to match all the characters in an xml tag including attributes. I was running into the "matches everything to the end" problem with:

/<simpleChoice.*>/

but was able to resolve the issue with:

/<simpleChoice[^>]*>/

after reading this post. Thanks all.

Plotting using a CSV file

You can also plot to a png file using gnuplot (which is free):

terminal commands

gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'

note: you always need to give the right extension (.png here) at set output

Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:

plot '<Fromfile.csv>' with line lt -1 lw 2

More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html

  • gnuplot is available in most linux distros via the package manager (e.g. on an apt based distro, run apt-get install gnuplot)
  • gnuplot is available in windows via Cygwin
  • gnuplot is available on macOS via homebrew (run brew install gnuplot)

What is the Oracle equivalent of SQL Server's IsNull() function?

Also use NVL2 as below if you want to return other value from the field_to_check:

NVL2( field_to_check, value_if_NOT_null, value_if_null )

Usage: ORACLE/PLSQL: NVL2 FUNCTION

DataAdapter.Fill(Dataset)

leDbConnection connection = 
new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet1 DS = new DataSet1();
connection.Open();

OleDbDataAdapter DBAdapter = new OleDbDataAdapter(
@"SELECT tbl_Computer.*,  tbl_Besitzer.*
  FROM tbl_Computer 
  INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID 
  WHERE (((tbl_Besitzer.Vorname)='ma'));", 
connection);

How to convert integer to char in C?

Just assign the int to a char variable.

int i = 65;
char c = i;
printf("%c", c); //prints A