Programs & Examples On #Openoffice impress

related to OpenOffice.org Impress, a presentation application which is similar to Microsoft PowerPoint.

How to get PID of process by specifying process name and store it in a variable to use further?

pids=$(pgrep <name>)

will get you the pids of all processes with the given name. To kill them all, use

kill -9 $pids

To refrain from using a variable and directly kill all processes with a given name issue

pkill -9 <name>

jquery smooth scroll to an anchor?

I wanted a version that worked for <a href="#my-id"> and <a href="/page#my-id">

<script>        
    $('a[href*=#]:not([href=#])').on('click', function (event) {
        event.preventDefault();
        var element = $(this.hash);
        $('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
    });
</script>

Set the maximum character length of a UITextField

Using Interface builder you can link and get the event for "Editing changed" in any of your function. Now there you can put check for the length

- (IBAction)onValueChange:(id)sender 
{
    NSString *text = nil;
    int MAX_LENGTH = 20;
    switch ([sender tag] ) 
    {
        case 1: 
        {
            text = myEditField.text;
            if (MAX_LENGTH < [text length]) {
                myEditField.text = [text substringToIndex:MAX_LENGTH];
            }
        }
            break;
        default:
            break;
    }

}

Best way to disable button in Twitter's Bootstrap

For input and button:

$('button').prop('disabled', true);

For anchor:

$('a').attr('disabled', true);

Checked in firefox, chrome.

See http://jsfiddle.net/czL54/2/

Set variable with multiple values and use IN

Use a Temp Table or a Table variable, e.g.

select 'A' as [value]
into #tmp
union
select 'B'
union 
select 'C'

and then

SELECT   
blah 
FROM    foo 
WHERE   myField IN (select [value] from #tmp) 

or

SELECT   
f.blah 
FROM foo f INNER JOIN #tmp t ON f.myField = t.[value]

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

Determine the size of an InputStream

I just wanted to add, Apache Commons IO has stream support utilities to perform the copy. (Btw, what do you mean by placing the file into an inputstream? Can you show us your code?)

Edit:

Okay, what do you want to do with the contents of the item? There is an item.get() which returns the entire thing in a byte array.

Edit2

item.getSize() will return the uploaded file size.

IF... OR IF... in a windows batch file

There is no IF <arg> OR or ELIF or ELSE IF in Batch, however...

Try nesting the other IF's inside the ELSE of the previous IF.

IF <arg> (
    ....
) ELSE (
    IF <arg> (
        ......
    ) ELSE (
        IF <arg> (
            ....
        ) ELSE (
    )
)

Is there a way to make HTML5 video fullscreen?

The complete solution:

    function bindFullscreen(video) {
            $(video).unbind('click').click(toggleFullScreen);
    }

    function toggleFullScreen() {
            if (!document.fullscreenElement &&    // alternative standard method
                    !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) {  // current working methods
                    if (document.documentElement.requestFullscreen) {
                            document.documentElement.requestFullscreen();
                    } else if (document.documentElement.msRequestFullscreen) {
                            document.documentElement.msRequestFullscreen();
                    } else if (document.documentElement.mozRequestFullScreen) {
                            document.documentElement.mozRequestFullScreen();
                    } else if (document.documentElement.webkitRequestFullscreen) {
                            document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
                    }
            } 
            else {
                    if (document.exitFullscreen) {
                            document.exitFullscreen();
                    } else if (document.msExitFullscreen) {
                            document.msExitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                            document.mozCancelFullScreen();
                    } else if (document.webkitExitFullscreen) {
                            document.webkitExitFullscreen();
                    }
            }
    }

Response.Redirect with POST instead of Get?

Copy-pasteable code based on Pavlo Neyman's method

RedirectPost(string url, T bodyPayload) and GetPostData() are for those who just want to dump some strongly typed data in the source page and fetch it back in the target one. The data must be serializeable by NewtonSoft Json.NET and you need to reference the library of course.

Just copy-paste into your page(s) or better yet base class for your pages and use it anywhere in you application.

My heart goes out to all of you who still have to use Web Forms in 2019 for whatever reason.

        protected void RedirectPost(string url, IEnumerable<KeyValuePair<string,string>> fields)
        {
            Response.Clear();

            const string template =
@"<html>
<body onload='document.forms[""form""].submit()'>
<form name='form' action='{0}' method='post'>
{1}
</form>
</body>
</html>";

            var fieldsSection = string.Join(
                    Environment.NewLine,
                    fields.Select(x => $"<input type='hidden' name='{HttpUtility.UrlEncode(x.Key)}' value='{HttpUtility.UrlEncode(x.Value)}'>")
                );

            var html = string.Format(template, HttpUtility.UrlEncode(url), fieldsSection);

            Response.Write(html);

            Response.End();
        }

        private const string JsonDataFieldName = "_jsonData";

        protected void RedirectPost<T>(string url, T bodyPayload)
        {
            var json = JsonConvert.SerializeObject(bodyPayload, Formatting.Indented);
            //explicit type declaration to prevent recursion
            IEnumerable<KeyValuePair<string, string>> postFields = new List<KeyValuePair<string, string>>()
                {new KeyValuePair<string, string>(JsonDataFieldName, json)};

            RedirectPost(url, postFields);

        }

        protected T GetPostData<T>() where T: class 
        {
            var urlEncodedFieldData = Request.Params[JsonDataFieldName];
            if (string.IsNullOrEmpty(urlEncodedFieldData))
            {
                return null;// default(T);
            }

            var fieldData = HttpUtility.UrlDecode(urlEncodedFieldData);

            var result = JsonConvert.DeserializeObject<T>(fieldData);
            return result;
        }

How to reload a div without reloading the entire page?

write a button tag and on click function

var x = document.getElementById('codeRefer').innerHTML;
  document.getElementById('codeRefer').innerHTML = x;

write this all in onclick function

Convert or extract TTC font to TTF - how to?

This is what worked for me for extracting TTFs from .dfont and .ttc files from Mac OS X: http://transfonter.org/ttc-unpack

The resulting TTFs work fine in Windows 7.

Difference between long and int data types

From this reference:

An int was originally intended to be the "natural" word size of the processor. Many modern processors can handle different word sizes with equal ease.

Also, this bit:

On many (but not all) C and C++ implementations, a long is larger than an int. Today's most popular desktop platforms, such as Windows and Linux, run primarily on 32 bit processors and most compilers for these platforms use a 32 bit int which has the same size and representation as a long.

adb uninstall failed

If you have problems uninstalling through adb, I can recommend the following tool:

https://github.com/patrickfav/uber-adb-tools

you can use wildcards and supports multiple devices, also has some better error handling than the vanilla ADB (but uses it in background of course). Will work on your platform.

console showcase

Full disclaimer: I am the developer

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

You can use a pseudo-element to insert that character before each list item:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: '?';_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Purpose of #!/usr/bin/python3 shebang

That's called a hash-bang. If you run the script from the shell, it will inspect the first line to figure out what program should be started to interpret the script.

A non Unix based OS will use its own rules for figuring out how to run the script. Windows for example will use the filename extension and the # will cause the first line to be treated as a comment.

If the path to the Python executable is wrong, then naturally the script will fail. It is easy to create links to the actual executable from whatever location is specified by standard convention.

What is Turing Complete?

From wikipedia:

Turing completeness, named after Alan Turing, is significant in that every plausible design for a computing device so far advanced can be emulated by a universal Turing machine — an observation that has become known as the Church-Turing thesis. Thus, a machine that can act as a universal Turing machine can, in principle, perform any calculation that any other programmable computer is capable of. However, this has nothing to do with the effort required to write a program for the machine, the time it may take for the machine to perform the calculation, or any abilities the machine may possess that are unrelated to computation.

While truly Turing-complete machines are very likely physically impossible, as they require unlimited storage, Turing completeness is often loosely attributed to physical machines or programming languages that would be universal if they had unlimited storage. All modern computers are Turing-complete in this sense.

I don't know how you can be more non-technical than that except by saying "turing complete means 'able to answer computable problem given enough time and space'".

How do you set the startup page for debugging in an ASP.NET MVC application?

This works for me under Specific Page for MVC:

/Home/Index

Update: Currently, I just use a forward slash in the "Specific Page" textbox, and it takes me to the home page as defined in the routing:

/

How to normalize a 2-dimensional numpy array in python less verbose?

it appears that this also works

def normalizeRows(M):
    row_sums = M.sum(axis=1)
    return M / row_sums

Simple Java Client/Server Program

Outstream is not closed ... close the stream so that response goes back to test client. Hope this helps.

Class has been compiled by a more recent version of the Java Environment

I'm writing this because I found the other answers hard to understand.

Essentially your JRE is not updated and/or Eclipse is not configured to use the most recent JRE.

On Windows, go to Control Panel -> Programs -> Java -> update and proceed to update java

or if you don't have Java, go to Oracle's website and download the most recent JRE.

Once this is done, go into eclipse, and under the project view, right click on your project, select Java Build Path, double click on JRE System Library, then Select Workspace Default JRE 14.1.

If a recent version of Java doesn't show up here, it probably isn't installed. Check you JRE(NOT JDK) version and make sure it's recent. If it is, try restarting the computer then trying this again.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

1.Right click on your java project.

2.Select "RUN AS".

3.Select "RUN CONFIGURATIOS...".

4.Here select your server at left side of the page and then u would see "CLASS PATH" tab at riht side,just click on it.

5.Here clilck on "USER ENTRIES" and select "ADD EXTERNAL JARS".

6.Select "ojdbc14.jar" file.

7.Click on Apply.

8.Click on Run.

9.Finally Restart your server then it would be execute.

String replace a Backslash

Try replaceAll("\\\\", "") or replaceAll("\\\\/", "/").

The problem here is that a backslash is (1) an escape chararacter in Java string literals, and (2) an escape character in regular expressions – each of this uses need doubling the character, in effect needing 4 \ in row.

Of course, as Bozho said, you need to do something with the result (assign it to some variable) and not throw it away. And in this case the non-regex variant is better.

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

TensorFlow: "Attempting to use uninitialized value" in variable initialization

I want to give my resolution, it work when i replace the line [session = tf.Session()] with [sess = tf.InteractiveSession()]. Hope this will be useful to others.

DLL and LIB files - what and why?

There are static libraries (LIB) and dynamic libraries (DLL) - but note that .LIB files can be either static libraries (containing object files) or import libraries (containing symbols to allow the linker to link to a DLL).

Libraries are used because you may have code that you want to use in many programs. For example if you write a function that counts the number of characters in a string, that function will be useful in lots of programs. Once you get that function working correctly you don't want to have to recompile the code every time you use it, so you put the executable code for that function in a library, and the linker can extract and insert the compiled code into your program. Static libraries are sometimes called 'archives' for this reason.

Dynamic libraries take this one step further. It seems wasteful to have multiple copies of the library functions taking up space in each of the programs. Why can't they all share one copy of the function? This is what dynamic libraries are for. Rather than building the library code into your program when it is compiled, it can be run by mapping it into your program as it is loaded into memory. Multiple programs running at the same time that use the same functions can all share one copy, saving memory. In fact, you can load dynamic libraries only as needed, depending on the path through your code. No point in having the printer routines taking up memory if you aren't doing any printing. On the other hand, this means you have to have a copy of the dynamic library installed on every machine your program runs on. This creates its own set of problems.

As an example, almost every program written in 'C' will need functions from a library called the 'C runtime library, though few programs will need all of the functions. The C runtime comes in both static and dynamic versions, so you can determine which version your program uses depending on particular needs.

CardView background color always white

Kotlin for XML

app:cardBackgroundColor="@android:color/red"

code

cardName.setCardBackgroundColor(ContextCompat.getColor(this, R.color.colorGray));

position: fixed doesn't work on iPad and iPhone

using jquery i am able to come up with this. it doesnt scroll smooth, but it does the trick. you can scroll down, and the fixed div pops up on top.

THE CSS

<style type="text/css">
    .btn_cardDetailsPg {height:5px !important;margin-top:-20px;}
    html, body {overflow-x:hidden;overflow-y:auto;}
    #lockDiv {
  background-color: #fff;
  color: #000;
  float:left;
  -moz-box-shadow: 0px 4px 2px 2px #ccc;-webkit-box-shadow: 0px 4px 2px 2px #ccc;box-shadow:0px 4px 2px 2px #ccc;
  }
#lockDiv.stick {
  position: fixed;
  top: 0;
  z-index: 10000;
  margin-left:0px;
  }
</style>

THE HTML

<div id="lockSticky"></div>
<div id="lockDiv">fooo</div>

THE jQUERY

<script type="text/javascript">
    function sticky_relocate() {
        var window_top = $(window).scrollTop();
        var div_top = $('#lockSticky').offset().top;
        if (window_top > div_top)
            $('#lockDiv').addClass('stick')
        else
            $('#lockDiv').removeClass('stick');
    }
    $(function() {
        $(window).scroll(sticky_relocate);
        sticky_relocate();
    });
</script>

Finally we want to determine if the ipod touch in landscape or portrait mode to display accordingly

<script type="text/javascript">
    if (navigator.userAgent.match(/like Mac OS X/i)) {
        window.onscroll = function() {

        if (window.innerWidth > window.innerHeight) {
            //alert("landscape [ ]");
            document.getElementById('lockDiv').style.top =
            (window.pageYOffset + window.innerHeight - 268) + 'px';
        }

        if (window.innerHeight > window.innerWidth) {
            //alert("portrait ||");
            document.getElementById('lockDiv').style.top =
            (window.pageYOffset + window.innerHeight - 418) + 'px';
        }
        };
    }
</script>

How to check if an element of a list is a list (in Python)?

Probably, more intuitive way would be like this

if type(e) is list:
    print('Found a list element inside the list') 

What's the best way to limit text length of EditText in Android

it simple way in xml:

android:maxLength="@{length}"

for setting it programmatically you can use the following function

public static void setMaxLengthOfEditText(EditText editText, int length) {
    InputFilter[] filters = editText.getFilters();
    List arrayList = new ArrayList();
    int i2 = 0;
    if (filters != null && filters.length > 0) {
        int filtersSize = filters.length;
        int i3 = 0;
        while (i2 < filtersSize) {
            Object obj = filters[i2];
            if (obj instanceof LengthFilter) {
                arrayList.add(new LengthFilter(length));
                i3 = 1;
            } else {
                arrayList.add(obj);
            }
            i2++;
        }
        i2 = i3;
    }
    if (i2 == 0) {
        arrayList.add(new LengthFilter(length));
    }
    if (!arrayList.isEmpty()) {
        editText.setFilters((InputFilter[]) arrayList.toArray(new InputFilter[arrayList.size()]));
    }
}

An example of how to use getopts in bash

POSIX 7 example

It is also worth checking the example from the standard: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html

aflag=
bflag=
while getopts ab: name
do
    case $name in
    a)    aflag=1;;
    b)    bflag=1
          bval="$OPTARG";;
    ?)   printf "Usage: %s: [-a] [-b value] args\n" $0
          exit 2;;
    esac
