Programs & Examples On #Markov chains

Markov chains are systems which transition from one state to another based only upon their current state. They are used widely in various statistical domains to generate sequences based upon probabilities.

Configure WAMP server to send email

Configuring a working email client from localhost is quite a chore, I have spent hours of frustration attempting it. I'm sure someone more experienced may be able to help, or they may perhaps agree with me.

If you just want to test, here is a great tool for testing mail locally, that requires almost no configuration:

http://www.toolheap.com/test-mail-server-tool/

It worked right off the bat for me, hope this helps you.

Cannot run the macro... the macro may not be available in this workbook

I had the same problem as OP and found was due to the options declaration being misspelled:

' Comment comment  

Options Explicit  

Sub someMacroMakechart()

in a sub module, instead of correct;

' Comment comment  

Option Explicit  

Sub someMacroMakechart()

Node.js – events js 72 throw er unhandled 'error' event

Well, your script throws an error and you just need to catch it (and/or prevent it from happening). I had the same error, for me it was an already used port (EADDRINUSE).

SQL WHERE ID IN (id1, id2, ..., idn)

In most database systems, IN (val1, val2, …) and a series of OR are optimized to the same plan.

The third way would be importing the list of values into a temporary table and join it which is more efficient in most systems, if there are lots of values.

You may want to read this articles:

How to detect the character encoding of a text file?

Several answers are here but nobody has posted usefull code.

Here is my code that detects all encodings that Microsoft detects in Framework 4 in the StreamReader class.

Obviously you must call this function immediately after opening the stream before reading anything else from the stream because the BOM are the first bytes in the stream.

This function requires a Stream that can seek (for example a FileStream). If you have a Stream that cannot seek you must write a more complicated code that returns a Byte buffer with the bytes that have already been read but that are not BOM.

/// <summary>
/// UTF8    : EF BB BF
/// UTF16 BE: FE FF
/// UTF16 LE: FF FE
/// UTF32 BE: 00 00 FE FF
/// UTF32 LE: FF FE 00 00
/// </summary>
public static Encoding DetectEncoding(Stream i_Stream)
{
    if (!i_Stream.CanSeek || !i_Stream.CanRead)
        throw new Exception("DetectEncoding() requires a seekable and readable Stream");

    // Try to read 4 bytes. If the stream is shorter, less bytes will be read.
    Byte[] u8_Buf = new Byte[4];
    int s32_Count = i_Stream.Read(u8_Buf, 0, 4);
    if (s32_Count >= 2)
    {
        if (u8_Buf[0] == 0xFE && u8_Buf[1] == 0xFF)
        {
            i_Stream.Position = 2;
            return new UnicodeEncoding(true, true);
        }

        if (u8_Buf[0] == 0xFF && u8_Buf[1] == 0xFE)
        {
            if (s32_Count >= 4 && u8_Buf[2] == 0 && u8_Buf[3] == 0)
            {
                i_Stream.Position = 4;
                return new UTF32Encoding(false, true);
            }
            else
            {
                i_Stream.Position = 2;
                return new UnicodeEncoding(false, true);
            }
        }

        if (s32_Count >= 3 && u8_Buf[0] == 0xEF && u8_Buf[1] == 0xBB && u8_Buf[2] == 0xBF)
        {
            i_Stream.Position = 3;
            return Encoding.UTF8;
        }

        if (s32_Count >= 4 && u8_Buf[0] == 0 && u8_Buf[1] == 0 && u8_Buf[2] == 0xFE && u8_Buf[3] == 0xFF)
        {
            i_Stream.Position = 4;
            return new UTF32Encoding(true, true);
        }
    }

    i_Stream.Position = 0;
    return Encoding.Default;
}

How to get the first five character of a String

Append five whitespace characters then cut off the first five and trim the result. The number of spaces you append should match the number you are cutting. Be sure to include the parenthesis before .Substring(0,X) or you'll append nothing.

string str = (yourStringVariable + "    ").Substring(0,5).Trim();

With this technique you won't have to worry about the ArgumentOutOfRangeException mentioned in other answers.

Inline instantiation of a constant List

You are looking for a simple code, like this:

    List<string> tagList = new List<string>(new[]
    {
         "A"
        ,"B"
        ,"C"
        ,"D"
        ,"E"
    });

error: strcpy was not declared in this scope

Observations:

  • #include <cstring> should introduce std::strcpy().
  • using namespace std; (as written in medico.h) introduces any identifiers from std:: into the global namespace.

Aside from using namespace std; being somewhat clumsy once the application grows larger (as it introduces one hell of a lot of identifiers into the global namespace), and that you should never use using in a header file (see below!), using namespace does not affect identifiers introduced after the statement.

(using namespace std is written in the header, which is included in medico.cpp, but #include <cstring> comes after that.)

My advice: Put the using namespace std; (if you insist on using it at all) into medico.cpp, after any includes, and use explicit std:: in medico.h.


strcmpi() is not a standard function at all; while being defined on Windows, you have to solve case-insensitive compares differently on Linux.

(On general terms, I would like to point to this answer with regards to "proper" string handling in C and C++ that takes Unicode into account, as every application should. Summary: The standard cannot handle these things correctly; do use ICU.)


warning: deprecated conversion from string constant to ‘char*’

A "string constant" is when you write a string literal (e.g. "Hello") in your code. Its type is const char[], i.e. array of constant characters (as you cannot change the characters). You can assign an array to a pointer, but assigning to char *, i.e. removing the const qualifier, generates the warning you are seeing.


OT clarification: using in a header file changes visibility of identifiers for anyone including that header, which is usually not what the user of your header file wants. For example, I could use std::string and a self-written ::string just perfectly in my code, unless I include your medico.h, because then the two classes will clash.

Don't use using in header files.

And even in implementation files, it can introduce lots of ambiguity. There is a case to be made to use explicit namespacing in implementation files as well.

Appending to an object

jQuery $.extend(obj1, obj2) would merge 2 objects for you, but you should really be using an array.

var alertsObj = {
    1: {app:'helloworld','message'},
    2: {app:'helloagain',message:'another message'}
};

var alertArr = [
    {app:'helloworld','message'},
    {app:'helloagain',message:'another message'}
];

var newAlert = {app:'new',message:'message'};

$.extend(alertsObj, newAlert);
alertArr.push(newAlert);

Python: printing a file to stdout

f = open('file.txt', 'r')
print f.read()
f.close()

From http://docs.python.org/tutorial/inputoutput.html

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").

How do I remove the horizontal scrollbar in a div?

To hide the horizontal scrollbar, we can just select the scrollbar of the required div and set it to display: none;

One thing to note is that this will only work for WebKit-based browsers (like Chrome) as there is no such option available for Mozilla.

In order to select the scrollbar, use ::-webkit-scrollbar

So the final code will be like this:

div::-webkit-scrollbar {
  display: none;
}

Clone only one branch

You could create a new repo with

git init 

and then use

git fetch url-to-repo branchname:refs/remotes/origin/branchname

to fetch just that one branch into a local remote-tracking branch.

How to kill a child process by the parent process?

In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.

When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).

Remember to call wait() on the child process to prevent any lingering zombies.

How to uninstall / completely remove Oracle 11g (client)?

Do everything suggested by ziesemer.

You may also want to remove from the registry:

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\<any Ora* drivers> keys     

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers<any Ora* driver> values

So they no longer appear in the "ODBC Drivers that are installed on your system" in ODBC Data Source Administrator

LINQ Group By into a Dictionary Object

Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToDictionary(g => g.Key, g => g.ToList());

What is the easiest way to initialize a std::vector with hardcoded elements?

"How do I create an STL vector and initialize it like the above? What is the best way to do so with the minimum typing effort?"

The easiest way to initialize a vector as you've initialized your built-in array is using an initializer list which was introduced in C++11.

// Initializing a vector that holds 2 elements of type int.
Initializing:
std::vector<int> ivec = {10, 20};


// The push_back function is more of a form of assignment with the exception of course
//that it doesn't obliterate the value of the object it's being called on.
Assigning
ivec.push_back(30);

ivec is 3 elements in size after Assigning (labeled statement) is executed.

How can I create objects while adding them into a vector?

I know the thread is already all, but as I was checking through I've come up with a solution (code listed below). Hope it can help.

#include <iostream>
#include <vector>

class Box
{
    public:

    static int BoxesTotal;
    static int BoxesEver;
    int Id;

    Box()
    {
        ++BoxesTotal;
        ++BoxesEver;
        Id = BoxesEver;
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") initialized." << std::endl;
    }

    ~Box()
    {
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") ended." << std::endl;
        --BoxesTotal;
    }

};

int Box::BoxesTotal = 0;
int Box::BoxesEver = 0;

int main(int argc, char* argv[])
{
    std::cout << "Objects (Boxes) example." << std::endl;
    std::cout << "------------------------" << std::endl;

    std::vector <Box*> BoxesTab;

    Box* Indicator;
    for (int i = 1; i<4; ++i)
    {
        std::cout << "i = " << i << ":" << std::endl;
        Box* Indicator = new(Box);
        BoxesTab.push_back(Indicator);
        std::cout << "Adres Blowera: " <<  BoxesTab[i-1] << std::endl;
    }

    std::cout << "Summary" << std::endl;
    std::cout << "-------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Adres Blowera: " <<  BoxesTab[i] << std::endl;
    }

    std::cout << "Deleting" << std::endl;
    std::cout << "--------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Deleting Box: " << i+1 << " (" <<  BoxesTab[i] << ") " << std::endl;
        Indicator = (BoxesTab[i]);
        delete(Indicator);
    }

    return 0;
}

And the result it produces is:

Objects (Boxes) example.
------------------------
i = 1:
Box (1/1/1) initialized.
Adres Blowera: 0xdf8ca0
i = 2:
Box (2/2/2) initialized.
Adres Blowera: 0xdf8ce0
i = 3:
Box (3/3/3) initialized.
Adres Blowera: 0xdf8cc0
Summary
-------
Adres Blowera: 0xdf8ca0
Adres Blowera: 0xdf8ce0
Adres Blowera: 0xdf8cc0
Deleting
--------
Deleting Box: 1 (0xdf8ca0) 
Box (1/3/3) ended.
Deleting Box: 2 (0xdf8ce0) 
Box (2/2/3) ended.
Deleting Box: 3 (0xdf8cc0) 
Box (3/1/3) ended.

Does it matter what extension is used for SQLite database files?

In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db

The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!

Totally depends on your usage scenario I suppose.

Change string color with NSAttributedString?

One liner for Swift:

NSAttributedString(string: "Red Text", attributes: [.foregroundColor: UIColor.red])

How to change background color of cell in table using java script

<table border="1" cellspacing="0" cellpadding= "20">
    <tr>
    <td id="id1" ></td>
    </tr>
</table>
<script>
    document.getElementById('id1').style.backgroundColor='#003F87';
</script>

Put id for cell and then change background of the cell.

Data at the root level is invalid

I found that the example I was using had an xml document specification on the first line. I was using a stylesheet I got at this blog entry and the first line was

<?xmlversion="1.0"encoding="utf-8"?>

which was causing the error. When I removed that line, so that the stylesheet started with the line

<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

my transform worked. By the way, that blog post was the first good, easy-to follow example I have found for trying to get information from the XML definition of an SSIS package, but I did have to modify the paths in the example for my SSIS 2008 packages, so you might too. I also created a version to extract the "flow" from the precedence constraints. My final one looks like this:

    <xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="utf-8" />
    <xsl:template match="/">
    <xsl:text>From,To~</xsl:text>
    <xsl:text>
</xsl:text>
    <xsl:for-each select="//DTS:PrecedenceConstraints/DTS:PrecedenceConstraint">
      <xsl:value-of select="@DTS:From"/>
      <xsl:text>,</xsl:text>
      <xsl:value-of select="@DTS:To"/>
       <xsl:text>~</xsl:text>
      <xsl:text>
</xsl:text>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

and gave me a CSV with the tilde as my line delimiter. I replaced that with a line feed in my text editor then imported into excel to get a with look at the data flow in the package.

What are these attributes: `aria-labelledby` and `aria-hidden`

HTML5 ARIA attribute is what you're looking for. It can be used in your code even without bootstrap.

Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications (especially those developed with Ajax and JavaScript) more accessible to people with disabilities.

To be precise for your question, here is what your attributes are called as ARIA attribute states and model

aria-labelledby: Identifies the element (or elements) that labels the current element.

aria-hidden (state): Indicates that the element and all of its descendants are not visible or perceivable to any user as implemented by the author.

How can I view array structure in JavaScript with alert()?

Better use Firebug (chrome console etc) and use console.dir()

How can I get query string values in JavaScript?

There is a nice little url utility for this with some cool sugaring:

http://www.example.com/path/index.html?silly=willy#chucky=cheese

url();            // http://www.example.com/path/index.html?silly=willy#chucky=cheese
url('domain');    // example.com
url('1');         // path
url('-1');        // index.html
url('?');         // silly=willy
url('?silly');    // willy
url('?poo');      // (an empty string)
url('#');         // chucky=cheese
url('#chucky');   // cheese
url('#poo');      // (an empty string)

Check out more examples and download here: https://github.com/websanova/js-url#url

Why use prefixes on member variables in C++ classes

You have to be careful with using a leading underscore. A leading underscore before a capital letter in a word is reserved. For example:

_Foo

_L

are all reserved words while

_foo

_l

are not. There are other situations where leading underscores before lowercase letters are not allowed. In my specific case, I found the _L happened to be reserved by Visual C++ 2005 and the clash created some unexpected results.

I am on the fence about how useful it is to mark up local variables.

Here is a link about which identifiers are reserved: What are the rules about using an underscore in a C++ identifier?

MySQL skip first 10 results

There is an OFFSET as well that should do the trick:

SELECT column FROM table
LIMIT 10 OFFSET 10

How to remove leading and trailing zeros in a string? Python

Remove leading + trailing '0':

list = [i.strip('0') for i in listOfNum ]

Remove leading '0':

list = [ i.lstrip('0') for i in listOfNum ]

Remove trailing '0':

list = [ i.rstrip('0') for i in listOfNum ]

Installing cmake with home-brew

  1. Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)

  2. Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.

  3. Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"

  4. Reload your .bashrc file: source ~/.bashrc

  5. Verify the latest cmake version is installed: cmake --version

  6. You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.

How to check if running as root in a bash script

