Programs & Examples On #Tablelayoutpanel

A Winforms control that allows the dynamic addition of components which are arranged in a grid pattern using columns and rows.

Winforms TableLayoutPanel adding rows programmatically

Create a table layout panel with two columns in your form and name it tlpFields.

Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).

tlpFields.RowStyles.Clear();  //first you must clear rowStyles

for (int ii = 0; ii < 5; ii++)
{
    Label l1= new Label();
    TextBox t1 = new TextBox();

    l1.Text = "field : ";

    tlpFields.Controls.Add(l1, 0, ii);  // add label in column0
    tlpFields.Controls.Add(t1, 1, ii);  // add textbox in column1

    tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}

Finally, run the code.

How to remove specific elements in a numpy array

Using np.delete is the fastest way to do it, if we know the indices of the elements that we want to remove. However, for completeness, let me add another way of "removing" array elements using a boolean mask created with the help of np.isin. This method allows us to remove the elements by specifying them directly or by their indices:

import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Remove by indices:

indices_to_remove = [2, 3, 6]
a = a[~np.isin(np.arange(a.size), indices_to_remove)]

Remove by elements (don't forget to recreate the original a since it was rewritten in the previous line):

elements_to_remove = a[indices_to_remove]  # [3, 4, 7]
a = a[~np.isin(a, elements_to_remove)]

#define macro for debug printing in C?

Here's the version I use:

#ifdef NDEBUG
#define Dprintf(FORMAT, ...) ((void)0)
#define Dputs(MSG) ((void)0)
#else
#define Dprintf(FORMAT, ...) \
    fprintf(stderr, "%s() in %s, line %i: " FORMAT "\n", \
        __func__, __FILE__, __LINE__, __VA_ARGS__)
#define Dputs(MSG) Dprintf("%s", MSG)
#endif

Convert char * to LPWSTR

I'm using the following in VC++ and it works like a charm for me.

CA2CT(charText)

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

//simple json object in asp.net mvc

var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({    url: 'test/[ControllerName]',
                        type: "POST",
                        data: model,
                        success: function (res) {
                            if (res != null) {
                                alert("done.");
                            }
                        },
                        error: function (res) {

                        }
                    });


//model in c#
public class MyModel
{
 public string Id {get; set;}
 public string Name {get; set;}
}

//controller in asp.net mvc


public ActionResult test(MyModel model)
{
 //now data in your model 
}

jQuery - selecting elements from inside a element

Have a look here -- to query a sub-element of an element:

$(document.getElementById('parentid')).find('div#' + divID + ' span.child');

How to delete zero components in a vector in Matlab?

I just came across this problem and wanted to find something about the performance, but I couldn't, so I wrote a benchmarking script on my own:

% Config:
rows = 1e6;
runs = 50;

% Start:
orig = round(rand(rows, 1));

t1 = 0;
for i = 1:runs
    A = orig;
    tic
    A(A == 0) = [];
    t1 = t1 + toc;
end
t1 = t1 / runs;

t2 = 0;
for i = 1:runs
    A = orig;
    tic
    A = A(A ~= 0);
    t2 = t2 + toc;
end
t2 = t2 / runs;

t1
t2
t1 / t2

So you see, the solution using A = A(A ~= 0) is the quicker of the two :)

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

This error occurred for me because i was trying to store the minimum date and time in a column using inline queries directly from C# code.

The date variable was set to 01/01/0001 12:00:00 AM in the code given the fact that DateTime in C# is initialized with this date and time if not set elsewise. And the least possible date allowed in the MS-SQL 2008 datetime datatype is 1753-01-01 12:00:00 AM.

I changed the date from the code and set it to 01/01/1900 and no errors were reported further.

What is the "realm" in basic authentication

A realm can be seen as an area (not a particular page, it could be a group of pages) for which the credentials are used; this is also the string that will be shown when the browser pops up the login window, e.g.

Please enter your username and password for <realm name>:

When the realm changes, the browser may show another popup window if it doesn't have credentials for that particular realm.

Returning multiple objects in an R function

You could use for() with assign() to create many objects. See the example from assign():

for(i in 1:6) { #-- Create objects  'r.1', 'r.2', ... 'r.6' --
    nam <- paste("r", i, sep = ".")
    assign(nam, 1:i)

Looking the new objects

ls(pattern = "^r..$")

Add element to a JSON file?

You can do this.

data[0]['f'] = var

Using :after to clear floating elements

This will work as well:

.clearfix:before,
.clearfix:after {
    content: "";
    display: table;
} 

.clearfix:after {
    clear: both;
}

/* IE 6 & 7 */
.clearfix {
    zoom: 1;
}

Give the class clearfix to the parent element, for example your ul element.

Sources here and here.

Bitbucket fails to authenticate on git pull

If you've changed the password on Windows 10, go to credential manager and update the password:

go to credential manager and update the password

How can I sort generic list DESC and ASC?

With Linq

var ascendingOrder = li.OrderBy(i => i);
var descendingOrder = li.OrderByDescending(i => i);

Without Linq

li.Sort((a, b) => a.CompareTo(b)); // ascending sort
li.Sort((a, b) => b.CompareTo(a)); // descending sort

Note that without Linq, the list itself is being sorted. With Linq, you're getting an ordered enumerable of the list but the list itself hasn't changed. If you want to mutate the list, you would change the Linq methods to something like

li = li.OrderBy(i => i).ToList();

How to limit the maximum value of a numeric field in a Django model?

I had this very same problem; here was my solution:

SCORE_CHOICES = zip( range(1,n), range(1,n) )
score = models.IntegerField(choices=SCORE_CHOICES, blank=True)

How do I restart my C# WinForm Application?

You are forgetting the command-line options/parameters that were passed in to your currently running instance. If you don't pass those in, you are not doing a real restart. Set the Process.StartInfo with a clone of your process' parameters, then do a start.

For example, if your process was started as myexe -f -nosplash myfile.txt, your method would only execute myexe without all those flags and parameters.

Java SSLException: hostname in certificate didn't match

You can also try to set a HostnameVerifier as described here. This worked for me to avoid this error.

// Do not do this in production!!!
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

DefaultHttpClient client = new DefaultHttpClient();

SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

// Set verifier     
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

// Example send http request
final String url = "https://encrypted.google.com/";  
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);

How to make Visual Studio copy a DLL file to the output directory?

$(OutDir) turned out to be a relative path in VS2013, so I had to combine it with $(ProjectDir) to achieve the desired effect:

xcopy /y /d  "$(ProjectDir)External\*.dll" "$(ProjectDir)$(OutDir)"

BTW, you can easily debug the scripts by adding 'echo ' at the beginning and observe the expanded text in the build output window.

Read text file into string array (and write)

Cannot update first answer.
Anyway, after Go1 release, there are some breaking changes, so I updated as shown below:

package main

import (
    "os"
    "bufio"
    "bytes"
    "io"
    "fmt"
    "strings"
)

// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    defer file.Close()

    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 0))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == io.EOF {
        err = nil
    }
    return
}

func writeLines(lines []string, path string) (err error) {
    var (
        file *os.File
    )

    if file, err = os.Create(path); err != nil {
        return
    }
    defer file.Close()

    //writer := bufio.NewWriter(file)
    for _,item := range lines {
        //fmt.Println(item)
        _, err := file.WriteString(strings.TrimSpace(item) + "\n"); 
        //file.Write([]byte(item)); 
        if err != nil {
            //fmt.Println("debug")
            fmt.Println(err)
            break
        }
    }
    /*content := strings.Join(lines, "\n")
    _, err = writer.WriteString(content)*/
    return
}

func main() {
    lines, err := readLines("foo.txt")
    if err != nil {
        fmt.Println("Error: %s\n", err)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }
    //array := []string{"7.0", "8.5", "9.1"}
    err = writeLines(lines, "foo2.txt")
    fmt.Println(err)
}

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

Here is a link to VeriSign's SSL Certificate Installation Checker: https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR1130

Enter your URL, click "Test this Web Server" and it will tell you if there are issues with your intermediate certificate authority.

How can I do a line break (line continuation) in Python?

If you want to break your line because of a long literal string, you can break that string into pieces:

long_string = "a very long string"
print("a very long string")

will be replaced by

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

Output for both print statements:

a very long string

Notice the parenthesis in the affectation.

Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string and mix the delimiters:

s = (
  '''2+2='''
  f"{2+2}"
)

textarea character limit

... onkeydown="if(value.length>500)value=value.substr(0,500); if(value.length==500)return false;" ...

It ought to work.

Load Image from javascript

this worked for me though... i wanted to display the image after the pencil icon is being clicked... and i wanted it seamless.. and this was my approach..

pencil button to display image

i created an input[file] element and made it hidden,

<input type="file" id="upl" style="display:none"/>

this input-file's click event will be trigged by the getImage function.

<a href="javascript:;" onclick="getImage()"/>
    <img src="/assets/pen.png"/>
</a>

<script>
     function getImage(){
       $('#upl').click();
     }
</script>

this is done while listening to the change event of the input-file element with ID of #upl.

_x000D_
_x000D_
   $(document).ready(function(){_x000D_
     _x000D_
       $('#upl').bind('change', function(evt){_x000D_
         _x000D_
    var preview = $('#logodiv').find('img');_x000D_
    var file    = evt.target.files[0];_x000D_
    var reader  = new FileReader();_x000D_
  _x000D_
    reader.onloadend = function () {_x000D_
   $('#logodiv > img')_x000D_
    .prop('src',reader.result)  //set the scr prop._x000D_
    .prop('width', 216);  //set the width of the image_x000D_
    .prop('height',200);  //set the height of the image_x000D_
    }_x000D_
  _x000D_
    if (file) {_x000D_
   reader.readAsDataURL(file);_x000D_
    } else {_x000D_
   preview.src = "";_x000D_
    }_x000D_
  _x000D_
    });_x000D_
_x000D_
   })
_x000D_
_x000D_
_x000D_

and BOOM!!! - it WORKS....

Adding a JAR to an Eclipse Java library

You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.

What does the colon (:) operator do?

It will prints the string"something" three times.

JLabel[] labels = {new JLabel(), new JLabel(), new JLabel()};                   

for ( JLabel label : labels )                  
 {              
   label.setText("something");  

 panel.add(label);             
 }

CSS scrollbar style cross browser

Scrollbar CSS styles are an oddity invented by Microsoft developers. They are not part of the W3C standard for CSS and therefore most browsers just ignore them.

How to convert char to integer in C?

The standard function atoi() will likely do what you want.