done
if [ ! -z "$aflag" ]; then
    printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
    printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"

And then we can try it out:

$ sh a.sh
Remaining arguments are: 
$ sh a.sh -a
Option -a specified
Remaining arguments are: 
$ sh a.sh -b
No arg for -b option
Usage: a.sh: [-a] [-b value] args
$ sh a.sh -b myval
Option -b "myval" specified
Remaining arguments are: 
$ sh a.sh -a -b myval
Option -a specified
Option -b "myval" specified
Remaining arguments are: 
$ sh a.sh remain
Remaining arguments are: remain
$ sh a.sh -- -a remain
Remaining arguments are: -a remain

Tested in Ubuntu 17.10, sh is dash 0.5.8.

Web scraping with Python

I would strongly suggest checking out pyquery. It uses jquery-like (aka css-like) syntax which makes things really easy for those coming from that background.

For your case, it would be something like:

from pyquery import *

html = PyQuery(url='http://www.example.com/')
trs = html('table.spad tbody tr')

for tr in trs:
  tds = tr.getchildren()
  print tds[1].text, tds[2].text

Output:

5:16 AM 9:28 PM
5:15 AM 9:30 PM
5:13 AM 9:31 PM
5:12 AM 9:33 PM
5:11 AM 9:34 PM
5:10 AM 9:35 PM
5:09 AM 9:37 PM

Difference in months between two dates

Here's how we approach this:

public static int MonthDiff(DateTime date1, DateTime date2)
{
    if (date1.Month < date2.Month)
    {
        return (date2.Year - date1.Year) * 12 + date2.Month - date1.Month;
    }
    else
    {
        return (date2.Year - date1.Year - 1) * 12 + date2.Month - date1.Month + 12;
    }
}

How to create an email form that can send email using html

You can't, the only things you can do with html is open your default email application. You must use a server code to send an email, php, asp .net....

'const int' vs. 'int const' as function parameters in C++ and C

There is no difference. They both declare "a" to be an integer that cannot be changed.

The place where differences start to appear is when you use pointers.

Both of these:

const int *a
int const *a

declare "a" to be a pointer to an integer that doesn't change. "a" can be assigned to, but "*a" cannot.

int * const a

declares "a" to be a constant pointer to an integer. "*a" can be assigned to, but "a" cannot.

const int * const a

declares "a" to be a constant pointer to a constant integer. Neither "a" nor "*a" can be assigned to.

static int one = 1;

int testfunc3 (const int *a)
{
  *a = 1; /* Error */
  a = &one;
  return *a;
}

int testfunc4 (int * const a)
{
  *a = 1;
  a = &one; /* Error */
  return *a;
}

int testfunc5 (const int * const a)
{
  *a = 1;   /* Error */
  a = &one; /* Error */
  return *a;
}

Why does background-color have no effect on this DIV?

Floats don't have a height so the containing div has a height of zero.

<div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

overflow:hidden clears the float for most browsers.

zoom:1 clears the float for IE.

Search and replace in bash using regular expressions

If you are making repeated calls and are concerned with performance, This test reveals the BASH method is ~15x faster than forking to sed and likely any other external process.

hello=123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X123456789X

P1=$(date +%s)

for i in {1..10000}
do
   echo $hello | sed s/X//g > /dev/null
done

P2=$(date +%s)
echo $[$P2-$P1]