A few answers have been given, but it appears that the best method is to use is:

  • id -u
  • If run as root, will return an id of 0.

This appears to be more reliable than the other methods, and it seems that it return an id of 0 even if the script is run through sudo.

Android Color Picker

I ended up here looking for a HSV color picker that offered transparency and copy/paste of the hex value. None of the existing answers met those needs, so here's the library I ended up writing:

HSV-Alpha Color Picker for Android (GitHub).

HSV-Alpha Color Picker Demo (Google Play).

I hope it's useful for somebody else.

Color Picker Dialog

Is it possible to run a .NET 4.5 app on XP?

Last version to support windows XP (SP3) is mono-4.3.2.467-gtksharp-2.12.30.1-win32-0.msi and that doesnot replace .NET 4.5 but could be of interest for some applications.

see there: https://download.mono-project.com/archive/4.3.2/windows-installer/

using nth-child in tables tr td

table tr td:nth-child(2) {
    background: #ccc;
}

Working example: http://jsfiddle.net/gqr3J/

Android Studio not showing modules in project structure

Check settings.gradle. You'll find this : include ':app'

Just add your own module name and it should look like this :

include ':app', ':yourModuleName'

Sync.

That's it.

ReferenceError: document is not defined (in plain JavaScript)

Try adding the script element just before the /body tag like that

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>
<body>

    <div id="divid">Next</div>
    <script type="text/javascript" src="js/quiz.js"></script>
</body>
</html>

python global name 'self' is not defined

The self name is used as the instance reference in class instances. It is only used in class method definitions. Don't use it in functions.

You also cannot reference local variables from other functions or methods with it. You can only reference instance or class attributes using it.

Changing the space between each item in Bootstrap navbar

As of Bootstrap 4, you can use the spacing utilities.

Add for instance px-2 in the classes of the nav-item to increase the padding.

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

You do not need to use ORDER BY in inner query after WHERE clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC).

SELECT 
    * 
FROM (
    SELECT 
        Stockmain.VRNOA, 
        item.description as item_description, 
        party.name as party_name, 
        stockmain.vrdate, 
        stockdetail.qty, 
        stockdetail.rate, 
        stockdetail.amount, 
        ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum  --< ORDER BY
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
) AS MyDerivedTable
WHERE 
    MyDerivedTable.RowNum BETWEEN 1 and 5 

Extract number from string with Oracle function

You'd use REGEXP_REPLACE in order to remove all non-digit characters from a string:

select regexp_replace(column_name, '[^0-9]', '')
from mytable;

or

select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;

Of course you can write a function extract_number. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.

create function extract_number(in_number varchar2) return varchar2 is
begin
  return regexp_replace(in_number, '[^[:digit:]]', '');
end; 

php: check if an array has duplicates

Here's my take on this… after some benchmarking, I found this to be the fastest method for this.

function has_duplicates( $array ) {
    return count( array_keys( array_flip( $array ) ) ) !== count( $array );
}

…or depending on circumstances this could be marginally faster.

function has_duplicates( $array ) {
    $array = array_count_values( $array );
    rsort( $array );
    return $array[0] > 1;
}

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

Simple and easy:

$this->db->order_by("name", "asc");
$query = $this->db->get($this->table_name);
return $query->result();

How to resolve Unneccessary Stubbing exception

Silent is not a solution. You need fix your mock in your test. See official documentation here.

Unnecessary stubs are stubbed method calls that were never realized during test execution (see also MockitoHint), example:

//code under test:
 ...
 String result = translator.translate("one")
 ...

 //test:
 ...
 when(translator.translate("one")).thenReturn("jeden"); // <- stubbing realized during code execution
 when(translator.translate("two")).thenReturn("dwa"); // <- stubbing never realized
 ...

Notice that one of the stubbed methods were never realized in the code under test, during test execution. The stray stubbing might be an oversight of the developer, the artifact of copy-paste or the effect not understanding the test/code. Either way, the developer ends up with unnecessary test code. In order to keep the codebase clean & maintainable it is necessary to remove unnecessary code. Otherwise tests are harder to read and reason about.

To find out more about detecting unused stubbings see MockitoHint.

Is it possible to validate the size and type of input=file in html5

    <form  class="upload-form">
        <input class="upload-file" data-max-size="2048" type="file" >
        <input type=submit>
    </form>
    <script>
$(function(){
    var fileInput = $('.upload-file');
    var maxSize = fileInput.data('max-size');
    $('.upload-form').submit(function(e){
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                alert('file size is more then' + maxSize + ' bytes');
                return false;
            }else{
                alert('file size is correct- '+fileSize+' bytes');
            }
        }else{
            alert('choose file, please');
            return false;
        }

    });
});
    </script>

http://jsfiddle.net/9bhcB/2/

FCM getting MismatchSenderId

  • I cross verified all the credentials

  • Added new server key and deleted old one

  • Downloaded google-services.json again

Nothing solved the issue

Then I just clean the project and then rebuild the project.After that it's working fine

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

How to force garbage collection in Java?

Under the documentation for OutOfMemoryError it declares that it will not be thrown unless the VM has failed to reclaim memory following a full garbage collection. So if you keep allocating memory until you get the error, you will have already forced a full garbage collection.

Presumably the question you really wanted to ask was "how can I reclaim the memory I think I should be reclaiming by garbage collection?"

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

The link posted by Jose has been updated and pylab now has a tight_layout() function that does this automatically (in matplotlib version 1.1.0).

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout

http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout

Where does the @Transactional annotation belong?

Service layer is best place to add @Transactional annotations as most of the business logic present here, it contain detail level use-case behaviour.

Suppose we add it to DAO and from service we are calling 2 DAO classes , one failed and other success , in this case if @Transactional not on service one DB will commit and other will rollback.

Hence my recommendation is use this annotation wisely and use at Service layer only.

Github project- java-algos

Why I can't access remote Jupyter Notebook server?

I got the same problem but none of workarounds above work for me. But if I setup a docker version jupyter notebook, with the same configuration, it works out for me.

For my stituation, it might be iptables rule issues. Sometimes you may just using ufw to allow all route to your server. But mine just iptables -F to clear all rule. Then check iptables -L -n to see if its works.

Problem fixed.

C++: what regex library should I use?

Thanks for all the suggestions.

I tried out a few things today, and with the stuff we're trying to do, I opted for the simplest solution where I don't have to download any other 3rd-party library. In the end, I #include <regex.h> and used the standard C POSIX calls regcomp() and regexec(). Not C++, but in a pinch this proved to be the easiest.

Keras, How to get the output of each layer?

I wrote this function for myself (in Jupyter) and it was inspired by indraforyou's answer. It will plot all the layer outputs automatically. Your images must have a (x, y, 1) shape where 1 stands for 1 channel. You just call plot_layer_outputs(...) to plot.

%matplotlib inline
import matplotlib.pyplot as plt
from keras import backend as K

def get_layer_outputs():
    test_image = YOUR IMAGE GOES HERE!!!
    outputs    = [layer.output for layer in model.layers]          # all layer outputs
    comp_graph = [K.function([model.input]+ [K.learning_phase()], [output]) for output in outputs]  # evaluation functions

    # Testing
    layer_outputs_list = [op([test_image, 1.]) for op in comp_graph]
    layer_outputs = []

    for layer_output in layer_outputs_list:
        print(layer_output[0][0].shape, end='\n-------------------\n')
        layer_outputs.append(layer_output[0][0])

    return layer_outputs

def plot_layer_outputs(layer_number):    
    layer_outputs = get_layer_outputs()

    x_max = layer_outputs[layer_number].shape[0]
    y_max = layer_outputs[layer_number].shape[1]
    n     = layer_outputs[layer_number].shape[2]

    L = []
    for i in range(n):
        L.append(np.zeros((x_max, y_max)))

    for i in range(n):
        for x in range(x_max):
            for y in range(y_max):
                L[i][x][y] = layer_outputs[layer_number][x][y][i]


    for img in L:
        plt.figure()
        plt.imshow(img, interpolation='nearest')

SVN- How to commit multiple files in a single shot

I've had no issues committing a few files like this:

svn commit fileDir1/ fileDir2/ -m "updated!"

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

I am able to use this feature on my machine using MS Access 2007.

  • On the Ribbon, select External Data
  • Select the "Text File" option
  • This displays the Get External Data Wizard
  • Specify the location of the file you wish to import
  • Click OK. This displays the "Import Text Wizard"
  • On the bottom of this dialog screen is the Advanced button you referenced
  • Clicking on this button should display the Import Specification screen and allow you to select and modify an existing import spec.

For what its worth, I'm using Access 2007 SP1

ArrayList vs List<> in C#

ArrayList is the collections of different types data whereas List<> is the collection of similar type of its own depedencties.

How do I use cx_freeze?

I ran into a similar issue. I solved it by setting the Executable options in a variable and then simply calling the variable. Below is a sample setup.py that I use:

from cx_Freeze import setup, Executable
import sys

productName = "ProductName"
if 'bdist_msi' in sys.argv:
    sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName]
    sys.argv += ['--install-script', 'install.py']

exe = Executable(
      script="main.py",
      base="Win32GUI",
      targetName="Product.exe"
     )
setup(
      name="Product.exe",
      version="1.0",
      author="Me",
      description="Copyright 2012",
      executables=[exe],
      scripts=[
               'install.py'
               ]
      ) 

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

Why use pip over easy_install?

As an addition to fuzzyman's reply:

pip won't install binary packages and isn't well tested on Windows.

As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.

Here is a trick on Windows:

  • you can use easy_install <package> to install binary packages to avoid building a binary

  • you can use pip uninstall <package> even if you used easy_install.

This is just a work-around that works for me on windows. Actually I always use pip if no binaries are involved.

See the current pip doku: http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install

I will ask on the mailing list what is planned for that.

Here is the latest update:

The new supported way to install binaries is going to be wheel! It is not yet in the standard, but almost. Current version is still an alpha: 1.0.0a1

https://pypi.python.org/pypi/wheel

http://wheel.readthedocs.org/en/latest/

I will test wheel by creating an OS X installer for PySide using wheel instead of eggs. Will get back and report about this.

cheers - Chris

A quick update:

The transition to wheel is almost over. Most packages are supporting wheel.

I promised to build wheels for PySide, and I did that last summer. Works great!

HINT: A few developers failed so far to support the wheel format, simply because they forget to replace distutils by setuptools. Often, it is easy to convert such packages by replacing this single word in setup.py.

How to Solve Max Connection Pool Error

Before you begin to curse your application you need to check this:

  1. Is your application the only one using that instance of SQL Server. a. If the answer to that is NO then you need to investigate how the other applications are consuming resources on your SQl Server.run b. If the answer is yes then you must investigate your application.

  2. Run SQL Server Profiler and check what activity is happening in other applications (1a) using SQL Server and check your application as well (1b).

  3. If indeed your application is starved off of resources then you need to make farther investigations. For more read on this http://sqlserverplanet.com/troubleshooting/sql-server-slowness

Are global variables bad?

Global variables are fine in small programs, but horrible if used the same way in large ones.

This means that you can easily get in the habit of using them while learning. This is what your professor is trying to protect you from.

When you are more experienced it will be easier to learn when they are okay.

How do I fix "The expression of type List needs unchecked conversion...'?

It looks like SyndFeed is not using generics.

You could either have an unsafe cast and a warning suppression:

@SuppressWarnings("unchecked")
List<SyndEntry> entries = (List<SyndEntry>) sf.getEntries();

or call Collections.checkedList - although you'll still need to suppress the warning:

@SuppressWarnings("unchecked")
List<SyndEntry> entries = Collections.checkedList(sf.getEntries(), SyndEntry.class);

Get unique values from a list in python

If you want to get unique elements from a list and keep their original order, then you may employ OrderedDict data structure from Python's standard library:

from collections import OrderedDict

def keep_unique(elements):
    return list(OrderedDict.fromkeys(elements).keys())

elements = [2, 1, 4, 2, 1, 1, 5, 3, 1, 1]
required_output = [2, 1, 4, 5, 3]

assert keep_unique(elements) == required_output

In fact, if you are using Python = 3.6, you can use plain dict for that:

def keep_unique(elements):
    return list(dict.fromkeys(elements).keys())

It's become possible after the introduction of "compact" representation of dicts. Check it out here. Though this "considered an implementation detail and should not be relied upon".

iOS: How to store username/password within an app?

If you need an ARC version of the wrapper here is the link https://gist.github.com/1170641 Thanks to

How to compare character ignoring case in primitive types

You can't actually do the job quite right with toLowerCase, either on a string or in a character. The problem is that there are variant glyphs in either upper or lower case, and depending on whether you uppercase or lowercase your glyphs may or may not be preserved. It's not even clear what you mean when you say that two variants of a lower-case glyph are compared ignoring case: are they or are they not the same? (Note that there are also mixed-case glyphs: \u01c5, \u01c8, \u01cb, \u01f2 or ?, ?, ?, ?, but any method suggested here will work on those as long as they should count as the same as their fully upper or full lower case variants.)

There is an additional problem with using Char: there are some 80 code points not representable with a single Char that are upper/lower case variants (40 of each), at least as detected by Java's code point upper/lower casing. You therefore need to get the code points and change the case on these.

But code points don't help with the variant glyphs.

Anyway, here's a complete list of the glyphs that are problematic due to variants, showing how they fare against 6 variant methods:

  1. Character toLowerCase
  2. Character toUpperCase
  3. String toLowerCase
  4. String toUpperCase
  5. String equalsIgnoreCase
  6. Character toLowerCase(toUpperCase) (or vice versa)

For these methods, S means that the variants are treated the same as each other, D means the variants are treated as different from each other.