A simple example using "atoi":

#include <unistd.h>

int main(int argc, char *argv[])
{
    int useconds = atoi(argv[1]); 
    usleep(useconds);
}

Eclipse won't compile/run java file

Your project has to have a builder set for it. If there is not one Eclipse will default to Ant. Which you can use you have to create an Ant build file, which you can Google how to do. It is rather involved though. This is not required to run locally in Eclipse though. If your class is run-able. It looks like yours is, but we can not see all of it.

If you look at your project build path do you have an output folder selected? If you check that folder have the compiled class files been put there? If not the something is not set in Eclpise for it to know to compile. You might check to see if auto build is set for your project.

Div 100% height works on Firefox but not in IE

I'm not sure what problem you are solving, but when I have two side by side containers that need to be the same height, I run a little javascript on page load that finds the maximum height of the two and explicitly sets the other to the same height. It seems to me that height: 100% might just mean "make it the size needed to fully contain the content" when what you really want is "make both the size of the largest content."

Note: you'll need to resize them again if anything happens on the page to change their height -- like a validation summary being made visible or a collapsible menu opening.

Split varchar into separate columns in Oracle

Simple way is to convert into column

SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))

CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);

CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
   RETURN split_tbl
   PIPELINED IS
   l_idx PLS_INTEGER;
   l_list VARCHAR2 (32767) := p_list;
   l_value VARCHAR2 (32767);
BEGIN
   LOOP
      l_idx := INSTR (l_list, p_del);

      IF l_idx > 0 THEN
         PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
         l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
      ELSE
         PIPE ROW (l_list);
         EXIT;
      END IF;
   END LOOP;

   RETURN;
END split;

How to make parent wait for all child processes to finish?

Use waitpid() like this:

pid_t childPid;  // the child process that the execution will soon run inside of. 
childPid = fork();

if(childPid == 0)  // fork succeeded 
{   
   // Do something   
   exit(0); 
}

else if(childPid < 0)  // fork failed 
{    
   // log the error
}

else  // Main (parent) process after fork succeeds 
{    
    int returnStatus;    
    waitpid(childPid, &returnStatus, 0);  // Parent process waits here for child to terminate.

    if (returnStatus == 0)  // Verify child process terminated without error.  
    {
       printf("The child process terminated normally.");    
    }

    if (returnStatus == 1)      
    {
       printf("The child process terminated with an error!.");    
    }
}

ReferenceError: describe is not defined NodeJs

i have this error when using "--ui tdd". remove this or using "--ui bdd" fix problem.

Split string into list in jinja?

If there are up to 10 strings then you should use a list in order to iterate through all values.

{% set list1 = variable1.split(';') %}
{% for list in list1 %}
<p>{{ list }}</p>
{% endfor %}

Entity Framework. Delete all rows in table

if

      using(var db = new MyDbContext())
            {
               await db.Database.ExecuteSqlCommandAsync(@"TRUNCATE TABLE MyTable"););
            }

causes

Cannot truncate table 'MyTable' because it is being referenced by a FOREIGN KEY constraint.

I use this :

      using(var db = new MyDbContext())
               {
                   await db.Database.ExecuteSqlCommandAsync(@"DELETE FROM MyTable WHERE ID != -1");
               }

Resize Cross Domain Iframe Height

Minimum crossdomain set I've used for embedding fitted single iframe on a page.

On embedding page (containing iframe):

<iframe frameborder="0" id="sizetracker" src="http://www.hurtta.com/Services/SizeTracker/DE" width="100%"></iframe>
<script type="text/javascript">
  // Create browser compatible event handler.
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
  // Listen for a message from the iframe.
  eventer(messageEvent, function(e) {
    if (isNaN(e.data)) return;

    // replace #sizetracker with what ever what ever iframe id you need
    document.getElementById('sizetracker').style.height = e.data + 'px';

  }, false);
</script>

On embedded page (iframe):

<script type="text/javascript">
function sendHeight()
{
    if(parent.postMessage)
    {
        // replace #wrapper with element that contains 
        // actual page content
        var height= document.getElementById('wrapper').offsetHeight;
        parent.postMessage(height, '*');
    }
}

// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen for a message from the iframe.
eventer(messageEvent, function(e) {

    if (isNaN(e.data)) return;

    sendHeight();

}, 
false);
</script>

How do I create a file AND any folders, if the folders don't exist?

Use Directory.CreateDirectory before you create the file. It creates the folder recursively for you.

What's the best UI for entering date of birth?

I have just discovered a plugin on JSFiddle. Two possible alternatives : 1 single input OR 3 inputs, but looks like a single one... (use Tab key to go to the next input)

[link]http://jsfiddle.net/davidelrizzo/c8ASE/ It seems interesting !

window.open target _self v window.location.href?

You can omit window and just use location.href. For example:

location.href = 'http://google.im/';

install apt-get on linux Red Hat server

If you insist on using yum, try yum install apt. As read on this site: Link

Convert data.frame column format from character to factor

# To do it for all names
df[] <- lapply( df, factor) # the "[]" keeps the dataframe structure
 col_names <- names(df)
# to do it for some names in a vector named 'col_names'
df[col_names] <- lapply(df[col_names] , factor)