for i in {1..10000}
do
   echo ${hello//X/} > /dev/null
done

P3=$(date +%s)
echo $[$P3-$P2]

Removing special characters VBA Excel

This is what I use, based on this link

Function StripAccentb(RA As Range)

Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
'Const AccChars = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
'Const RegChars = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
S = RA.Cells.Text
For i = 1 To Len(AccChars)
A = Mid(AccChars, i, 1)
B = Mid(RegChars, i, 1)
S = Replace(S, A, B)
'Debug.Print (S)
Next


StripAccentb = S

Exit Function
End Function

Usage:

=StripAccentb(B2) ' cell address

Sub version for all cells in a sheet:

Sub replacesub()
Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
Range("A1").Resize(Cells.Find(what:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row, _
Cells.Find(what:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column).Select '
For Each cell In Selection
If cell <> "" Then
S = cell.Text
    For i = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    S = replace(S, A, B)
    Next
cell.Value = S
Debug.Print "celltext "; (cell.Text)
End If
Next cell
End Sub

ORA-12560: TNS:protocol adaptor error

It really has worked on my machine. But instead of OracleServiceORCL I found OracleServiceXE.

How do you get the current text contents of a QComboBox?

Getting the Text of ComboBox when the item is changed

     self.ui.comboBox.activated.connect(self.pass_Net_Adap)

  def pass_Net_Adap(self):
      print str(self.ui.comboBox.currentText())

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.

df['date'] = df['date'].astype('datetime64[ns]')

or use datetime64[D] if you want Day precision and not nanoseconds

print(type(df_launath['date'].iloc[0]))

yields

<class 'pandas._libs.tslib.Timestamp'> the same as when you use pandas.to_datetime

You can try it with other formats then '%Y-%m-%d' but at least this works.

jQuery textbox change event doesn't fire until textbox loses focus?

On modern browsers, you can use the input event:

DEMO

$("#textbox").on('input',function() {alert("Change detected!");});

Tomcat 7 is not running on browser(http://localhost:8080/ )

I had the same issue and for me, I tried changing the options in

  • Server Locations

    and it worked.

    1. Double click on the Tomcat Server under the Servers tab in Eclipse
    2. Doing that opens a window in the editor with the top heading being Overview opens (there are 2 tabs-Overview and Modules).
    3. In that change the options under Server Locations, and give Ctrl+S (Save configurations) For me, Use Tomcat installation (takes control of Tomcat installation) worked
    4. Try starting the server and checking if localhost opens in the browser. Else select a different option.

I do not understand why that issue came up. I did search but did not find a relevant answer(Maybe I didn't use the right keywords). If someone knows why that worked, kindly share.

Thanks.

How to display activity indicator in middle of the iphone screen?

Swift 4, Autolayout version

func showActivityIndicator(on parentView: UIView) {
    let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    activityIndicator.startAnimating()
    activityIndicator.translatesAutoresizingMaskIntoConstraints = false

    parentView.addSubview(activityIndicator)

    NSLayoutConstraint.activate([
        activityIndicator.centerXAnchor.constraint(equalTo: parentView.centerXAnchor),
        activityIndicator.centerYAnchor.constraint(equalTo: parentView.centerYAnchor),
    ])
}

Using SSH keys inside docker container

You can use multi stage build to build containers This is the approach you can take :-

Stage 1 building an image with ssh

FROM ubuntu as sshImage
LABEL stage=sshImage
ARG SSH_PRIVATE_KEY
WORKDIR /root/temp

RUN apt-get update && \
    apt-get install -y git npm 

RUN mkdir /root/.ssh/ &&\
    echo "${SSH_PRIVATE_KEY}" > /root/.ssh/id_rsa &&\
    chmod 600 /root/.ssh/id_rsa &&\
    touch /root/.ssh/known_hosts &&\
    ssh-keyscan github.com >> /root/.ssh/known_hosts

COPY package*.json ./

RUN npm install

RUN cp -R node_modules prod_node_modules

Stage 2: build your container

FROM node:10-alpine

RUN mkdir -p /usr/app

WORKDIR /usr/app

COPY ./ ./

COPY --from=sshImage /root/temp/prod_node_modules ./node_modules

EXPOSE 3006

CMD ["npm", "run", "dev"] 

add env attribute in your compose file:

   environment:
      - SSH_PRIVATE_KEY=${SSH_PRIVATE_KEY}

then pass args from build script like this:

docker-compose build --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/id_rsa)"

And remove the intermediate container it for security. This Will help you cheers.

How do you run CMD.exe under the Local System Account?

Found an answer here which seems to solve the problem by adding /k start to the binPath parameter. So that would give you:

sc create testsvc binpath= "cmd /K start" type= own type= interact

However, Ben said that didn't work for him and when I tried it on Windows Server 2008 it did create the cmd.exe process under local system, but it wasn't interactive (I couldn't see the window).

I don't think there is an easy way to do what you ask, but I'm wondering why you're doing it at all? Are you just trying to see what is happening when you run your service? Seems like you could just use logging to determine what is happening instead of having to run the exe as local system...

Find kth smallest element in a binary search tree in Optimum way

A simpler solution would be to do an inorder traversal and keep track of the element currently to be printed (without printing it). When we reach k, print the element and skip rest of tree traversal.

void findK(Node* p, int* k) {
  if(!p || k < 0) return;
  findK(p->left, k);
  --k;
  if(k == 0) { 
    print p->data;
    return;  
  } 
  findK(p->right, k); 
}

Spring Boot: Cannot access REST Controller on localhost (404)

For me, the problem was that I had set up the Application in a way that it always immediately shut down after starting. So by the time I tried out if I could access the controller, the Application wasn't running anymore. The problem with immediately shutting down is adressed in this thread.

TypeError: Cannot read property 'then' of undefined

You need to return your promise to the calling function.

islogged:function(){
    var cUid=sessionService.get('uid');
    alert("in loginServce, cuid is "+cUid);
    var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
    $checkSessionServer.then(function(){
        alert("session check returned!");
        console.log("checkSessionServer is "+$checkSessionServer);
    });
    return $checkSessionServer; // <-- return your promise to the calling function
}

Django: List field in model?

If you're on Django 1.10 or newer AND Postgres as your database, you can use ArrayField. It's better to use than django-taggit or other alternatives, as it's native to the Django framework. https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#arrayfield

from django.db import models
from django.contrib.postgres.fields import ArrayField

class ChessBoard(models.Model):
    board = ArrayField(
        ArrayField(
            models.CharField(max_length=10, blank=True),
            size=8,
        ),
        size=8,
    )

If you're on Django 3.1 or newer they've added support for JSONField with most database backends (MariaDB 10.2.7+, MySQL 5.7.8+, Oracle, PostgreSQL, and SQLite 3.9.0+). You can use this to store your Array!

https://docs.djangoproject.com/en/3.1/ref/models/fields/#jsonfield

from django.db import models

class ChessBoard(models.Model):
    list_of_pieces = models.JSONField()

Exit/save edit to sudoers file? Putty SSH

#UBUNTU20

if you are opening this file as root, then type

root# visudo

the file will be opened, go to the line where you want to add/modifiy anything simply without any insert or i button pressed.

press ctrl + O
press ctrl + x
press enter

How do I remove a comma off the end of a string?

Precede that with:

if(substr($string, -1)==",")

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

How to run single test method with phpunit?

Here's the more generic answer:

If you are sure the method name is unique you can only filter by method name (this works for me)

phpunit --filter {TestMethodName}

However it is safer to specify the file path/reference as well

phpunit --filter {TestMethodName} {FilePath}

Example:

phpunit --filter testSaveAndDrop reference/to/escalation/EscalationGroupTest.php

Quick note: I've noticed that if I have a function named testSave and another function named testSaveAndDrop using command phpunit --filter testSave will also run testSaveAndDrop and any other function that starts with testSave*, it's weird!!

How to use goto statement correctly

The Java keyword list specifies the goto keyword, but it is marked as "not used".

This was probably done in case it were to be added to a later version of Java.

If goto weren't on the list, and it were added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etcetera) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.

Linux find file names with given string recursively

Use the find command,

find . -type f -name "*John*"

How to disable text selection using jQuery?

I've tried all the approaches, and this one is the simplest for me because I'm using IWebBrowser2 and don't have 10 browsers to contend with:

document.onselectstart = new Function('return false;');

Works perfectly for me!

How to get rid of blank pages in PDF exported from SSRS

I've successfully used pdftk to remove pages I didn't want/need in pdfs. You can download the program here

You might try something like the following. Taken from here under examples

Remove 'page 13' from in1.pdf to create out1.pdf pdftk in.pdf cat 1-12 14-end output out1.pdf

or:

pdftk A=in1.pdf cat A1-12 A14-end output out1.pdf

Get the time difference between two datetimes

This will work for any date in the format YYYY-MM-DD HH:mm:ss

const moment=require("moment");
let startDate=moment("2020-09-16 08:39:27");
const endDate=moment();


const duration=moment.duration(endDate.diff(startDate))
console.log(duration.asSeconds());
 console.log(duration.asHours());

What exactly does the "u" do? "git push -u origin master" vs "git push origin master"

git push -u origin master

… is the same as:

git push origin master ; git branch --set-upstream master origin/master

Do the last statement, if you forget the -u!

Or you could force it:

git config branch.master.remote origin
git config branch.master.merge refs/heads/master

If you let the command do it for you, it will pick your mistakes like if you typed a non-existent branch or you didn't git remote add; though that might be what you want. :)

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Python: most idiomatic way to convert None to empty string?

return s or '' will work just fine for your stated problem!

Write a file in UTF-8 using FileWriter (Java)?

In my opinion

If you wanna write follow kind UTF-8.You should create a byte array.Then,you can do such as the following: byte[] by=("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+"Your string".getBytes();

Then, you can write each byte into file you created. Example:

OutputStream f=new FileOutputStream(xmlfile);
    byte[] by=("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+"Your string".getBytes();
    for (int i=0;i<by.length;i++){
    byte b=by[i];
    f.write(b);

    }
    f.close();

Upload Image using POST form data in Python-requests

For Rest API to upload images from host to host:

import urllib2
import requests

api_host = 'https://host.url.com/upload/'
headers = {'Content-Type' : 'image/jpeg'}
image_url = 'http://image.url.com/sample.jpeg'

img_file = urllib2.urlopen(image_url)

response = requests.post(api_host, data=img_file.read(), headers=headers, verify=False)

You can use option verify set to False to omit SSL verification for HTTPS requests.

'do...while' vs. 'while'

This is sort of an indirect answer, but this question got me thinking about the logic behind it, and I thought this might be worth sharing.

As everyone else has said, you use a do ... while loop when you want to execute the body at least once. But under what circumstances would you want to do that?

Well, the most obvious class of situations I can think of would be when the initial ("unprimed") value of the check condition is the same as when you want to exit. This means that you need to execute the loop body once to prime the condition to a non-exiting value, and then perform the actual repetition based on that condition. What with programmers being so lazy, someone decided to wrap this up in a control structure.

So for example, reading characters from a serial port with a timeout might take the form (in Python):

response_buffer = []
char_read = port.read(1)

while char_read:
    response_buffer.append(char_read)
    char_read = port.read(1)

# When there's nothing to read after 1s, there is no more data

response = ''.join(response_buffer)

Note the duplication of code: char_read = port.read(1). If Python had a do ... while loop, I might have used:

do:
    char_read = port.read(1)
    response_buffer.append(char_read)
while char_read

The added benefit for languages that create a new scope for loops: char_read does not pollute the function namespace. But note also that there is a better way to do this, and that is by using Python's None value:

response_buffer = []
char_read = None

while char_read != '':
    char_read = port.read(1)
    response_buffer.append(char_read)

response = ''.join(response_buffer)

So here's the crux of my point: in languages with nullable types, the situation initial_value == exit_value arises far less frequently, and that may be why you do not encounter it. I'm not saying it never happens, because there are still times when a function will return None to signify a valid condition. But in my hurried and briefly-considered opinion, this would happen a lot more if the languages you used did not allow for a value that signifies: this variable has not been initialised yet.

This is not perfect reasoning: in reality, now that null-values are common, they simply form one more element of the set of valid values a variable can take. But practically, programmers have a way to distinguish between a variable being in sensible state, which may include the loop exit state, and it being in an uninitialised state.

Border Height on CSS

table td {
    border-right:1px solid #000;
    height: 100%;
}

Just you add height under the border property.

C++ printing boolean, what is displayed?

The standard streams have a boolalpha flag that determines what gets displayed -- when it's false, they'll display as 0 and 1. When it's true, they'll display as false and true.

There's also an std::boolalpha manipulator to set the flag, so this:

#include <iostream>
#include <iomanip>

int main() {
    std::cout<<false<<"\n";
    std::cout << std::boolalpha;   
    std::cout<<false<<"\n";
    return 0;
}

...produces output like:

0
false

For what it's worth, the actual word produced when boolalpha is set to true is localized--that is, <locale> has a num_put category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true and false as they're represented in that locale. For example,

#include <iostream>
#include <iomanip>
#include <locale>

int main() {
    std::cout.imbue(std::locale("fr"));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux instead of false. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false for every language I've checked.

The names that get used are defined in a numpunct facet though, so if you really want them to print out correctly for particular language, you can create a numpunct facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:

#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>

class my_fr : public std::numpunct< char > {
protected:
    char do_decimal_point() const { return ','; }
    char do_thousands_sep() const { return '.'; }
    std::string do_grouping() const { return "\3"; }
    std::string do_truename() const { return "vrai";  }
    std::string do_falsename() const { return "faux"; }
};

int main() {
    std::cout.imbue(std::locale(std::locale(), new my_fr));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

And the result is (as you'd probably expect):

0
faux

MySQL duplicate entry error even though there is no duplicate entry

I had a similar issue, but in my case it turned out that I used case insensitive collation - utf8_general_ci.

Thus, when I tried to insert two strings which were different in a case-sensitive comparison, but the same in the case-insensitive one, MySQL fired the error and I couldn't understand what a problem, because I used a case-sensitive search.

The solution is to change the collation of a table, e.g. I used utf8_bin which is case-sensitive (or utf8_general_cs should be appropriate one too).

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

While this question has been answered already (it's a bug that causes bottomLeftRadius and bottomRightRadius to be reversed), the bug has been fixed in android 3.1 (api level 12 - tested on the emulator).

So to make sure your drawables look correct on all platforms, you should put "corrected" versions of the drawables (i.e. where bottom left/right radii are actually correct in the xml) in the res/drawable-v12 folder of your app. This way all devices using an android version >= 12 will use the correct drawable files, while devices using older versions of android will use the "workaround" drawables that are located in the res/drawables folder.

MongoDB Aggregation: How to get total records count?

//const total_count = await User.find(query).countDocuments();
//const users = await User.find(query).skip(+offset).limit(+limit).sort({[sort]: order}).select('-password');
const result = await User.aggregate([
  {$match : query},
  {$sort: {[sort]:order}},
  {$project: {password: 0, avatarData: 0, tokens: 0}},
  {$facet:{
      users: [{ $skip: +offset }, { $limit: +limit}],
      totalCount: [
        {
          $count: 'count'
        }
      ]
    }}
  ]);
console.log(JSON.stringify(result));
console.log(result[0]);
return res.status(200).json({users: result[0].users, total_count: result[0].totalCount[0].count});

AVD Manager - No system image installed for this target

Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.

Ajax success event not working

in my case the error was this was in the server side and for that reason it was returning a html

wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

Managing SSH keys within Jenkins for Git

It looks like the github.com host which jenkins tries to connect to is not listed under the Jenkins user's $HOME/.ssh/known_hosts. Jenkins runs on most distros as the user jenkins and hence has its own .ssh directory to store the list of public keys and known_hosts.

The easiest solution I can think of to fix this problem is:

# Login as the jenkins user and specify shell explicity,
# since the default shell is /bin/false for most
# jenkins installations.
sudo su jenkins -s /bin/bash

cd SOME_TMP_DIR
# git clone YOUR_GITHUB_URL

# Allow adding the SSH host key to your known_hosts

# Exit from su
exit

why are there two different kinds of for loops in java?

The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state incrementing/decrementing counter (There are exceptions, but this is the classic)

For that,

for (int i=0;i<myString.length;i++) { 
  System.out.println(myString[i]); 
}

is correct.

For Java 5 an alternative was proposed. Any thing that implements iterable can be supported. This is particularly nice in Collections. For example you can iterate the list like this

List<String> list = ....load up with stuff

for (String string : list) {
  System.out.println(string);
}

instead of

for (int i=0; i<list.size();i++) {
  System.out.println(list.get(i));
}

So it's just an alternative notation really. Any item that implements Iterable (i.e. can return an iterator) can be written that way.

What's happening behind the scenes is somethig like this: (more efficient, but I'm writing it explicitly)

Iterator<String> it = list.iterator();
while (it.hasNext()) {
  String string=it.next();
  System.out.println(string);
}

In the end it's just syntactic sugar, but rather convenient.

How to use a jQuery plugin inside Vue

Step 1 We place ourselves with the terminal in the folder of our project and install JQuery through npm or yarn.

npm install jquery --save

Step 2 Within our file where we want to use JQuery, for example app.js (resources/js/app.js), in the script section we include the following code.

// We import JQuery
const $ = require('jquery');
// We declare it globally
window.$ = $;

// You can use it now
$('body').css('background-color', 'orange');

// Here you can add the code for different plugins

Difference between rake db:migrate db:reset and db:schema:load

You could simply look in the Active Record Rake tasks as that is where I believe they live as in this file. https://github.com/rails/rails/blob/fe1f4b2ad56f010a4e9b93d547d63a15953d9dc2/activerecord/lib/active_record/tasks/database_tasks.rb

What they do is your question right?

That depends on where they come from and this is just and example to show that they vary depending upon the task. Here we have a different file full of tasks.

https://github.com/rails/rails/blob/fe1f4b2ad56f010a4e9b93d547d63a15953d9dc2/activerecord/Rakefile

which has these tasks.

namespace :db do
  task create: ["db:mysql:build", "db:postgresql:build"]
  task drop: ["db:mysql:drop", "db:postgresql:drop"]
end

This may not answer your question but could give you some insight into go ahead and look the source over especially the rake files and tasks. As they do a pretty good job of helping you use rails they don't always document the code that well. We could all help there if we know what it is supposed to do.

numpy matrix vector multiplication

Simplest solution

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

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

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


Other Solutions

Also know there are other options:

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

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

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

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

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

Rarer options for edge cases

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

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

Authentication versus Authorization

Authentication is the process of verifying your log in username and password.

Authorization is the process of verifying that you can access to something.

Init method in Spring Controller (annotation version)

Alternatively you can have your class implement the InitializingBean interface to provide a callback function (afterPropertiesSet()) which the ApplicationContext will invoke when the bean is constructed.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

protected $primaryKey = 'SongID';

After adding to my model to tell the primary key because it was taking id(SongID) by default

How to check if a process is running via a batch script

Here's how I've worked it out:

tasklist /FI "IMAGENAME eq notepad.exe" /FO CSV > search.log

FOR /F %%A IN (search.log) DO IF %%~zA EQU 0 GOTO end

start notepad.exe

:end

del search.log

The above will open Notepad if it is not already running.

Edit: Note that this won't find applications hidden from the tasklist. This will include any scheduled tasks running as a different user, as these are automatically hidden.

Self-reference for cell, column and row in worksheet functions

where F13 is the cell you need to reference:

=CELL("Row",F13)  yields 13; its row number

=CELL("Col",F13)  yields 6; its column number;  

=SUBSTITUTE(ADDRESS(1,COLUMN(F13)*1,4),"1","") yields F; its column letter

Why are arrays of references illegal?

Because like many have said here, references are not objects. they are simply aliases. True some compilers might implement them as pointers, but the standard does not force/specify that. And because references are not objects, you cannot point to them. Storing elements in an array means there is some kind of index address (i.e., pointing to elements at a certain index); and that is why you cannot have arrays of references, because you cannot point to them.

Use boost::reference_wrapper, or boost::tuple instead; or just pointers.

Maximize a window programmatically and prevent the user from changing the windows state

When your form is maximized, set its minimum size = max size, so user cannot resize it.

    this.WindowState = FormWindowState.Maximized;
    this.MinimumSize = this.Size;
    this.MaximumSize = this.Size;

When does a cookie with expiration time 'At end of session' expire?

When you use setcookie, you can either set the expiration time to 0 or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).

How to change status bar color to match app in Lollipop? [Android]

Also if you want different status-bar color for different activity (fragments) you can do it with following steps (work on API 21 and above):

First create values21/style.xml and put following code:

 <style name="AIO" parent="AIOBase">
            <item name="android:windowDrawsSystemBarBackgrounds">true</item>
            <item name="android:windowContentTransitions">true</item>
    </style>

Then define White|Dark themes in your values/style.xml like following:

 <style name="AIOBase" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/color_primary</item>
        <item name="colorPrimaryDark">@color/color_primary_dark</item>
        <item name="colorAccent">@color/color_accent</item>
        <item name="android:textColorPrimary">@android:color/black</item>
        <item name="android:statusBarColor" tools:targetApi="lollipop">@color/color_primary_dark
        </item>
        <item name="android:textColor">@color/gray_darkest</item>
        <item name="android:windowBackground">@color/default_bg</item>
        <item name="android:colorBackground">@color/default_bg</item>
    </style>


    <style name="AIO" parent="AIOBase" />

    <style name="AIO.Dark" parent="AIOBase">
        <item name="android:statusBarColor" tools:targetApi="lollipop">#171717
        </item>
    </style>

    <style name="AIO.White" parent="AIOBase">
        <item name="android:statusBarColor" tools:targetApi="lollipop">#bdbdbd
        </item>
    </style>

Also don't forget to apply themes in your manifest.xml.

UITextField border color

Here's a Swift implementation. You can make an extension so that it will be usable by other views if you like.

extension UIView {
    func addBorderAndColor(color: UIColor, width: CGFloat, corner_radius: CGFloat = 0, clipsToBounds: Bool = false) {
        self.layer.borderWidth  = width
        self.layer.borderColor  = color.cgColor
        self.layer.cornerRadius = corner_radius
        self.clipsToBounds      = clipsToBounds
    }
}

Call this like: email.addBorderAndColor(color: UIColor.white, width: 0.5, corner_radius: 5, clipsToBounds: true).

How to select multiple rows filled with constants?

SELECT * 
FROM DUAL 
CONNECT BY ROWNUM <= 9;

Converting java.sql.Date to java.util.Date

The class java.sql.Date is designed to carry only a date without time, so the conversion result you see is correct for this type. You need to use a java.sql.Timestamp to get a full date with time.

java.util.Date newDate = result.getTimestamp("VALUEDATE");

How to generate a random number in C++?

#include <iostream>
#include <cstdlib>
#include <ctime>

int main() {
    srand(time(NULL));
    int random_number = std::rand(); // rand() return a number between ?0? and RAND_MAX
    std::cout << random_number;
    return 0;
}

http://en.cppreference.com/w/cpp/numeric/random/rand

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

gcloud command not found - while installing Google Cloud SDK

When installing the SDK I used this method:

curl https://sdk.cloud.google.com | bash

When using this method from the original author make sure you have accepted the security preferences in your mac settings to allow apps downloaded from app store and identified developers.

React component initialize state from props

you could use key value to reset state when need, pass props to state it's not a good practice , because you have uncontrolled and controlled component in one place. Data should be in one place handled read this https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

HTML / CSS Popup div on text click

You can simply use jQuery UI Dialog

Example:

_x000D_
_x000D_
$(function() {_x000D_
  $("#dialog").dialog();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8" />_x000D_
  <title>jQuery UI Dialog - Default functionality</title>_x000D_
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />_x000D_
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>_x000D_
  <link rel="stylesheet" href="/resources/demos/style.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="dialog" title="Basic dialog">_x000D_
    <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

MySQL root access from all hosts

Update the bind-address = 0.0.0.0 in the /etc/mysql/mysql.conf.d/mysqld.cnf and from the mysql command line allow the root user to connect from any Ip.

Below was the only commands worked for mysql-8.0 as other were failing with error syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY 'abcd'' at line 1

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
UPDATE mysql.user SET host='%' WHERE user='root';

Restart the mysql client

sudo service mysql restart

Initialize 2D array

You can follow what paxdiablo(on Dec '12) suggested for an automated, more versatile approach:

for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
    table[row][col] = (char) ('1' + row * 3 + col);

In terms of efficiency, it depends on the scale of your implementation. If it is to simply initialize a 2D array to values 0-9, it would be much easier to just define, declare and initialize within the same statement like this: private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

Or if you're planning to expand the algorithm, the previous code would prove more, efficient.

Apache: Restrict access to specific source IP inside virtual host

For Apache 2.4, you would use the Require IP directive. So to only allow machines from the 192.168.0.0/24 network (range 192.168.0.0 - 192.168.0.255)

<VirtualHost *:80>
    <Location />
      Require ip 192.168.0.0/24
    </Location>
    ...
</VirtualHost>

And if you just want the localhost machine to have access, then there's a special Require local directive.

The local provider allows access to the server if any of the following conditions is true:

  • the client address matches 127.0.0.0/8
  • the client address is ::1
  • both the client and the server address of the connection are the same

This allows a convenient way to match connections that originate from the local host:

<VirtualHost *:80>
    <Location />
      Require local
    </Location>
    ...
</VirtualHost>

Java JTable getting the data of the selected row

http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html

You will find these methods in it:

getValueAt(int row, int column)
getSelectedRow()
getSelectedColumn()

Use a mix of these to achieve your result.

How to change the Eclipse default workspace?

File > Switch workspace > add the workspace you like > Eclipse will restart using the workspace you wanted.

Get Time from Getdate()

You can use the datapart to maintain time date type and you can compare it to another time.
Check below example:

declare @fromtime time = '09:30'
declare @totime time
SET @totime=CONVERT(TIME, CONCAT(DATEPART(HOUR, GETDATE()),':', DATEPART(MINUTE, GETDATE())))
if @fromtime <= @totime 
begin print 'true' end
else begin print 'no' end

Set background color in PHP?

<?php
    header('Content-Type: text/css');
?>

some selector {
    background-color: <?php echo $my_colour_that_has_been_checked_to_be_a_safe_value; ?>;
}

phpinfo() - is there an easy way for seeing it?

From the CLI:

php -r 'phpinfo();'

How to set RelativeLayout layout params in code not in xml?

I hope the below code will help. It will create an EditText and a Log In button. Both placed relatively. All done in MainActivity.java.

package com.example.atul.allison;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.graphics.Color;
import android.widget.EditText;
import android.content.res.Resources;
import android.util.TypedValue;     
    public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //Layout
            RelativeLayout atulsLayout = new RelativeLayout(this);
            atulsLayout.setBackgroundColor(Color.GREEN);

            //Button
            Button redButton = new Button(this);
            redButton.setText("Log In");
            redButton.setBackgroundColor(Color.RED);

            //Username input
            EditText username =  new EditText(this);

            redButton.setId(1);
            username.setId(2);

            RelativeLayout.LayoutParams buttonDetails= new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
            );

            RelativeLayout.LayoutParams usernameDetails= new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
            );

            //give rules to position widgets
            usernameDetails.addRule(RelativeLayout.ABOVE,redButton.getId());
            usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
            usernameDetails.setMargins(0,0,0,50);

            buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
            buttonDetails.addRule(RelativeLayout.CENTER_VERTICAL);

            Resources r = getResources();
            int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200,r.getDisplayMetrics());
            username.setWidth(px);

            //Add widget to layout(button is now a child of layout)
            atulsLayout.addView(redButton,buttonDetails);
            atulsLayout.addView(username,usernameDetails);

            //Set these activities content/display to this view
            setContentView(atulsLayout);
        }
    }

Get button click inside UITableViewCell

Swift 2.2

You need to add target for that button.

myButton.addTarget(self, action: #selector(ClassName.FunctionName(_:), forControlEvents: .TouchUpInside)

FunctionName: connected // for example

And of course you need to set tag of that button since you are using it.

myButton.tag = indexPath.row

You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.

To get the tag in the connected function:

func connected(sender: UIButton) {
    let buttonTag = sender.tag
    // Do any additional setup
}

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

only with this:

const a = true; const b = false;

console.log(+a);//1 console.log(+b);//0

How to add 20 minutes to a current date?

you have a lot of answers in the post

var d1 = new Date (),
d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 20 );
alert ( d2 );

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

You need the Apache Commons Codec library 1.4 or above in your classpath. This library contains Base64 implementation.

Generating random integer from a range

The following expression should be unbiased if I am not mistaken:

std::floor( ( max - min + 1.0 ) * rand() ) + min;

I am assuming here that rand() gives you a random value in the range between 0.0 and 1.0 NOT including 1.0 and that max and min are integers with the condition that min < max.

How to apply filters to *ngFor?

pipes in Angular2 are similar to pipes on the command line. The output of each preceding value is fed into the filter after the pipe which makes it easy to chain filters as well like this:

<template *ngFor="#item of itemsList">
    <div *ngIf="conditon(item)">{item | filter1 | filter2}</div>
</template>

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

MySQL: View with Subquery in the FROM Clause Limitation

You can work around this by creating a separate VIEW for any subquery you want to use and then join to that in the VIEW you're creating. Here's an example: http://blog.gruffdavies.com/2015/01/25/a-neat-mysql-hack-to-create-a-view-with-subquery-in-the-from-clause/

This is quite handy as you'll very likely want to reuse it anyway and helps you keep your SQL DRY.

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

how to update the multiple rows at a time using linq to sql?

Do not use the ToList() method as in the accepted answer !

Running SQL profiler, I verified and found that ToList() function gets all the records from the database. It is really bad performance !!

I would have run this query by pure sql command as follows:

string query = "Update YourTable Set ... Where ...";    
context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));

This would operate the update in one-shot without selecting even one row.

Python function as a function argument?

def x(a):
    print(a)
    return a

def y(func_to_run, a):
    return func_to_run(a)

y(x, 1)

That I think would be a more proper sample. Now what I wonder is if there is a way to code the function to use within the argument submission to another function. I believe there is in C++, but in Python I am not sure.

Why is there no tuple comprehension in Python?

Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments.

Once a Tuple is created, it can not be appended to, extended, or assigned to. The only way to modify a Tuple is if one of its objects can itself be assigned to (is a non-tuple container). Because the Tuple is only holding a reference to that kind of object.

Also - a tuple has its own constructor tuple() which you can give any iterator. Which means that to create a tuple, you could do:

tuple(i for i in (1,2,3))

How do I get rid of an element's offset using CSS?

If you're using the IE developer tools, make sure you haven't accidentally left them at an older setting. I was making myself crazy with this same issue until I saw that it was set to Internet Explorer 7 Standards. Changed it to Internet Explorer 9 Standards and everything snapped right into place.

Left Join without duplicate rows from left table

You can do this using generic SQL with group by:

SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
     tbl_Media M
     ON M.Content_Id = C.Content_Id 
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;

Or with a correlated subquery:

SELECT C.Content_ID, C.Contt_Title,
       (SELECT M.Media_Id
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
        ORDER BY M.MEDIA_ID DESC
        LIMIT 1
       ) as Media_Id
FROM tbl_Contents C 
ORDER BY C.Content_DatePublished ASC;

Of course, the syntax for limit 1 varies between databases. Could be top. Or rownum = 1. Or fetch first 1 rows. Or something like that.

SQL Logic Operator Precedence: And and Or

  1. Arithmetic operators
  2. Concatenation operator
  3. Comparison conditions
  4. IS [NOT] NULL, LIKE, [NOT] IN
  5. [NOT] BETWEEN
  6. Not equal to
  7. NOT logical condition
  8. AND logical condition
  9. OR logical condition

You can use parentheses to override rules of precedence.

Changing the cursor in WPF sometimes works, sometimes doesn't

You can use a data trigger (with a view model) on the button to enable a wait cursor.

<Button x:Name="NextButton"
        Content="Go"
        Command="{Binding GoCommand }">
    <Button.Style>
         <Style TargetType="{x:Type Button}">
             <Setter Property="Cursor" Value="Arrow"/>
             <Style.Triggers>
                 <DataTrigger Binding="{Binding Path=IsWorking}" Value="True">
                     <Setter Property="Cursor" Value="Wait"/>
                 </DataTrigger>
             </Style.Triggers>
         </Style>
    </Button.Style>
</Button>

Here is the code from the view-model:

public class MainViewModel : ViewModelBase
{
   // most code removed for this example

   public MainViewModel()
   {
      GoCommand = new DelegateCommand<object>(OnGoCommand, CanGoCommand);
   }

   // flag used by data binding trigger
   private bool _isWorking = false;
   public bool IsWorking
   {
      get { return _isWorking; }
      set
      {
         _isWorking = value;
         OnPropertyChanged("IsWorking");
      }
   }

   // button click event gets processed here
   public ICommand GoCommand { get; private set; }
   private void OnGoCommand(object obj)
   {
      if ( _selectedCustomer != null )
      {
         // wait cursor ON
         IsWorking = true;
         _ds = OrdersManager.LoadToDataSet(_selectedCustomer.ID);
         OnPropertyChanged("GridData");

         // wait cursor off
         IsWorking = false;
      }
   }
}

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

How to make an empty div take space

Slight update to @no1cobla answer. This hides the period. This solution works in IE8+.

.class:after
{
    content: '.';
    visibility: hidden;
}

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

looking at jQuery they in there jQuery.isArray(...) they do:

    isArray = Array.isArray || function( obj ) {
    return jQuery.type(obj) === "array";
}

this leads us to: jQuery.type:

    type = function( obj ) {
    return obj == null ?
        String( obj ) :
        class2type[ toString.call(obj) ] || "object";
}

and again we have to look in: class2type

class2type = {};

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
    class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

and in native JS:

var a, t = "Boolean Number String Function Array Date RegExp Object".split(" ");
for( a in t ) {
    class2type[ "[object " + t[a] + "]" ] = t[a].toLowerCase();
}

this ends up with:

var isArray = Array.isArray || function( obj ) {
    return toString.call(obj) === "[object Array]";
}

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

Copy every nth line from one sheet to another

Add new column and fill it with ascending numbers. Then filter by ([column] mod 7 = 0) or something like that (don't have Excel in front of me to actually try this);

If you can't filter by formula, add one more column and use the formula =MOD([column; 7]) in it then filter zeros and you'll get all seventh rows.

adb not finding my device / phone (MacOS X)

When I plugged the Android 10 device to the Mac OS a popup showed on the phone saying:

The Mac OS cannot access data on this device, you will have to download filetransfer or smart-switch.

  1. Download file transfer https://www.android.com/filetransfer/ for android
  2. Download smart-switch https://www.samsung.com/us/smart-switch/ for Samsung I guess

Though not sure why there are two options here!

I downloaded file transfer and it worked perfectly even though the device was Samsung Note.

Note: I forgot to mention that first you have to enable Developer mode then USB Debugging.

How to trigger a build only if changes happen on particular set of files

I wrote this script to skip or execute tests if there are changes:

#!/bin/bash

set -e -o pipefail -u

paths=()
while [ "$1" != "--" ]; do
    paths+=( "$1" ); shift
done
shift

if git diff --quiet --exit-code "${BASE_BRANCH:-origin/master}"..HEAD ${paths[@]}; then
    echo "No changes in ${paths[@]}, skipping $@..." 1>&2
    exit 0
fi
echo "Changes found in ${paths[@]}, running $@..." 1>&2

exec "$@"

So you can do something like:

./scripts/git-run-if-changed.sh cmd vendor go.mod go.sum fixtures/ tools/ -- go test

How are parameters sent in an HTTP POST request?

The default media type in a POST request is application/x-www-form-urlencoded. This is a format for encoding key-value pairs. The keys can be duplicate. Each key-value pair is separated by an & character, and each key is separated from its value by an = character.

For example:

Name: John Smith
Grade: 19

Is encoded as:

Name=John+Smith&Grade=19

This is placed in the request body after the HTTP headers.

How to set a variable inside a loop for /F

set list = a1-2019 a3-2018 a4-2017
setlocal enabledelayedexpansion
set backup=
set bb1=

for /d %%d in (%list%) do (
   set td=%%d
   set x=!td!
   set y=!td!
   set y=!y:~-4!
   if !y! gtr !bb1! (
     set bb1=!y!
     set backup=!x!
   )
)

rem: backup will be 2019
echo %backup% 

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

Add an extra attribute to that EditText programmatically and you are done:

password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

For numeric password (pin):

password.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

Also, make sure that the cursor is at the end of the text in the EditText because when you change the input type the cursor will be automatically set to the starting point. So I suggest using the following code:

et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
et_password.setSelection(et_password.getText().length());

When using Data Binding, you can make use of the following code:

<data>
        <import type="android.text.InputType"/>
.
.
.
<EditText
android:inputType='@{someViewModel.isMasked ? 
(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) :
InputType.TYPE_CLASS_TEXT }'

If using Kotlin:

password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD

Generating Unique Random Numbers in Java

With Java 8+ you can use the ints method of Random to get an IntStream of random values then distinct and limit to reduce the stream to a number of unique random values.

ThreadLocalRandom.current().ints(0, 100).distinct().limit(5).forEach(System.out::println);

Random also has methods which create LongStreams and DoubleStreams if you need those instead.

If you want all (or a large amount) of the numbers in a range in a random order it might be more efficient to add all of the numbers to a list, shuffle it, and take the first n because the above example is currently implemented by generating random numbers in the range requested and passing them through a set (similarly to Rob Kielty's answer), which may require generating many more than the amount passed to limit because the probability of a generating a new unique number decreases with each one found. Here's an example of the other way:

List<Integer> range = IntStream.range(0, 100).boxed()
        .collect(Collectors.toCollection(ArrayList::new));
Collections.shuffle(range);
range.subList(0, 99).forEach(System.out::println);

Concatenating strings in C, which method is more efficient?

  • strcpy and strcat are much simpler oprations compared to sprintf, which needs to parse the format string
  • strcpy and strcat are small so they will generally be inlined by the compilers, saving even one more extra function call overhead. For example, in llvm strcat will be inlined using a strlen to find copy starting position, followed by a simple store instruction

How to get the category title in a post in Wordpress?

Use get_the_category() like this:

<?php
foreach((get_the_category()) as $category) { 
    echo $category->cat_name . ' '; 
} 
?>

It returns a list because a post can have more than one category.

The documentation also explains how to do this from outside the loop.

How to change 1 char in the string?

While it does not answer the OP's question precisely, depending on what you're doing it might be a good solution. Below is going to solve my problem.

Let's say that you have to do a lot of individual manipulation of various characters in a string. Instead of using a string the whole time use a char[] array while you're doing the manipulation. Because you can do this:

 char[] array = "valta is the best place in the World".ToCharArray();

Then manipulate to your hearts content as much as you need...

 array[0] = "M";

Then convert it to a string once you're done and need to use it as a string:

string str = new string(array);

Why should I use an IDE?

It depends highly on what you're doing and what language you're doing it in. Personally, I tend to not use an IDE (or "my IDE consists of 3 xterms running vim, one running a database client, and one with a bash prompt or tailing logs", depending on how broadly you define "IDE") for most of my work, but, if I were to find myself developing a platform-native GUI, then I'd reach for a language-appropriate IDE in an instant - IMO, IDEs and graphical form editing are clearly made for each other.

How to sort an ArrayList?

If you have to sort object based on its id in the ArrayList , then use java8 stream.

 List<Person> personList = new ArrayList<>();

    List<Person> personListSorted =
                personList.stream()
                  .sorted(Comparator.comparing(Person::getPersonId))
                  .collect(Collectors.toList());

css width: calc(100% -100px); alternative using jquery

If you have a browser that doesn't support the calc expression, it's not hard to mimic with jQuery:

$('#yourEl').css('width', '100%').css('width', '-=100px');

It's much easier to let jQuery handle the relative calculation than doing it yourself.

array of string with unknown size

You can't create an array without a size. You'd need to use a list for that.

Radio button checked event handling

Update in 2017: Hey. This is a terrible answer. Don't use it. Back in the old days this type of jQuery use was common. And it probably worked back then. Just read it, realize it's terrible, then move on (or downvote or, whatever) to one of the other answers that are better for today's jQuery.


$("input[type=radio]").change(function(){
    alert( $("input[type=radio][name="+ this.name + "]").val() );
});

Change collations of all columns of all tables in SQL Server

Sorry late to the party, but here is mine - cater for table with a schema and funny column and table names. Yes I had some of them.

SELECT 
    'ALTER TABLE [' +  TABLE_SCHEMA + '].[' + TABLE_NAME  
    + '] ALTER COLUMN [' + COLUMN_NAME + '] ' + DATA_TYPE 
    + '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS nvarchar(100)) 
    + ') COLLATE ' + 'Latin1_General_CI_AS' 
    + CASE WHEN IS_NULLABLE = 'YES' THEN ' NULL' ELSE ' NOT NULL' END 
FROM 
    INFORMATION_SCHEMA.COLUMNS 
WHERE 
    DATA_TYPE like '%char'

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

How to read the shell variable in groovy / how to assign shell return value to groovy variable.

Requirement : Open a text file read the lines using shell and store the value in groovy and get the parameter for each line .

Here , is delimiter

Ex: releaseModule.txt

./APP_TSBASE/app/team/i-home/deployments/ip-cc.war/cs_workflowReport.jar,configurable-wf-report,94,23crb1,artifact



./APP_TSBASE/app/team/i-home/deployments/ip.war/cs_workflowReport.jar,configurable-temppweb-report,394,rvu3crb1,artifact

========================

Here want to get module name 2nd Parameter (configurable-wf-report) , build no 3rd Parameter (94), commit id 4th (23crb1)

def  module = sh(script: """awk -F',' '{ print \$2 "," \$3 "," \$4 }' releaseModules.txt  | sort -u """, returnStdout: true).trim()

echo module

List lines = module.split( '\n' ).findAll { !it.startsWith( ',' ) }

def buildid

def Modname

lines.each {

List det1 =  it.split(',')

buildid=det1[1].trim() 

Modname = det1[0].trim()

tag= det1[2].trim()

               

echo Modname               

echo buildid

                echo tag

                        

}

Open a URL without using a browser from a batch file

Try winhttpjs.bat. It uses a winhttp request object that should be faster than
Msxml2.XMLHTTP as there isn't any DOM parsing of the response. It is capable to do requests with body and all HTTP methods.

call winhttpjs.bat  http://somelink.com/something.html -saveTo c:\something.html

Convert python datetime to epoch with strftime

For an explicit timezone-independent solution, use the pytz library.

import datetime
import pytz

pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()

Output (float): 1333238400.0

How to change the MySQL root account password on CentOS7?

For me work like this: 1. Stop mysql: systemctl stop mysqld

  1. Set the mySQL environment option systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"

  2. Start mysql usig the options you just set systemctl start mysqld

  3. Login as root mysql -u root

  4. After login I use FLUSH PRIVILEGES; tell the server to reload the grant tables so that account-management statements work. If i don't do that i receive this error trying to update the password: "Can't find any matching row in the user table"

How to set selected value of jquery select2?

This may help someone loading select2 data from AJAX while loading data for editing (applicable for single or multi-select):

During my form/model load :

  $.ajax({
        type: "POST",
        ...        
        success: function (data) {
          selectCountries(fixedEncodeURI(data.countries));
         }

Call to select data for Select2:

var countrySelect = $('.select_country');
function selectCountries(countries)
    {
        if (countries) {
            $.ajax({
                type: 'GET',
                url: "/regions/getCountries/",
                data: $.param({ 'idsSelected': countries }, true),

            }).then(function (data) {
                // create the option and append to Select2                     
                $.each(data, function (index, value) {
                    var option = new Option(value.text, value.id, true, true);
                    countrySelect.append(option).trigger('change');
                    console.log(option);
                });
                // manually trigger the `select2:select` event
                countrySelect.trigger({
                    type: 'select2:select',
                    params: {
                        data: data
                    }
                });
            });
        }
    }

and if you may be having issues with encoding you may change as your requirement:

function fixedEncodeURI(str) {
        return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%22/g,"");

    }

Convert string[] to int[] in one line of code using LINQ

var asIntegers = arr.Select(s => int.Parse(s)).ToArray(); 

Have to make sure you are not getting an IEnumerable<int> as a return

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

How do I download a file using VBA (without Internet Explorer)

This solution is based from this website: http://social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save-csv-from-url

It is slightly modified to overwrite existing file and to pass along login credentials.

Sub DownloadFile()

Dim myURL As String
myURL = "https://YourWebSite.com/?your_query_parameters"

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "username", "password"
WinHttpReq.send

If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.responseBody
    oStream.SaveToFile "C:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite
    oStream.Close
End If

End Sub

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

I'm learning from udemy. I followed every step that my instructor show me to do. In spring mvc crud section while setting up the devlopment environment i had the same error for:

<mvc:annotation-driven/> and <tx:annotation-driven transaction-manager="myTransactionManager" />

then i just replaced

    http://www.springframework.org/schema/mvc/spring-mvc.xsd 

with

    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd

and

    http://www.springframework.org/schema/tx/spring-tx.xsd

with

    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd

actually i visited these two sites http://www.springframework.org/schema/mvc/ and http://www.springframework.org/schema/tx/ and just added the latest version of spring-mvc and spring-tx i.e, spring-mvc-4.2.xsd and spring-tx-4.2.xsd

So, i suggest to try this. Hope this helps. Thank you.

How to access the request body when POSTing using Node.js and Express?

As of Express 4, the following code appears to do the trick. Note that you'll need to install body-parser using npm.

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));


app.listen(8888);

app.post('/update', function(req, res) {
    console.log(req.body); // the posted data
});

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

This is something that I use:

#wait for jobs
for job in `jobs -p`; do wait ${job}; done

Gridview with two columns and auto resized images

Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2"/>

</FrameLayout>

Make a custom ImageView that maintains its aspect ratio:

src/com/example/graphicstest/SquareImageView.java

public class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
    }
}

Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:

res/layout/grid_item.xml

<?xml version="1.0" encoding="utf-8"?>

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

    <com.example.graphicstest.SquareImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"/>

</FrameLayout>

Now make some sort of adapter for your GridView:

src/com/example/graphicstest/MyAdapter.java

private final class MyAdapter extends BaseAdapter {
    private final List<Item> mItems = new ArrayList<Item>();
    private final LayoutInflater mInflater;

    public MyAdapter(Context context) {
        mInflater = LayoutInflater.from(context);

        mItems.add(new Item("Red",       R.drawable.red));
        mItems.add(new Item("Magenta",   R.drawable.magenta));
        mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
        mItems.add(new Item("Gray",      R.drawable.gray));
        mItems.add(new Item("Green",     R.drawable.green));
        mItems.add(new Item("Cyan",      R.drawable.cyan));
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Item getItem(int i) {
        return mItems.get(i);
    }

    @Override
    public long getItemId(int i) {
        return mItems.get(i).drawableId;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        ImageView picture;
        TextView name;

        if (v == null) {
            v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
            v.setTag(R.id.picture, v.findViewById(R.id.picture));
            v.setTag(R.id.text, v.findViewById(R.id.text));
        }

        picture = (ImageView) v.getTag(R.id.picture);
        name = (TextView) v.getTag(R.id.text);

        Item item = getItem(i);

        picture.setImageResource(item.drawableId);
        name.setText(item.name);

        return v;
    }

    private static class Item {
        public final String name;
        public final int drawableId;

        Item(String name, int drawableId) {
            this.name = name;
            this.drawableId = drawableId;
        }
    }
}

Set that adapter to your GridView:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GridView gridView = (GridView)findViewById(R.id.gridview);
    gridView.setAdapter(new MyAdapter(this));
}

And enjoy the results:

Example GridView

no module named zlib

After you install the missing zlib dev package you can also use pythonbrew to uninstall and then reinstall the version of python you wanted and it seems like it picks up the new package to compile to correct abilities. This way you can keep using pythonbrew and don't have to do the compilation yourself (though it isn't that difficult)

Failed to load JavaHL Library

For Eclipse/STS v3.9.X windows user, you may need to update your subclipse version.

Go to Help > Install New Software > Click on Subclipse and edit the version from 1.6.X to 1.8.X

This method also apply to those who encounter JavaHL not available. You can check whether JavaHL is available or not by Go to Windows > Preference > Team > SVN. You may check it in SVN Interface > Client section.

If this work on MAC OS, kindly response in comment section. :)

How do I prevent Conda from activating the base environment by default?

I faced the same problem. Initially I deleted the .bash_profile but this is not the right way. After installing anaconda it is showing the instructions clearly for this problem. Please check the image for solution provided by Anaconda

Using pip behind a proxy with CNTLM

With Ubuntu I could not get the proxy option to work as advertised – so following command did not work:

sudo pip --proxy http://web-proxy.mydomain.com install somepackage

But exporting the https_proxy environment variable (note its https_proxy not http_proxy) did the trick:

export https_proxy=http://web-proxy.mydomain.com

then

sudo -E pip install somepackage

Creating a very simple linked list

A Linked List, at its core is a bunch of Nodes linked together.

So, you need to start with a simple Node class:

public class Node {
    public Node next;
    public Object data;
}

Then your linked list will have as a member one node representing the head (start) of the list:

public class LinkedList {
    private Node head;
}

Then you need to add functionality to the list by adding methods. They usually involve some sort of traversal along all of the nodes.

public void printAllNodes() {
    Node current = head;
    while (current != null) 
    {
        Console.WriteLine(current.data);
        current = current.next;
    }
}

Also, inserting new data is another common operation:

public void Add(Object data) {
    Node toAdd = new Node();
    toAdd.data = data;
    Node current = head;
    // traverse all nodes (see the print all nodes method for an example)
    current.next = toAdd;
}

This should provide a good starting point.

How to remove listview all items

use any one of the bellow options which suites your requirement

listview.removeViews(1,listview.getChildCount());

or

listview.removeViewInLayout(your view);

open a url on click of ok button in android

create an intent and set an action for it while passing the url to the intent

yourbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String theurl = "http://google.com";
                Uri urlstr = Uri.parse(theurl);
                Intent urlintent = new Intent();
                urlintent.setData(urlstr);
                urlintent.setAction(Intent.ACTION_VIEW);
                startActivity(urlintent);

Creating a JSON response using Django and Python

With Django Class-based views you can write:

from django.views import View
from django.http import JsonResponse

class JsonView(View):
    def get(self, request):
        return JsonResponse({'some': 'data'})

and with Django-Rest-Framework you can write:

from rest_framework.views import APIView
from rest_framework.response import Response

class JsonView(APIView):
    def get(self, request):
        return Response({'some': 'data'})

AngularJS : Clear $watch

Ideally, every custom watch should be removed when you leave the scope.

It helps in better memory management and better app performance.

// call to $watch will return a de-register function
var listener = $scope.$watch(someVariableToWatch, function(....));

$scope.$on('$destroy', function() {
    listener(); // call the de-register function on scope destroy
});

Best way to handle list.index(might-not-exist) in python?

Comparison of implementations

Simple comparison on Python 3.8

TL;DR maybeidx2 is faster in general except for arrays (n<100) with lots of misses

def maybeidx1(l, v):
    return l.index(v) if v in l else None

def maybeidx2(l, v):
    try:
        return l.index(v)
    except ValueError:
        return None

Test cases:

a = [*range(100_000)]
# Case 1: index in list
maybeidx1(a, 50_000)
Out[20]: 50000
maybeidx2(a, 50_000)
Out[21]: 50000
# Case 2: index not in list
maybeidx1(a, 100_000) is None
Out[23]: True
maybeidx2(a, 100_000) is None
Out[24]: True

Timing case 1

%timeit maybeidx1(a, 50_000)
1.06 ms ± 15.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit maybeidx2(a, 50_000)
530 µs ± 8.47 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Timing case 2

%timeit maybeidx1(a, 100_000)
1.07 ms ± 21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit maybeidx2(a, 100_000)
1.07 ms ± 16.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Result

Use the maybeidx2 method for larger arrays. This is faster due to maybeidx1 having two scans of the array in search of the value - this is still O(n) time but has a constant multiplier of 2 and thus slower in practice. This holds in the case of the value being present in the list. When the value is not present, these times will be roughly equal; they both have to scan the full array exactly once, then return None. The overhead of the try-except is negligible, even with an array size of 10 - unless case two occurs. Then the try-except overhead is noticeable. Example:

a = [*range(10)]
%timeit maybeidx1(a, 10)
191 ns ± 2.61 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit maybeidx2(a, 10)
566 ns ± 5.93 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

This overhead becomes negligible (on my machine) when a has above 100 elements.

how to overwrite css style

You can add your styles in the required page after the external style sheet so they'll cascade and overwrite the first set of rules.

<link rel="stylesheet" href="allpages.css">
<style>
.flex-control-thumbs li {
  width: auto;
  float: none;
}
</style>

PL/pgSQL checking if a row exists

Use count(*)

declare 
   cnt integer;
begin
  SELECT count(*) INTO cnt
  FROM people
  WHERE person_id = my_person_id;

IF cnt > 0 THEN
  -- Do something
END IF;

Edit (for the downvoter who didn't read the statement and others who might be doing something similar)

The solution is only effective because there is a where clause on a column (and the name of the column suggests that its the primary key - so the where clause is highly effective)

Because of that where clause there is no need to use a LIMIT or something else to test the presence of a row that is identified by its primary key. It is an effective way to test this.

Getting error: ISO C++ forbids declaration of with no type

You forgot the return types in your member function definitions:

int ttTree::ttTreeInsert(int value) { ... }
^^^               

and so on.

How to get the list of all printers in computer

If you need more information than just the name of the printer you can use the System.Management API to query them:

var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer");
foreach (var printer in printerQuery.Get())
{
    var name = printer.GetPropertyValue("Name");
    var status = printer.GetPropertyValue("Status");
    var isDefault = printer.GetPropertyValue("Default");
    var isNetworkPrinter = printer.GetPropertyValue("Network");

    Console.WriteLine("{0} (Status: {1}, Default: {2}, Network: {3}", 
                name, status, isDefault, isNetworkPrinter);
}

Cancel split window in Vim

Press Control+w, then hit q to close each window at a time.

Update: Also consider eckes answer which may be more useful to you, involving :on (read below) if you don't want to do it one window at a time.

Scale image to fit a bounding box

This example to stretch the image proportionally to fit the entire window. An improvisation to the above correct code is to add $( window ).resize(function(){});

function stretchImg(){
    $('div').each(function() {
      ($(this).height() > $(this).find('img').height()) 
        ? $(this).find('img').removeClass('fillwidth').addClass('fillheight')
        : '';
      ($(this).width() > $(this).find('img').width()) 
        ? $(this).find('img').removeClass('fillheight').addClass('fillwidth')
        : '';
    });
}
stretchImg();

$( window ).resize(function() {
    strechImg();
});

There are two if conditions. The first one keeps checking if the image height is less than the div and applies .fillheight class while the next checks for width and applies .fillwidth class. In both cases the other class is removed using .removeClass()

Here is the CSS

.fillwidth { 
   width: 100%;
   max-width: none;
   height: auto; 
}
.fillheight { 
   height: 100vh;
   max-width: none;
   width: auto; 
}

You can replace 100vh by 100% if you want to stretch the image with in a div. This example to stretch the image proportionally to fit the entire window.

Time stamp in the C programming language

Also making aware of interactions between clock() and usleep(). usleep() suspends the program, and clock() only measures the time the program is running.

If might be better off to use gettimeofday() as mentioned here

Creating custom function in React component

You can create functions in react components. It is actually regular ES6 class which inherits from React.Component. Just be careful and bind it to the correct context in onClick event:

export default class Archive extends React.Component { 

    saySomething(something) {
        console.log(something);
    }

    handleClick(e) {
        this.saySomething("element clicked");
    }

    componentDidMount() {
        this.saySomething("component did mount");
    }

    render() {
        return <button onClick={this.handleClick.bind(this)} value="Click me" />;
    }
}

MySQL CONCAT returns NULL if any field contain NULL

convert the NULL values with empty string by wrapping it in COALESCE

SELECT CONCAT(COALESCE(`affiliate_name`,''),'-',COALESCE(`model`,''),'-',COALESCE(`ip`,''),'-',COALESCE(`os_type`,''),'-',COALESCE(`os_version`,'')) AS device_name
FROM devices

What does "#include <iostream>" do?

That is a C++ standard library header file for input output streams. It includes functionality to read and write from streams. You only need to include it if you wish to use streams.

Is there a performance difference between i++ and ++i in C?

I can think of a situation where postfix is slower than prefix increment:

Imagine a processor with register A is used as accumulator and it's the only register used in many instructions (some small microcontrollers are actually like this).

Now imagine the following program and their translation into a hypothetical assembly:

Prefix increment:

a = ++b + c;

; increment b
LD    A, [&b]
INC   A
ST    A, [&b]

; add with c
ADD   A, [&c]

; store in a
ST    A, [&a]

Postfix increment:

a = b++ + c;

; load b
LD    A, [&b]

; add with c
ADD   A, [&c]

; store in a
ST    A, [&a]

; increment b
LD    A, [&b]
INC   A
ST    A, [&b]

Note how the value of b was forced to be reloaded. With prefix increment, the compiler can just increment the value and go ahead with using it, possibly avoid reloading it since the desired value is already in the register after the increment. However, with postfix increment, the compiler has to deal with two values, one the old and one the incremented value which as I show above results in one more memory access.

Of course, if the value of the increment is not used, such as a single i++; statement, the compiler can (and does) simply generate an increment instruction regardless of postfix or prefix usage.


As a side note, I'd like to mention that an expression in which there is a b++ cannot simply be converted to one with ++b without any additional effort (for example by adding a - 1). So comparing the two if they are part of some expression is not really valid. Often, where you use b++ inside an expression you cannot use ++b, so even if ++b were potentially more efficient, it would simply be wrong. Exception is of course if the expression is begging for it (for example a = b++ + 1; which can be changed to a = ++b;).

How do I create ColorStateList programmatically?

My builder class for create ColorStateList

private class ColorStateListBuilder {
    List<Integer> colors = new ArrayList<>();
    List<int[]> states = new ArrayList<>();

    public ColorStateListBuilder addState(int[] state, int color) {
        states.add(state);
        colors.add(color);
        return this;
    }

    public ColorStateList build() {
        return new ColorStateList(convertToTwoDimensionalIntArray(states),
                convertToIntArray(colors));
    }

    private int[][] convertToTwoDimensionalIntArray(List<int[]> integers) {
        int[][] result = new int[integers.size()][1];
        Iterator<int[]> iterator = integers.iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            result[i] = iterator.next();
        }
        return result;
    }

    private int[] convertToIntArray(List<Integer> integers) {
        int[] result = new int[integers.size()];
        Iterator<Integer> iterator = integers.iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            result[i] = iterator.next();
        }
        return result;
    }
}