Behavior     Unicode                             Glyphs
===========  ==================================  =========
1 2 3 4 5 6  Upper  Lower  Var Up Var Lo Vr Lo2  U L u l l2
- - - - - -  ------ ------ ------ ------ ------  - - - - -
D D D D S S  \u0049 \u0069 \u0130 \u0131         I i I i   
S D S D S S  \u004b \u006b \u212a                K k K     
D S D S S S  \u0053 \u0073        \u017f         S s   ?   
D S D S S S  \u039c \u03bc        \u00b5         ? µ   µ   
S D S D S S  \u00c5 \u00e5 \u212b                Å å Å     
D S D S S S  \u0399 \u03b9        \u0345 \u1fbe  ? ?   ? ? 
D S D S S S  \u0392 \u03b2        \u03d0         ? ß   ?   
D S D S S S  \u0395 \u03b5        \u03f5         ? e   ?   
D D D D S S  \u0398 \u03b8 \u03f4 \u03d1         T ? ? ?   
D S D S S S  \u039a \u03ba        \u03f0         ? ?   ?   
D S D S S S  \u03a0 \u03c0        \u03d6         ? p   ?   
D S D S S S  \u03a1 \u03c1        \u03f1         ? ?   ?   
D S D S S S  \u03a3 \u03c3        \u03c2         S s   ?   
D S D S S S  \u03a6 \u03c6        \u03d5         F f   ?   
S D S D S S  \u03a9 \u03c9 \u2126                O ? ?     
D S D S S S  \u1e60 \u1e61        \u1e9b         ? ?   ?   

Complicating this still further is that there is no way to get the Turkish I's right (i.e. the dotted versions are different than the undotted versions) unless you know you're in Turkish; none of these methods give correct behavior and cannot unless you know the locale (i.e. non-Turkish: i and I are the same ignoring case; Turkish, not).

Overall, using toUpperCase gives you the closest approximation, since you have only five uppercase variants (or four, not counting Turkish).

You can also try to specifically intercept those five troublesome cases and call toUpperCase(toLowerCase(c)) on them alone. If you choose your guards carefully (just toUpperCase if c < 0x130 || c > 0x212B, then work through the other alternatives) you can get only a ~20% speed penalty for characters in the low range (as compared to ~4x if you convert single characters to strings and equalsIgnoreCase them) and only about a 2x penalty if you have a lot in the danger zone. You still have the locale problem with dotted I, but otherwise you're in decent shape. Of course if you can use equalsIgnoreCase on a larger string, you're better off doing that.

Here is sample Scala code that does the job:

def elevateCase(c: Char): Char = {
  if (c < 0x130 || c > 0x212B) Character.toUpperCase(c)
  else if (c == 0x130 || c == 0x3F4 || c == 0x2126 || c >= 0x212A)
    Character.toUpperCase(Character.toLowerCase(c))
  else Character.toUpperCase(c)
}

How to "properly" create a custom object in JavaScript?

I use this pattern fairly frequently - I've found that it gives me a pretty huge amount of flexibility when I need it. In use it's rather similar to Java-style classes.

var Foo = function()
{

    var privateStaticMethod = function() {};
    var privateStaticVariable = "foo";

    var constructor = function Foo(foo, bar)
    {
        var privateMethod = function() {};
        this.publicMethod = function() {};
    };

    constructor.publicStaticMethod = function() {};

    return constructor;
}();

This uses an anonymous function that is called upon creation, returning a new constructor function. Because the anonymous function is called only once, you can create private static variables in it (they're inside the closure, visible to the other members of the class). The constructor function is basically a standard Javascript object - you define private attributes inside of it, and public attributes are attached to the this variable.

Basically, this approach combines the Crockfordian approach with standard Javascript objects to create a more powerful class.

You can use it just like you would any other Javascript object:

Foo.publicStaticMethod(); //calling a static method
var test = new Foo();     //instantiation
test.publicMethod();      //calling a method

node.js remove file

Here below my code which works fine.

         const fs = require('fs');
         fs.unlink(__dirname+ '/test.txt', function (err) {            
              if (err) {                                                 
                  console.error(err);                                    
              }                                                          
             console.log('File has been Deleted');                           
          });                                                            

Min width in window resizing

You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:

body{
   min-width:1000px;        /* Suppose you want minimum width of 1000px */
   width: auto !important;  /* Firefox will set width as auto */
   width:1000px;            /* As IE6 ignores !important it will set width as 1000px; */
}

Or:

body{
   min-width:1000px; // Suppose you want minimum width of 1000px
   _width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

On windows be sure the console is started as aministrator

how to execute php code within javascript

You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:

alert("<?php echo "asdasda";?>");

don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.

as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:

$.ajax({
  url: 'test.php',
  success: function(data) {
    $('.result').html(data);
  }
});

and test.php would be:

<?php 
  echo 'asdasda';
?>

it would write the contents of test.php to whatever element has the result class.

How do I rename a column in a SQLite database table?

Since version 2018-09-15 (3.25.0) sqlite supports renaming columns

https://sqlite.org/changes.html

What is the difference between SQL and MySQL?

SQL - Structured Query Language. It is declarative computer language aimed at querying relational databases.

MySQL is a relational database - a piece of software optimized for data storage and retrieval. There are many such databases - Oracle, Microsoft SQL Server, SQLite and many others are examples of such.

Setting up connection string in ASP.NET to SQL SERVER

Store connection string in web.config

It is a good practice to store the connection string for your application in a config file rather than as a hard coded string in your code. The way to do this differs between .NET 2.0 and .NET 3.5 (and above). This article cover both. https://www.connectionstrings.com/store-connection-string-in-webconfig/

PHP: Call to undefined function: simplexml_load_string()

If the XML module is not installed, install it.

Current version 5.6 on ubuntu 14.04:

sudo apt-get install php5.6-xml

And don't forget to run sudo service apache2 restart command after it

Zulhilmi Zainudi

Exit a while loop in VBS/VBA

what about changing the while loop to a do while loop

and exit using

Exit Do

How To Use DateTimePicker In WPF?

There is no out of the box DateTime picker for WPF..

There are however a lot of third party DateTime pickers of course :)

http://www.devcomponents.com/dotnetbar-wpf/WPFDateTimePicker.aspx

http://marlongrech.wordpress.com/2007/09/11/wpf-datepicker/

http://www.codeplex.com/AvalonControlsLib

Just do a quick google to find more!

JavaScript Editor Plugin for Eclipse

In 2015 I would go with:

  • For small scripts: The js editor + jsHint plugin
  • For large code bases: TypeScript Eclipse plugin, or a similar transpiled language... I only know that TypeScript works well in Eclipse.

Of course you may want to keep JS for easy project setup and to avoid the transpilation process... there is no ultimate solution.

Or just wait for ECMA6, 7, ... :)

LOAD DATA INFILE Error Code : 13

I too have struggled with this problem over the past few days and I too turned to stack overflow for answers.

However, no one seems to mention the simplest way to import data into MySQL is actually through their very own import data wizard tool!!

Just right-click on the table and it comes up there.

just right click on the table and it comes up there

None of the above answers helped me, so just use this if you're stuck! :)

Should I put input elements inside a label element?

As most people have said, both ways work indeed, but I think only the first one should. Being semantically strict, the label does not "contain" the input. In my opinion, containment (parent/child) relationship in the markup structure should reflect containment in the visual output. i.e., an element surrounding another one in the markup should be drawn around that one in the browser. According to this, the label should be the input's sibling, not it's parent. So option number two is arbitrary and confusing. Everyone that has read the Zen of Python will probably agree (Flat is better than nested, Sparse is better than dense, There should be one-- and preferably only one --obvious way to do it...).

Because of decisions like that from W3C and major browser vendors (allowing "whichever way you prefer to do it", instead of "do it the right way") is that the web is so messed up today and we developers have to deal with tangled and so diverse legacy code.

I want to use CASE statement to update some records in sql server 2005

If you don't want to repeat the list twice (as per @J W's answer), then put the updates in a table variable and use a JOIN in the UPDATE:

declare @ToDo table (FromName varchar(10), ToName varchar(10))
insert into @ToDo(FromName,ToName) values
 ('AAA','BBB'),
 ('CCC','DDD'),
 ('EEE','FFF')

update ts set LastName = ToName
from dbo.TestStudents ts
       inner join
     @ToDo t
       on
         ts.LastName = t.FromName

How can I convince IE to simply display application/json rather than offer to download it?

I just had the same issue with an XMLHttpRequest. The site functions flawlessly in Chrome and FF, and in dozens upon dozens of Internet Explorer browsers in production. This ONE machine (the one our company is setting up to be a demo machine, of course) decided that it was going to prompt to save the json response to an ajax request.

The accepted regedit solution below fixed it. Thanks.

How to get Time from DateTime format in SQL?

Get date of server

SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), GETDATE(), 100), 7)) FROM TABLENAME WHERE ...

or

If it is stored in the table

SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), datename, 100), 7)) FROM TABLENAME WHERE ...

Result:

11:41AM

TypeError: ObjectId('') is not JSON serializable

SOLUTION for: mongoengine + marshmallow

If you use mongoengine and marshamallow then this solution might be applicable for you.

Basically, I imported String field from marshmallow, and I overwritten default Schema id to be String encoded.

from marshmallow import Schema
from marshmallow.fields import String

class FrontendUserSchema(Schema):

    id = String()

    class Meta:
        fields = ("id", "email")

Eloquent get only one column as an array

That can be done in short as:

Model::pluck('column')

where model is the Model such as User model & column as column name like id

if you do

User::pluck('id') // [1,2,3, ...]

& of course you can have any other clauses like where clause before pluck

How to ignore SSL certificate errors in Apache HttpClient 4.0

You need to create a SSLContext with your own TrustManager and create HTTPS scheme using this context. Here is the code,

SSLContext sslContext = SSLContext.getInstance("SSL");

// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                    System.out.println("getAcceptedIssuers =============");
                    return null;
            }

            public void checkClientTrusted(X509Certificate[] certs,
                            String authType) {
                    System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs,
                            String authType) {
                    System.out.println("checkServerTrusted =============");
            }
} }, new SecureRandom());

SSLSocketFactory sf = new SSLSocketFactory(sslContext);
Scheme httpsScheme = new Scheme("https", 443, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);

// apache HttpClient version >4.2 should use BasicClientConnectionManager
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

Getting a list of all subdirectories in the current directory

Listing Out only directories

print("\nWe are listing out only the directories in current directory -")
directories_in_curdir = filter(os.path.isdir, os.listdir(os.curdir))
print(directories_in_curdir)

Listing Out only files in current directory

files = filter(os.path.isfile, os.listdir(os.curdir))
print("\nThe following are the list of all files in the current directory -")
print(files)

Make Https call using HttpClient

I had the same problem when connecting to GitHub, which requires a user agent. Thus it is sufficient to provide this rather than generating a certificate

var client = new HttpClient();

client.BaseAddress = new Uri("https://api.github.com");
client.DefaultRequestHeaders.Add(
    "Authorization",
    "token 123456789307d8c1d138ddb0848ede028ed30567");
client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add(
    "User-Agent",
    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");

How to delete a specific file from folder using asp.net

Check the GridView1.SelectedRow is not null:

if (GridView1.SelectedRow == null) return;
string DeleteThis = GridView1.SelectedRow.Cells[0].Text;

How to speed up insertion performance in PostgreSQL

For optimal Insertion performance disable the index if that's an option for you. Other than that, better hardware (disk, memory) is also helpful

constant pointer vs pointer on a constant value

char * const a;

*a is writable, but a is not; in other words, you can modify the value pointed to by a, but you cannot modify a itself. a is a constant pointer to char.

const char * a; 

a is writable, but *a is not; in other words, you can modify a (pointing it to a new location), but you cannot modify the value pointed to by a.

Note that this is identical to

char const * a;

In this case, a is a pointer to a const char.

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

How to select last one week data from today's date

to select records for the last 7 days

WHERE Created_Date >= DATEADD(day, -7, GETDATE())

to select records for the current week

SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM
WHERE CreatedDate >= DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE())) 
  AND CreatedDate <  DATEADD(day, 8 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))

if you want to select records for last week instead of the last 7 days

SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM  
WHERE CreatedDate >= DATEADD(day, -(DATEPART(dw, GETDATE()) + 6), CONVERT(DATE, GETDATE())) 
  AND CreatedDate <  DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))

How to run console application from Windows Service?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.ServiceProcess;
using System.Runtime.InteropServices;

namespace SystemControl
{
    class Services
    {
        static string strPath = @"D:\";
        static void Main(string[] args)
        {
            string strServiceName = "WindowsService1";
            CreateFolderStructure(strPath);
            string svcPath = @"D:\Applications\MSC\Agent\bin\WindowsService1.exe";
            if (!IsInstalled(strServiceName))
            {
                InstallAndStart(strServiceName, strServiceName, svcPath + " -k runservice");                
            }
            else
            {
                Console.Write(strServiceName + " already installed. Do you want to Uninstalled the Service.Y/N.?");
                string strKey = Console.ReadLine();

                if (!string.IsNullOrEmpty(strKey) && (strKey.StartsWith("y")|| strKey.StartsWith("Y")))
                {
                    StopService(strServiceName);
                    Uninstall(strServiceName);
                    ServiceLogs(strServiceName + " Uninstalled.!", strPath);
                    Console.Write(strServiceName + " Uninstalled.!");
                    Console.Read();
                }
            }
        }

        #region "Environment Variables"
        public static string GetEnvironment(string name, bool ExpandVariables = true)
        {
            if (ExpandVariables)
            {
                return System.Environment.GetEnvironmentVariable(name);
            }
            else
            {
                return (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\").GetValue(name, "", Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames);
            }
        }

        public static void SetEnvironment(string name, string value)
        {
            System.Environment.SetEnvironmentVariable(name, value);
        }
        #endregion

        #region "ServiceCalls Native"
        public static ServiceController[] List { get { return ServiceController.GetServices(); } }

        public static void Start(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = new ServiceController(serviceName);
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch(Exception ex)
            {
                // ...
            }
        }

        public static void Stop(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = new ServiceController(serviceName);
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            }
            catch
            {
                // ...
            }
        }