Explanation. All dataframes are lists and the results of [ used with multiple valued arguments are likewise lists, so looping over lists is the task of lapply. The above assignment will create a set of lists that the function data.frame.[<- should successfully stick back into into the dataframe, df

Another strategy would be to convert only those columns where the number of unique items is less than some criterion, let's say fewer than the log of the number of rows as an example:

cols.to.factor <- sapply( df, function(col) length(unique(col)) < log10(length(col)) )
df[ cols.to.factor] <- lapply(df[ cols.to.factor] , factor)

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

Pointers in C: when to use the ampersand and the asterisk?

Actually, you have it down pat, there's nothing more you need to know :-)

I would just add the following bits:

  • the two operations are opposite ends of the spectrum. & takes a variable and gives you the address, * takes an address and gives you the variable (or contents).
  • arrays "degrade" to pointers when you pass them to functions.
  • you can actually have multiple levels on indirection (char **p means that p is a pointer to a pointer to a char.

As to things working differently, not really:

  • arrays, as already mentioned, degrade to pointers (to the first element in the array) when passed to functions; they don't preserve size information.
  • there are no strings in C, just character arrays that, by convention, represent a string of characters terminated by a zero (\0) character.
  • When you pass the address of a variable to a function, you can de-reference the pointer to change the variable itself (normally variables are passed by value (except for arrays)).

How to download a file from a website in C#

With the WebClient class:

using System.Net;
//...
WebClient Client = new WebClient ();
Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

Incase you have multiple versions of Postgres installed on your machine. You can remove all via brew command as:

brew uninstall --force postgresql

IsNothing versus Is Nothing

Is Nothing requires an object that has been assigned to the value Nothing. IsNothing() can take any variable that has not been initialized, including of numeric type. This is useful for example when testing if an optional parameter has been passed.

How do I check/uncheck all checkboxes with a button using jQuery?

<script type="text/javascript">
    function myFunction(checked,total_boxes){ 
         for ( i=0 ; i < total_boxes ; i++ ){ 
           if (checked){   
             document.forms[0].checkBox[i].checked=true; 
            }else{  
             document.forms[0].checkBox[i].checked=false; 
            } 
        }   
    } 
</script>
    <body>
        <FORM> 
            <input type="checkbox" name="checkBox" >one<br> 
            <input type="checkbox" name="checkBox" >two<br> 
            <input type="checkbox" name="checkBox" >three<br> 
            <input type="checkbox" name="checkBox" >four<br> 
            <input type="checkbox" name="checkBox" >five<br> 
            <input type="checkbox" name="checkBox" >six<br> 
            <input type="checkbox" name="checkBox" >seven<br> 
            <input type="checkbox" name="checkBox" >eight<br> 
            <input type="checkbox" name="checkBox" >nine<br>
            <input type="checkbox" name="checkBox" >ten<br>  s
            <input type=button name="CheckAll" value="Select_All" onClick="myFunction(true,10)"> 
            <input type=button name="UnCheckAll" value="UnCheck All Boxes" onClick="myFunction(false,10)"> 
        </FORM> 
    </body>

How to get a Color from hexadecimal Color String

XML file saved at res/values/colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="opaque_red">#f00</color>
   <color name="translucent_red">#80ff0000</color>
</resources>

This application code retrieves the color resource:

Resources res = getResources();
int color = res.getColor(R.color.opaque_red);

This layout XML applies the color to an attribute:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/translucent_red"
    android:text="Hello"/>

Are table names in MySQL case sensitive?

Database and table names are not case sensitive in Windows, and case sensitive in most varieties of Unix or Linux.

To resolve the issue, set the lower_case_table_names to 1

lower_case_table_names=1

This will make all your tables lowercase, no matter how you write them.

Getting the folder name from a path

This is ugly but avoids allocations:

private static string GetFolderName(string path)
{
    var end = -1;
    for (var i = path.Length; --i >= 0;)
    {
        var ch = path[i];
        if (ch == System.IO.Path.DirectorySeparatorChar ||
            ch == System.IO.Path.AltDirectorySeparatorChar ||
            ch == System.IO.Path.VolumeSeparatorChar)
        {
            if (end > 0)
            {
                return path.Substring(i + 1, end - i - 1);
            }

            end = i;
        }
    }

    if (end > 0)
    {
        return path.Substring(0, end);
    }

    return path;
}

Call two functions from same onclick

You can create a single function that calls both of those, and then use it in the event.

function myFunction(){
    pay();
    cls();
}

And then, for the button:

<input id="btn" type="button" value="click" onclick="myFunction();"/>

Using "&times" word in html changes to ×

&times; stands for × in html. Use &amp;times to get &times

What is the size of a pointer?

To answer your other question. The size of a pointer and the size of what it points to are not related. A good analogy is to consider them like postal addresses. The size of the address of a house has no relationship to the size of the house.

Appending output of a Batch file To log file

This is not an answer to your original question: "Appending output of a Batch file To log file?"

For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"

(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")

Timeout:

Example (1 second):

TIMEOUT /T 1000 /NOBREAK

Sleep:

Example (1 second):

sleep -m 1000

Alternative methods:

Here's an answer to your 2nd followup question: "Along with the Timestamp?"

Create a date and time stamp in your batch files

Example:

echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log

can't multiply sequence by non-int of type 'float'

In this line:

fund = fund * (1 + 0.01 * growthRates) + depositPerYear

I think you mean this:

fund = fund * (1 + 0.01 * i) + depositPerYear

When you try to multiply a float by growthRates (which is a list), you get that error.

What are the ways to make an html link open a folder

Hope it will help someone someday. I was making a small POC and came across this. A button, onClick display contents of the folder. Below is the HTML,

<input type=button onClick="parent.location='file:///C:/Users/' " value='Users'>

How to add external library in IntelliJ IDEA?

Intellij IDEA 15: File->Project Structure...->Project Settings->Libraries

lvalue required as left operand of assignment

You need to compare, not assign:

if (strcmp("hello", "hello") == 0)
                             ^

Because you want to check if the result of strcmp("hello", "hello") equals to 0.

About the error:

lvalue required as left operand of assignment

lvalue means an assignable value (variable), and in assignment the left value to the = has to be lvalue (pretty clear).

Both function results and constants are not assignable (rvalues), so they are rvalues. so the order doesn't matter and if you forget to use == you will get this error. (edit:)I consider it a good practice in comparison to put the constant in the left side, so if you write = instead of ==, you will get a compilation error. for example:

int a = 5;
if (a = 0) // Always evaluated as false, no error.
{
    //...
}

vs.

int a = 5;
if (0 = a) // Generates compilation error, you cannot assign a to 0 (rvalue)
{
    //...
}

(see first answer to this question: https://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined)

$(document).ready(function() is not working

I found we need to use noConflict sometimes:

jQuery.noConflict()(function ($) { // this was missing for me
    $(document).ready(function() { 

       other code here....

    });
});

From the docs:

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.

Save file to specific folder with curl command

curl doesn't have an option to that (without also specifying the filename), but wget does. The directory can be relative or absolute. Also, the directory will automatically be created if it doesn't exist.

wget -P relative/dir "$url"

wget -P /absolute/dir "$url"

Difference between static class and singleton pattern?

static classes are not for anything that needs state. It is useful for putting a bunch of functions together i.e Math (or Utils in projects). So the class name just gives us a clue where we can find the functions and nothing more.

Singleton is my favorite pattern and I use it to manage something at a single point. It's more flexible than static classes and can maintain it's state. It can implement interfaces, inherit from other classes and allow inheritance.

My rule for choosing between static and singleton:

If there is a bunch of functions that should be kept together, then static is the choice. Anything else which needs single access to some resources, could be implemented as a singleton.

String comparison technique used by Python

Python and just about every other computer language use the same principles as (I hope) you would use when finding a word in a printed dictionary:

(1) Depending on the human language involved, you have a notion of character ordering: 'a' < 'b' < 'c' etc

(2) First character has more weight than second character: 'az' < 'za' (whether the language is written left-to-right or right-to-left or boustrophedon is quite irrelevant)

(3) If you run out of characters to test, the shorter string is less than the longer string: 'foo' < 'food'

Typically, in a computer language the "notion of character ordering" is rather primitive: each character has a human-language-independent number ord(character) and characters are compared and sorted using that number. Often that ordering is not appropriate to the human language of the user, and then you need to get into "collating", a fun topic.

Is there a simple JavaScript slider?

Here is another light JavaScript Slider that seems to fit your needs.

'' is not recognized as an internal or external command, operable program or batch file

This is a very common question seen on Stackoverflow.

The important part here is not the command displayed in the error, but what the actual error tells you instead.

a Quick breakdown on why this error is received.

cmd.exe Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.

How do I fix this:

When Actual Command/executable fails

First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.

If you have any executable which you are attempting to run from cmd.exe then you need to tell cmd.exe where this file is located. There are 2 ways of doing this.

  1. specify the full path to the file.

    "C:\My_Files\mycommand.exe"

  2. Add the location of the file to your environment Variables.

Goto:
------> Control Panel-> System-> Advanced System Settings->Environment Variables

In the System Variables Window, locate path and select edit

Now simply add your path to the end of the string, seperated by a semicolon ; as:

;C:\My_Files\

Save the changes and exit. You need to make sure that ANY cmd.exe windows you had open are then closed and re-opened to allow it to re-import the environment variables. Now you should be able to run mycommand.exe from any path, within cmd.exe as the environment is aware of the path to it.

When C:\Program or Similar fails

This is a very simple error. Each string after a white space is seen as a different command in cmd.exe terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe to see it as a single string, and not separate commands.

So to execute C:\Program Files\My-App\Mobile.exe simply run as:

"C:\Program Files\My-App\Mobile.exe"

Export DataBase with MySQL Workbench with INSERT statements

I had some problems to find this option in newer versions, so for Mysql Workbench 6.3, go to schemas and enter in your connection:

enter image description here


Go to Tools -> Data Export

enter image description here


Click on Advanced Options

enter image description here


Scroll down and uncheck extended-inserts

enter image description here


Then export the data you want and you will see the result file as this:

enter image description here

What is the main difference between Inheritance and Polymorphism?

inheritance is kind of polymorphism, Exactly in fact inheritance is the dynamic polymorphism. So, when you remove inheritance you can not override anymore.

jQuery Event Keypress: Which key was pressed?

Checkout the excellent jquery.hotkeys plugin which supports key combinations:

$(document).bind('keydown', 'ctrl+c', fn);

Transition of background-color

As far as I know, transitions currently work in Safari, Chrome, Firefox, Opera and Internet Explorer 10+.

This should produce a fade effect for you in these browsers:

_x000D_
_x000D_
a {_x000D_
    background-color: #FF0;_x000D_
}_x000D_
_x000D_
a:hover {_x000D_
    background-color: #AD310B;_x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
}
_x000D_
<a>Navigation Link</a>
_x000D_
_x000D_
_x000D_

Note: As pointed out by Gerald in the comments, if you put the transition on the a, instead of on a:hover it will fade back to the original color when your mouse moves away from the link.

This might come in handy, too: CSS Fundamentals: CSS 3 Transitions

Bootstrap4 adding scrollbar to div

_x000D_
_x000D_
.Scroll {
  height:600px;
  overflow-y: scroll;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>

<h1>Smooth Scroll</h1>

<div class="Scroll">
  <div class="main" id="section1">
    <h2>Section 1</h2>
    <p>Click on the link to see the "smooth" scrolling effect.</p>
    <p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
  </div>
  <div class="main" id="section2">
    <h2>Section 2</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section3">
    <h2>Section 3</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section4">
    <h2>Section 4</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>

  <div class="main" id="section5">
    <h2>Section 5</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
  <div class="main" id="section6">
    <h2>Section 6</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section7">
    <h2>Section 7</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
</div>
</body>
</html>
_x000D_
_x000D_
_x000D_

How to calculate difference between two dates in oracle 11g SQL

Oracle DateDiff is from a different product, probably mysql (which is now owned by Oracle).

The difference between two dates (in oracle's usual database product) is in days (which can have fractional parts). Factor by 24 to get hours, 24*60 to get minutes, 24*60*60 to get seconds (that's as small as dates go). The math is 100% accurate for dates within a couple of hundred years or so. E.g. to get the date one second before midnight of today, you could say

select trunc(sysdate) - 1/24/60/60 from dual;

That means "the time right now", truncated to be just the date (i.e. the midnight that occurred this morning). Then it subtracts a number which is the fraction of 1 day that measures one second. That gives you the date from the previous day with the time component of 23:59:59.

How to replace all occurrences of a character in string?

A simple find and replace for a single character would go something like:

s.replace(s.find("x"), 1, "y")

To do this for the whole string, the easy thing to do would be to loop until your s.find starts returning npos. I suppose you could also catch range_error to exit the loop, but that's kinda ugly.

Concrete Javascript Regex for Accented Characters (Diacritics)

The XRegExp library has a plugin named Unicode that helps solve tasks like this.

<script src="xregexp.js"></script>
<script src="addons/unicode/unicode-base.js"></script>
<script>
  var unicodeWord = XRegExp("^\\p{L}+$");

  unicodeWord.test("???????"); // true
  unicodeWord.test("???"); // true
  unicodeWord.test("???????"); // true
</script>

It's mentioned in the comments to the question, but it's easy to miss. I've noticed it only after I submitted this answer.

How do I encode/decode HTML entities in Ruby?

If you don't want to add a new dependency just to do this (like HTMLEntities) and you're already using Hpricot, it can both escape and unescape for you. It handles much more than CGI:

Hpricot.uxs "foo&nbsp;b&auml;r"
=> "foo bär"

How can I get the executing assembly version?

I finally settled on typeof(MyClass).GetTypeInfo().Assembly.GetName().Version for a netstandard1.6 app. All of the other proposed answers presented a partial solution. This is the only thing that got me exactly what I needed.

Sourced from a combination of places:

https://msdn.microsoft.com/en-us/library/x4cw969y(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/2exyydhb(v=vs.110).aspx

Inserting Data into Hive Table

Use this -

create table dummy_table_name as select * from source_table_name;

This will create the new table with existing data available on source_table_name.

Accessing localhost of PC from USB connected Android mobile device

  1. Make sure you have adb installed on the computer, USB debugging enabled on the phone, and the phone has allowed access to the computer. Plug the phone into the computer via USB cable, and make sure it's visible (it should show up in the Bash command adb devices.
  2. In your computer's Chrome browser, open chrome://inspect/#devices, click the "Port forwarding" button, check "Enable port forwarding", and add the port on the computer that you want to be accessible from the phone (detailed instructions here). You'll need to keep open the tab running chrome://inspect/#devices.
  3. In your phone's browser, navigate to localhost:[port_number], and it should display whatever is running on the computer.

This works on Windows and Ubuntu Linux, and should work on Mac as well.

Loop inside React JSX

Here's a simple solution to it.

var Object_rows = [];
for (var i = 0; i < numrows; i++) {
  Object_rows.push(<ObjectRow />);
}
<tbody>{Object_rows}</tbody>;

No mapping and complex code required. You just need to push the rows to the array and return the values to render it.

Inserting HTML into a div

Using JQuery would take care of that browser inconsistency. With the jquery library included in your project simply write:

$('#yourDivName').html('yourtHTML');

You may also consider using:

$('#yourDivName').append('yourtHTML');

This will add your gallery as the last item in the selected div. Or:

$('#yourDivName').prepend('yourtHTML');

This will add it as the first item in the selected div.

See the JQuery docs for these functions:

How to change the time format (12/24 hours) of an <input>?

By HTML5 drafts, input type=time creates a control for time of the day input, expected to be implemented using “the user’s preferred presentation”. But this really means using a widget where time presentation follows the rules of the browser’s locale. So independently of the language of the surrounding content, the presentation varies by the language of the browser, the language of the underlying operating system, or the system-wide locale settings (depending on browser). For example, using a Finnish-language version of Chrome, I see the widget as using the standard 24-hour clock. Your mileage will vary.

Thus, input type=time are based on an idea of localization that takes it all out of the hands of the page author. This is intentional; the problem has been raised in HTML5 discussions several times, with the same outcome: no change. (Except possibly added clarifications to the text, making this behavior described as intended.)

Note that pattern and placeholder attributes are not allowed in input type=time. And placeholder="hrs:mins", if it were implemented, would be potentially misleading. It’s quite possible that the user has to type 12.30 (with a period) and not 12:30, when the browser locale uses “.” as a separator in times.

My conclusion is that you should use input type=text, with pattern attribute and with some JavaScript that checks the input for correctness on browsers that do not support the pattern attribute natively.

How to add an item to a drop down list in ASP.NET?

Try following code;

DropDownList1.Items.Add(new ListItem(txt_box1.Text));

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

Had the same problem, nothing was helping, but I looked in Info.plist and found out that bundle ID was changed to other name (I don't know how it happened), so when I changed it to correct one everything was fine again.

Angular ng-class if else

Just make a rule for each case:

<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1)  }">

Or use the ternary operator:

<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">

Write a number with two decimal places SQL Server

If you only need two decimal places, simplest way is..

SELECT CAST(12 AS DECIMAL(16,2))

OR

SELECT CAST('12' AS DECIMAL(16,2))

Output

12.00

HTML img onclick Javascript

use this simple cod:

    <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}

#myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

/* Caption of Modal Image */
#caption {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

/* Add Animation */
.modal-content, #caption {  
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
  from {-webkit-transform:scale(0)} 
  to {-webkit-transform:scale(1)}
}

@keyframes zoom {
  from {transform:scale(0)} 
  to {transform:scale(1)}
}

/* The Close Button */
.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
  .modal-content {
    width: 100%;
  }
}
</style>
</head>
<body>

<h2>Image Modal</h2>
<p>In this example, we use CSS to create a modal (dialog box) that is hidden by default.</p>
<p>We use JavaScript to trigger the modal and to display the current image inside the modal when it is clicked on. Also note that we use the value from the image's "alt" attribute as an image caption text inside the modal.</p>

<img id="myImg" src="img_snow.jpg" alt="Snow" style="width:100%;max-width:300px">

<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
  <div id="caption"></div>
</div>

<script>
// Get the modal
var modal = document.getElementById("myModal");

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("modal")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() { 
  modal.style.display = "none";
}
</script>

</body>
</html>

this code open and close your photo.

What is the easiest way to remove all packages installed by pip?

Cross-platform support by using only pip:

#!/usr/bin/env python

from sys import stderr
from pip.commands.uninstall import UninstallCommand
from pip import get_installed_distributions

pip_uninstall = UninstallCommand()
options, args = pip_uninstall.parse_args([
    package.project_name
    for package in
    get_installed_distributions()
    if not package.location.endswith('dist-packages')
])

options.yes = True  # Don't confirm before uninstall
# set `options.require_venv` to True for virtualenv restriction

try:
    print pip_uninstall.run(options, args)
except OSError as e:
    if e.errno != 13:
        raise e
    print >> stderr, "You lack permissions to uninstall this package.
                      Perhaps run with sudo? Exiting."
    exit(13)
# Plenty of other exceptions can be thrown, e.g.: `InstallationError`
# handle them if you want to.

How do I select the "last child" with a specific class name in CSS?

This can be done using an attribute selector.

[class~='list']:last-of-type  {
    background: #000;
}

The class~ selects a specific whole word. This allows your list item to have multiple classes if need be, in various order. It'll still find the exact class "list" and apply the style to the last one.

See a working example here: http://codepen.io/chasebank/pen/ZYyeab

Read more on attribute selectors:

http://css-tricks.com/attribute-selectors/ http://www.w3schools.com/css/css_attribute_selectors.asp

How to get memory available or used in C#

System.Environment has WorkingSet- a 64-bit signed integer containing the number of bytes of physical memory mapped to the process context.

If you want a lot of details there is System.Diagnostics.PerformanceCounter, but it will be a bit more effort to setup.

Node.js: How to send headers with form data using request module?

Just remember set method to POST in options. Here is my code

var options = {
    url: 'http://www.example.com',
    method: 'POST', // Don't forget this line
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-MicrosoftAjax': 'Delta=true', // blah, blah, blah...
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
    },
    form: {
        'key-1':'value-1',
        'key-2':'value-2',
        ...
    }
};

//console.log('options:', options);

// Create request to get data
request(options, (err, response, body) => {
    if (err) {
        //console.log(err);
    } else {
        console.log('body:', body);
    }
});

How to extract hours and minutes from a datetime.datetime object?

It's easier to use the timestamp for this things since Tweepy gets both

import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))