Example Using

ColorStateListBuilder builder = new ColorStateListBuilder();
builder.addState(new int[] { android.R.attr.state_pressed }, ContextCompat.getColor(this, colorRes))
       .addState(new int[] { android.R.attr.state_selected }, Color.GREEN)
       .addState(..., some color);

if(// some condition){
      builder.addState(..., some color);
}
builder.addState(new int[] {}, colorNormal); // must add default state at last of all state

ColorStateList stateList = builder.build(); // ColorStateList created here

// textView.setTextColor(stateList);

What's the difference between struct and class in .NET?

Difference between Structs and Classes:

  • Structs are value type whereas Classes are reference type.
  • Structs are stored on the stack whereas Classes are stored on the heap.
  • Value types hold their value in memory where they are declared, but reference type holds a reference to an object memory.
  • Value types destroyed immediately after the scope is lost whereas reference type only the variable destroy after the scope is lost. The object is later destroyed by the garbage collector.
  • When you copy struct into another struct, a new copy of that struct gets created modified of one struct won't affect the value of the other struct.
  • When you copy a class into another class, it only copies the reference variable.
  • Both the reference variable point to the same object on the heap. Change to one variable will affect the other reference variable.
  • Structs can not have destructors, but classes can have destructors.
  • Structs can not have explicit parameterless constructors whereas classes can. Structs don't support inheritance, but classes do. Both support inheritance from an interface.
  • Structs are sealed type.