        public static void Restart(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = new ServiceController(serviceName);
            try
            {
                int millisec1 = Environment.TickCount;
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

                // count the rest of the timeout
                int millisec2 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch
            {
                // ...
            }
        }

        public static bool IsInstalled(string serviceName)
        {
            // get list of Windows services
            ServiceController[] services = ServiceController.GetServices();

            // try to find service name
            foreach (ServiceController service in services)
            {
                if (service.ServiceName == serviceName)
                    return true;
            }
            return false;
        }
        #endregion

        #region "ServiceCalls API"
        private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
        private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010;

        [Flags]
        public enum ServiceManagerRights
        {
            Connect = 0x0001,
            CreateService = 0x0002,
            EnumerateService = 0x0004,
            Lock = 0x0008,
            QueryLockStatus = 0x0010,
            ModifyBootConfig = 0x0020,
            StandardRightsRequired = 0xF0000,
            AllAccess = (StandardRightsRequired | Connect | CreateService |
            EnumerateService | Lock | QueryLockStatus | ModifyBootConfig)
        }

        [Flags]
        public enum ServiceRights
        {
            QueryConfig = 0x1,
            ChangeConfig = 0x2,
            QueryStatus = 0x4,
            EnumerateDependants = 0x8,
            Start = 0x10,
            Stop = 0x20,
            PauseContinue = 0x40,
            Interrogate = 0x80,
            UserDefinedControl = 0x100,
            Delete = 0x00010000,
            StandardRightsRequired = 0xF0000,
            AllAccess = (StandardRightsRequired | QueryConfig | ChangeConfig |
            QueryStatus | EnumerateDependants | Start | Stop | PauseContinue |
            Interrogate | UserDefinedControl)
        }

        public enum ServiceBootFlag
        {
            Start = 0x00000000,
            SystemStart = 0x00000001,
            AutoStart = 0x00000002,
            DemandStart = 0x00000003,
            Disabled = 0x00000004
        }

        public enum ServiceState
        {
            Unknown = -1, // The state cannot be (has not been) retrieved.
            NotFound = 0, // The service is not known on the host server.
            Stop = 1, // The service is NET stopped.
            Run = 2, // The service is NET started.
            Stopping = 3,
            Starting = 4,
        }

        public enum ServiceControl
        {
            Stop = 0x00000001,
            Pause = 0x00000002,
            Continue = 0x00000003,
            Interrogate = 0x00000004,
            Shutdown = 0x00000005,
            ParamChange = 0x00000006,
            NetBindAdd = 0x00000007,
            NetBindRemove = 0x00000008,
            NetBindEnable = 0x00000009,
            NetBindDisable = 0x0000000A
        }

        public enum ServiceError
        {
            Ignore = 0x00000000,
            Normal = 0x00000001,
            Severe = 0x00000002,
            Critical = 0x00000003
        }

        [StructLayout(LayoutKind.Sequential)]
        private class SERVICE_STATUS
        {
            public int dwServiceType = 0;
            public ServiceState dwCurrentState = 0;
            public int dwControlsAccepted = 0;
            public int dwWin32ExitCode = 0;
            public int dwServiceSpecificExitCode = 0;
            public int dwCheckPoint = 0;
            public int dwWaitHint = 0;
        }

        [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerA")]
        private static extern IntPtr OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerRights dwDesiredAccess);
        [DllImport("advapi32.dll", EntryPoint = "OpenServiceA", CharSet = CharSet.Ansi)]
        private static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceRights dwDesiredAccess);
        [DllImport("advapi32.dll", EntryPoint = "CreateServiceA")]
        private static extern IntPtr CreateService(IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceRights dwDesiredAccess, int dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword);
        [DllImport("advapi32.dll")]
        private static extern int CloseServiceHandle(IntPtr hSCObject);
        [DllImport("advapi32.dll")]
        private static extern int QueryServiceStatus(IntPtr hService, SERVICE_STATUS lpServiceStatus);
        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern int DeleteService(IntPtr hService);
        [DllImport("advapi32.dll")]
        private static extern int ControlService(IntPtr hService, ServiceControl dwControl, SERVICE_STATUS lpServiceStatus);
        [DllImport("advapi32.dll", EntryPoint = "StartServiceA")]
        private static extern int StartService(IntPtr hService, int dwNumServiceArgs, int lpServiceArgVectors);

        /// <summary>
        /// Takes a service name and tries to stop and then uninstall the windows serviceError
        /// </summary>
        /// <param name="ServiceName">The windows service name to uninstall</param>
        public static void Uninstall(string ServiceName)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);
            try
            {
                IntPtr service = OpenService(scman, ServiceName, ServiceRights.StandardRightsRequired | ServiceRights.Stop | ServiceRights.QueryStatus);
                if (service == IntPtr.Zero)
                {
                    throw new ApplicationException("Service not installed.");
                }
                try
                {
                    StopService(service);
                    int ret = DeleteService(service);
                    if (ret == 0)
                    {
                        int error = Marshal.GetLastWin32Error();
                        throw new ApplicationException("Could not delete service " + error);
                    }
                }
                finally
                {
                    CloseServiceHandle(service);
                }
            }
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Accepts a service name and returns true if the service with that service name exists
        /// </summary>
        /// <param name="ServiceName">The service name that we will check for existence</param>
        /// <returns>True if that service exists false otherwise</returns>
        public static bool ServiceIsInstalled(string ServiceName)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);
            try
            {
                IntPtr service = OpenService(scman, ServiceName,
                ServiceRights.QueryStatus);
                if (service == IntPtr.Zero) return false;
                CloseServiceHandle(service);
                return true;
            }
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Takes a service name, a service display name and the path to the service executable and installs / starts the windows service.
        /// </summary>
        /// <param name="ServiceName">The service name that this service will have</param>
        /// <param name="DisplayName">The display name that this service will have</param>
        /// <param name="FileName">The path to the executable of the service</param>
        public static void InstallAndStart(string ServiceName, string DisplayName,
        string FileName)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect |
            ServiceManagerRights.CreateService);
            try
            {
                string strKey = string.Empty;
                IntPtr service = OpenService(scman, ServiceName,
                ServiceRights.QueryStatus | ServiceRights.Start);
                if (service == IntPtr.Zero)
                {
                    service = CreateService(scman, ServiceName, DisplayName,
                    ServiceRights.QueryStatus | ServiceRights.Start, SERVICE_WIN32_OWN_PROCESS,
                    ServiceBootFlag.AutoStart, ServiceError.Normal, FileName, null, IntPtr.Zero,
                    null, null, null);
                    ServiceLogs(ServiceName + " Installed Sucessfully.!", strPath);
                    Console.Write(ServiceName + " Installed Sucessfully.! Do you want to Start the Service.Y/N.?");
                    strKey=Console.ReadLine();
                }
                if (service == IntPtr.Zero)
                {
                    ServiceLogs("Failed to install service.", strPath);
                    throw new ApplicationException("Failed to install service.");
                }
                try
                {
                    if (!string.IsNullOrEmpty(strKey) && (strKey.StartsWith("y") || strKey.StartsWith("Y")))
                    {
                        StartService(service);
                        ServiceLogs(ServiceName + " Started Sucessfully.!", strPath);
                        Console.Write(ServiceName + " Started Sucessfully.!");
                        Console.Read();
                    }
                }
                finally
                {
                    CloseServiceHandle(service);
                }
            }
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Takes a service name and starts it
        /// </summary>
        /// <param name="Name">The service name</param>
        public static void StartService(string Name)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);
            try
            {
                IntPtr hService = OpenService(scman, Name, ServiceRights.QueryStatus |
                ServiceRights.Start);
                if (hService == IntPtr.Zero)
                {
                    ServiceLogs("Could not open service.", strPath);
                    throw new ApplicationException("Could not open service.");
                }
                try
                {
                    StartService(hService);
                }
                finally
                {
                    CloseServiceHandle(hService);
                }
            }
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Stops the provided windows service
        /// </summary>
        /// <param name="Name">The service name that will be stopped</param>
        public static void StopService(string Name)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);
            try
            {
                IntPtr hService = OpenService(scman, Name, ServiceRights.QueryStatus |
                ServiceRights.Stop);
                if (hService == IntPtr.Zero)
                {
                    ServiceLogs("Could not open service.", strPath);
                    throw new ApplicationException("Could not open service.");
                }
                try
                {
                    StopService(hService);
                }
                finally
                {
                    CloseServiceHandle(hService);
                }



}
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Stars the provided windows service
        /// </summary>
        /// <param name="hService">The handle to the windows service</param>
        private static void StartService(IntPtr hService)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();
            StartService(hService, 0, 0);
            WaitForServiceStatus(hService, ServiceState.Starting, ServiceState.Run);
        }

        /// <summary>
        /// Stops the provided windows service
        /// </summary>
        /// <param name="hService">The handle to the windows service</param>
        private static void StopService(IntPtr hService)
        {
            SERVICE_STATUS status = new SERVICE_STATUS();
            ControlService(hService, ServiceControl.Stop, status);
            WaitForServiceStatus(hService, ServiceState.Stopping, ServiceState.Stop);
        }

        /// <summary>
        /// Takes a service name and returns the <code>ServiceState</code> of the corresponding service
        /// </summary>
        /// <param name="ServiceName">The service name that we will check for his <code>ServiceState</code></param>
        /// <returns>The ServiceState of the service we wanted to check</returns>
        public static ServiceState GetServiceStatus(string ServiceName)
        {
            IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);
            try
            {
                IntPtr hService = OpenService(scman, ServiceName,
                ServiceRights.QueryStatus);
                if (hService == IntPtr.Zero)
                {
                    return ServiceState.NotFound;
                }
                try
                {
                    return GetServiceStatus(hService);
                }
                finally
                {
                    CloseServiceHandle(scman);
                }
            }
            finally
            {
                CloseServiceHandle(scman);
            }
        }

        /// <summary>
        /// Gets the service state by using the handle of the provided windows service
        /// </summary>
        /// <param name="hService">The handle to the service</param>
        /// <returns>The <code>ServiceState</code> of the service</returns>
        private static ServiceState GetServiceStatus(IntPtr hService)
        {
            SERVICE_STATUS ssStatus = new SERVICE_STATUS();
            if (QueryServiceStatus(hService, ssStatus) == 0)
            {
                ServiceLogs("Failed to query service status.", strPath);
                throw new ApplicationException("Failed to query service status.");
            }
            return ssStatus.dwCurrentState;
        }

        /// <summary>
        /// Returns true when the service status has been changes from wait status to desired status
        /// ,this method waits around 10 seconds for this operation.
        /// </summary>
        /// <param name="hService">The handle to the service</param>
        /// <param name="WaitStatus">The current state of the service</param>
        /// <param name="DesiredStatus">The desired state of the service</param>
        /// <returns>bool if the service has successfully changed states within the allowed timeline</returns>
        private static bool WaitForServiceStatus(IntPtr hService, ServiceState
        WaitStatus, ServiceState DesiredStatus)
        {
            SERVICE_STATUS ssStatus = new SERVICE_STATUS();
            int dwOldCheckPoint;
            int dwStartTickCount;

            QueryServiceStatus(hService, ssStatus);
            if (ssStatus.dwCurrentState == DesiredStatus) return true;
            dwStartTickCount = Environment.TickCount;
            dwOldCheckPoint = ssStatus.dwCheckPoint;

            while (ssStatus.dwCurrentState == WaitStatus)
            {
                // Do not wait longer than the wait hint. A good interval is
                // one tenth the wait hint, but no less than 1 second and no
                // more than 10 seconds.

                int dwWaitTime = ssStatus.dwWaitHint / 10;

                if (dwWaitTime < 1000) dwWaitTime = 1000;
                else if (dwWaitTime > 10000) dwWaitTime = 10000;

                System.Threading.Thread.Sleep(dwWaitTime);

                // Check the status again.

                if (QueryServiceStatus(hService, ssStatus) == 0) break;

                if (ssStatus.dwCheckPoint > dwOldCheckPoint)
                {
                    // The service is making progress.
                    dwStartTickCount = Environment.TickCount;
                    dwOldCheckPoint = ssStatus.dwCheckPoint;
                }
                else
                {
                    if (Environment.TickCount - dwStartTickCount > ssStatus.dwWaitHint)
                    {
                        // No progress made within the wait hint
                        break;
                    }
                }
            }
            return (ssStatus.dwCurrentState == DesiredStatus);
        }

        /// <summary>
        /// Opens the service manager
        /// </summary>
        /// <param name="Rights">The service manager rights</param>
        /// <returns>the handle to the service manager</returns>
        private static IntPtr OpenSCManager(ServiceManagerRights Rights)
        {
            IntPtr scman = OpenSCManager(null, null, Rights);
            if (scman == IntPtr.Zero)
            {
                try
                {
                    throw new ApplicationException("Could not connect to service control manager.");
                }
                catch (Exception ex)
                {
                }
            }
            return scman;
        }

        #endregion

        #region"CreateFolderStructure"
        private static void CreateFolderStructure(string path)
        {
            if(!System.IO.Directory.Exists(path+"Applications"))
                System.IO.Directory.CreateDirectory(path+ "Applications");
            if (!System.IO.Directory.Exists(path + "Applications\\MSC"))
                System.IO.Directory.CreateDirectory(path + "Applications\\MSC");
            if (!System.IO.Directory.Exists(path + "Applications\\MSC\\Agent"))
                System.IO.Directory.CreateDirectory(path + "Applications\\MSC\\Agent");
            if (!System.IO.Directory.Exists(path + "Applications\\MSC\\Agent\\bin"))
                System.IO.Directory.CreateDirectory(path + "Applications\\MSC\\Agent\\bin");
            if (!System.IO.Directory.Exists(path + "Applications\\MSC\\AgentService"))
                System.IO.Directory.CreateDirectory(path + "Applications\\MSC\\AgentService");

            string fullPath = System.IO.Path.GetFullPath("MSCService");
            if (System.IO.Directory.Exists(fullPath))
            {
                foreach (string strFile in System.IO.Directory.GetFiles(fullPath))
                {
                    if (System.IO.File.Exists(strFile))
                    {
                        String[] strArr = strFile.Split('\\');
                        System.IO.File.Copy(strFile, path + "Applications\\MSC\\Agent\\bin\\"+ strArr[strArr.Count()-1], true);
                    }
                }
            }            
        }
        #endregion

        private static void ServiceLogs(string strLogInfo, string path)
        {
            string filePath = path + "Applications\\MSC\\AgentService\\ServiceLogs.txt";            
            System.IO.File.AppendAllLines(filePath, (strLogInfo + "--" + DateTime.Now.ToString()).ToString().Split('|'));
        }
    }
}

C - Convert an uppercase letter to lowercase

In ASCII the upper and lower case alphabet is 0x20 (in ASCII 0x20 is space ' ') apart from each other, so this is another way to do it.

int lower(int a) 
{
    return a | ' ';  
}

Simulate delayed and dropped packets on Linux

One of my colleagues uses tc to do this. Refer to the man page for more information. You can see an example of its usage here.

Get the ID of a drawable in ImageView

Digging StackOverflow for answers on the similar issue I found people usually suggesting 2 approaches:

  • Load a drawable into memory and compare ConstantState or bitmap itself to other one.
  • Set a tag with drawable id into a view and compare tags when you need that.