Angular - "has no exported member 'Observable'"

Just put:

import { Observable} from 'rxjs';

Just like that. Nothing more or less.

How can I remove duplicate rows?

Quick and Dirty to delete exact duplicated rows (for small tables):

select  distinct * into t2 from t1;
delete from t1;
insert into t1 select *  from t2;
drop table t2;

Laravel Eloquent - distinct() and count() not working properly together

Wouldn't this work?

$ad->getcodes()->distinct()->get(['pid'])->count();

See here for discussion..

Android java.lang.NoClassDefFoundError

I've run into this problem a few times opening old projects that include other Android libraries. What works for me is to:

move Android to the top in the Order and Export tab and deselecting it.

Yes, this really makes the difference. Maybe it's time for me to ditch ADT for Android Studio!

Set textbox to readonly and background color to grey in jquery

If supported by your browser, you may use CSS3 :read-only selector:

input[type="text"]:read-only {
    cursor: normal;
    background-color: #f8f8f8;
    color: #999;
}

Batch files: How to read a file?

A code that displays the contents of the myfile.txt file on the screen

set %filecontent%=0
type %filename% >> %filecontent%
echo %filecontent%

appending array to FormData and send via AJAX

add all type inputs to FormData

const formData = new FormData();
for (let key in form) {
    Array.isArray(form[key])
        ? form[key].forEach(value => formData.append(key + '[]', value))
        : formData.append(key, form[key]) ;
}

Allow access permission to write in Program Files of Windows 7

If you have such a program just install it in C:\, not in Program Files. I had a lot of problems when I was installing Android SDK. My problem got solved by installing it in C:\.

Default value of function parameter

In C++ the requirements imposed on default arguments with regard to their location in parameter list are as follows:

  1. Default argument for a given parameter has to be specified no more than once. Specifying it more than once (even with the same default value) is illegal.

  2. Parameters with default arguments have to form a contiguous group at the end of the parameter list.

Now, keeping that in mind, in C++ you are allowed to "grow" the set of parameters that have default arguments from one declaration of the function to the next, as long as the above requirements are continuously satisfied.

For example, you can declare a function with no default arguments

void foo(int a, int b);

In order to call that function after such declaration you'll have to specify both arguments explicitly.

Later (further down) in the same translation unit, you can re-declare it again, but this time with one default argument

void foo(int a, int b = 5);

and from this point on you can call it with just one explicit argument.

Further down you can re-declare it yet again adding one more default argument

void foo(int a = 1, int b);

and from this point on you can call it with no explicit arguments.

The full example might look as follows

void foo(int a, int b);

int main()
{
  foo(2, 3);

  void foo(int a, int b = 5); // redeclare
  foo(8); // OK, calls `foo(8, 5)`

  void foo(int a = 1, int b); // redeclare again
  foo(); // OK, calls `foo(1, 5)`
}

void foo(int a, int b)
{
  // ...
}

As for the code in your question, both variants are perfectly valid, but they mean different things. The first variant declares a default argument for the second parameter right away. The second variant initially declares your function with no default arguments and then adds one for the second parameter.

The net effect of both of your declarations (i.e. the way it is seen by the code that follows the second declaration) is exactly the same: the function has default argument for its second parameter. However, if you manage to squeeze some code between the first and the second declarations, these two variants will behave differently. In the second variant the function has no default arguments between the declarations, so you'll have to specify both arguments explicitly.

Why would you use Expression<Func<T>> rather than Func<T>?

There is a more philosophical explanation about it from Krzysztof Cwalina's book(Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries);

Rico Mariani

Edit for non-image version:

Most times you're going to want Func or Action if all that needs to happen is to run some code. You need Expression when the code needs to be analyzed, serialized, or optimized before it is run. Expression is for thinking about code, Func/Action is for running it.

Markdown `native` text alignment

For Markdown Extra you can use custom attributes:

# Example text {style=text-align:center}

This works for headers and blockquotes, but not for paragraphs, inline elements and code blocks.

A shorter version (but not supported in HTML 5):

# Example text {align=center}

Removing Java 8 JDK from Mac

You just need to use these commands