How to make MySQL handle UTF-8 properly

To make this 'permanent', in my.cnf:

[client]
default-character-set=utf8
[mysqld]
character-set-server = utf8

To check, go to the client and show some variables:

SHOW VARIABLES LIKE 'character_set%';

Verify that they're all utf8, except ..._filesystem, which should be binary and ..._dir, that points somewhere in the MySQL installation.

How to position three divs in html horizontally?

You add a

float: left;

to the style of the 3 elements and make sure the parent container has

overflow: hidden; position: relative;

this makes sure the floats take up actual space.

<html>
    <head>
        <title>Website Title </title>
    </head>
    <body>
        <div id="the-whole-thing" style="position: relative; overflow: hidden;">
            <div id="leftThing" style="position: relative; width: 25%; background-color: blue; float: left;">
                Left Side Menu
            </div>
            <div id="content" style="position: relative; width: 50%; background-color: green; float: left;">
                Random Content
            </div>
            <div id="rightThing" style="position: relative; width: 25%; background-color: yellow; float: left;">
                Right Side Menu
            </div>
        </div>
    </body>
</html>

Also please note that the width: 100% and height: 100% need to be removed from the container, otherwise the 3rd block will wrap to a 2nd line.

When to use self over $this?

Case 1: Use self can be used for class constants

 class classA { 
     const FIXED_NUMBER = 4; 
     self::POUNDS_TO_KILOGRAMS
}