Personally, I like the second approach for performance reason but tagging bunch of views with appropriate tags is painful and time consuming. This could be very frustrating in a big project. In my case I need to write a lot of Espresso tests which require comparing TextView drawables, ImageView resources, View background and foreground. A lot of work.

So I eventually came up with a solution to delegate a 'dirty' work to the custom inflater. In every inflated view I search for a specific attributes and and set a tag to the view with a resource id if any is found. This approach is pretty much the same guys from Calligraphy used. I wrote a simple library for that: TagView

If you use it, you can retrieve any of predefined tags, containing drawable resource id that was set in xml layout file:

TagViewUtils.getTag(view, ViewTag.IMAGEVIEW_SRC.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_LEFT.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_TOP.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_RIGHT.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_BOTTOM.id)
TagViewUtils.getTag(view, ViewTag.VIEW_BACKGROUND.id)
TagViewUtils.getTag(view, ViewTag.VIEW_FOREGROUND.id)

The library supports any attribute, actually. You can add them manually, just look into the Custom attributes section on Github. If you set a drawable in runtime you can use convenient library methods:

setImageViewResource(ImageView view, int id)

In this case tagging is done for you internally. If you use Kotlin you can write a handy extensions to call view itself. Something like this:

fun ImageView.setImageResourceWithTag(@DrawableRes int id) {
    TagViewUtils.setImageViewResource(this, id)
}

You can find additional info in Tagging in runtime

JSONResult to String

You're looking for the JavaScriptSerializer class, which is used internally by JsonResult:

string json = new JavaScriptSerializer().Serialize(jsonResult.Data);

PHP Composer update "cannot allocate memory" error (using Laravel 4)

I tried by just deleting the vendor folder and composer.lock file and then i run the command composer clear-cache and then composer install. So it working without any error.

Connect Java to a MySQL database

MySql JDBC Connection:

Class.forName("com.mysql.jdbc.Driver");     

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");         
Statement stmt=con.createStatement();            
stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("Select * from Table");  

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

Creating SolidColorBrush from hex color value

I've been using:

new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));

How to delete a file from SD card?

I had a similar issue with an application running on 4.4. What I did was sort of a hack.

I renamed the files and ignored them in my application.

ie.

File sdcard = Environment.getExternalStorageDirectory();
                File from = new File(sdcard,"/ecatAgent/"+fileV);
                File to = new File(sdcard,"/ecatAgent/"+"Delete");
                from.renameTo(to);

Search for "does-not-contain" on a DataFrame in pandas

I had to get rid of the NULL values before using the command recommended by Andy above. An example:

df = pd.DataFrame(index = [0, 1, 2], columns=['first', 'second', 'third'])
df.ix[:, 'first'] = 'myword'
df.ix[0, 'second'] = 'myword'
df.ix[2, 'second'] = 'myword'
df.ix[1, 'third'] = 'myword'
df

    first   second  third
0   myword  myword   NaN
1   myword  NaN      myword 
2   myword  myword   NaN

Now running the command:

~df["second"].str.contains(word)

I get the following error:

TypeError: bad operand type for unary ~: 'float'

I got rid of the NULL values using dropna() or fillna() first and retried the command with no problem.

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

try it:

EXEC [ServerName].[DatabaseName].dbo.sp_columns 'TableName'

and you can get some table structure information, such as:

TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, COLUMN_NAME, DATA_TYPE, TYPE_NAME...

What is difference between functional and imperative programming languages?

Here is the difference:

Imperative:

  • Start
  • Turn on your shoes size 9 1/2.
  • Make room in your pocket to keep an array[7] of keys.
  • Put the keys in the room for the keys in the pocket.
  • Enter garage.
  • Open garage.
  • Enter Car.

... and so on and on ...

  • Put the milk in the refrigerator.
  • Stop.

Declarative, whereof functional is a subcategory:

  • Milk is a healthy drink, unless you have problems digesting lactose.
  • Usually, one stores milk in a refrigerator.
  • A refrigerator is a box that keeps the things in it cool.
  • A store is a place where items are sold.
  • By "selling" we mean the exchange of things for money.
  • Also, the exchange of money for things is called "buying".

... and so on and on ...

  • Make sure we have milk in the refrigerator (when we need it - for lazy functional languages).

Summary: In imperative languages you tell the computer how to change bits, bytes and words in it's memory and in what order. In functional ones, we tell the computer what things, actions etc. are. For example, we say that the factorial of 0 is 1, and the factorial of every other natural number is the product of that number and the factorial of its predecessor. We don't say: To compute the factorial of n, reserve a memory region and store 1 there, then multiply the number in that memory region with the numbers 2 to n and store the result at the same place, and at the end, the memory region will contain the factorial.

How to access a dictionary element in a Django template?

Ideally, you would create a method on the choice object that found itself in votes, or create a relationship between the models. A template tag that performed the dictionary lookup would work, too.

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT * FROM 
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser

How do you POST to a page using the PHP header() function?

There is a good class that does what you want. It can be downloaded at: http://sourceforge.net/projects/snoopy/

Make git automatically remove trailing whitespace before committing

Please try my pre-commit hooks, it can auto detect trailing-whitespace and remove it. Thank you!

it can work under GitBash(windows), Mac OS X and Linux!


Snapshot:

$ git commit -am "test"
auto remove trailing whitespace in foobar/main.m!
auto remove trailing whitespace in foobar/AppDelegate.m!
[master 80c11fe] test
1 file changed, 2 insertions(+), 2 deletions(-)

selecting an entire row based on a variable excel vba

One needs to make sure the space between the variables and '&' sign. Check the image. (Red one showing invalid commands)

Error

The correct solution is

Dim copyToRow: copyToRow = 5      
Rows(copyToRow & ":" & copyToRow).Select

Using the slash character in Git branch name

I forgot that I had already an unused labs branch. Deleting it solved my problem:

git branch -d labs
git checkout -b labs/feature

Explanation:

Each name can only be a parent branch or a normal branch, not both. Thats why the branches labs and labs/feature can't exists both at the same time.

The reason: Branches are stored in the file system and there you also can't have a file labs and a directory labs at the same level.

how to call scalar function in sql server 2008

For some reason I was not able to use my scalar function until I referenced it using brackets, like so:

select [dbo].[fun_functional_score]('01091400003')

Angular redirect to login page

1. Create a guard as seen below. 2. Install ngx-cookie-service to get cookies returned by external SSO. 3. Create ssoPath in environment.ts (SSO Login redirection). 4. Get the state.url and use encodeURIComponent.

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from 
  '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { environment } from '../../../environments/environment.prod';

@Injectable()
export class AuthGuardService implements CanActivate {
  private returnUrl: string;
  constructor(private _router: Router, private cookie: CookieService) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.cookie.get('MasterSignOn')) {
      return true;
    } else {
      let uri = window.location.origin + '/#' + state.url;
      this.returnUrl = encodeURIComponent(uri);      
      window.location.href = environment.ssoPath +  this.returnUrl ;   
      return false;      
    }
  }
}

How to repair a serialized string which has been corrupted by an incorrect byte count length?

You will have to alter the collation type to utf8_unicode_ci and the problem will be fixed.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

Rank each of the squares with numeric scores. If a square is taken, move on to the next choice (sorted in descending order by rank). You're going to need to choose a strategy (there are two main ones for going first and three (I think) for second). Technically, you could just program all of the strategies and then choose one at random. That would make for a less predictable opponent.

How does #include <bits/stdc++.h> work in C++?

#include <bits/stdc++.h> is an implementation file for a precompiled header.

From, software engineering perspective, it is a good idea to minimize the include. If you use it actually includes a lot of files, which your program may not need, thus increase both compile-time and program size unnecessarily. [edit: as pointed out by @Swordfish in the comments that the output program size remains unaffected. But still, it's good practice to include only the libraries you actually need, unless it's some competitive competition]

But in contests, using this file is a good idea, when you want to reduce the time wasted in doing chores; especially when your rank is time-sensitive.

It works in most online judges, programming contest environments, including ACM-ICPC (Sub-Regionals, Regionals, and World Finals) and many online judges.

The disadvantages of it are that it:

  • increases the compilation time.
  • uses an internal non-standard header file of the GNU C++ library, and so will not compile in MSVC, XCode, and many other compilers

Fatal error: Out of memory, but I do have plenty of memory (PHP)

Hey I also got the same problem on my server. I just changed the following things :

change php.ini to...

memory_limit = 128M

and add to httpd.conf

RLimitMEM 1073741824 2147483648

and restart apache & i removed the error :

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Python: list of lists

Time traveller here

List_of_list =[([z for z in range(x-2,x+1) if z >= 0],y) for y in range(10) for x in range(10)]

This should do the trick. And the output is this:

[([0], 0), ([0, 1], 0), ([0, 1, 2], 0), ([1, 2, 3], 0), ([2, 3, 4], 0),  ([3, 4, 5], 0), ([4, 5, 6], 0), ([5, 6, 7], 0), ([6, 7, 8], 0), ([7, 8, 9], 0), ([0], 1), ([0, 1], 1), ([0, 1, 2], 1), ([1, 2, 3], 1), ([2, 3, 4], 1), ([3, 4, 5], 1), ([4, 5, 6], 1), ([5, 6, 7], 1), ([6, 7, 8], 1), ([7, 8, 9], 1), ([0], 2), ([0, 1], 2), ([0, 1, 2], 2), ([1, 2, 3], 2), ([2, 3, 4], 2), ([3, 4, 5], 2), ([4, 5, 6], 2), ([5, 6, 7], 2), ([6, 7, 8], 2), ([7, 8, 9], 2), ([0], 3), ([0, 1], 3), ([0, 1, 2], 3), ([1, 2, 3], 3), ([2, 3, 4], 3), ([3, 4, 5], 3), ([4, 5, 6], 3), ([5, 6, 7], 3), ([6, 7, 8], 3), ([7, 8, 9], 3), ([0], 4), ([0, 1], 4), ([0, 1, 2], 4), ([1, 2, 3], 4), ([2, 3, 4], 4), ([3, 4, 5], 4), ([4, 5, 6], 4), ([5, 6, 7], 4), ([6, 7, 8], 4), ([7, 8, 9], 4), ([0], 5), ([0, 1], 5), ([0, 1, 2], 5), ([1, 2, 3], 5), ([2, 3, 4], 5), ([3, 4, 5], 5), ([4, 5, 6], 5), ([5, 6, 7], 5), ([6, 7, 8], 5), ([7, 8, 9], 5), ([0], 6), ([0, 1], 6), ([0, 1, 2], 6), ([1, 2, 3], 6), ([2, 3, 4], 6), ([3, 4, 5], 6), ([4, 5, 6], 6), ([5, 6, 7], 6), ([6, 7, 8], 6), ([7, 8, 9], 6), ([0], 7), ([0, 1], 7), ([0, 1, 2], 7), ([1, 2, 3], 7), ([2, 3, 4], 7), ([3, 4, 5], 7), ([4, 5, 6], 7), ([5, 6, 7], 7), ([6, 7, 8], 7), ([7, 8, 9], 7), ([0], 8), ([0, 1], 8), ([0, 1, 2], 8), ([1, 2, 3], 8), ([2, 3, 4], 8), ([3, 4, 5], 8), ([4, 5, 6], 8), ([5, 6, 7], 8), ([6, 7, 8], 8), ([7, 8, 9], 8), ([0], 9), ([0, 1], 9), ([0, 1, 2], 9), ([1, 2, 3], 9), ([2, 3, 4], 9), ([3, 4, 5], 9), ([4, 5, 6], 9), ([5, 6, 7], 9), ([6, 7, 8], 9), ([7, 8, 9], 9)]    

This is done by list comprehension(which makes looping elements in a list via one line code possible). The logic behind this one-line code is the following:

(1) for x in range(10) and for y in range(10) are employed for two independent loops inside a list

(2) (a list, y) is the general term of the loop, which is why it is placed before two for's in (1)

(3) the length of the list in (2) cannot exceed 3, and the list depends on x, so

[z for z in range(x-2,x+1)] 

is used

(4) because z starts from zero but range(x-2,x+1) starts from -2 which isn't what we want, so a conditional statement if z >= 0 is placed at the end of the list in (2)

[z for z in range(x-2,x+1) if z >= 0] 

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

This solution may help you if you know your problem is limited to Facades and you are running Laravel 5.5 or above.

Install laravel-ide-helper

composer require --dev barryvdh/laravel-ide-helper

Add this conditional statement in your AppServiceProvider to register the helper class.

public function register()
{
    if ($this->app->environment() !== 'production') {
        $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
    }
    // ...
}

Then run php artisan ide-helper:generate to generate a file to help the IDE understand Facades. You will need to restart Visual Studio Code.

References

https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/16

https://github.com/barryvdh/laravel-ide-helper

How to use the PRINT statement to track execution as stored procedure is running?

SQL Server returns messages after a batch of statements has been executed. Normally, you'd use SQL GO to indicate the end of a batch and to retrieve the results:

PRINT '1'
GO

WAITFOR DELAY '00:00:05'

PRINT '2'
GO

WAITFOR DELAY '00:00:05'

PRINT '3'
GO

In this case, however, the print statement you want returned immediately is in the middle of a loop, so the print statements cannot be in their own batch. The only command I know of that will return in the middle of a batch is RAISERROR (...) WITH NOWAIT, which gbn has provided as an answer as I type this.

How to recover Git objects damaged by hard disk failure?

The solution by Daniel Fanjul looked promissing. I was able to find that blob file and extracted it ("git fsck --full --no-dangling", "git cat-file -t {hash}", "git show {hash} > file.tmp") but when I tried to update pack file with "git hash-object -w file.tmp", it displayed correct hash BUT the error remained.

So I decided to try different approach. I could simply delete local repository and download everything from remote but some branches in local repository were 8 commits ahead and I did not want to lose those changes. Since that tiny, 6kb mp3 file, I decided to delete it completely. I tried many ways but the best was from here: https://itextpdf.com/en/blog/technical-notes/how-completely-remove-file-git-repository

I got the file name by running this command "git rev-list --objects --all | grep {hash}". Then I did a backup (strongly recommend to do so because I failed 3 times) and then run the command:

"java -jar bfg.jar --delete-files {filename} --no-blob-protection ."