sudo rm -rf /Library/Java/*
sudo rm -rf /Library/PreferencePanes/Java*
sudo rm -rf /Library/Internet\ Plug-Ins/Java*

AngularJS : Custom filters and ng-repeat

One of the easiest ways to fix this is to use the $ which is the search all.

Here is a plunker that shows it working. I have changed the checkboxes to radio ( because I thought they should be complementary )..

http://plnkr.co/edit/dHzvm6hR5P8G4wPuTxoi?p=preview

If you want a very specific way of doing this ( instead of doing a generic search ) you need work with functions in the search.

The documentation is here

http://docs.angularjs.org/api/ng.filter:filter

How to set proxy for wget?

In my ubuntu, following lines in $HOME/.wgetrc did the trick!

http_proxy = http://uname:[email protected]:8080

use_proxy = on

Clear form after submission with jQuery

Better way to reset your form with jQuery is Simply trigger a reset event on your form.

$("#btn1").click(function () {
        $("form").trigger("reset");
    });

How to increase the distance between table columns in HTML?

If I understand correctly, you want this fiddle.

_x000D_
_x000D_
table {_x000D_
  background: gray;_x000D_
}_x000D_
td {    _x000D_
  display: block;_x000D_
  float: left;_x000D_
  padding: 10px 0;_x000D_
  margin-right:50px;_x000D_
  background: white;_x000D_
}_x000D_
td:last-child {_x000D_
  margin-right: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Hello HTML!</td>_x000D_
    <td>Hello CSS!</td>_x000D_
    <td>Hello JS!</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

100% width Twitter Bootstrap 3 template

This is the complete basic structure for 100% width layout in Bootstrap v3.0.0. You shouldn't wrap your <div class="row"> with container class. Cause container class will take lots of margin and this will not provide you full screen (100% width) layout where bootstrap has removed container-fluid class from their mobile-first version v3.0.0.

So just start writing <div class="row"> without container class and you are ready to go with 100% width layout.

<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap Basic 100% width Structure</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap -->
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
  <script src="http://getbootstrap.com/assets/js/html5shiv.js"></script>
  <script src="http://getbootstrap.com/assets/js/respond.min.js"></script>
<![endif]-->
<style>
    .red{
        background-color: red;
    }
    .green{
        background-color: green;
    }
</style>
</head>
<body>
    <div class="row">
        <div class="col-md-3 red">Test content</div>
        <div class="col-md-9 green">Another Content</div>
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="//code.jquery.com/jquery.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</body>
</html>

To see the result by yourself I have created a bootply. See the live output there. http://bootply.com/82136 And the complete basic bootstrap 3 100% width layout I have created a gist. you can use that. Get the gist from here

Reply me if you need more further assistance. Thanks.

How to detect when a UIScrollView has finished scrolling

If somebody needs, here's Ashley Smart answer in Swift

func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        perform(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation), with: nil, afterDelay: 0.3)
    ...
}

func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        NSObject.cancelPreviousPerformRequests(withTarget: self)
    ...
}

Best way to compare dates in Android

Your code could be reduced to

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}

or

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (System.currentTimeMillis() > strDate.getTime()) {
    catalog_outdated = 1;
}

How to get child element by ID in JavaScript?

Using jQuery

$('#note textarea');

or just

$('#textid');

CSS to make table 100% of max-width

I had the same issue it was due to that I had the bootstrap class "hidden-lg" on the table which caused it to stupidly become display: block !important;

I wonder how Bootstrap never considered to just instead do this:

@media (min-width: 1200px) {
    .hidden-lg {
         display: none;
    }
}

And then just leave the element whatever display it had before for other screensizes.. Perhaps it is too advanced for them to figure out..

Anyway so:

table {
    display: table; /* check so these really applies */
    width: 100%;
}

should work

How do I instantiate a JAXBElement<String> object?

When you imported the WSDL, you should have an ObjectFactory class which should have bunch of methods for creating various input parameters.

ObjectFactory factory = new ObjectFactory();
JAXBElement<String> createMessageDescription = factory.createMessageDescription("description");
message.setDescription(createMessageDescription);

String concatenation with Groovy

def my_string = "some string"
println "here: " + my_string 

Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.

Why is 1/1/1970 the "epoch time"?

History.

The earliest versions of Unix time had a 32-bit integer incrementing at a rate of 60 Hz, which was the rate of the system clock on the hardware of the early Unix systems. The value 60 Hz still appears in some software interfaces as a result. The epoch also differed from the current value. The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".

Using JQuery to open a popup window and print

Are you sure you can't alter the HTML in the popup window?

If you can, add a <script> tag at the end of the popup's HTML, and call window.print() inside it. Then it won't be called until the HTML has loaded.

Sending XML data using HTTP POST with PHP

you can use cURL library for posting data: http://www.php.net/curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);

where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

Validate a username and password against Active Directory?

For me both of these below worked, make sure your Domain is given with LDAP:// in start

//"LDAP://" + domainName
private void btnValidate_Click(object sender, RoutedEventArgs e)
{
    try
    {
        DirectoryEntry de = new DirectoryEntry(txtDomainName.Text, txtUsername.Text, txtPassword.Text);
        DirectorySearcher dsearch = new DirectorySearcher(de);
        SearchResult results = null;

        results = dsearch.FindOne();

        MessageBox.Show("Validation Success.");
    }
    catch (LdapException ex)
    {
        MessageBox.Show($"Validation Failure. {ex.GetBaseException().Message}");
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Validation Failure. {ex.GetBaseException().Message}");
    }
}

private void btnValidate2_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LdapConnection lcon = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
        NetworkCredential nc = new NetworkCredential(txtUsername.Text,
                               txtPassword.Text, txtDomainName.Text);
        lcon.Credential = nc;
        lcon.AuthType = AuthType.Negotiate;
        lcon.Bind(nc);

        MessageBox.Show("Validation Success.");
    }
    catch (LdapException ex)
    {
        MessageBox.Show($"Validation Failure. {ex.GetBaseException().Message}");
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Validation Failure. {ex.GetBaseException().Message}");
    }
}

Code formatting shortcuts in Android Studio for Operation Systems

It's Ctrl + Alt + L for Windows. For a complete list of keyboard shortcuts please take a look at the user manual: https://developer.android.com/studio/intro/keyboard-shortcuts.html

How can I open an Excel file in Python?

import pandas as pd 
import os 
files = os.listdir('path/to/files/directory/')
desiredFile = files[i]
filePath = 'path/to/files/directory/%s'
Ofile = filePath % desiredFile
xls_import = pd.read_csv(Ofile)

Now you can use the power of pandas DataFrames!

C# adding a character in a string

Here is my solution, without overdoing it.

    private static string AppendAtPosition(string baseString, int position, string character)
    {
        var sb = new StringBuilder(baseString);
        for (int i = position; i < sb.Length; i += (position + character.Length))
            sb.Insert(i, character);
        return sb.ToString();
    }


    Console.WriteLine(AppendAtPosition("abcdefghijklmnopqrstuvwxyz", 5, "-"));

Correct MySQL configuration for Ruby on Rails Database.yml file

You should separate the host from the port number. You could have something, like:

development:
  adapter: mysql2
  encoding: utf8
  database: my_db_name
  username: root
  password: my_password
  host: 127.0.0.1
  port: 3306

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

If you are having this problem with a homebrew installation of maven 3 on the OSX 10.9.4 then check out this blog post.

How to include view/partial specific styling in AngularJS

Could append a new stylesheet to head within $routeProvider. For simplicity am using a string but could create new link element also, or create a service for stylesheets

/* check if already exists first - note ID used on link element*/
/* could also track within scope object*/
if( !angular.element('link#myViewName').length){
    angular.element('head').append('<link id="myViewName" href="myViewName.css" rel="stylesheet">');
}

Biggest benefit of prelaoding in page is any background images will already exist, and less lieklyhood of FOUC

Check if two unordered lists are equal

If elements are always nearly sorted as in your example then builtin .sort() (timsort) should be fast:

>>> a = [1,1,2]
>>> b = [1,2,2]
>>> a.sort()
>>> b.sort()
>>> a == b
False

If you don't want to sort inplace you could use sorted().

In practice it might always be faster then collections.Counter() (despite asymptotically O(n) time being better then O(n*log(n)) for .sort()). Measure it; If it is important.

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

You should use html():

SEE DEMO

$(document).ready(function(){
    $("#date").html('<span>'+$("#date").text().substring(0, 2) + '</span><br />'+$("#date").text().substring(3));     
});

Post-increment and pre-increment within a 'for' loop produce same output

The result of your code will be the same. The reason is that the two incrementation operations can be seen as two distinct function calls. Both functions cause an incrementation of the variable, and only their return values are different. In this case, the return value is just thrown away, which means that there's no distinguishable difference in the output.

However, under the hood there's a difference: The post-incrementation i++ needs to create a temporary variable to store the original value of i, then performs the incrementation and returns the temporary variable. The pre-incrementation ++i doesn't create a temporary variable. Sure, any decent optimization setting should be able to optimize this away when the object is something simple like an int, but remember that the ++-operators are overloaded in more complicated classes like iterators. Since the two overloaded methods might have different operations (one might want to output "Hey, I'm pre-incremented!" to stdout for example) the compiler can't tell whether the methods are equivalent when the return value isn't used (basically because such a compiler would solve the unsolvable halting problem), it needs to use the more expensive post-incrementation version if you write myiterator++.

Three reasons why you should pre-increment:

  1. You won't have to think about whether the variable/object might have an overloaded post-incrementation method (for example in a template function) and treat it differently (or forget to treat it differently).
  2. Consistent code looks better.
  3. When someone asks you "Why do you pre-increment?" you'll get the chance to teach them about the halting problem and theoretical limits of compiler optimization. :)

jQuery: enabling/disabling datepicker

Also set the field to disabled when you disable the datePicker e.g

$("input").prop('disabled', true);

To stop the image being clickable you could unbind the click event on that

$('img#<id or class ref>').unbind('click');

How to use ConfigurationManager

Go to tools >> nuget >> console and type:

Install-Package System.Configuration.ConfigurationManager 

If you want a specific version:

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0

Your ConfigurationManager dll will now be imported and the code will begin to work.

ASP.NET MVC ActionLink and post method

Here was an answer baked into the default ASP.NET MVC 5 project I believe that accomplishes my styling goals nicely in the UI. Form submit using pure javascript to some containing form.

@using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
   <a href="javascript:document.getElementById('logoutForm').submit()">
      <span>Sign out</span>
   </a>
}

The fully shown use case is a logout dropdown in the navigation bar of a web app.

@using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
    @Html.AntiForgeryToken()

    <div class="dropdown">
        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            <span class="ma-nav-text ma-account-name">@User.Identity.Name</span>
            <i class="material-icons md-36 text-inverse">person</i>
        </button>

        <ul class="dropdown-menu dropdown-menu-right ma-dropdown-tray">
            <li>
                <a href="javascript:document.getElementById('logoutForm').submit()">
                    <i class="material-icons">system_update_alt</i>
                    <span>Sign out</span>
                </a>
            </li>
        </ul>
    </div>
}

How to set custom ActionBar color / style?

Custom Color:

 <style name="AppTheme" parent="Theme.AppCompat.Light">

                <item name="colorPrimary">@color/ColorPrimary</item>
                <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
                <!-- Customize your theme here. -->
     </style>

Custom Style:

 <style name="Theme.AndroidDevelopers" parent="android:style/Theme.Holo.Light">
        <item name="android:selectableItemBackground">@drawable/ad_selectable_background</item>
        <item name="android:popupMenuStyle">@style/MyPopupMenu</item>
        <item name="android:dropDownListViewStyle">@style/MyDropDownListView</item>
        <item name="android:actionBarTabStyle">@style/MyActionBarTabStyle</item>
        <item name="android:actionDropDownStyle">@style/MyDropDownNav</item>
        <item name="android:listChoiceIndicatorMultiple">@drawable/ad_btn_check_holo_light</item>
        <item name="android:listChoiceIndicatorSingle">@drawable/ad_btn_radio_holo_light</item>
    </style>

For More: Android ActionBar

HEAD and ORIG_HEAD in Git