If you want to call it outside of the class, use classA::POUNDS_TO_KILOGRAMS to access the constants

Case 2: For static properties

class classC {
     public function __construct() { 
     self::$_counter++; $this->num = self::$_counter;
   }
}

How to get cell value from DataGridView in VB.Net?

This helped me get close to what I needed and I will throw this out there for anyone else who needs it.

If you are looking for the value in the first cell in the selected column, you can try this. (I chose the first column, since you are asking for it to return "3", but you can change the number after Cells to get whichever column you need. Remember it is zero-based.)

This will copy the result to the clipboard: Clipboard.SetDataObject(Me.DataGridView1.CurrentRow.Cells(0).Value)

How to create a GUID / UUID

Here you can find a very small function that generates uuids https://gist.github.com/jed/982883

One of the final versions is:

function b(
  a                  // placeholder
){
  var cryptoObj = window.crypto || window.msCrypto; // for IE 11
  return a           // if the placeholder was passed, return
    ? (              // a random number from 0 to 15
      a ^            // unless b is 8,
      cryptoObj.getRandomValues(new Uint8Array(1))[0]  // in which case
      % 16           // a random number from
      >> a/4         // 8 to 11
      ).toString(16) // in hexadecimal
    : (              // or otherwise a concatenated string:
      [1e7] +        // 10000000 +
      -1e3 +         // -1000 +
      -4e3 +         // -4000 +
      -8e3 +         // -80000000 +
      -1e11          // -100000000000,
      ).replace(     // replacing
        /[018]/g,    // zeroes, ones, and eights with
        b            // random hex digits
      )
}