You can get bfg.jar file from here https://rtyley.github.io/bfg-repo-cleaner/ so according to documentation I should run this command next:

"git reflog expire --expire=now --all && git gc --prune=now --aggressive"

When I did so, I got errors on last step. So I recovered everything from backup and this time, after removing file, I checkout to the branch (which was causing that error), then check out back to main and only after run the command one after each other:

"git reflog expire --expire=now --all" "git gc --prune=now --aggressive"

Then I added my file back to its location and comit. However, since many local commits were changed, I was not able to push anything to server. So I backup everything on server (in case I screw it), check out to the branch which was affected and run the command "git push --force".

What I understood from this case? GIT is great but so senstive... I should have an option to simply disregard one f... 6kb file I know what I am doing. I have no clude why "git hash-object -w" did not work either =( Lessons learnt, push all commits, do not wait, do backup of repository time to time. Also I know how to remove files from repository, if I ever need =)

I hope this saves someone's time

how to redirect to external url from c# controller

Try this:

return Redirect("http://www.website.com");

What is the difference between substr and substring?

The difference is second parameter. Their second parameters, while both numbers, are expecting two different things:

When using substring the second parameter is the first index not to include:

var s = "string";
s.substring(1, 3); // would return 'tr'

var s = "another example";
s.substring(3, 7); // would return 'ther'

When using substr the second parameter is the number of characters to include in the substring:

var s = "string";
s.substr(1, 3); // would return 'tri'

var s = "another example";
s.substr(3, 7); // would return 'ther ex'

.NET NewtonSoft JSON deserialize map to a different property name

If you'd like to use dynamic mapping, and don't want to clutter up your model with attributes, this approach worked for me

Usage:

var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new CustomContractResolver();
this.DataContext = JsonConvert.DeserializeObject<CountResponse>(jsonString, settings);

Logic:

public class CustomContractResolver : DefaultContractResolver
{
    private Dictionary<string, string> PropertyMappings { get; set; }

    public CustomContractResolver()
    {
        this.PropertyMappings = new Dictionary<string, string> 
        {
            {"Meta", "meta"},
            {"LastUpdated", "last_updated"},
            {"Disclaimer", "disclaimer"},
            {"License", "license"},
            {"CountResults", "results"},
            {"Term", "term"},
            {"Count", "count"},
        };
    }

    protected override string ResolvePropertyName(string propertyName)
    {
        string resolvedName = null;
        var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
        return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
    }
}

What is secret key for JWT based authentication and how to generate it?

A Json Web Token made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

Now let's do some practices with nodejs:

Configuration file is perfect for storing JWT SECRET data. Using the standard HSA 256 encryption for the signature, the secret should at least be 32 characters long, but the longer the better.

config.env:

JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret
//after 90days JWT will no longer be valid, even the signuter is correct and everything is matched.
JWT_EXPIRES_IN=90

now install JWT using command

npm i jsonwebtoken

Example after user signup passing him JWT token so he can stay logged in and get access of resources.

exports.signup = catchAsync(async (req, res, next) => {
  const newUser = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    passwordConfirm: req.body.passwordConfirm,
  });
  const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });

  res.status(201).json({
    status: 'success',
    token,
    data: {
      newUser,
    },
  });
});

output: enter image description here

In my opinion, do not take help from a third-party to generate your super-secret key, because you can't say it's secret anymore. Just use your keyboard.

Program to find largest and second largest number in array

#include<stdio.h>

int main()
{
    int a[10];
    int i,b,c;

    printf("Enter ten values : \n");
    for(i=0; i<10; i++)
    {
        scanf("%d",&a[i]);
    }

    b=a[0];

    for(i=0; i<10; i++)
    {
        if(a[i]>b)
        {
            b=a[i];
        }

        else
        {
            b=b;
        }
    }

    if(b==a[1])
    {
        c=a[2];
    }
    else 
    {
        c=a[1];
    }

    for(i=0; i<10; i++)
    {
        if(a[i]>c && a[i]!=b)
        {
            c=a[i];
        }

        else if (b>c)
        {
            c=c;
        }

    }




    printf("Largest number is %d\nSecond largest number is %d",b,c);

}

How do you calculate log base 2 in Java for integers?

Some cases just worked when I used Math.log10:

public static double log2(int n)
{
    return (Math.log10(n) / Math.log10(2));
}

What's the most efficient way to test two integer ranges for overlap?

My case is different. i want check two time ranges overlap. there should not be a unit time overlap. here is Go implementation.

    func CheckRange(as, ae, bs, be int) bool {
    return (as >= be) != (ae > bs)
    }

Test cases

if CheckRange(2, 8, 2, 4) != true {
        t.Error("Expected 2,8,2,4 to equal TRUE")
    }

    if CheckRange(2, 8, 2, 4) != true {
        t.Error("Expected 2,8,2,4 to equal TRUE")
    }

    if CheckRange(2, 8, 6, 9) != true {
        t.Error("Expected 2,8,6,9 to equal TRUE")
    }

    if CheckRange(2, 8, 8, 9) != false {
        t.Error("Expected 2,8,8,9 to equal FALSE")
    }

    if CheckRange(2, 8, 4, 6) != true {
        t.Error("Expected 2,8,4,6 to equal TRUE")
    }

    if CheckRange(2, 8, 1, 9) != true {
        t.Error("Expected 2,8,1,9 to equal TRUE")
    }

    if CheckRange(4, 8, 1, 3) != false {
        t.Error("Expected 4,8,1,3 to equal FALSE")
    }

    if CheckRange(4, 8, 1, 4) != false {
        t.Error("Expected 4,8,1,4 to equal FALSE")
    }

    if CheckRange(2, 5, 6, 9) != false {
        t.Error("Expected 2,5,6,9 to equal FALSE")
    }

    if CheckRange(2, 5, 5, 9) != false {
        t.Error("Expected 2,5,5,9 to equal FALSE")
    }

you can see there is XOR pattern in boundary comparison

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

For Python 3, I did:

sudo apt install python3-dev postgresql postgresql-contrib python3-psycopg2 libpq-dev

and then I was able to do:

pip3 install psycopg2

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

JWT (JSON Web Token) automatic prolongation of expiration

Below are the steps to do revoke your JWT access token:

1) When you do login, send 2 tokens (Access token, Refresh token) in response to client .
2) Access token will have less expiry time and Refresh will have long expiry time .
3) Client (Front end) will store refresh token in his local storage and access token in cookies.
4) Client will use access token for calling apis. But when it expires, pick the refresh token from local storage and call auth server api to get the new token.
5) Your auth server will have an api exposed which will accept refresh token and checks for its validity and return a new access token.
6) Once refresh token is expired, User will be logged out.

Please let me know if you need more details , I can share the code (Java + Spring boot) as well.

Automatically create requirements.txt

best way for Python 3 is:

pip3 freeze > requirements.txt

it worked for me...

How to kill a child process after a given timeout in Bash?

Here's the third answer I've submitted here. This one handles signal interrupts and cleans up background processes when SIGINT is received. It uses the $BASHPID and exec trick used in the top answer to get the PID of a process (in this case $$ in a sh invocation). It uses a FIFO to communicate with a subshell that is responsible for killing and cleanup. (This is like the pipe in my second answer, but having a named pipe means that the signal handler can write into it too.)

run_with_timeout ()
{
  t=$1 ; shift

  trap cleanup 2

  F=$$.fifo ; rm -f $F ; mkfifo $F

  # first, run main process in background
  "$@" & pid=$!

  # sleeper process to time out
  ( sh -c "echo \$\$ >$F ; exec sleep $t" ; echo timeout >$F ) &
  read sleeper <$F

  # control shell. read from fifo.
  # final input is "finished".  after that
  # we clean up.  we can get a timeout or a
  # signal first.
  ( exec 0<$F
    while : ; do
      read input
      case $input in
        finished)
          test $sleeper != 0 && kill $sleeper
          rm -f $F
          exit 0
          ;;
        timeout)
          test $pid != 0 && kill $pid
          sleeper=0
          ;;
        signal)
          test $pid != 0 && kill $pid
          ;;
      esac
    done
  ) &

  # wait for process to end
  wait $pid
  status=$?
  echo finished >$F
  return $status
}

cleanup ()
{
  echo signal >$$.fifo
}

I've tried to avoid race conditions as far as I can. However, one source of error I couldn't remove is when the process ends near the same time as the timeout. For example, run_with_timeout 2 sleep 2 or run_with_timeout 0 sleep 0. For me, the latter gives an error:

timeout.sh: line 250: kill: (23248) - No such process

as it is trying to kill a process that has already exited by itself.

What's the difference between ISO 8601 and RFC 3339 Date Formats?

You shouldn't have to care that much. RFC 3339, according to itself, is a set of standards derived from ISO 8601. There's quite a few minute differences though, and they're all outlined in RFC 3339. I could go through them all here, but you'd probably do better just reading the document for yourself in the event you're worried:

http://tools.ietf.org/html/rfc3339

Changing Tint / Background color of UITabBar

I have been able to make it work by subclassing a UITabBarController and using private classes:

@interface UITabBarController (private)
- (UITabBar *)tabBar;
@end

@implementation CustomUITabBarController


- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, 48);
    UIView *v = [[UIView alloc] initWithFrame:frame];
    [v setBackgroundColor:kMainColor];
    [v setAlpha:0.5];
    [[self tabBar] addSubview:v];
    [v release];

}
@end

How to create an 2D ArrayList in java?

I want to create a 2D array that each cell is an ArrayList!

If you want to create a 2D array of ArrayList.Then you can do this :

ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList(); // add another ArrayList object to [0,0]
table[0][0].add(); // add object to that ArrayList

How to properly override clone method?

Use serialization to make deep copies. This is not the quickest solution but it does not depend on the type.

True and False for && logic and || Logic table

I`d like to add to the already good answers:

The symbols '+', '*' and '-' are sometimes used as shorthand in some older textbooks for OR,? and AND,? and NOT,¬ logical operators in Bool`s algebra. In C/C++ of course we use "and","&&" and "or","||" and "not","!".

Watch out: "true + true" evaluates to 2 in C/C++ via internal representation of true and false as 1 and 0, and the implicit cast to int!

int main ()
{
  std::cout <<  "true - true = " << true - true << std::endl;
// This can be used as signum function:
// "(x > 0) - (x < 0)" evaluates to +1 or -1 for numbers.
  std::cout <<  "true - false = " << true - false << std::endl;
  std::cout <<  "false - true = " << false - true << std::endl;
  std::cout <<  "false - false = " << false - false << std::endl << std::endl;

  std::cout <<  "true + true = " << true + true << std::endl;
  std::cout <<  "true + false = " << true + false << std::endl;
  std::cout <<  "false + true = " << false + true << std::endl;
  std::cout <<  "false + false = " << false + false << std::endl << std::endl;

  std::cout <<  "true * true = " << true * true << std::endl;
  std::cout <<  "true * false = " << true * false << std::endl;
  std::cout <<  "false * true = " << false * true << std::endl;
  std::cout <<  "false * false = " << false * false << std::endl << std::endl;

  std::cout <<  "true / true = " << true / true << std::endl;
  //  std::cout <<  true / false << std::endl; ///-Wdiv-by-zero
  std::cout <<  "false / true = " << false / true << std::endl << std::endl;
  //  std::cout <<  false / false << std::endl << std::endl; ///-Wdiv-by-zero

  std::cout <<  "(true || true) = " << (true || true) << std::endl;
  std::cout <<  "(true || false) = " << (true || false) << std::endl;
  std::cout <<  "(false || true) = " << (false || true) << std::endl;
  std::cout <<  "(false || false) = " << (false || false) << std::endl << std::endl;

  std::cout <<  "(true && true) = " << (true && true) << std::endl;
  std::cout <<  "(true && false) = " << (true && false) << std::endl;
  std::cout <<  "(false && true) = " << (false && true) << std::endl;
  std::cout <<  "(false && false) = " << (false && false) << std::endl << std::endl;

}

yields :

true - true = 0
true - false = 1
false - true = -1
false - false = 0

true + true = 2
true + false = 1
false + true = 1
false + false = 0

true * true = 1
true * false = 0
false * true = 0
false * false = 0

true / true = 1
false / true = 0

(true || true) = 1
(true || false) = 1
(false || true) = 1
(false || false) = 0

(true && true) = 1
(true && false) = 0
(false && true) = 0
(false && false) = 0

How can I decrypt a password hash in PHP?

The passwords cannot be decrypted as will makes a vulnerability for users. So, you can simply use password_verify() method to compare the passwords.

if(password_verify($upass, $userRow['user_pass'])){
     //code for redirecting to login screen }

where, $upass is password entered by user and $userRow['user_pass'] is user_pass field in database which is encrypted by password_hash() function.

how to run a command at terminal from java program?

I know this question is quite old, but here's a library that encapsulates the ProcessBuilder api.

Maximum filename length in NTFS (Windows XP and Windows Vista)?

255 chars, though the complete path should not be longer than that as well. There is a nice table over at Wikipedia about this: http://en.wikipedia.org/wiki/Filename.

Illegal mix of collations error in MySql

[MySQL]

In these (very rare) cases:

  • two tables that really need different collation types
  • values not coming from a table, but from an explicit enumeration, for instance:

    SELECT 1 AS numbers UNION ALL SELECT 2 UNION ALL SELECT 3

you can compare the values between the different tables by using CAST or CONVERT:

CAST('my text' AS CHAR CHARACTER SET utf8)

CONVERT('my text' USING utf8)

See CONVERT and CAST documentation on MySQL website.

jQuery access input hidden value

To get value, use:

$.each($('input'),function(i,val){
    if($(this).attr("type")=="hidden"){
        var valueOfHidFiled=$(this).val();
        alert(valueOfHidFiled);
    }
});

or:

var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);

To set value, use:

$('input[type=hidden]').attr('value',newValue);

node.js - how to write an array to file

A simple solution is to use writeFile :

require("fs").writeFile(
     somepath,
     arr.map(function(v){ return v.join(', ') }).join('\n'),
     function (err) { console.log(err ? 'Error :'+err : 'ok') }
);

How to get week number of the month from the date in sql server 2008

Similar to the second solution, less code:

declare @date datetime = '2014-03-31'
SELECT DATEDIFF(week,0,@date) - (DATEDIFF(week,0,DATEADD(dd, -DAY(@date)+1, @date))-1)

Check date with todays date