My understanding is that HEAD points the current branch, while ORIG_HEAD is used to store the previous HEAD before doing "dangerous" operations.

For example git-rebase and git-am record the original tip of branch before they apply any changes.

Twig ternary operator, Shorthand if-then-else

Support for the extended ternary operator was added in Twig 1.12.0.

  1. If foo echo yes else echo no:

    {{ foo ? 'yes' : 'no' }}
    
  2. If foo echo it, else echo no:

    {{ foo ?: 'no' }}
    

    or

    {{ foo ? foo : 'no' }}
    
  3. If foo echo yes else echo nothing:

    {{ foo ? 'yes' }}
    

    or

    {{ foo ? 'yes' : '' }}
    
  4. Returns the value of foo if it is defined and not null, no otherwise:

    {{ foo ?? 'no' }}
    
  5. Returns the value of foo if it is defined (empty values also count), no otherwise:

    {{ foo|default('no') }}
    

Get single row result with Doctrine NativeQuery

You can use $query->getSingleResult(), which will throw an exception if more than one result are found, or if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)

There's also the less famous $query->getOneOrNullResult() which will throw an exception if more than one result are found, and return null if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)

How to unlock a file from someone else in Team Foundation Server

In my case, I tried unlocking the file with tf lock but was told I couldn't because the stale workspace on an old computer that no longer existed was a local workspace. I then tried deleting the workspace with tf workspace /delete, but deleting the workspace did not remove the lock (and then I couldn't try to unlock it again because I just got an error saying the workspace no longer existed).

I ended up tf destroying the file and checking it in again, which was pretty silly and had the undesirable effect of removing\ it from previous changesets, but at least got us working again. It wasn't that big a deal in this case since the file had never been changed since being checked in.

How do I print the type or class of a variable in Swift?

Not exactly what you are after, but you can also check the type of the variable against Swift types like so:

let object: AnyObject = 1

if object is Int {
}
else if object is String {
}

For example.

How to include route handlers in multiple files in Express?

Even though this an older question I stumbled here looking for a solution to a similar issue. After trying some of the solutions here I ended up going a different direction and thought I would add my solution for anyone else who ends up here.

In express 4.x you can get an instance of the router object and import another file that contains more routes. You can even do this recursively so your routes import other routes allowing you to create easy to maintain url paths. For example if I have a separate route file for my '/tests' endpoint already and want to add a new set of routes for '/tests/automated' I may want to break these '/automated' routes out into a another file to keep my '/test' file small and easy to manage. It also lets you logically group routes together by URL path which can be really convenient.

Contents of ./app.js:

var express = require('express'),
    app = express();

var testRoutes = require('./routes/tests');

// Import my test routes into the path '/test'
app.use('/tests', testRoutes);

Contents of ./routes/tests.js

var express = require('express'),
    router = express.Router();

var automatedRoutes = require('./testRoutes/automated');

router
  // Add a binding to handle '/tests'
  .get('/', function(){
    // render the /tests view
  })

  // Import my automated routes into the path '/tests/automated'
  // This works because we're already within the '/tests' route so we're simply appending more routes to the '/tests' endpoint
  .use('/automated', automatedRoutes);
 
module.exports = router;

Contents of ./routes/testRoutes/automated.js:

var express = require('express'),
    router = express.Router();

router
   // Add a binding for '/tests/automated/'
  .get('/', function(){
    // render the /tests/automated view
  })

module.exports = router;

Add a tooltip to a div

You don't need JavaScript for this at all; just set the title attribute:

<div title="Hello, World!">
  <label>Name</label>
  <input type="text"/>
</div>

Note that the visual presentation of the tooltip is browser/OS dependent, so it might fade in and it might not. However, this is the semantic way to do tooltips, and it will work correctly with accessibility software like screen readers.

Demo in Stack Snippets

_x000D_
_x000D_
<div title="Hello, World!">_x000D_
  <label>Name</label>_x000D_
  <input type="text"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Sql query to insert datetime in SQL Server

You will want to use the YYYYMMDD for unambiguous date determination in SQL Server.

insert into table1(approvaldate)values('20120618 10:34:09 AM');

If you are married to the dd-mm-yy hh:mm:ss xm format, you will need to use CONVERT with the specific style.

insert into table1 (approvaldate)
       values (convert(datetime,'18-06-12 10:34:09 PM',5));

5 here is the style for Italian dates. Well, not just Italians, but that's the culture it's attributed to in Books Online.

Is ASCII code 7-bit or 8-bit?

ASCII was indeed originally conceived as a 7-bit code. This was done well before 8-bit bytes became ubiquitous, and even into the 1990s you could find software that assumed it could use the 8th bit of each byte of text for its own purposes ("not 8-bit clean"). Nowadays people think of it as an 8-bit coding in which bytes 0x80 through 0xFF have no defined meaning, but that's a retcon.

There are dozens of text encodings that make use of the 8th bit; they can be classified as ASCII-compatible or not, and fixed- or variable-width. ASCII-compatible means that regardless of context, single bytes with values from 0x00 through 0x7F encode the same characters that they would in ASCII. You don't want to have anything to do with a non-ASCII-compatible text encoding if you can possibly avoid it; naive programs expecting ASCII tend to misinterpret them in catastrophic, often security-breaking fashion. They are so deprecated nowadays that (for instance) HTML5 forbids their use on the public Web, with the unfortunate exception of UTF-16. I'm not going to talk about them any more.

A fixed-width encoding means what it sounds like: all characters are encoded using the same number of bytes. To be ASCII-compatible, a fixed-with encoding must encode all its characters using only one byte, so it can have no more than 256 characters. The most common such encoding nowadays is Windows-1252, an extension of ISO 8859-1.

There's only one variable-width ASCII-compatible encoding worth knowing about nowadays, but it's very important: UTF-8, which packs all of Unicode into an ASCII-compatible encoding. You really want to be using this if you can manage it.

As a final note, "ASCII" nowadays takes its practical definition from Unicode, not its original standard (ANSI X3.4-1968), because historically there were several dozen variations on the ASCII 127-character repertoire -- for instance, some of the punctuation might be replaced with accented letters to facilitate the transmission of French text. Nowadays all of those variations are obsolescent, and when people say "ASCII" they mean that the bytes with value 0x00 through 0x7F encode Unicode codepoints U+0000 through U+007F. This will probably only matter to you if you ever find yourself writing a technical standard.

If you're interested in the history of ASCII and the encodings that preceded it, start with the paper "The Evolution of Character Codes, 1874-1968" (samizdat copy at http://falsedoor.com/doc/ascii_evolution-of-character-codes.pdf) and then chase its references (many of which are not available online and may be hard to find even with access to a university library, I regret to say).

How to initialize a vector with fixed length in R

The initialization method easiest to remember is

vec = vector(,10); #the same as "vec = vector(length = 10);"

The values of vec are: "[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE" (logical mode) by default.

But after setting a character value, like

vec[2] = 'abc'

vec becomes: "FALSE" "abc" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"", which is of the character mode.

Creating temporary files in bash

You might want to look at mktemp

The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of 'Xs' appended to it, for example /tmp/tfile.XXXXXXXXXX. The trailing 'Xs' are replaced with a combination of the current process number and random letters.

For more details: man mktemp

Is it possible to use jQuery to read meta tags

For select twitter meta name , you can add a data attribute.

example :

meta name="twitter:card" data-twitterCard="" content=""
$('[data-twitterCard]').attr('content');

Which mime type should I use for mp3

Use .mp3 audio/mpeg, that's the one I always used. I guess others are just aliases.

Grep characters before and after match?

With gawk , you can use match function:

    x="hey there how are you"
    echo "$x" |awk --re-interval '{match($0,/(.{4})how(.{4})/,a);print a[1],a[2]}'
    ere   are

If you are ok with perl, more flexible solution : Following will print three characters before the pattern followed by actual pattern and then 5 character after the pattern.

echo hey there how are you |perl -lne 'print "$1$2$3" if /(.{3})(there)(.{5})/'
ey there how

This can also be applied to words instead of just characters.Following will print one word before the actual matching string.

echo hey there how are you |perl -lne 'print $1 if /(\w+) there/'
hey

Following will print one word after the pattern:

echo hey there how are you |perl -lne 'print $2 if /(\w+) there (\w+)/'
how

Following will print one word before the pattern , then the actual word and then one word after the pattern:

echo hey there how are you |perl -lne 'print "$1$2$3" if /(\w+)( there )(\w+)/'
hey there how

Customizing the template within a Directive

The above answers unfortunately don't quite work. In particular, the compile stage does not have access to scope, so you can't customize the field based on dynamic attributes. Using the linking stage seems to offer the most flexibility (in terms of asynchronously creating dom, etc.) The below approach addresses that:

<!-- Usage: -->
<form>
  <form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
  return { 
    restrict: 'E', 
    compile: function(element, attrs) {
      var fieldGetter = $parse(attrs.field);

      return function (scope, element, attrs) {
        var template, field, id;
        field = fieldGetter(scope);
        template = '..your dom structure here...'
        element.replaceWith($compile(template)(scope));
      }
    }
  }
})

I've created a gist with more complete code and a writeup of the approach.

How does DateTime.Now.Ticks exactly work?

The resolution of DateTime.Now depends on your system timer (~10ms on a current Windows OS)...so it's giving the same ending value there (it doesn't count any more finite than that).

Calling Java from Python

I'm just beginning to use JPype 0.5.4.2 (july 2011) and it looks like it's working nicely...
I'm on Xubuntu 10.04

pandas python how to count the number of records or rows in a dataframe

To get the number of rows in a dataframe use:

df.shape[0]

(and df.shape[1] to get the number of columns).

As an alternative you can use

len(df)

or

len(df.index)

(and len(df.columns) for the columns)

shape is more versatile and more convenient than len(), especially for interactive work (just needs to be added at the end), but len is a bit faster (see also this answer).

To avoid: count() because it returns the number of non-NA/null observations over requested axis

len(df.index) is faster

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(24).reshape(8, 3),columns=['A', 'B', 'C'])
df['A'][5]=np.nan
df
# Out:
#     A   B   C
# 0   0   1   2
# 1   3   4   5
# 2   6   7   8
# 3   9  10  11
# 4  12  13  14
# 5 NaN  16  17
# 6  18  19  20
# 7  21  22  23

%timeit df.shape[0]
# 100000 loops, best of 3: 4.22 µs per loop

%timeit len(df)
# 100000 loops, best of 3: 2.26 µs per loop