Disable nginx cache for JavaScript files

I have the following Nginx virtual host(static content) for local development work to disable all browser caching:

    upstream testCom
        {
         server localhost:1338;
        }

    server
        {

            listen 80;
            server_name <your ip or domain>;
            location / {

            # proxy_cache   datacache;
            proxy_cache_key $scheme$host$request_method$request_uri;
            proxy_cache_valid       200     60m;
            proxy_cache_min_uses    1;
            proxy_cache_use_stale   updating;

            proxy_pass_header Server;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Scheme $scheme;

            proxy_ignore_headers    Set-Cookie;

            userid          on;
            userid_name     __uid;
            userid_domain   <your ip or domain>;
            userid_path     /;
            userid_expires  max;
            userid_p3p      'policyref="/w3c/p3p.xml", CP="CUR ADM OUR NOR STA NID"';


            add_header Last-Modified $date_gmt;
            add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
            if_modified_since off;
            expires off;
            etag off;

            proxy_pass http://testCom;
        }
    }

ECONNREFUSED error when connecting to mongodb from node.js

OK, this was another case of not being truly forthcoming in the info I posted above. My node.js app was very simple, but I was including another couple lines in my node.js code that apparently caused this issue.

Specifically, I had another variable declared which was calling some other code that made a separate database call using incorrect db info. This is why, when using Xinzz's code, the console log error seemed not to change. It wasn't actually the mongoose.connect command that was throwing the error!

Lesson learned, localize the problem and comment out unrelated code! Sorry guys, I knew this was me being dumb.

Good MapReduce examples

Map reduce is a framework that was developed to process massive amounts of data efficiently. For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these.

For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases. Map Reduce provides a cluster based implementation where data is processed in a distributed manner

Here is a wikipedia article explaining what map-reduce is all about

Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and a well used use-case.

Personally, found this link quite useful to understand the concept

Copying the explanation provided in the blog (In case the link goes stale)

Finding Friends

MapReduce is a framework originally developed at Google that allows for easy large scale distributed computing across a number of domains. Apache Hadoop is an open source implementation.

I'll gloss over the details, but it comes down to defining two functions: a map function and a reduce function. The map function takes a value and outputs key:value pairs. For instance, if we define a map function that takes a string and outputs the length of the word as the key and the word itself as the value then map(steve) would return 5:steve and map(savannah) would return 8:savannah. You may have noticed that the map function is stateless and only requires the input value to compute it's output value. This allows us to run the map function against values in parallel and provides a huge advantage. Before we get to the reduce function, the mapreduce framework groups all of the values together by key, so if the map functions output the following key:value pairs:

3 : the
3 : and
3 : you
4 : then
4 : what
4 : when
5 : steve
5 : where
8 : savannah
8 : research

They get grouped as:

3 : [the, and, you]
4 : [then, what, when]
5 : [steve, where]
8 : [savannah, research]

Each of these lines would then be passed as an argument to the reduce function, which accepts a key and a list of values. In this instance, we might be trying to figure out how many words of certain lengths exist, so our reduce function will just count the number of items in the list and output the key with the size of the list, like:

3 : 3
4 : 3
5 : 2
8 : 2

The reductions can also be done in parallel, again providing a huge advantage. We can then look at these final results and see that there were only two words of length 5 in our corpus, etc...

The most common example of mapreduce is for counting the number of times words occur in a corpus. Suppose you had a copy of the internet (I've been fortunate enough to have worked in such a situation), and you wanted a list of every word on the internet as well as how many times it occurred.

The way you would approach this would be to tokenize the documents you have (break it into words), and pass each word to a mapper. The mapper would then spit the word back out along with a value of 1. The grouping phase will take all the keys (in this case words), and make a list of 1's. The reduce phase then takes a key (the word) and a list (a list of 1's for every time the key appeared on the internet), and sums the list. The reducer then outputs the word, along with it's count. When all is said and done you'll have a list of every word on the internet, along with how many times it appeared.

Easy, right? If you've ever read about mapreduce, the above scenario isn't anything new... it's the "Hello, World" of mapreduce. So here is a real world use case (Facebook may or may not actually do the following, it's just an example):

Facebook has a list of friends (note that friends are a bi-directional thing on Facebook. If I'm your friend, you're mine). They also have lots of disk space and they serve hundreds of millions of requests everyday. They've decided to pre-compute calculations when they can to reduce the processing time of requests. One common processing request is the "You and Joe have 230 friends in common" feature. When you visit someone's profile, you see a list of friends that you have in common. This list doesn't change frequently so it'd be wasteful to recalculate it every time you visited the profile (sure you could use a decent caching strategy, but then I wouldn't be able to continue writing about mapreduce for this problem). We're going to use mapreduce so that we can calculate everyone's common friends once a day and store those results. Later on it's just a quick lookup. We've got lots of disk, it's cheap.

Assume the friends are stored as Person->[List of Friends], our friends list is then:

A -> B C D
B -> A C D E
C -> A B D E
D -> A B C E
E -> B C D

Each line will be an argument to a mapper. For every friend in the list of friends, the mapper will output a key-value pair. The key will be a friend along with the person. The value will be the list of friends. The key will be sorted so that the friends are in order, causing all pairs of friends to go to the same reducer. This is hard to explain with text, so let's just do it and see if you can see the pattern. After all the mappers are done running, you'll have a list like this:

For map(A -> B C D) :

(A B) -> B C D
(A C) -> B C D
(A D) -> B C D

For map(B -> A C D E) : (Note that A comes before B in the key)

(A B) -> A C D E
(B C) -> A C D E
(B D) -> A C D E
(B E) -> A C D E
For map(C -> A B D E) :

(A C) -> A B D E
(B C) -> A B D E
(C D) -> A B D E
(C E) -> A B D E
For map(D -> A B C E) :

(A D) -> A B C E
(B D) -> A B C E
(C D) -> A B C E
(D E) -> A B C E
And finally for map(E -> B C D):

(B E) -> B C D
(C E) -> B C D
(D E) -> B C D
Before we send these key-value pairs to the reducers, we group them by their keys and get:

(A B) -> (A C D E) (B C D)
(A C) -> (A B D E) (B C D)
(A D) -> (A B C E) (B C D)
(B C) -> (A B D E) (A C D E)
(B D) -> (A B C E) (A C D E)
(B E) -> (A C D E) (B C D)
(C D) -> (A B C E) (A B D E)
(C E) -> (A B D E) (B C D)
(D E) -> (A B C E) (B C D)

Each line will be passed as an argument to a reducer. The reduce function will simply intersect the lists of values and output the same key with the result of the intersection. For example, reduce((A B) -> (A C D E) (B C D)) will output (A B) : (C D) and means that friends A and B have C and D as common friends.

The result after reduction is:

(A B) -> (C D)
(A C) -> (B D)
(A D) -> (B C)
(B C) -> (A D E)
(B D) -> (A C E)
(B E) -> (C D)
(C D) -> (A B E)
(C E) -> (B D)
(D E) -> (B C)

Now when D visits B's profile, we can quickly look up (B D) and see that they have three friends in common, (A C E).

sqlplus how to find details of the currently connected database session

We can get the details and status of session from below query as:

select ' Sid, Serial#, Aud sid : '|| s.sid||' , '||s.serial#||' , '||
       s.audsid||chr(10)|| '     DB User / OS User : '||s.username||
       '   /   '||s.osuser||chr(10)|| '    Machine - Terminal : '||
       s.machine||'  -  '|| s.terminal||chr(10)||
       '        OS Process Ids : '||
       s.process||' (Client)  '||p.spid||' (Server)'|| chr(10)||
       '   Client Program Name : '||s.program "Session Info"
  from v$process p,v$session s
 where p.addr = s.paddr
   and s.sid = nvl('&SID',s.sid)
   and nvl(s.terminal,' ') = nvl('&Terminal',nvl(s.terminal,' '))
   and s.process = nvl('&Process',s.process)
   and p.spid = nvl('&spid',p.spid)
   and s.username = nvl('&username',s.username)
   and nvl(s.osuser,' ') = nvl('&OSUser',nvl(s.osuser,' '))
   and nvl(s.machine,' ') = nvl('&machine',nvl(s.machine,' '))
   and nvl('&SID',nvl('&TERMINAL',nvl('&PROCESS',nvl('&SPID',nvl('&USERNAME',
       nvl('&OSUSER',nvl('&MACHINE','NO VALUES'))))))) <> 'NO VALUES'
/

For more details: https://ora-data.blogspot.in/2016/11/query-session-details.html

Thanks,

using lodash .groupBy. how to add your own keys for grouped output?

Here is an updated version using lodash 4 and ES6

const result = _.chain(data)
    .groupBy("color")
    .toPairs()
    .map(pair => _.zipObject(['color', 'users'], pair))
    .value();

jQuery - prevent default, then continue default

You can use e.preventDefault() which will stop the current operation.

than you can do$("#form").submit();

 $('#form').submit(function (e)
{
    return !!e.submit;
});
if(blabla...)
{...
}
else
{
    $('#form').submit(
    {
        submit: true
    });
}

IE prompts to open or save json result from server

Sadly, this is just another annoying quirk of using Internet Explorer.

enter image description here

The simple solution is to run a small .reg file on your PC, to tell IE to automatically open .json files, rather than nag about whether to open/save it.

I've put a copy of the file you'll need here:

JSON mime type

You'll need to have Admin rights to run this.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Phone number validation Android

Use isGlobalPhoneNumber() method of PhoneNumberUtils to detect whether a number is valid phone number or not.

Example

System.out.println("....g1..."+PhoneNumberUtils.isGlobalPhoneNumber("+912012185234"));
System.out.println("....g2..."+PhoneNumberUtils.isGlobalPhoneNumber("120121852f4"));

The result of first print statement is true while the result of second is false because the second phone number contains f.

Underscore prefix for property and method names in JavaScript

JavaScript actually does support encapsulation, through a method that involves hiding members in closures (Crockford). That said, it's sometimes cumbersome, and the underscore convention is a pretty good convention to use for things that are sort of private, but that you don't actually need to hide.

The default for KeyValuePair

You can create a general (and generic) extension method, like this one:

public static class Extensions
{
    public static bool IsDefault<T>(this T value) where T : struct
    {
        bool isDefault = value.Equals(default(T));

        return isDefault;
    }
}

Usage:

// We have to set explicit default value '0' to avoid build error:
// Use of unassigned local variable 'intValue'
int intValue = 0;
long longValue = 12;
KeyValuePair<String, int> kvp1 = new KeyValuePair<String, int>("string", 11);
KeyValuePair<String, int> kvp2 = new KeyValuePair<String, int>();
List<KeyValuePair<String, int>> kvps = new List<KeyValuePair<String, int>> { kvp1, kvp2 };
KeyValuePair<String, int> kvp3 = kvps.FirstOrDefault(kvp => kvp.Value == 11);
KeyValuePair<String, int> kvp4 = kvps.FirstOrDefault(kvp => kvp.Value == 15);

Console.WriteLine(intValue.IsDefault()); // results 'True'
Console.WriteLine(longValue.IsDefault()); // results 'False'
Console.WriteLine(kvp1.IsDefault()); // results 'False'
Console.WriteLine(kvp2.IsDefault()); // results 'True'
Console.WriteLine(kvp3.IsDefault()); // results 'False'
Console.WriteLine(kvp4.IsDefault()); // results 'True'

Presenting modal in iOS 13 fullscreen

For Objective-C users

Just Use this code

 [vc setModalPresentationStyle: UIModalPresentationFullScreen];

Or if you want to add it particular in iOS 13.0 then use

 if (@available(iOS 13.0, *)) {
     [vc setModalPresentationStyle: UIModalPresentationFullScreen];
 } else {
     // Fallback on earlier versions
 }

Select by partial string from a pandas DataFrame

Maybe you want to search for some text in all columns of the Pandas dataframe, and not just in the subset of them. In this case, the following code will help.

df[df.apply(lambda row: row.astype(str).str.contains('String To Find').any(), axis=1)]

Warning. This method is relatively slow, albeit convenient.

Connecting to TCP Socket from browser using javascript

ws2s project is aimed at bring socket to browser-side js. It is a websocket server which transform websocket to socket.

ws2s schematic diagram

enter image description here

code sample:

var socket = new WS2S("wss://ws2s.feling.io/").newSocket()

socket.onReady = () => {
  socket.connect("feling.io", 80)
  socket.send("GET / HTTP/1.1\r\nHost: feling.io\r\nConnection: close\r\n\r\n")
}

socket.onRecv = (data) => {
  console.log('onRecv', data)
}

When do I need to do "git pull", before or after "git add, git commit"?

I'd suggest pulling from the remote branch as often as possible in order to minimise large merges and possible conflicts.

Having said that, I would go with the first option:

git add foo.js
git commit foo.js -m "commit"
git pull
git push

Commit your changes before pulling so that your commits are merged with the remote changes during the pull. This may result in conflicts which you can begin to deal with knowing that your code is already committed should anything go wrong and you have to abort the merge for whatever reason.

I'm sure someone will disagree with me though, I don't think there's any correct way to do this merge flow, only what works best for people.

Adding a new entry to the PATH variable in ZSH

  1. Added path to ~/.zshrc

    sudo vi ~/.zshrc

    add new path

    export PATH="$PATH:[NEW_DIRECTORY]/bin"
    
  2. Update ~/.zshrc

    Save ~/.zshrc

    source ~/.zshrc

  3. Check PATH

    echo $PATH

When restoring a backup, how do I disconnect all active connections?

None of the above worked for me. My database didn't show any active connections using Activity Monitor or sp_who. I ultimately had to:

  • Right click the database node
  • Select "Detach..."
  • Check the "Drop Connections" box
  • Reattach

Not the most elegant solution but it works and it doesn't require restarting SQL Server (not an option for me, since the DB server hosted a bunch of other databases)

Error TF30063: You are not authorized to access ... \DefaultCollection

Now I got the solution to the problem which I have faced: The TFS remembered the prior password when I got logged in by using my mobile VPN.

Solution:

Resetting the account that I used to connect using VPN

Bootstrap combining rows (rowspan)

Check this one. hope it will help full for you.

http://jsfiddle.net/j6amM/

.row-fix { margin-bottom:20px;}

.row-fix > [class*="span"]{ height:100px; background:#f1f1f1;}

.row-fix .two-col{ background:none;}

.two-col > [class*="col"]{ height:40px; background:#ccc;}

.two-col > .col1{margin-bottom:20px;}