Don't complicate it that much. Use this easy way. Import DateUtils java class and call the following methods which returns a boolean.

DateUtils.isSameDay(date1,date2);
DateUtils.isSameDay(calender1,calender2);
DateUtils.isToday(date1);

For more info refer this article DateUtils Java

resize2fs: Bad magic number in super-block while trying to open

How to resize root partition online :  

1)  [root@oel7 ~]# df -h  
Filesystem                         Size  Used Avail Use% Mounted on  
/dev/mapper/root_vg-root           5.0G  4.5G  548M  90% /

2)   

PV /dev/sda2   VG root_vg     lvm2 [6.00 GiB / 0    free]

as here it shows that there is no space left on root_vg volume group, so first i need to extend VG 

3)  
[root@oel7 ~]# vgextend root_vg /dev/sdb5  

  Volume group "root_vg" successfully extended

4)  

[root@oel7 ~]# pvscan  
    PV /dev/sda2   VG root_vg     lvm2 [6.00 GiB / 0    free]  
    PV /dev/sdb5   VG root_vg     lvm2 [2.00 GiB / 2.00 GiB free]

5)  Now extend the logical volume   

[root@oel7 ~]# lvextend -L +1G /dev/root_vg/root  

  Size of logical volume root_vg/root changed from 5.00 GiB (1280 extents) to 6.00 GiB (1536 extents).
  Logical volume root successfully resized  

3)  [root@oel7 ~]# resize2fs /dev/root_vg/root  

resize2fs 1.42.9 (28-Dec-2013)  
resize2fs: Bad magic number in super-block while trying to open /dev/root_vg  /root  
Couldn't find valid filesystem superblock.  

as root partition is not a ext* partiton so , you resize2fs will not work for you.  

4)  to check the filesystem type of a partition 
[root@oel7 ~]# df -Th  
Filesystem                        Type      Size  Used Avail Use% Mounted on  
/dev/mapper/root_vg-root          xfs       6.0G  4.5G  1.6G  75% /  
devtmpfs                          devtmpfs  481M     0  481M   0% /dev  
tmpfs                             tmpfs     491M   80K  491M   1% /dev/shm  
tmpfs                             tmpfs     491M  7.1M  484M   2% /run  
tmpfs                             tmpfs     491M     0  491M   0% /sys/fs  /cgroup
/dev/mapper/data_vg-home          xfs       3.5G  2.9G  620M  83% /home  
/dev/sda1                         xfs       497M  132M  365M  27% /boot  
/dev/mapper/data_vg01-data_lv001  ext3      4.0G  2.4G  1.5G  62% /sybase  
/dev/mapper/data_vg02-backup_lv01 ext3      4.0G  806M  3.0G  22% /backup  

above command shows that root is an xfs filesystem , so we are sure that we need to use xfs_growfs command to resize the partition.

6)  [root@oel7 ~]# xfs_growfs /dev/root_vg/root  
meta-data=/dev/mapper/root_vg-root isize=256    agcount=4, agsize=327680 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=0        finobt=0
data     =                       bsize=4096   blocks=1310720, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=0
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
data blocks changed from 1310720 to 1572864  

[root@oel7 ~]# df -Th  

Filesystem                        Type      Size  Used Avail Use% Mounted on
/dev/mapper/root_vg-root          xfs       6.0G  4.5G  1.6G  75% /  

current/duration time of html5 video?

I am assuming you want to display this as part of the player.

This site breaks down how to get both the current and total time regardless of how you want to display it though using jQuery:

http://dev.opera.com/articles/view/custom-html5-video-player-with-css3-and-jquery/

This will also cover how to set it to a specific div. As philip has already mentioned, .currentTime will give you where you are in the video.

Difference between HashSet and HashMap?

A HashSet uses a HashMap internally to store its entries. Each entry in the internal HashMap is keyed by a single Object, so all entries hash into the same bucket. I don't recall what the internal HashMap uses to store its values, but it doesn't really matter since that internal container will never contain duplicate values.

EDIT: To address Matthew's comment, he's right; I had it backwards. The internal HashMap is keyed with the Objects that make up the Set elements. The values of the HashMap are an Object that's just simply stored in the HashMap buckets.

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

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

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

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

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

How to get a unix script to run every 15 seconds?

To avoid possible overlapping of execution, use a locking mechanism as described in that thread.

What is apache's maximum url length?

Allowed default size of URI is 8177 characters in GET request. Simple code in python for such testing.

#!/usr/bin/env python2

import sys
import socket

if __name__ == "__main__":
    string = sys.argv[1]
    buf_get = "x" * int(string)
    buf_size = 1024
    request = "HEAD %s HTTP/1.1\nHost:localhost\n\n" % buf_get
    print "===>", request

    sock_http = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_http.connect(("localhost", 80))
    sock_http.send(request)
    while True:
       print "==>", sock_http.recv(buf_size)
       if not sock_http.recv(buf_size):
           break
    sock_http.close()

On 8178 characters you will get such message: HTTP/1.1 414 Request-URI Too Large

Netbeans - Error: Could not find or load main class

Possible Fixes:

Fix 1

  1. Go to project properties (right click on the folder of your project in netbeans)
  2. On left tab where it shows the categories, click on the "Run" selection
  3. Then click on Browse to find the Main class you use on your project

Fix 2

  1. Go to C:\Users\name\AppData\Local\Netbeans
  2. delete the Cache folder.
  3. Rebuild and Run

Fix 3 Download most recent version of Netbeans

Fix 4 Download most recent version of JDK and configure Netbeans to use that

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

To center the table in the middle of the email use

<table width="100%" align="center" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td>
            Your Content
        </td>
    </tr>
</table>

To align the content in the middle use:

<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td align="center">
            Your Content
        </td>
    </tr>
</table>

Check if an element is a child of a parent

In addition to the other answers, you can use this less-known method to grab elements of a certain parent like so,

$('child', 'parent');

In your case, that would be

if ($(event.target, 'div#hello')[0]) console.log(`${event.target.tagName} is an offspring of div#hello`);

Note the use of commas between the child and parent and their separate quotation marks. If they were surrounded by the same quotes

$('child, parent');

you'd have an object containing both objects, regardless of whether they exist in their document trees.

How to get unique device hardware id in Android?

Update: 19 -11-2019

The below answer is no more relevant to present day.

So for any one looking for answers you should look at the documentation linked below

https://developer.android.com/training/articles/user-data-ids


Old Answer - Not relevant now. You check this blog in the link below

http://android-developers.blogspot.in/2011/03/identifying-app-installations.html

ANDROID_ID

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                    Secure.ANDROID_ID); 

The above is from the link @ Is there a unique Android device ID?

More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.

ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.

The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.

You get the imei number of the device using the below

  TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  telephonyManager.getDeviceId();

http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29

Add this is manifest

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

How to display with n decimal places in Matlab

i use like tim say sprintf('%0.6f', x), it's a string then i change it to number by using command str2double(x).

Equivalent of Math.Min & Math.Max for Dates?

Linq.Min() / Linq.Max() approach:

DateTime date1 = new DateTime(2000,1,1);
DateTime date2 = new DateTime(2001,1,1);

DateTime minresult = new[] { date1,date2 }.Min();
DateTime maxresult = new[] { date1,date2 }.Max(); 

show loading icon until the page is load?

HTML, CSS, JS are all good as given in above answers. However they won't stop user from clicking the loader and visiting page. And if page time is large, it looks broken and defeats the purpose.

So in CSS consider adding

pointer-events: none;
cursor: default;

Also, instead of using gif files, if you are using fontawesome which everybody uses now a days, consider using in your html

<i class="fa fa-spinner fa-spin">

Convert string in base64 to image and save on filesystem in Python

Starting with

img_data = b'iVBORw0KGgoAAAANSUhEUgAABoIAAAaCCAYAAAABZu+EAAAqOElEQVR42uzBAQEAAACAkP6v7ggK\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAIcAeHkAAeLqlDIAAAAASUVORK5CYII='

Decoded the data using the base64 codec, and then write it to the filesystem.

# In Python 2.7
fh = open("imageToSave.png", "wb")
fh.write(img_data.decode('base64'))
fh.close()

# or, more concisely using with statement
with open("imageToSave.png", "wb") as fh:
    fh.write(img_data.decode('base64'))

Modernizing this example to Python 3, which removed arbitrary codec support from string/bytes .encode() and .decode() functions:

# For both Python 2.7 and Python 3.x
import base64
with open("imageToSave.png", "wb") as fh:
    fh.write(base64.decodebytes(img_data))

Create a hidden field in JavaScript

var input = document.createElement("input");

input.setAttribute("type", "hidden");

input.setAttribute("name", "name_you_want");

input.setAttribute("value", "value_you_want");

//append to form element that you want .
document.getElementById("chells").appendChild(input);

What is the difference between display: inline and display: inline-block?

display: inline; is a display mode to use in a sentence. For instance, if you have a paragraph and want to highlight a single word you do:

<p>
    Pellentesque habitant morbi <em>tristique</em> senectus
    et netus et malesuada fames ac turpis egestas.
</p>

The <em> element has a display: inline; by default, because this tag is always used in a sentence. The <p> element has a display: block; by default, because it's neither a sentence nor in a sentence, it's a block of sentences.

An element with display: inline; cannot have a height or a width or a vertical margin. An element with display: block; can have a width, height and margin.
If you want to add a height to the <em> element, you need to set this element to display: inline-block;. Now you can add a height to the element and every other block style (the block part of inline-block), but it is placed in a sentence (the inline part of inline-block).

How to debug Javascript with IE 8

This won't help you step through code or break on errors, but it's a useful way to get the same debug console for your project on all browsers.

myLog = function() {
    if (!myLog._div) { myLog.createDiv(); }

    var logEntry = document.createElement('span');
    for (var i=0; i < arguments.length; i++) {
        logEntry.innerHTML += myLog.toJson(arguments[i]) + '<br />';
    }
    logEntry.innerHTML += '<br />';

    myLog._div.appendChild(logEntry);
}
myLog.createDiv = function() {
    myLog._div = document.body.appendChild(document.createElement('div'));
    var props = {
        position:'absolute', top:'10px', right:'10px', background:'#333', border:'5px solid #333', 
        color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
        fontSize: '11px', whiteSpace: 'nowrap'
    }
    for (var key in props) { myLog._div.style[key] = props[key]; }
}
myLog.toJSON = function(obj) {
    if (typeof window.uneval == 'function') { return uneval(obj); }
    if (typeof obj == 'object') {
        if (!obj) { return 'null'; }
        var list = [];
        if (obj instanceof Array) {
            for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
            return '[' + list.join(',') + ']';
        } else {
            for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
            return '{' + list.join(',') + '}';
        }
    } else if (typeof obj == 'string') {
        return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
    } else {
        return new String(obj);
    }
}

myLog('log statement');
myLog('logging an object', { name: 'Marcus', likes: 'js' });

This is put together pretty hastily and is a bit sloppy, but it's useful nonetheless and can be improved easily!

Coloring Buttons in Android with Material Design and AppCompat

I actually didn't want a change to my custom button styles but unfortunately they weren't working anymore.

My App has a minSdkVersion of 9 and everything worked before.

I don't know why but since I removed the android: before the buttonStyle it seems to work again

now = working:

<item name="buttonStyle">@style/ButtonmyTime</item>

before = just gray material buttons:

<item name="android:buttonStyle">@style/ButtonmyTime</item>

I have no spezial folder for newver android version since my buttons are quite flat and they should look the same across all android versions.

Maybe someone can tell me why I had to remove the "android:" The ImageButton is still working with "android:"

<item name="android:imageButtonStyle">@style/ImageButtonmyTimeGreen</item>

What special characters must be escaped in regular expressions?

Modern RegEx Flavors (PCRE)

Includes C, C++, Delphi, EditPad, Java, JavaScript, Perl, PHP (preg), PostgreSQL, PowerGREP, PowerShell, Python, REALbasic, Real Studio, Ruby, TCL, VB.Net, VBScript, wxWidgets, XML Schema, Xojo, XRegExp.
PCRE compatibility may vary

    Anywhere: . ^ $ * + - ? ( ) [ ] { } \ |


Legacy RegEx Flavors (BRE/ERE)

Includes awk, ed, egrep, emacs, GNUlib, grep, PHP (ereg), MySQL, Oracle, R, sed.
PCRE support may be enabled in later versions or by using extensions