%timeit len(df.index)
# 1000000 loops, best of 3: 1.46 µs per loop

df.__len__ is just a call to len(df.index)

import inspect 
print(inspect.getsource(pd.DataFrame.__len__))
# Out:
#     def __len__(self):
#         """Returns length of info axis, but here we use the index """
#         return len(self.index)

Why you should not use count()

df.count()
# Out:
# A    7
# B    8
# C    8

php random x digit number

Treat your number as a list of digits and just append a random digit each time:

function n_digit_random($digits) {
  $temp = "";

  for ($i = 0; $i < $digits; $i++) {
    $temp .= rand(0, 9);
  }

  return (int)$temp;
}

Or a purely numerical solution:

function n_digit_random($digits)
  return rand(pow(10, $digits - 1) - 1, pow(10, $digits) - 1);
}

How to check if AlarmManager already has an alarm set?

I have 2 alarms. I am using intent with extras instead of action to identify the events:

Intent i = new Intent(context, AppReciever.class);
i.putExtra("timer", "timer1");

the thing is that with diff extras the intent (and the alarm) wont be unique. So to able to identify which alarm is active or not, I had to define diff requestCode-s:

boolean alarmUp = (PendingIntent.getBroadcast(context, MyApp.TIMER_1, i, 
                    PendingIntent.FLAG_NO_CREATE) != null);

and here is how alarm was created:

public static final int TIMER_1 = 1;
public static final int TIMER_2 = 2;

PendingIntent pending = PendingIntent.getBroadcast(context, TIMER_1, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pending);
pending = PendingIntent.getBroadcast(context, TIMER_2, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pending);

How do I change the color of radio buttons?

It may be helpful to bind radio-button to styled label. Futher details in this answer.

How to do a newline in output

You can do this all in the File.open block:

Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'

File.open playlist_name, 'w' do |f|
  music.each do |z|
    f.puts z
  end
end

How to show current user name in a cell?

Without VBA macro, you can use this tips to get the username from the path :

=MID(INFO("DIRECTORY"),10,LEN(INFO("DIRECTORY"))-LEN(MID(INFO("DIRECTORY"),FIND("\",INFO("DIRECTORY"),10),1000))-LEN("C:\Users\"))

Mobile Redirect using htaccess

First, go to the following URL and download the mobile_detect.php file:

http://code.google.com/p/php-mobile-detect/

Insert the following code on your index or home page:

<?php
@include("Mobile_Detect.php");
$detect = new Mobile_Detect();
if ($detect->isMobile() && isset($_COOKIE['mobile']))
{
$detect = "false";
}
elseif ($detect->isMobile())
{
header("Location:http://www.yourmobiledirectory.com");
}
?>

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Another case that could cause this error is

>>> np.ndindex(np.random.rand(60,60))
TypeError: only integer scalar arrays can be converted to a scalar index

Using the actual shape will fix it.

>>> np.ndindex(np.random.rand(60,60).shape)
<numpy.ndindex object at 0x000001B887A98880>

Is there an Eclipse plugin to run system shell in the Console?

I just found out about WickedShell, but it seems to work wrong with GNU/Linux and bash. Seems like some sort of encoding issue, all the characters in my prompt are displayed wrong.

Seems to be the best (only) tool for the job anyways, so I'll give it some more testing and see if it's good enough. I'll contact the developer anyways about this issue.

Find the index of a char in string?

Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains("d") Then
        numberString = myString.IndexOf("d")
    End If
End Sub

Another sample with TextBox

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains(me.TextBox1.Text) Then
        numberString = myString.IndexOf(Me.TextBox1.Text)
    End If
End Sub

Regards

Git: Installing Git in PATH with GitHub client for Windows

To fix a problem, in my case: I checked Git folder under c:\program files\Git. I didn't find git.exe, so delete the Git folder and install it again. Declare them in the environment variables as shown above. the problem will be solved.

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

Solution for me is: I clean both the solution and the project. And just rebuild the project. This error happens because I tried to delete the main file (only keep library files) in the previous build so at the current build the old stuff is still kept in the built directory. That's why unresolved things happened. "unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) "

phpmyadmin logs out after 1440 secs

Steps for doing this using phpMyAdmin settings without any problem or requirements to change configs in php my.ini or defining .htaccess file:

  1. Goto your phpMyAdmin install path (ex. /usr/share/phpMyAdmin/ on my centos7) and find create_tables.sql in one of its subfolders (phpMyAdmin/sql/create_tables.sql in my 4.4.9 version.) and execute whole file contents on your current phpMyAdmin site from your web browser. This will create a database named phpmyadmin which can keep all your phpMyAdmin options saved permanently.
  2. In phpMyAdmin's config.inc.php (located on /etc/phpMyAdmin/ in my centos7 server) find the commented line $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin'; and uncomment it (Now phpMyAdmin will use that custom database we generated in previous step).
  3. Goto phpMyAdmin from web browser and goto Server >> Settings >> Features >> "Login Cookie Validity" as in picture described by Pavnish and set the desired value. It works now.

References: Niccolas Answer ,PhpMyAdmin Configuration Storage, flashMarks Answer

How to run an external program, e.g. notepad, using hyperlink?

Make a batch file and call the bacth file in Window.open. Here how it works

  1. make a file in notepad
  2. write your script : start wmplayer "\dotnet\sc\1234.mp4" /fullscreen
  3. save as : test.bat in \dotnet\sc\test.bat

in html

window.open('file://dotnet/sc/test.bat')

Enjoy..

Correct use of transactions in SQL Server

At the beginning of stored procedure one should put SET XACT_ABORT ON to instruct Sql Server to automatically rollback transaction in case of error. If ommited or set to OFF one needs to test @@ERROR after each statement or use TRY ... CATCH rollback block.

How do I use Maven through a proxy?

Just to add my own experiences with this: my company's proxy is http://webproxy.intra.companyname.com:3128. For maven to work via this proxy, the settings have to be exactly like this

<settings>
  <proxies>
    <proxy>
      <id>default</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>webproxy.intra.companyname.com</host>
      <port>3128</port>
    </proxy>
  </proxies>
</settings>

Unlike some other proxy-configuration files, the protocol here describes how to connect to the proxy server, not which kinds of protocol should be proxied. The http part of the target has to be split off from the hostname, else it won't work.

Using Laravel Homestead: 'no input file specified'

This happens because you need to configure your nginx server properly in order to serve you application. You can do this following this guide, starting in the topic Configure Nginx and the Web Root.

After properly configuring your symbolic link between your /etc/nginx/sites-available and /etc/nginx/sites-enabled you need to make sure your root variable is set to your application's folder path. Set your nginx root from

root /usr/share/nginx/html;

to

/home/vagrant/Projects/ProjectOne/public

Also, you have to place index.php before your html files so php is served before html. Change this

index index.html index.htm;

to this

index index.php index.html index.htm;

After finish your configuration restart your nginx server with

sudo service nginx restart

Your application should be served now.

Convert pyQt UI to python

Update for anyone using PyQt5 with python 3.x:

  1. Open terminal (eg. Powershell, cmd etc.)
  2. cd into the folder with your .ui file.
  3. Type: "C:\python\Lib\site-packages\PyQt5\pyuic5.bat" -x Trial.ui -o trial_gui.py for cases where PyQt5 is not a path variable. The path in quotes " " represents where the pyuic5.bat file is.

This should work!

MSVCP120d.dll missing

I downloaded msvcr120d.dll and msvcp120d.dll for 32-bit version and then, I put them into Debug folder of my project. It worked well. (My computer is 64-bit version)

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

I tried other solutions and the exception didn't go away. So I decompiled the entire jose4j 0.6.5 jar with a Java Decomplier and look at its pom.xml.

I realised it has a specific dependency on slf4j-api, version 1.7.21: enter image description here

So in my project's pom.xml, I added the exact same dependency, updated my Maven project so that it downloads this jar into my repository and the exception was gone.

However it may bring up another error caused by slf4j itself:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

To overcome this issue, I added the following into my project's pom.xml. So altogether you need to add the following to your pom.xml and my jose4j ran without anymore issues:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.21</version>
</dependency>   

<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version>1.6.4</version>
</dependency>

Remember to update your Maven project after amending your pom.xml.

(Right-click Project folder in Eclipse -> Maven -> Update Project..)

How to get all child inputs of a div element (jQuery)

Use it without the greater than:

$("#panel :input");

The > means only direct children of the element, if you want all children no matter the depth just use a space.

git remove merge commit from history

There are two ways to tackle this based on what you want:

Solution 1: Remove purple commits, preserving history (incase you want to roll back)

git revert -m 1 <SHA of merge>

-m 1 specifies which parent line to choose

Purple commits will still be there in history but since you have reverted, you will not see code from those commits.


Solution 2: Completely remove purple commits (disruptive change if repo is shared)

git rebase -i <SHA before branching out>

and delete (remove lines) corresponding to purple commits.

This would be less tricky if commits were not made after merge. Additional commits increase the chance of conflicts during revert/rebase.

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

My favorite slow sorting algorithm is the stooge sort:

void stooges(long *begin, long *end) {
   if( (end-begin) <= 1 ) return;
   if( begin[0] < end[-1] ) swap(begin, end-1);
   if( (end-begin) > 1 ) {
      int one_third = (end-begin)/3;
      stooges(begin, end-one_third);
      stooges(begin+one_third, end);
      stooges(begin, end-one_third);
   }
}

The worst case complexity is O(n^(log(3) / log(1.5))) = O(n^2.7095...).

Another slow sorting algorithm is actually named slowsort!

void slow(long *start, long *end) {
   if( (end-start) <= 1 ) return;
   long *middle = start + (end-start)/2;
   slow(start, middle);
   slow(middle, end);
   if( middle[-1] > end[-1] ) swap(middle-1, end-1);
   slow(start, end-1);
}

This one takes O(n ^ (log n)) in the best case... even slower than stoogesort.

Convert object string to JSON

Using new Function() is better than eval, but still should only be used with safe input.

const parseJSON = obj => Function('"use strict";return (' + obj + ')')();

console.log(parseJSON("{a:(4-1), b:function(){}, c:new Date()}"))
// outputs: Object { a: 3, b: b(), c: Date 2019-06-05T09:55:11.777Z }

Sources: MDN, 2ality

How to write text in ipython notebook?

As it is written in the documentation you have to change the cell type to a markdown.

enter image description here

Run a single migration file

If you want to run it from console, this is what you are looking for:

$ rails console
irb(main)> require "#{Rails.root.to_s}/db/migrate/XXXXX_my_migration.rb"
irb(main)> AddFoo.migrate(:up)

I tried the other answers, but requiring without Rails.root didnt work for me.

Also, .migrate(:up) part forces the migration to rerun regardless if it has already run or not. This is useful for when you already ran a migration, have kinda undone it by messing around with the db and want a quick solution to have it up again.

how to get param in method post spring mvc?

When I want to get all the POST params I am using the code below,

@RequestMapping(value = "/", method = RequestMethod.POST)
public ViewForResponseClass update(@RequestBody AClass anObject) {
    // Source..
}

I am using the @RequestBody annotation for post/put/delete http requests instead of the @RequestParam which reads the GET parameters.

SQL Server: Attach incorrect version 661

To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.

Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:

SELECT @@VERSION

Calculate difference in keys contained in two Python dictionaries

There is an other question in stackoverflow about this argument and i have to admit that there is a simple solution explained: the datadiff library of python helps printing the difference between two dictionaries.

Using current time in UTC as default value in PostgreSQL

A function is not even needed. Just put parentheses around the default expression:

create temporary table test(
    id int, 
    ts timestamp without time zone default (now() at time zone 'utc')
);

What is 'Currying'?

It can be a way to use functions to make other functions.

In javascript:

let add = function(x){
  return function(y){ 
   return x + y
  };
};

Would allow us to call it like so:

let addTen = add(10);

When this runs the 10 is passed in as x;

let add = function(10){
  return function(y){
    return 10 + y 
  };
};

which means we are returned this function:

function(y) { return 10 + y };

So when you call

 addTen();

you are really calling:

 function(y) { return 10 + y };

So if you do this:

 addTen(4)

it's the same as:

function(4) { return 10 + 4} // 14

So our addTen() always adds ten to whatever we pass in. We can make similar functions in the same way:

let addTwo = add(2)       // addTwo(); will add two to whatever you pass in
let addSeventy = add(70)  // ... and so on...

Now the obvious follow up question is why on earth would you ever want to do that? It turns what was an eager operation x + y into one that can be stepped through lazily, meaning we can do at least two things 1. cache expensive operations 2. achieve abstractions in the functional paradigm.

Imagine our curried function looked like this:

let doTheHardStuff = function(x) {
  let z = doSomethingComputationallyExpensive(x)
  return function (y){
    z + y
  }
}

We could call this function once, then pass around the result to be used in lots of places, meaning we only do the computationally expensive stuff once:

let finishTheJob = doTheHardStuff(10)
finishTheJob(20)
finishTheJob(30)

We can get abstractions in a similar way.

"Could not find the main class" error when running jar exported by Eclipse

Ok, so I finally got it to work. If I use the JRE 6 instead of 7 everything works great. No idea why, but it works.

Twitter bootstrap scrollable table

Re Jonathan Wood's suggestion. I don't have the option of wrapping tables with a new div as i'm using a CMS. Using JQuery here's what i did:

$( "table" ).wrap( "<div class='table-overflow'></div>" );

This wraps table elements with a new div with the class "table-overflow".

You can then simply add the following definition in your css file:

.table-overflow { overflow: auto; }     

Android ClassNotFoundException: Didn't find class on path

I had the same issue for my project. It happened due to the conflict in android support library version between my project and the library project that I added in my project. Put the same version android support library in your project and library projects you included and clean build... Everything will work...

How to fill color in a cell in VBA?

You need to use cell.Text = "#N/A" instead of cell.Value = "#N/A". The error in the cell is actually just text stored in the cell.

jQuery get the location of an element relative to window

    function trbl(e, relative) {
            var r = $(e).get(0).getBoundingClientRect(); relative = $(relative);

            return {
                    t : r.top    + relative['scrollTop'] (),
                    r : r.right  + relative['scrollLeft'](),
                    b : r.bottom + relative['scrollTop'] (),
                    l : r.left   + relative['scrollLeft']() 

            }
    }

    // Example
    trbl(e, window);

undefined reference to WinMain@16 (codeblocks)

You should create a new project in Code::Blocks, and make sure it's 'Console Application'.

Add your .cpp files into the project so they are all compiled and linked together.

How to convert InputStream to FileInputStream

You need something like:

    URL resource = this.getClass().getResource("/path/to/resource.res");
    File is = null;
    try {
        is = new File(resource.toURI());
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        FileInputStream input = new FileInputStream(is);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

Using C++ filestreams (fstream), how can you determine the size of a file?

Like this:

long begin, end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size: " << (end-begin) << " bytes." << endl;

How do I find the data directory for a SQL Server instance?

Alex's answer is the right one, but for posterity here's another option: create a new empty database. If you use CREATE DATABASE without specifying a target dir you get... the default data / log directories. Easy.

Personally however I'd probably either:

  • RESTORE the database to the developer's PC, rather than copy/attach (backups can be compressed, exposed on a UNC), or
  • Use a linked server to avoid doing this in the first place (depends how much data goes over the join)

ps: 20gb is not huge, even in 2015. But it's all relative.

How to set session timeout dynamically in Java web applications?

I need to give my user a web interface to change the session timeout interval. So, different installations of the web application would be able to have different timeouts for their sessions, but their web.xml cannot be different.

your question is simple, you need session timeout interval should be configurable at run time and configuration should be done through web interface and there shouldn't be overhead of restarting the server.

I am extending Michaels answer to address your question.

Logic: You need to store configured value in either .properties file or to database. On server start read that stored value and copy to a variable use that variable until server is UP. As config is updated update variable also. Thats it.

Expaination

In MyHttpSessionListener class 1. create a static variable with name globalSessionTimeoutInterval.

  1. create a static block(executed for only for first time of class is being accessed) and read timeout value from config.properties file and set value to globalSessionTimeoutInterval variable.

  2. Now use that value to set maxInactiveInterval

  3. Now Web part i.e, Admin configuration page

    a. Copy configured value to static variable globalSessionTimeoutInterval.

    b. Write same value to config.properties file. (consider server is restarted then globalSessionTimeoutInterval will be loaded with value present in config.properties file)

  4. Alternative .properties file OR storing it into database. Choice is yours.

Logical code for achieving the same

public class MyHttpSessionListener implements HttpSessionListener 
{
  public static Integer globalSessionTimeoutInterval = null;

  static
  {
      globalSessionTimeoutInterval =  Read value from .properties file or database;
  }
  public void sessionCreated(HttpSessionEvent event)
  {
      event.getSession().setMaxInactiveInterval(globalSessionTimeoutInterval);
  }

  public void sessionDestroyed(HttpSessionEvent event) {}

}

And in your Configuration Controller or Configuration servlet

String valueReceived = request.getParameter(timeoutValue);
if(valueReceived  != null)
{
    MyHttpSessionListener.globalSessionTimeoutInterval = Integer.parseInt(timeoutValue);
          //Store valueReceived to config.properties file or database
}

Messagebox with input field

You can do it by making form and displaying it using ShowDialogBox....

Form.ShowDialog Method - Shows the form as a modal dialog box.

Example:

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

Event handler not working on dynamic content

You are missing the selector in the .on function:

.on(eventType, selector, function)

This selector is very important!

http://api.jquery.com/on/

If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler

See jQuery 1.9 .live() is not a function for more details.

jQuery CSS Opacity

Try with this :

jQuery('#main').css({ opacity: 0.6 });

PHP list of specific files in a directory

you can mix between glob() function & pathinfo() function like below.

the below code will show files information for specific extension "pdf"

foreach ( glob("*.pdf") as $file ) {

    $file_info = pathinfo( getcwd().'/'.$file );

    echo $file_info['dirname'], "<br>";
    echo $file_info['basename'], "<br>";
    echo $file_info['extension'], "<br>";
    echo $file_info['filename'], "<br>"; 
    echo '<hr>';
}

How to convert local time string to UTC?

I found the best answer on another question here. It only uses python built-in libraries and does not require you to input your local timezone (a requirement in my case)

import time
import calendar

local_time = time.strptime("2018-12-13T09:32:00.000", "%Y-%m-%dT%H:%M:%S.%f")
local_seconds = time.mktime(local_time)
utc_time = time.gmtime(local_seconds)

I'm reposting the answer here since this question pops up in google instead of the linked question depending on the search keywords.

How to change the author and committer name and e-mail of multiple commits in Git?

A safer alternative to git's filter-branch is filter-repo tool as suggested by git docs here.

git filter-repo --commit-callback '

  old_email = b"[email protected]"
  correct_name = b"Your Correct Name"
  correct_email = b"[email protected]"

  if commit.committer_email == old_email :
    commit.committer_name = correct_name
    commit.committer_email = correct_email

  if commit.author_email == old_email : 
    commit.author_name = correct_name
    commit.author_email = correct_email
  '

The above command mirrors the logic used in this script but uses filter-repo instead of filter-branch.

The code body after commit-callback option is basically python code used for processing commits. You can write your own logic in python here. See more about commit object and its attributes here.

Since filter-repo tool is not bundled with git you need to install it separately.

See Prerequisties and Installation Guide

If you have a python env >= 3.5, you can use pip to install it.

pip3 install git-filter-repo

Note: It is strongly recommended to try filter-repo tool on a fresh clone. Also remotes are removed once the operation is done. Read more on why remotes are removed here. Also read the limitations of this tool under INTERNALS section.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

in my case it was unused parameter in room persistence function in DAO class

How do I create a MongoDB dump of my database?

Or you can make backup script on Windows, remember to add Winrar to %PATH%

bin\mongodump --db=COL1 -o D:\BACK\COL1
rar.exe a -ep1 -r COL1.rar COL1
rename COL1.rar "COL1_%date:~10,4%_%date:~7,2%_%date:~4,2%_%time:~0,2%_%time:~3,2%.rar"

#rmdir /s /q COL1 -> don;t run this on your mongodb/ dir !!!!!

Is there a difference between using a dict literal and a dict constructor?

From python 2.7 tutorial:

A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

tel = {'jack': 4098, 'sape': 4139}
data = {k:v for k,v in zip(xrange(10), xrange(10,20))}

While:

The dict() constructor builds dictionaries directly from lists of key-value pairs stored as tuples. When the pairs form a pattern, list comprehensions can compactly specify the key-value list.

tel = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
data = dict((k,v) for k,v in zip(xrange(10), xrange(10,20)))

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

dict(sape=4139, guido=4127, jack=4098)
>>>  {'sape': 4139, 'jack':4098, 'guido': 4127}

So both {} and dict() produce dictionary but provide a bit different ways of dictionary data initialization.