ERE/awk/egrep/emacs

    Outside a character class: . ^ $ * + ? ( ) [ { } \ |
    Inside a character class: ^ - [ ]

BRE/ed/grep/sed

    Outside a character class: . ^ $ * [ \
    Inside a character class: ^ - [ ]
    For literals, don't escape: + ? ( ) { } |
    For standard regex behavior, escape: \+ \? \( \) \{ \} \|


Notes

  • If unsure about a specific character, it can be escaped like \xFF
  • Alphanumeric characters cannot be escaped with a backslash
  • Arbitrary symbols can be escaped with a backslash in PCRE, but not BRE/ERE (they must only be escaped when required). For PCRE ] - only need escaping within a character class, but I kept them in a single list for simplicity
  • Quoted expression strings must also have the surrounding quote characters escaped, and often with backslashes doubled-up (like "(\")(/)(\\.)" versus /(")(\/)(\.)/ in JavaScript)
  • Aside from escapes, different regex implementations may support different modifiers, character classes, anchors, quantifiers, and other features. For more details, check out regular-expressions.info, or use regex101.com to test your expressions live

What's the easiest way to install a missing Perl module?

On Fedora you can use

# yum install foo

as long as Fedora has an existing package for the module.

How to force a hover state with jQuery?

Also, you could try triggering a mouseover.

$("#btn").click(function() {
   $("#link").trigger("mouseover");
});

Not sure if this will work for your specific scenario, but I've had success triggering mouseover instead of hover for various cases.

How to name and retrieve a stash by name in git?

This is one way to accomplish this using PowerShell:

<#
.SYNOPSIS
Restores (applies) a previously saved stash based on full or partial stash name.

.DESCRIPTION
Restores (applies) a previously saved stash based on full or partial stash name and then optionally drops the stash. Can be used regardless of whether "git stash save" was done or just "git stash". If no stash matches a message is given. If multiple stashes match a message is given along with matching stash info.

.PARAMETER message
A full or partial stash message name (see right side output of "git stash list"). Can also be "@stash{N}" where N is 0 based stash index.

.PARAMETER drop
If -drop is specified, the matching stash is dropped after being applied.

.EXAMPLE
Restore-Stash "Readme change"
Apply-Stash MyStashName
Apply-Stash MyStashName -drop
Apply-Stash "stash@{0}"
#>
function Restore-Stash  {
    [CmdletBinding()]
    [Alias("Apply-Stash")]
    PARAM (
        [Parameter(Mandatory=$true)] $message,         
        [switch]$drop
    )

    $stashId = $null

    if ($message -match "stash@{") {
        $stashId = $message
    }

    if (!$stashId) {
        $matches = git stash list | Where-Object { $_ -match $message }

        if (!$matches) {
            Write-Warning "No stashes found with message matching '$message' - check git stash list"
            return
        }

        if ($matches.Count -gt 1) {
            Write-Warning "Found $($matches.Count) matches for '$message'. Refine message or pass 'stash{@N}' to this function or git stash apply"
            return $matches
        }

        $parts = $matches -split ':'
        $stashId = $parts[0]
    }

    git stash apply ''$stashId''

    if ($drop) {
        git stash drop ''$stashId''
    }
}

More details here

How to compare strings in an "if" statement?

if(strcmp(aString, bString) == 0){
    //strings are the same
}

godspeed

Python, Matplotlib, subplot: How to set the axis range?

Using axes objects is a great approach for this. It helps if you want to interact with multiple figures and sub-plots. To add and manipulate the axes objects directly:

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,9))

signal_axes = fig.add_subplot(211)
signal_axes.plot(xs,rawsignal)

fft_axes = fig.add_subplot(212)
fft_axes.set_title("FFT")
fft_axes.set_autoscaley_on(False)
fft_axes.set_ylim([0,1000])
fft = scipy.fft(rawsignal)
fft_axes.plot(abs(fft))

plt.show()

What is the difference between UTF-8 and ISO-8859-1?

ISO-8859-1 is a legacy standards from back in 1980s. It can only represent 256 characters so only suitable for some languages in western world. Even for many supported languages, some characters are missing. If you create a text file in this encoding and try copy/paste some Chinese characters, you will see weird results. So in other words, don't use it. Unicode has taken over the world and UTF-8 is pretty much the standards these days unless you have some legacy reasons (like HTTP headers which needs to compatible with everything).

How to wrap text in textview in Android

Try @Guykun's approach

android:layout_weight="1" android:ellipsize="none" android:maxLines="100" android:scrollHorizontally="false"

Also, make sure that parents width is not set to wrap content. This is the thing that I was missing.

Django download a file

When you upload a file using FileField, the file will have a URL that you can use to point to the file and use HTML download attribute to download that file you can simply do this.

models.py

The model.py looks like this

class CsvFile(models.Model):
    csv_file = models.FileField(upload_to='documents')

views.py

#csv upload

class CsvUploadView(generic.CreateView):

   model = CsvFile
   fields = ['csv_file']
   template_name = 'upload.html'

#csv download

class CsvDownloadView(generic.ListView):

    model = CsvFile
    fields = ['csv_file']
    template_name = 'download.html'

Then in your templates.

#Upload template

upload.html

<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.media }}
    {{ form.as_p }}
    <button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>

#download template

download.html

  {% for document in object_list %}

     <a href="{{ document.csv_file.url }}" download  class="btn btn-dark float-right">Download</a>

  {% endfor %}

I did not use forms, just rendered model but either way, FileField is there and it will work the same.

Spring Boot, Spring Data JPA with multiple DataSources

thanks to the answers of Steve Park and Rafal Borowiec I got my code working, however, I had one issue: the DriverManagerDataSource is a "simple" implementation and does NOT give you a ConnectionPool (check http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/DriverManagerDataSource.html).

Hence, I replaced the functions which returns the DataSource for the secondDB to.

public DataSource <secondaryDB>DataSource() {
    // use DataSourceBuilder and NOT DriverManagerDataSource 
    // as this would NOT give you ConnectionPool
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.url(databaseUrl);
    dataSourceBuilder.username(username);
    dataSourceBuilder.password(password);
    dataSourceBuilder.driverClassName(driverClassName);
    return dataSourceBuilder.build();
}

Also, if do you not need the EntityManager as such, you can remove both the entityManager() and the @Bean annotation.

Plus, you may want to remove the basePackages annotation of your configuration class: maintaining it with the factoryBean.setPackagesToScan() call is sufficient.

How do I hide a menu item in the actionbar?

use invalidateOptionsMenu()

in order to call onPrepareOptionsMenu(menu: Menu?)

you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle...

When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

https://developer.android.com/guide/topics/ui/menus

How to get "GET" request parameters in JavaScript?

All data is available under

window.location.search

you have to parse the string, eg.

function get(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}

just call the function with GET variable name as parameter, eg.

get('foo');

this function will return the variables value or undefined if variable has no value or doesn't exist

How to append data to a json file?

I have some code which is similar, but does not rewrite the entire contents each time. This is meant to run periodically and append a JSON entry at the end of an array.

If the file doesn't exist yet, it creates it and dumps the JSON into an array. If the file has already been created, it goes to the end, replaces the ] with a , drops the new JSON object in, and then closes it up again with another ]

# Append JSON object to output file JSON array
fname = "somefile.txt"
if os.path.isfile(fname):
    # File exists
    with open(fname, 'a+') as outfile:
        outfile.seek(-1, os.SEEK_END)
        outfile.truncate()
        outfile.write(',')
        json.dump(data_dict, outfile)
        outfile.write(']')
else: 
    # Create file
    with open(fname, 'w') as outfile:
        array = []
        array.append(data_dict)
        json.dump(array, outfile)

saving a file (from stream) to disk using c#

I have to quote Jon (the master of c#) Skeet:

Well, the easiest way would be to open a file stream and then use:

byte[] data = memoryStream.ToArray(); fileStream.Write(data, 0, data.Length);

That's relatively inefficient though, as it involves copying the buffer. It's fine for small streams, but for huge amounts of data you should consider using:

fileStream.Write(memoryStream.GetBuffer(), 0, memoryStream.Position);

How to find good looking font color if background color is known?

In a recent application that I made, I used the inverted colors. With the r,g and b values in hand, just calculate (in this example, the color range varies from 0 to 255) :

r = 127-(r-127) and so on.

jquery select element by xpath

If you are debugging or similar - In chrome developer tools, you can simply use

$x('/html/.//div[@id="text"]')

How To Create Table with Identity Column

This has already been answered, but I think the simplest syntax is:

CREATE TABLE History (
    ID int primary key IDENTITY(1,1) NOT NULL,
    . . .

The more complicated constraint index is useful when you actually want to change the options.

By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.

How to push local changes to a remote git repository on bitbucket

Meaning the 2nd parameter('master') of the "git push" command -

$ git push origin master

can be made clear by initiating "push" command from 'news-item' branch. It caused local "master" branch to be pushed to the remote 'master' branch. For more information refer

https://git-scm.com/docs/git-push

where <refspec> in

[<repository> [<refspec>…?]

is written to mean "specify what destination ref to update with what source object."

For your reference, here is a screen capture how I verified this statement.

<code>enter image description here</code>

How to convert float value to integer in php?

What do you mean by converting?

  • casting*: (int) $float or intval($float)
  • truncating: floor($float) (down) or ceil($float) (up)
  • rounding: round($float) - has additional modes, see PHP_ROUND_HALF_... constants

*: casting has some chance, that float values cannot be represented in int (too big, or too small), f.ex. in your case.

PHP_INT_MAX: The largest integer supported in this build of PHP. Usually int(2147483647).

But, you could use the BCMath, or the GMP extensions for handling these large numbers. (Both are boundled, you only need to enable these extensions)

UIAlertController custom font, size, color

Use UIAppearance protocol. Example for setting a font - create a category to extend UILabel:

@interface UILabel (FontAppearance)
@property (nonatomic, copy) UIFont * appearanceFont UI_APPEARANCE_SELECTOR;
@end


@implementation UILabel (FontAppearance)

-(void)setAppearanceFont:(UIFont *)font {
    if (font)
        [self setFont:font];
}

-(UIFont *)appearanceFont {
    return self.font;
}

@end

And its usage:

UILabel * appearanceLabel = [UILabel appearanceWhenContainedIn:UIAlertController.class, nil];
[appearanceLabel setAppearanceFont:[UIFont boldSystemFontOfSize:10]]; //for example

Tested and working with style UIAlertControllerStyleActionSheet, but I guess it will work with UIAlertControllerStyleAlert too.

P.S. Better check for class availability instead of iOS version:

if ([UIAlertController class]) {
    // UIAlertController code (iOS 8)
} else {
    // UIAlertView code (pre iOS 8)
}

Auto start node.js server on boot

This can easily be done manually with the Windows Task Scheduler.

  • First, install forever.
  • Then, create a batch file that contains the following:

    cd C:\path\to\project\root
    call C:\Users\Username\AppData\Roaming\npm\forever.cmd start server.js
    exit 0
    
  • Lastly, create a scheduled task that runs when you log on. This task should call the batch file.

How to draw a rounded Rectangle on HTML Canvas?

The HTML5 canvas doesn't provide a method to draw a rectangle with rounded corners.

How about using the lineTo() and arc() methods?

You can also use the quadraticCurveTo() method instead of the arc() method.

Javascript to Select Multiple options

This type of thing should be done server-side, so as to limit the amount of resources used on the client for such trivial tasks. That being said, if you were to do it on the front-end, I would encourage you to consider using something like underscore.js to keep the code clean and concise:

var values = ["Red", "Green"],
    colors = document.getElementById("colors");

_.each(colors.options, function (option) {
    option.selected = ~_.indexOf(values, option.text);
});

If you're using jQuery, it could be even more terse:

var values = ["Red", "Green"];

$("#colors option").prop("selected", function () {
    return ~$.inArray(this.text, values);
});

If you were to do this without a tool like underscore.js or jQuery, you would have a bit more to write, and may find it to be a bit more complicated:

var color, i, j,
    values = ["Red", "Green"],
    options = document.getElementById("colors").options;

for ( i = 0; i < values.length; i++ ) {
    for ( j = 0, color = values[i]; j < options.length; j++ ) {
        options[j].selected = options[j].selected || color === options[j].text;
    }
}

What is the difference between an IntentService and a Service?

Intent service is child of Service

IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.

Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication

Cannot find libcrypto in Ubuntu

I solved this on 12.10 by installing libssl-dev.

sudo apt-get install libssl-dev

How do I get the MAX row with a GROUP BY in LINQ query?

I've checked DamienG's answer in LinqPad. Instead of

g.Group.Max(s => s.uid)

should be

g.Max(s => s.uid)

Thank you!

How to check the Angular version?

  1. ng v
  2. ng --v

you shall see something like the following:

Angular CLI: 7.3.8
Node: 10.15.1
OS: win32 x64
Angular: 5.2.10
... animations, common, compiler, core, forms, http
... platform-browser, platform-browser-dynamic, router

Angular version is in line 4 above

Enabling/installing GD extension? --without-gd

In CentOS (but the same may apply to other distros too) if you install the php7x-gd module followed by Apache restart and still the php -i does not show the GD Support => enabled it might mean that the php.ini was not automatically configured to support this extension.

All you have to to is either to edit the /etc/php/php.ini or to create a /etc/php.d/gd.ini file with the following content:

[gd]
extension=/path/to/gd.so # use the gd.so absolute path here

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

I don't think this is allowed by most browsers for security reasons, in a pure JavaScript context as the question asks.

Redirecting a request using servlets and the "setHeader" method not working

Oh no no! That's not how you redirect. It's far more simpler:

public class ModHelloWorld extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.sendRedirect("http://www.google.com");
    }
}

Also, it's a bad practice to write HTML code within a servlet. You should consider putting all that markup into a JSP and invoking the JSP using:

response.sendRedirect("/path/to/mynewpage.jsp");

check if a std::vector contains a certain object?

See question: How to find an item in a std::vector?

You'll also need to ensure you've implemented a suitable operator==() for your object, if the default one isn't sufficient for a "deep" equality test.

Instagram API: How to get all user media?

Use the next_url object to get the next 20 images.

In the JSON response there is an pagination array:

 "pagination":{
      "next_max_tag_id":"1411892342253728",
      "deprecation_warning":"next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
      "next_max_id":"1411892342253728",
      "next_min_id":"1414849145899763",
      "min_tag_id":"1414849145899763",
      "next_url":"https:\/\/api.instagram.com\/v1\/tags\/lemonbarclub\/media\/recent?client_id=xxxxxxxxxxxxxxxxxx\u0026max_tag_id=1411892342253728"
 }

This is the information on specific API call and the object next_url shows the URL to get the next 20 pictures so just take that URL and call it for the next 20 pictures.

For more information about the Instagram API check out this blogpost: Getting Friendly With Instagram’s API

Using Application context everywhere?

Application Class:

import android.app.Application;
import android.content.Context;

public class MyApplication extends Application {

    private static Context mContext;

    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getAppContext() {
        return mContext;
    }

}

Declare the Application in the AndroidManifest:

<application android:name=".MyApplication"
    ...
/>

Usage:

MyApplication.getAppContext()

Removing the title text of an iOS UIBarButtonItem

If you are using Storyboards you can go to Attributes Inspector of the ViewController's Navigation Item (click on Navigation Bar) and set the Back Button property to " " (one space character). This will set the Back Button title to one space character, leaving the chevron visible. No need to mess with code.

example image

Note that this will set Back Button title for the Back Button that will segue to this View Controller from the one that was pushed on top of it, not for the Back Button that will be displayed inside this Controller!

How to modify values of JsonObject / JsonArray directly?

It's actually all in the documentation.
JSONObject and JSONArray can both be used to replace the standard data structure.
To implement a setter simply call a remove(String name) before a put(String name, Object value).

Here's an simple example:

public class BasicDB {

private JSONObject jData = new JSONObject;

public BasicDB(String username, String tagline) {
    try {
        jData.put("username", username);
        jData.put("tagline" , tagline);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public String getUsername () { 
    String ret = null;
    try {
        ret = jData.getString("username");
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } 
    return ret;
}

public void setUsername (String username) { 
    try {
        jData.remove("username");
        jData.put("username" , username);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public String getTagline () {
    String ret = null;
    try {
        ret = jData.getString("tagline");
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } 
    return ret;
}