Programs & Examples On #Openfaces

OpenFaces is an open-source library of AJAX-powered JSF components, an Ajax framework and a client-side validation framework.

Mockito test a void method throws an exception

If you ever wondered how to do it using the new BDD style of Mockito:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing:

willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));

How to check if spark dataframe is empty?

If you do df.count > 0. It takes the counts of all partitions across all executors and add them up at Driver. This take a while when you are dealing with millions of rows.

The best way to do this is to perform df.take(1) and check if its null. This will return java.util.NoSuchElementException so better to put a try around df.take(1).

The dataframe return an error when take(1) is done instead of an empty row. I have highlighted the specific code lines where it throws the error.

enter image description here

Handling warning for possible multiple enumeration of IEnumerable

First off, that warning does not always mean so much. I usually disabled it after making sure it's not a performance bottle neck. It just means the IEnumerable is evaluated twice, wich is usually not a problem unless the evaluation itself takes a long time. Even if it does take a long time, in this case your only using one element the first time around.

In this scenario you could also exploit the powerful linq extension methods even more.

var firstObject = objects.First();
return DoSomeThing(firstObject).Concat(DoSomeThingElse(objects).ToList();

It is possible to only evaluate the IEnumerable once in this case with some hassle, but profile first and see if it's really a problem.

remove kernel on jupyter notebook

Just for completeness, you can get a list of kernels with jupyter kernelspec list, but I ran into a case where one of the kernels did not show up in this list. You can find all kernel names by opening a Jupyter notebook and selecting Kernel -> Change kernel. If you do not see everything in this list when you run jupyter kernelspec list, try looking in common Jupyter folders:

ls ~/.local/share/jupyter/kernels  # usually where local kernels go
ls /usr/local/share/jupyter/kernels  # usually where system-wide kernels go
ls /usr/share/jupyter/kernels  # also where system-wide kernels can go

Also, you can delete a kernel with jupyter kernelspec remove or jupyter kernelspec uninstall. The latter is an alias for remove. From the in-line help text for the command:

uninstall
    Alias for remove
remove
    Remove one or more Jupyter kernelspecs by name.

Background thread with QThread in PyQt

PySide2 Solution:

Unlike in PyQt5, in PySide2 the QThread.started signal is received/handled on the original thread, not the worker thread! Luckily it still receives all other signals on the worker thread.

In order to match PyQt5's behavior, you have to create the started signal yourself.

Here is an easy solution:

# Use this class instead of QThread
class QThread2(QThread):
    # Use this signal instead of "started"
    started2 = Signal()

    def __init__(self):
        QThread.__init__(self)
        self.started.connect(self.onStarted)

    def onStarted(self):
        self.started2.emit()

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

That usually means a null is being posted to the query instead of your desired value, you might try to run the SQL Profiler to see exactly what is getting passed to SQL Server from linq.

How do I put my website's logo to be the icon image in browser tabs?

<link rel="apple-touch-icon" sizes="114x114" href="${resource(dir: 'images', file: 
'apple-touch-icon-retina.png')}">

or you can use this one

<link rel="shortcut icon" sizes="114x114" href="${resource(dir: 'images', file: 'favicon.ico')}"
type="image/x-icon">

SQL: capitalize first letter only

Please check the query without using a function:

declare @T table(Insurance varchar(max))

insert into @T values ('wezembeek-oppem')
insert into @T values ('roeselare')
insert into @T values ('BRUGGE')
insert into @T values ('louvain-la-neuve')

select (
       select upper(T.N.value('.', 'char(1)'))+
                lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+(CASE WHEN RIGHT(T.N.value('.', 'varchar(max)'), 1)='-' THEN '' ELSE ' ' END)
       from X.InsXML.nodes('/N') as T(N)
       for xml path(''), type
       ).value('.', 'varchar(max)') as Insurance
from 
  (
  select cast('<N>'+replace(
            replace(
                Insurance, 
                ' ', '</N><N>'),
            '-', '-</N><N>')+'</N>' as xml) as InsXML
  from @T
  ) as X

INNER JOIN vs INNER JOIN (SELECT . FROM)

You did the right thing by checking from query plans. But I have 100% confidence in version 2. It is faster when the number off records are on the very high side.

My database has around 1,000,000 records and this is exactly the scenario where the query plan shows the difference between both the queries. Further, instead of using a where clause, if you use it in the join itself, it makes the query faster :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID WHERE p.isactive = 1

The better version of this query is :

SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID AND p.isactive = 1

(Assuming isactive is a field in product table which represents the active/inactive products).

Returning http 200 OK with error within response body

No, this is very incorrect.

HTTP is an application protocol. 200 implies that the response contains a payload that represents the status of the requested resource. An error message usually is not a representation of that resource.

If something goes wrong while processing GET, the right status code is 4xx ("you messed up") or 5xx ("I messed up").

npm global path prefix

Any one got the same issue it's related to a conflict between brew and npm Please check this solution https://gist.github.com/DanHerbert/9520689

Javascript: Easier way to format numbers?

No, there is no built-in support for number formatting, but googling will turn up loads of code snippets that will do this for you.

EDIT: I missed the last sentence of your post. Try http://code.google.com/p/jquery-utils/wiki/StringFormat for a jQuery solution.

geom_smooth() what are the methods available?

Sometimes it's asking the question that makes the answer jump out. The methods and extra arguments are listed on the ggplot2 wiki stat_smooth page.

Which is alluded to on the geom_smooth() page with:

"See stat_smooth for examples of using built in model fitting if you need some more flexible, this example shows you how to plot the fits from any model of your choosing".

It's not the first time I've seen arguments in examples for ggplot graphs that aren't specifically in the function. It does make it tough to work out the scope of each function, or maybe I am yet to stumble upon a magic explicit list that says what will and will not work within each function.

Select Row number in postgres

SELECT tab.*,
    row_number() OVER () as rnum
  FROM tab;

Here's the relevant section in the docs.

P.S. This, in fact, fully matches the answer in the referenced question.

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

Open the registry and search for key LoginMode under:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server

Update the LoginMode value as 2.

Windows command prompt log to a file

You can redirect the output of a cmd prompt to a file using > or >> to append to a file.

i.e.

echo Hello World >C:\output.txt
echo Hello again! >>C:\output.txt

or

mybatchfile.bat >C:\output.txt

Note that using > will automatically overwrite the file if it already exists.

You also have the option of redirecting stdin, stdout and stderr.

See here for a complete list of options.

In excel how do I reference the current row but a specific column?

To static either a row or a column, put a $ sign in front of it. So if you were to use the formula =AVERAGE($A1,$C1) and drag it down the entire sheet, A and C would remain static while the 1 would change to the current row

If you're on Windows, you can achieve the same thing by repeatedly pressing F4 while in the formula editing bar. The first F4 press will static both (it will turn A1 into $A$1), then just the row (A$1) then just the column ($A1)

Although technically with the formulas that you have, dragging down for the entirety of the column shouldn't be a problem without putting a $ sign in front of the column. Setting the column as static would only come into play if you're dragging ACROSS columns and want to keep using the same column, and setting the row as static would be for dragging down rows but wanting to use the same row.

Is it possible to view RabbitMQ message contents directly from the command line?

you can use RabbitMQ API to get count or messages :

/api/queues/vhost/name/get

Get messages from a queue. (This is not an HTTP GET as it will alter the state of the queue.) You should post a body looking like:

{"count":5,"requeue":true,"encoding":"auto","truncate":50000}

count controls the maximum number of messages to get. You may get fewer messages than this if the queue cannot immediately provide them.

requeue determines whether the messages will be removed from the queue. If requeue is true they will be requeued - but their redelivered flag will be set. encoding must be either "auto" (in which case the payload will be returned as a string if it is valid UTF-8, and base64 encoded otherwise), or "base64" (in which case the payload will always be base64 encoded). If truncate is present it will truncate the message payload if it is larger than the size given (in bytes). truncate is optional; all other keys are mandatory.

Please note that the publish / get paths in the HTTP API are intended for injecting test messages, diagnostics etc - they do not implement reliable delivery and so should be treated as a sysadmin's tool rather than a general API for messaging.

http://hg.rabbitmq.com/rabbitmq-management/raw-file/rabbitmq_v3_1_3/priv/www/api/index.html

Make a div fill the height of the remaining screen space

 style="height:100vh"

solved the problem for me. In my case I applied this to the required div

Excel Define a range based on a cell value

Say you have number 1,2,3,4,5,6, in cell A1,A2,A3,A4,A5,A6 respectively. in cell A7 we calculate the sum of A1:Ax. x is specified in cell B1 (in this case, x can be any number from 1 to 6). in cell A7, you can write the following formular:

=SUM(A1:INDIRECT(CONCATENATE("A",B1)))

CONCATENATE will give you the index of the cell Ax(if you put 3 in B1, CONCATENATE("A",B1)) gives A3).

INDIRECT convert "A3" to a index.

see this link Using the value in a cell as a cell reference in a formula?

How to run a .awk file?

If you put #!/bin/awk -f on the first line of your AWK script it is easier. Plus editors like Vim and ... will recognize the file as an AWK script and you can colorize. :)

#!/bin/awk -f
BEGIN {}  # Begin section
{}        # Loop section
END{}     # End section

Change the file to be executable by running:

chmod ugo+x ./awk-script

and you can then call your AWK script like this:

`$ echo "something" | ./awk-script`

Download file from web in Python 3

I hope I understood the question right, which is: how to download a file from a server when the URL is stored in a string type?

I download files and save it locally using the below code:

import requests

url = 'https://www.python.org/static/img/python-logo.png'
fileName = 'D:\Python\dwnldPythonLogo.png'
req = requests.get(url)
file = open(fileName, 'wb')
for chunk in req.iter_content(100000):
    file.write(chunk)
file.close()

View HTTP headers in Google Chrome?

My favorite way in Chrome is clicking on a bookmarklet:

javascript:(function(){function read(url){var r=new XMLHttpRequest();r.open('HEAD',url,false);r.send(null);return r.getAllResponseHeaders();}alert(read(window.location))})();

Put this code in your developer console pad.

Source: http://www.danielmiessler.com/blog/a-bookmarklet-that-displays-http-headers

How to do encryption using AES in Openssl

Check out this link it has a example code to encrypt/decrypt data using AES256CBC using EVP API.

https://github.com/saju/misc/blob/master/misc/openssl_aes.c

Also you can check the use of AES256 CBC in a detailed open source project developed by me at https://github.com/llubu/mpro

The code is detailed enough with comments and if you still need much explanation about the API itself i suggest check out this book Network Security with OpenSSL by Viega/Messier/Chandra (google it you will easily find a pdf of this..) read chapter 6 which is specific to symmetric ciphers using EVP API.. This helped me a lot actually understanding the reasons behind using various functions and structures of EVP.

and if you want to dive deep into the Openssl crypto library, i suggest download the code from the openssl website (the version installed on your machine) and then look in the implementation of EVP and aeh api implementation.

One more suggestion from the code you posted above i see you are using the api from aes.h instead use EVP. Check out the reason for doing this here OpenSSL using EVP vs. algorithm API for symmetric crypto nicely explained by Daniel in one of the question asked by me..

Meaning of @classmethod and @staticmethod for beginner?

A slightly different way to think about it that might be useful for someone... A class method is used in a superclass to define how that method should behave when it's called by different child classes. A static method is used when we want to return the same thing regardless of the child class that we are calling.

How to create a JQuery Clock / Timer

    var timeInterval = 5;
    var blinkTime = 1;
    var open_signal = 'signal1';
    var total_signal = 1;

    $(document).ready(function () {
        for (var i = 1; i <= total_signal; i++) {
            var timer = (i == 1) ? timeInterval : (timeInterval * (i - 1));

            var str_html = '<div id="signal' + i + '">' +
                           '<span class="float_left">Signal ' + i + ' : </span>' +
                           '<div class="red float_left"></div>' +
                           '<div class="yellow float_left"></div>' +
                           '<div class="green float_left"></div>' +
                           '<div class="timer float_left">' + timer + '</div>' +
                           '<div style="clear: both;"></div>' +
                           '</div><div class="div_separate"></div>';

            $('.div_demo').append(str_html);
        }

        $('.div_demo .green').eq(0).css('background-color', 'green');
        $('.div_demo .red').css('background-color', 'red');
        $('.div_demo .red').eq(0).css('background-color', 'white');

        setInterval(function () {
            manageSignals();
        }, 1000);
    });

    function manageSignals() {
        var obj_timer = {};

        var temp_i = parseInt(open_signal.substr(6));
        if ($('#' + open_signal + ' .timer').html() == '0')
            open_signal = (temp_i == total_signal) ? 'signal1' : 'signal' + (temp_i + 1);

        for (var i = 1; i <= total_signal; i++) {
            var next_signal = (i == total_signal) ? 'signal1' : 'signal' + (i + 1);

            obj_timer['signal' + i] = parseInt($('#signal' + i + ' .timer').html()) - 1;

            if (obj_timer['signal' + i] == -1 && open_signal == next_signal && total_signal!=1) {
                obj_timer['signal' + i] = (timeInterval * (total_signal - 1)) - 1;

                $('#signal' + i + ' .red').css('background-color', 'red');
                $('#signal' + i + ' .yellow').css('background-color', 'white');
            }
            else if (obj_timer['signal' + i] == -1 && open_signal == 'signal' + i) {
                obj_timer['signal' + i] = (timeInterval - 1);

                $('#signal' + i + ' .red').css('background-color', 'white');
                $('#signal' + i + ' .yellow').css('background-color', 'white');
                $('#signal' + i + ' .green').css('background-color', 'green');
            }
            else if (obj_timer['signal' + i] == blinkTime && open_signal == 'signal' + i) {
                $('#signal' + i + ' .yellow').css('background-color', 'yellow');
                $('#signal' + i + ' .green').css('background-color', 'white');
            }

            $('#signal' + i + ' .timer').html(obj_timer['signal' + i]);
        }
    }
</script>

How to delete files/subfolders in a specific directory at the command prompt in Windows

RD stands for REMOVE Directory.

/S : Delete all files and subfolders in addition to the folder itself. Use this to remove an entire folder tree.

/Q : Quiet - do not display YN confirmation

Example :

RD /S /Q C:/folder_path/here

Regular expression for letters, numbers and - _

To actually cover your pattern, i.e, valid file names according to your rules, I think that you need a little more. Note this doesn't match legal file names from a system perspective. That would be system dependent and more liberal in what it accepts. This is intended to match your acceptable patterns.

^([a-zA-Z0-9]+[_-])*[a-zA-Z0-9]+\.[a-zA-Z0-9]+$

Explanation:

  • ^ Match the start of a string. This (plus the end match) forces the string to conform to the exact expression, not merely contain a substring matching the expression.
  • ([a-zA-Z0-9]+[_-])* Zero or more occurrences of one or more letters or numbers followed by an underscore or dash. This causes all names that contain a dash or underscore to have letters or numbers between them.
  • [a-zA-Z0-9]+ One or more letters or numbers. This covers all names that do not contain an underscore or a dash.
  • \. A literal period (dot). Forces the file name to have an extension and, by exclusion from the rest of the pattern, only allow the period to be used between the name and the extension. If you want more than one extension that could be handled as well using the same technique as for the dash/underscore, just at the end.
  • [a-zA-Z0-9]+ One or more letters or numbers. The extension must be at least one character long and must contain only letters and numbers. This is typical, but if you wanted allow underscores, that could be addressed as well. You could also supply a length range {2,3} instead of the one or more + matcher, if that were more appropriate.
  • $ Match the end of the string. See the starting character.

What Vim command(s) can be used to quote/unquote words?

Here's some mapping that could help:

:nnoremap <Leader>q" ciw""<Esc>P
:nnoremap <Leader>q' ciw''<Esc>P
:nnoremap <Leader>qd daW"=substitute(@@,"'\\\|\"","","g")<CR>P

If you haven't changed the mapleader variable, then activate the mapping with \q" \q' or \qd. They add double quote around the word under the cursor, single quote around the word under the cursor, delete any quotes around the word under the cursor respectively.

How to detect orientation change?

Here is an easy way to detect the device orientation: (Swift 3)

override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
            handleViewRotaion(orientation: toInterfaceOrientation)
        }

    //MARK: - Rotation controls
    func handleViewRotaion(orientation:UIInterfaceOrientation) -> Void {
        switch orientation {
        case .portrait :
            print("portrait view")
            break
        case .portraitUpsideDown :
            print("portraitUpsideDown view")
            break
        case .landscapeLeft :
            print("landscapeLeft view")
            break
        case .landscapeRight :
            print("landscapeRight view")
            break
        case .unknown :
            break
        }
    }

JavaScript style.display="none" or jQuery .hide() is more efficient?

Talking about efficiency:

document.getElementById( 'elemtId' ).style.display = 'none';

What jQuery does with its .show() and .hide() methods is, that it remembers the last state of an element. That can come in handy sometimes, but since you asked about efficiency that doesn't matter here.

C# elegant way to check if a property's property is null

I saw something in the new C# 6.0, this is by using '?' instead of checking

for example instead of using

if (Person != null && Person.Contact!=null && Person.Contact.Address!= null && Person.Contact.Address.City != null)
{ 
  var city = person.contact.address.city;
}

you simply use

var city = person?.contact?.address?.city;

I hope it helped somebody.


UPDATE:

You could do like this now

 var city = (Person != null)? 
           ((Person.Contact!=null)? 
              ((Person.Contact.Address!= null)?
                      ((Person.Contact.Address.City!=null)? 
                                 Person.Contact.Address.City : null )
                       :null)
               :null)
            : null;

JSON.stringify doesn't work with normal Javascript array

Nice explanation and example above. I found this (JSON.stringify() array bizarreness with Prototype.js) to complete the answer. Some sites implements its own toJSON with JSONFilters, so delete it.

if(window.Prototype) {
    delete Object.prototype.toJSON;
    delete Array.prototype.toJSON;
    delete Hash.prototype.toJSON;
    delete String.prototype.toJSON;
}

it works fine and the output of the test:

console.log(json);

Result:

"{"a":"test","b":["item","item2","item3"]}"

Setting selected values for ng-options bound select elements

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

How to zip a file using cmd line?

tar.exe -acf out.zip in.txt

out.zip is an output folder or filename and in.txt is an input folder or filename. To use this command you should be in the file existing folder.

Go to next item in ForEach-Object

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

How to convert a file into a dictionary?

def get_pair(line):
    key, sep, value = line.strip().partition(" ")
    return int(key), value

with open("file.txt") as fd:    
    d = dict(get_pair(line) for line in fd)

how to execute php code within javascript

put your php into a hidden div and than call it with javascript

php part

<div id="mybox" style="visibility:hidden;"> some php here </div>

javascript part

var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';

now, you can do anything with myfield...

Target WSGI script cannot be loaded as Python module

As this question became sort of a pool for collecting solutions for problems that result in the error giving this question its title, I'd like to add this one, too.

In my case, I want to run OpenStack Keystone (Ocata) using Apache and WSGI on Ubuntu 16.04.2. The processes start but as soon as I query keystone I get

mod_wsgi (pid=20103): Target WSGI script '/opt/openstack/bin/keystone-wsgi-public' cannot be loaded as Python module.

I had two vhosts, one had

WSGIDaemonProcess keystone-public ...
WSGIProcessGroup keystone-public ...

while the other had

WSGIDaemonProcess keystone-admin ...
WSGIProcessGroup keystone-admin ...

I solved the problem by renaming them. The vhost entries now read:

WSGIDaemonProcess kst-pub ...
WSGIProcessGroup kst-pub ...

and

WSGIDaemonProcess kst-adm ...
WSGIProcessGroup kst-adm ...

I didn't investigate any further. Solved as works for me.

Bootstrap 4: responsive sidebar menu to top navbar

Big screen:

navigation side bar in big screen size

Small screen (Mobile)

sidebar in small mobile size screen

if this is what you wanted this is code https://plnkr.co/edit/PCCJb9f7f93HT4OubLmM?p=preview

CSS + HTML + JQUERY :

_x000D_
_x000D_
    _x000D_
    @import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";_x000D_
    body {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      background: #fafafa;_x000D_
    }_x000D_
    _x000D_
    p {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      font-size: 1.1em;_x000D_
      font-weight: 300;_x000D_
      line-height: 1.7em;_x000D_
      color: #999;_x000D_
    }_x000D_
    _x000D_
    a,_x000D_
    a:hover,_x000D_
    a:focus {_x000D_
      color: inherit;_x000D_
      text-decoration: none;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    .navbar {_x000D_
      padding: 15px 10px;_x000D_
      background: #fff;_x000D_
      border: none;_x000D_
      border-radius: 0;_x000D_
      margin-bottom: 40px;_x000D_
      box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
    }_x000D_
    _x000D_
    .navbar-btn {_x000D_
      box-shadow: none;_x000D_
      outline: none !important;_x000D_
      border: none;_x000D_
    }_x000D_
    _x000D_
    .line {_x000D_
      width: 100%;_x000D_
      height: 1px;_x000D_
      border-bottom: 1px dashed #ddd;_x000D_
      margin: 40px 0;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    SIDEBAR STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #sidebar {_x000D_
      width: 250px;_x000D_
      position: fixed;_x000D_
      top: 0;_x000D_
      left: 0;_x000D_
      height: 100vh;_x000D_
      z-index: 999;_x000D_
      background: #7386D5;_x000D_
      color: #fff !important;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    #sidebar.active {_x000D_
      margin-left: -250px;_x000D_
    }_x000D_
    _x000D_
    #sidebar .sidebar-header {_x000D_
      padding: 20px;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul.components {_x000D_
      padding: 20px 0;_x000D_
      border-bottom: 1px solid #47748b;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul p {_x000D_
      color: #fff;_x000D_
      padding: 10px;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a {_x000D_
      padding: 10px;_x000D_
      font-size: 1.1em;_x000D_
      display: block;_x000D_
      color:white;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a:hover {_x000D_
      color: #7386D5;_x000D_
      background: #fff;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li.active>a,_x000D_
    a[aria-expanded="true"] {_x000D_
      color: #fff;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    a[data-toggle="collapse"] {_x000D_
      position: relative;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="false"]::before,_x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e259';_x000D_
      display: block;_x000D_
      position: absolute;_x000D_
      right: 20px;_x000D_
      font-family: 'Glyphicons Halflings';_x000D_
      font-size: 0.6em;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e260';_x000D_
    }_x000D_
    _x000D_
    ul ul a {_x000D_
      font-size: 0.9em !important;_x000D_
      padding-left: 30px !important;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs {_x000D_
      padding: 20px;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs a {_x000D_
      text-align: center;_x000D_
      font-size: 0.9em !important;_x000D_
      display: block;_x000D_
      border-radius: 5px;_x000D_
      margin-bottom: 5px;_x000D_
    }_x000D_
    _x000D_
    a.download {_x000D_
      background: #fff;_x000D_
      color: #7386D5;_x000D_
    }_x000D_
    _x000D_
    a.article,_x000D_
    a.article:hover {_x000D_
      background: #6d7fcc !important;_x000D_
      color: #fff !important;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    CONTENT STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #content {_x000D_
      width: calc(100% - 250px);_x000D_
      padding: 40px;_x000D_
      min-height: 100vh;_x000D_
      transition: all 0.3s;_x000D_
      position: absolute;_x000D_
      top: 0;_x000D_
      right: 0;_x000D_
    }_x000D_
    _x000D_
    #content.active {_x000D_
      width: 100%;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    MEDIAQUERIES_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    @media (max-width: 768px) {_x000D_
      #sidebar {_x000D_
        margin-left: -250px;_x000D_
      }_x000D_
      #sidebar.active {_x000D_
        margin-left: 0;_x000D_
      }_x000D_
      #content {_x000D_
        width: 100%;_x000D_
      }_x000D_
      #content.active {_x000D_
        width: calc(100% - 250px);_x000D_
      }_x000D_
      #sidebarCollapse span {_x000D_
        display: none;_x000D_
      }_x000D_
    }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
_x000D_
  <title>Collapsible sidebar using Bootstrap 3</title>_x000D_
_x000D_
  <!-- Bootstrap CSS CDN -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <!-- Our Custom CSS -->_x000D_
  <link rel="stylesheet" href="style2.css">_x000D_
  <!-- Scrollbar Custom CSS -->_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
  <div class="wrapper">_x000D_
    <!-- Sidebar Holder -->_x000D_
    <nav id="sidebar">_x000D_
      <div class="sidebar-header">_x000D_
        <h3>Header as you want </h3>_x000D_
        </h3>_x000D_
      </div>_x000D_
_x000D_
      <ul class="list-unstyled components">_x000D_
        <p>Dummy Heading</p>_x000D_
        <li class="active">_x000D_
          <a href="#menu">Animación</a>_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Ilustración</a>_x000D_
_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Interacción</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Blog</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Acerca</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">contacto</a>_x000D_
        </li>_x000D_
_x000D_
_x000D_
      </ul>_x000D_
_x000D_
_x000D_
    </nav>_x000D_
_x000D_
    <!-- Page Content Holder -->_x000D_
    <div id="content">_x000D_
_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container-fluid">_x000D_
_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
                                <i class="glyphicon glyphicon-align-left"></i>_x000D_
                                <span>Toggle Sidebar</span>_x000D_
                            </button>_x000D_
          </div>_x000D_
_x000D_
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="#">Page</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </nav>_x000D_
_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
  <!-- jQuery CDN -->_x000D_
  <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>_x000D_
  <!-- Bootstrap Js CDN -->_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <!-- jQuery Custom Scroller CDN -->_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>_x000D_
_x000D_
  <script type="text/javascript">_x000D_
    $(document).ready(function() {_x000D_
_x000D_
_x000D_
      $('#sidebarCollapse').on('click', function() {_x000D_
        $('#sidebar, #content').toggleClass('active');_x000D_
        $('.collapse.in').toggleClass('in');_x000D_
        $('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_
      });_x000D_
    });_x000D_
  </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

if this is what you want .

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

Persist javascript variables across pages?

I recommend web storage. Example:

// Storing the data: localStorage.setItem("variableName","Text"); // Receiving the data: localStorage.getItem("variableName");

Just replace variable with your variable name and text with what you want to store. According to W3Schools, it's better than cookies.

SMTP connect() failed PHPmailer - PHP

 $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

How can I use Helvetica Neue Condensed Bold in CSS?

"Helvetica Neue Condensed Bold" get working with firefox:

.class {
  font-family: "Helvetica Neue";
  font-weight: bold;
  font-stretch: condensed;
}

But it's fail with Opera.

Checking for an empty field with MySQL

check this code for the problem:

$sql = "SELECT * FROM tablename WHERE condition";

$res = mysql_query($sql);

while ($row = mysql_fetch_assoc($res)) {

    foreach($row as $key => $field) {  

        echo "<br>";

        if(empty($row[$key])){

            echo $key." : empty field :"."<br>"; 

        }else{

        echo $key." =" . $field."<br>";     

        }
    }
}

How to view the committed files you have not pushed yet?

I'm not great with Git, but this is what I do. This does not necessarily compare with the remote repo, but you can modify the git diff with the appropriate commit hash from the remote.

Say you made one commit that you haven't pushed...

First find the last two commits...

git log -2

This shows the last commit first, and descends from there...

[jason:~/git/my_project] git log -2
commit ea7937edc8b10
Author: xyz
Date:   Wed Jul 27 14:06:41 2016 -0500

    Made a change in July

commit 52f9bf7956f0
Author: xyz
Date:   Tue Jun 14 14:29:52 2016 -0500

    Made a change in June

Now just use the two commit hashes (which I abbreviated) to run a diff:

git diff 52f9bf7956f0 ea7937edc8b10

HTML5 input type range show range value

Try This :

 <input min="0" max="100" id="when_change_range" type="range">
 <input type="text" id="text_for_show_range">

and in jQuery section :

 $('#when_change_range').change(function(){
 document.getElementById('text_for_show_range').value=$(this).val();
  });

Duplicate / Copy records in the same MySQL table

You KNOW for sure, that the DUPLICATE KEY will trigger, thus you can select the MAX(ID)+1 beforehand:

INSERT INTO invoices SELECT MAX(ID)+1, ... other fields ... FROM invoices AS iv WHERE iv.ID=XXXXX 

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

No indexer? Then make your own!

I've globally defined this as an easy way to define an object signature. T can be any if needed:

type Indexer<T> = { [ key: string ]: T };

I just add indexer as a class member.

indexer = this as unknown as Indexer<Fruit>;

So I end up with this:

constructor(private breakpointResponsiveService: FeatureBoxBreakpointResponsiveService) {

}

apple: Fruit<string>;
pear: Fruit<string>;

// just a reference to 'this' at runtime
indexer = this as unknown as Indexer<Fruit>;

something() {

    this.indexer['apple'] = ...    // typed as Fruit

Benefit of doing this is that you get the proper type back - many solutions that use <any> will lose the typing for you. Remember this doesn't perform any runtime verification. You'll still need to check if something exists if you don't know for sure it exists.

If you want to be overly cautious, and you're using strict you can do this to reveal all the places you may need to do an explicit undefined check:

type OptionalIndexed<T> = { [ key: string ]: T | undefined };

I don't usually find this necessary since if I have as a string property from somewhere I usually know that it's valid.

I've found this method especially useful if I have a lot of code that needs to access the indexer, and the typing can be changed in just one place.

Note: I'm using strict mode, and the unknown is definitely necessary.

The compiled code will just be indexer = this, so it's very similar to when typescript creates _this = this for you.

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

SimpleDateFormat("MM-dd-yyyy");

instead of

SimpleDateFormat("mm-dd-yyyy");

because MM points Month, mm points minutes

SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);

x86 Assembly on a Mac

Also, on the Intel Macs, can I use generic x86 asm? or is there a modified instruction set? Any information about post Intel Mac assembly helps.

It's the same instruction set; it's the same chips.

How do I change db schema to dbo

You can batch change schemas of multiple database objects as described in this post:

How to change schema of all tables, views and stored procedures in MSSQL

What is the purpose of the word 'self'?

Let's say you have a class ClassA which contains a method methodA defined as:

def methodA(self, arg1, arg2):
    # do something

and ObjectA is an instance of this class.

Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as:

ClassA.methodA(ObjectA, arg1, arg2)

The self variable refers to the object itself.

jquery Ajax call - data parameters are not being passed to MVC Controller action

  var json = {"ListID" : "1", "ItemName":"test"};
    $.ajax({
            url: url,
            type: 'POST',        
            data: username, 
            cache:false,
            beforeSend: function(xhr) {  
                xhr.setRequestHeader("Accept", "application/json");  
                xhr.setRequestHeader("Content-Type", "application/json");  
            },       
            success:function(response){
             console.log("Success")
            },
              error : function(xhr, status, error) {
            console.log("error")
            }
);

React-router: How to manually invoke Link?

React Router 4 includes a withRouter HOC that gives you access to the history object via this.props:

import React, {Component} from 'react'
import {withRouter} from 'react-router-dom'

class Foo extends Component {
  constructor(props) {
    super(props)

    this.goHome = this.goHome.bind(this)
  }

  goHome() {
    this.props.history.push('/')
  }

  render() {
    <div className="foo">
      <button onClick={this.goHome} />
    </div>
  }
}

export default withRouter(Foo)

How can I run a html file from terminal?

we could open html file from linux/unix by using firefox .html

Algorithm to compare two images

In the form described by you, the problem is tough. Do you consider copy, paste of part of the image into another larger image as a copy ? etc.

If you take a step-back, this is easier to solve if you watermark the master images. You will need to use a watermarking scheme to embed a code into the image. To take a step back, as opposed to some of the low-level approaches (edge detection etc) suggested by some folks, a watermarking method is superior because:

It is resistant to Signal processing attacks ? Signal enhancement – sharpening, contrast, etc. ? Filtering – median, low pass, high pass, etc. ? Additive noise – Gaussian, uniform, etc. ? Lossy compression – JPEG, MPEG, etc.

It is resistant to Geometric attacks ? Affine transforms ? Data reduction – cropping, clipping, etc. ? Random local distortions ? Warping

Do some research on watermarking algorithms and you will be on the right path to solving your problem. ( Note: You can benchmark you method using the STIRMARK dataset. It is an accepted standard for this type of application.

Rename a column in MySQL

Use the following query:

ALTER TABLE tableName CHANGE oldcolname newcolname datatype(length);

The RENAME function is used in Oracle databases.

ALTER TABLE tableName RENAME COLUMN oldcolname TO newcolname datatype(length);

@lad2025 mentions it below, but I thought it'd be nice to add what he said. Thank you @lad2025!

You can use the RENAME COLUMN in MySQL 8.0 to rename any column you need renamed.

ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;

ALTER TABLE Syntax: RENAME COLUMN:

  • Can change a column name but not its definition.
  • More convenient than CHANGE to rename a column without changing its definition.

Create database from command line

PGPORT=5432
PGHOST="my.database.domain.com"
PGUSER="postgres"
PGDB="mydb"
createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB

How to detect the swipe left or Right in Android?

the best answer is @Gal Rom 's. there is more information about it: touch event return's to child views first. and if you define onClick or onTouch listener for them, parnt view (for example fragment) will not receive any touch listener. So if you want define swipe listener for fragment in this situation, you must implement it in a new class:

    package com.neganet.QRelations.fragments;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout;

public class SwipeListenerFragment extends FrameLayout {
    private float x1,x2;
    static final int MIN_DISTANCE=150;
    private onSwipeEventDetected mSwipeDetectedListener;


    public SwipeListenerFragment(Context context) {
        super(context);
    }

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

    public SwipeListenerFragment(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean result=false;
        switch(ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                x1 = ev.getX();
                break;
            case MotionEvent.ACTION_UP:
                x2 = ev.getX();
                float deltaX = x2 - x1;
                if (Math.abs(deltaX) > MIN_DISTANCE)
                {
                    if(deltaX<0)
                    {
                        result=true;
                        if(mSwipeDetectedListener!=null)
                            mSwipeDetectedListener.swipeLeftDetected();

                    }else if(deltaX>0){
                        result=true;
                        if(mSwipeDetectedListener!=null)
                            mSwipeDetectedListener.swipeRightDetected();
                    }
                }
                break;
        }
        return result;
    }

    public interface onSwipeEventDetected
    {
        public void swipeLeftDetected();
        public void swipeRightDetected();

    }

    public void registerToSwipeEvents(onSwipeEventDetected listener)
    {
        this.mSwipeDetectedListener=listener;
    }
}

I changed @Gal Rom 's class. So it can detect both right and left swipe and specially it returns onInterceptTouchEvent true after detect. its important because if we dont do it some times child views maybe receive event and both of Swipe for fragment and onClick for child view (for example) runs and cause some issues. after making this class, you must change your fragment xml file:

    <com.neganet.QRelations.fragments.SwipeListenerFragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:id="@+id/main_list_layout"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_height="match_parent" tools:context="com.neganet.QRelations.fragments.mainList"
    android:background="@color/main_frag_back">

    <!-- TODO: Update blank fragment layout -->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/farazList"
        android:scrollbars="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="left|center_vertical" />
</com.neganet.QRelations.fragments.SwipeListenerFragment>

you see that begin tag is the class that we made. now in fragment class:

            View view=inflater.inflate(R.layout.fragment_main_list, container, false);
        SwipeListenerFragment tdView=(SwipeListenerFragment) view;
        tdView.registerToSwipeEvents(this);


and then Implement SwipeListenerFragment.onSwipeEventDetected in it:

        @Override
    public void swipeLeftDetected() {
        Toast.makeText(getActivity(), "left", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void swipeRightDetected() {
        Toast.makeText(getActivity(), "right", Toast.LENGTH_SHORT).show();
    }

It's a little complicated but works perfect :)

JavaScript - Replace all commas in a string

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

_x000D_
_x000D_
var myStr = 'this,is,a,test';_x000D_
var newStr = myStr.replace(/,/g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

Still have issues?

It is important to note, that regular expressions use special characters that need to be escaped. As an example, if you need to escape a dot (.) character, you should use /\./ literal, as in the regex syntax a dot matches any single character (except line terminators).

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var newStr = myStr.replace(/\./g, '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \ when included in a string) will be necessary.

_x000D_
_x000D_
var myStr = 'this.is.a.test';_x000D_
var reStr = '\\.';_x000D_
var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');_x000D_
_x000D_
console.log( newStr );  // "this-is-a-test"
_x000D_
_x000D_
_x000D_

datetimepicker is not a function jquery

It's all about the order of the scripts. Try to reorder them, place jquery.datetimepicker.js to be last of all scripts!

Why does HTML think “chucknorris” is a color?

The rules for parsing colors on legacy attributes involves additional steps than those mentioned in existing answers. The truncate component to 2 digits part is described as:

  1. Discard all characters except the last 8
  2. Discard leading zeros one by one as long as all components have a leading zero
  3. Discard all characters except the first 2

Some examples:

oooFoooFoooF
000F 000F 000F                <- replace, pad and chunk
0F 0F 0F                      <- leading zeros truncated
0F 0F 0F                      <- truncated to 2 characters from right

oooFooFFoFFF
000F 00FF 0FFF                <- replace, pad and chunk
00F 0FF FFF                   <- leading zeros truncated
00 0F FF                      <- truncated to 2 characters from right

ABCooooooABCooooooABCoooooo
ABC000000 ABC000000 ABC000000 <- replace, pad and chunk
BC000000 BC000000 BC000000    <- truncated to 8 characters from left
BC BC BC                      <- truncated to 2 characters from right

AoCooooooAoCooooooAoCoooooo
A0C000000 A0C000000 A0C000000 <- replace, pad and chunk
0C000000 0C000000 0C000000    <- truncated to 8 characters from left
C000000 C000000 C000000       <- leading zeros truncated
C0 C0 C0                      <- truncated to 2 characters from right

Below is a partial implementation of the algorithm. It does not handle errors or cases where the user enters a valid color.

_x000D_
_x000D_
function parseColor(input) {_x000D_
  // todo: return error if input is ""_x000D_
  input = input.trim();_x000D_
  // todo: return error if input is "transparent"_x000D_
  // todo: return corresponding #rrggbb if input is a named color_x000D_
  // todo: return #rrggbb if input matches #rgb_x000D_
  // todo: replace unicode code points greater than U+FFFF with 00_x000D_
  if (input.length > 128) {_x000D_
    input = input.slice(0, 128);_x000D_
  }_x000D_
  if (input.charAt(0) === "#") {_x000D_
    input = input.slice(1);_x000D_
  }_x000D_
  input = input.replace(/[^0-9A-Fa-f]/g, "0");_x000D_
  while (input.length === 0 || input.length % 3 > 0) {_x000D_
    input += "0";_x000D_
  }_x000D_
  var r = input.slice(0, input.length / 3);_x000D_
  var g = input.slice(input.length / 3, input.length * 2 / 3);_x000D_
  var b = input.slice(input.length * 2 / 3);_x000D_
  if (r.length > 8) {_x000D_
    r = r.slice(-8);_x000D_
    g = g.slice(-8);_x000D_
    b = b.slice(-8);_x000D_
  }_x000D_
  while (r.length > 2 && r.charAt(0) === "0" && g.charAt(0) === "0" && b.charAt(0) === "0") {_x000D_
    r = r.slice(1);_x000D_
    g = g.slice(1);_x000D_
    b = b.slice(1);_x000D_
  }_x000D_
  if (r.length > 2) {_x000D_
    r = r.slice(0, 2);_x000D_
    g = g.slice(0, 2);_x000D_
    b = b.slice(0, 2);_x000D_
  }_x000D_
  return "#" + r.padStart(2, "0") + g.padStart(2, "0") + b.padStart(2, "0");_x000D_
}_x000D_
_x000D_
$(function() {_x000D_
  $("#input").on("change", function() {_x000D_
    var input = $(this).val();_x000D_
    var color = parseColor(input);_x000D_
    var $cells = $("#result tbody td");_x000D_
    $cells.eq(0).attr("bgcolor", input);_x000D_
    $cells.eq(1).attr("bgcolor", color);_x000D_
_x000D_
    var color1 = $cells.eq(0).css("background-color");_x000D_
    var color2 = $cells.eq(1).css("background-color");_x000D_
    $cells.eq(2).empty().append("bgcolor: " + input, "<br>", "getComputedStyle: " + color1);_x000D_
    $cells.eq(3).empty().append("bgcolor: " + color, "<br>", "getComputedStyle: " + color2);_x000D_
  });_x000D_
});
_x000D_
body { font: medium monospace; }_x000D_
input { width: 20em; }_x000D_
table { table-layout: fixed; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
_x000D_
<p><input id="input" placeholder="Enter color e.g. chucknorris"></p>_x000D_
<table id="result">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Left Color</th>_x000D_
      <th>Right Color</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to draw text using only OpenGL methods?

enter image description here

Use glutStrokeCharacter(GLUT_STROKE_ROMAN, myCharString).

An example: A STAR WARS SCROLLER.

#include <windows.h>
#include <string.h>
#include <GL\glut.h>
#include <iostream.h>
#include <fstream.h>

GLfloat UpwardsScrollVelocity = -10.0;
float view=20.0;

char quote[6][80];
int numberOfQuotes=0,i;

//*********************************************
//*  glutIdleFunc(timeTick);                  *
//*********************************************

void timeTick(void)
{
    if (UpwardsScrollVelocity< -600)
        view-=0.000011;
    if(view < 0) {view=20; UpwardsScrollVelocity = -10.0;}
    //  exit(0);
    UpwardsScrollVelocity -= 0.015;
  glutPostRedisplay();

}


//*********************************************
//* printToConsoleWindow()                *
//*********************************************

void printToConsoleWindow()
{
    int l,lenghOfQuote, i;

    for(  l=0;l<numberOfQuotes;l++)
    {
        lenghOfQuote = (int)strlen(quote[l]);

        for (i = 0; i < lenghOfQuote; i++)
        {
          //cout<<quote[l][i];
        }
          //out<<endl;
    }

}

//*********************************************
//* RenderToDisplay()                       *
//*********************************************

void RenderToDisplay()
{
    int l,lenghOfQuote, i;

    glTranslatef(0.0, -100, UpwardsScrollVelocity);
    glRotatef(-20, 1.0, 0.0, 0.0);
    glScalef(0.1, 0.1, 0.1);



    for(  l=0;l<numberOfQuotes;l++)
    {
        lenghOfQuote = (int)strlen(quote[l]);
        glPushMatrix();
        glTranslatef(-(lenghOfQuote*37), -(l*200), 0.0);
        for (i = 0; i < lenghOfQuote; i++)
        {
            glColor3f((UpwardsScrollVelocity/10)+300+(l*10),(UpwardsScrollVelocity/10)+300+(l*10),0.0);
            glutStrokeCharacter(GLUT_STROKE_ROMAN, quote[l][i]);
        }
        glPopMatrix();
    }

}
//*********************************************
//* glutDisplayFunc(myDisplayFunction);       *
//*********************************************

void myDisplayFunction(void)
{
  glClear(GL_COLOR_BUFFER_BIT);
  glLoadIdentity();
  gluLookAt(0.0, 30.0, 100.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
  RenderToDisplay();
  glutSwapBuffers();
}
//*********************************************
//* glutReshapeFunc(reshape);               *
//*********************************************

void reshape(int w, int h)
{
  glViewport(0, 0, w, h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(60, 1.0, 1.0, 3200);
  glMatrixMode(GL_MODELVIEW);
}

//*********************************************
//* int main()                                *
//*********************************************


int main()
{
    strcpy(quote[0],"Luke, I am your father!.");
    strcpy(quote[1],"Obi-Wan has taught you well. ");
    strcpy(quote[2],"The force is strong with this one. ");
    strcpy(quote[3],"Alert all commands. Calculate every possible destination along their last known trajectory. ");
    strcpy(quote[4],"The force is with you, young Skywalker, but you are not a Jedi yet.");
    numberOfQuotes=5;

    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(800, 400);
    glutCreateWindow("StarWars scroller");
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glLineWidth(3);

    glutDisplayFunc(myDisplayFunction);
    glutReshapeFunc(reshape);
    glutIdleFunc(timeTick);
    glutMainLoop();

    return 0;
}

T-SQL split string

Instead of recursive CTEs and while loops, has anyone considered a more set-based approach? Note that this function was written for the question, which was based on SQL Server 2008 and comma as the delimiter. In SQL Server 2016 and above (and in compatibility level 130 and above), STRING_SPLIT() is a better option.

CREATE FUNCTION dbo.SplitString
(
  @List     nvarchar(max),
  @Delim    nvarchar(255)
)
RETURNS TABLE
AS
  RETURN ( SELECT [Value] FROM 
  ( 
    SELECT [Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],
      CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))
    FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
      FROM sys.all_columns) AS x WHERE Number <= LEN(@List)
      AND SUBSTRING(@Delim + @List, [Number], DATALENGTH(@Delim)/2) = @Delim
    ) AS y
  );
GO

If you want to avoid the limitation of the length of the string being <= the number of rows in sys.all_columns (9,980 in model in SQL Server 2017; much higher in your own user databases), you can use other approaches for deriving the numbers, such as building your own table of numbers. You could also use a recursive CTE in cases where you can't use system tables or create your own:

CREATE FUNCTION dbo.SplitString
(
  @List     nvarchar(max),
  @Delim    nvarchar(255)
)
RETURNS TABLE WITH SCHEMABINDING
AS
   RETURN ( WITH n(n) AS (SELECT 1 UNION ALL SELECT n+1 
       FROM n WHERE n <= LEN(@List))
       SELECT [Value] = SUBSTRING(@List, n, 
       CHARINDEX(@Delim, @List + @Delim, n) - n)
       FROM n WHERE n <= LEN(@List)
      AND SUBSTRING(@Delim + @List, n, DATALENGTH(@Delim)/2) = @Delim
   );
GO

But you'll have to append OPTION (MAXRECURSION 0) (or MAXRECURSION <longest possible string length if < 32768>) to the outer query in order to avoid errors with recursion for strings > 100 characters. If that is also not a good alternative then see this answer as pointed out in the comments.

(Also, the delimiter will have to be NCHAR(<=1228). Still researching why.)

More on split functions, why (and proof that) while loops and recursive CTEs don't scale, and better alternatives, if splitting strings coming from the application layer:

javax vs java package

The javax namespace is usually (that's a loaded word) used for standard extensions, currently known as optional packages. The standard extensions are a subset of the non-core APIs; the other segment of the non-core APIs obviously called the non-standard extensions, occupying the namespaces like com.sun.* or com.ibm.. The core APIs take up the java. namespace.

Not everything in the Java API world starts off in core, which is why extensions are usually born out of JSR requests. They are eventually promoted to core based on 'wise counsel'.

The interest in this nomenclature, came out of a faux pas on Sun's part - extensions could have been promoted to core, i.e. moved from javax.* to java.* breaking the backward compatibility promise. Programmers cried hoarse, and better sense prevailed. This is why, the Swing API although part of the core, continues to remain in the javax.* namespace. And that is also how packages get promoted from extensions to core - they are simply made available for download as part of the JDK and JRE.

Python: 'break' outside loop

Because break can only be used inside a loop. It is used to break out of a loop (stop the loop).

How to insert data into elasticsearch

To avoid using curl or Chrome plugins you can just use the the built in windows Powershell. From the Powershell command window run

Invoke-WebRequest -UseBasicParsing "http://127.0.0.1:9200/sampleindex/sampleType/" -
Method POST -ContentType "application/json" -Body '{
"user" : "Test",
"post_date" : "2017/11/13 11:07:00",
"message" : "trying out Elasticsearch"
}'

Note the Index name MUST be in lowercase.

How do pointer-to-pointer's work in C? (and when might you use them?)

How it works: It is a variable that can store another pointer.

When would you use them : Many uses one of them is if your function wants to construct an array and return it to the caller.

//returns the array of roll nos {11, 12} through paramater
// return value is total number of  students
int fun( int **i )
{
    int *j;
    *i = (int*)malloc ( 2*sizeof(int) );
    **i = 11;  // e.g., newly allocated memory 0x2000 store 11
    j = *i;
    j++;
    *j = 12; ;  // e.g., newly allocated memory 0x2004 store 12

    return 2;
}

int main()
{
    int *i;
    int n = fun( &i ); // hey I don't know how many students are in your class please send all of their roll numbers.
    for ( int j=0; j<n; j++ )
        printf( "roll no = %d \n", i[j] );

    return 0;
}

Convert Select Columns in Pandas Dataframe to Numpy Array

Please use the Pandas to_numpy() method. Below is an example--

>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1, 2], "B":[3, 4], "C":[5, 6]})
>>> df 
    A  B  C
 0  1  3  5
 1  2  4  6
>>> s_array = df[["A", "B", "C"]].to_numpy()
>>> s_array

array([[1, 3, 5],
   [2, 4, 6]]) 

>>> t_array = df[["B", "C"]].to_numpy() 
>>> print (t_array)

[[3 5]
 [4 6]]

Hope this helps. You can select any number of columns using

columns = ['col1', 'col2', 'col3']
df1 = df[columns]

Then apply to_numpy() method.

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

How to add some non-standard font to a website?

You can add some fonts via Google Web Fonts.

Technically, the fonts are hosted at Google and you link them in the HTML header. Then, you can use them freely in CSS with @font-face (read about it).

For example:

In the <head> section:

 <link href=' http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'>

Then in CSS:

h1 { font-family: 'Droid Sans', arial, serif; }

The solution seems quite reliable (even Smashing Magazine uses it for an article title.). There are, however, not so many fonts available so far in Google Font Directory.

How is a JavaScript hash map implemented?

Here is an easy and convenient way of using something similar to the Java map:

var map= {
    'map_name_1': map_value_1,
    'map_name_2': map_value_2,
    'map_name_3': map_value_3,
    'map_name_4': map_value_4
    }

And to get the value:

alert( map['map_name_1'] );    // fives the value of map_value_1

......  etc  .....

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

I was facing this issue while deploying my ear to my local weblogic instance. Clearing the local repository and building the ear again resolved the issue for me.

How to set lifetime of session

Sessions can be configured in your php.ini file or in your .htaccess file. Have a look at the PHP session documentation.

What you basically want to do is look for the line session.cookie_lifetime in php.ini and make it's value is 0 so that the session cookie is valid until the browser is closed. If you can't edit that file, you could add php_value session.cookie_lifetime 0 to your .htaccess file.

Prevent flex items from overflowing a container

max-width works for me.

aside {
  flex: 0 1 200px;
  max-width: 200px;
}

Variables of CSS pre-processors allows to avoid hard-coding.

aside {
  $WIDTH: 200px;
  flex: 0 1 $WIDTH;
  max-width: $WIDTH;
}

overflow: hidden also works, but I lately I try do not use it because it hides the elements as popups and dropdowns.

Regex for remove everything after | (with | )

In a .txt file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+ in the space Find what
and let the space Replace with blank

Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button

The request was rejected because no multipart boundary was found in springboot

Unchecked the content type in Postman and postman automatically detect the content type based on your input in the run time.

Sample

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

How to disable <br> tags inside <div> by css?

I used it like this:

@media (max-width: 450px) {
  br {
    display: none;
  }
}

nb: media query via Foundation nb2: this is useful if one of the editor intend to use
tags in his/her copy and you need to deal with it specifically under some conditions—on mobile for example.

Reactive forms - disabled attribute

I have been using [attr.disabled] because I still like this template driven than programmatic enable()/disable() as it is superior IMO.

Change

<md-input formControlName="id" placeholder="ID" [disabled]="true"></md-input>

to

<md-input formControlName="id" placeholder="ID" [attr.disabled]="true"></md-input>

If you are on newer material change md-input to mat-input.

How to install package from github repo in Yarn

I use this short format for github repositories:

yarn add github_user/repository_name#commit_hash

Set the maximum character length of a UITextField

This should be enough to solve the problem (replace 4 by the limit u want). Just make sure to add delegate in IB.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
     return (newString.length<=4);
}

Evaluate list.contains string in JSTL

The following is more of a workaround than an answer to your question but it may be what you are looking for. If you can put your values in a map instead of a list, that would solve your problem. Just map your values to a non null value and do this <c:if test="${mymap.myValue ne null}">style='display:none;'</c:if> or you can even map to style='display:none; and simply output ${mymap.myValue}

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

Set-ExecutionPolicy Unrestricted -Scope CurrentUser

This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.

Change application's starting activity

Follow to below instructions:

1:) Open your AndroidManifest.xml file.

2:) Go to the activity code which you want to make your main activity like below.

such as i want to make SplashScreen as main activity

<activity
    android:name=".SplashScreen"
    android:screenOrientation="sensorPortrait"
    android:label="City Retails">
</activity>

3:) Now copy the below code in between activity tags same as:

<activity
    android:name=".SplashScreen"
    android:screenOrientation="sensorPortrait"
    android:label="City Retails">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

and also check that newly added lines are not attached with other activity tags.

Converting string format to datetime in mm/dd/yyyy

I did like this

var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Also something that can go wrong: Make sure you exit Docker for Mac (possibly all other kind of docker installations as well).

Getting Hour and Minute in PHP

function get_time($time) {
    $duration = $time / 1000;
    $hours = floor($duration / 3600);
    $minutes = floor(($duration / 60) % 60);
    $seconds = $duration % 60;
    if ($hours != 0)
        echo "$hours:$minutes:$seconds";
    else
        echo "$minutes:$seconds";
}

get_time('1119241');

How can I simulate an array variable in MySQL?

Nowadays using a JSON array would be an obvious answer.

Since this is an old but still relevant question I produced a short example. JSON functions are available since mySQL 5.7.x / MariaDB 10.2.3

I prefer this solution over ELT() because it's really more like an array and this 'array' can be reused in the code.

But be careful: It (JSON) is certainly much slower than using a temporary table. Its just more handy. imo.

Here is how to use a JSON array:

SET @myjson = '["gmail.com","mail.ru","arcor.de","gmx.de","t-online.de",
                "web.de","googlemail.com","freenet.de","yahoo.de","gmx.net",
                "me.com","bluewin.ch","hotmail.com","hotmail.de","live.de",
                "icloud.com","hotmail.co.uk","yahoo.co.jp","yandex.ru"]';

SELECT JSON_LENGTH(@myjson);
-- result: 19

SELECT JSON_VALUE(@myjson, '$[0]');
-- result: gmail.com

And here a little example to show how it works in a function/procedure:

DELIMITER //
CREATE OR REPLACE FUNCTION example() RETURNS varchar(1000) DETERMINISTIC
BEGIN
  DECLARE _result varchar(1000) DEFAULT '';
  DECLARE _counter INT DEFAULT 0;
  DECLARE _value varchar(50);

  SET @myjson = '["gmail.com","mail.ru","arcor.de","gmx.de","t-online.de",
                "web.de","googlemail.com","freenet.de","yahoo.de","gmx.net",
                "me.com","bluewin.ch","hotmail.com","hotmail.de","live.de",
                "icloud.com","hotmail.co.uk","yahoo.co.jp","yandex.ru"]';

  WHILE _counter < JSON_LENGTH(@myjson) DO
    -- do whatever, e.g. add-up strings...
    SET _result = CONCAT(_result, _counter, '-', JSON_VALUE(@myjson, CONCAT('$[',_counter,']')), '#');

    SET _counter = _counter + 1;
  END WHILE;

  RETURN _result;
END //
DELIMITER ;

SELECT example();

Get decimal portion of a number with JavaScript

This function splits float number into integers and returns it in array:

_x000D_
_x000D_
function splitNumber(num)
{
  num = ("0" + num).match(/([0-9]+)([^0-9]([0-9]+))?/);
  return [ ~~num[1], ~~num[3] ];
}

console.log(splitNumber(3.2));     // [ 3, 2 ]
console.log(splitNumber(123.456)); // [ 123, 456 ]
console.log(splitNumber(789));     // [ 789, 0 ]
console.log(splitNumber("test"));  // [ 0, 0 ]
_x000D_
_x000D_
_x000D_

You can extend it to only return existing numbers and null if no number exists:

_x000D_
_x000D_
function splitNumber(num)
{
  num = ("" + num).match(/([0-9]+)([^0-9]([0-9]+))?/);
  return [num ? ~~num[1] : null, num && num[3] !== undefined ? ~~num[3] : null];
}

console.log(splitNumber(3.2));     // [ 3, 2 ]
console.log(splitNumber(123.456)); // [ 123, 456 ]
console.log(splitNumber(789));     // [ 789, null ]
console.log(splitNumber("test"));  // [ null, null ]
_x000D_
_x000D_
_x000D_

how to open .mat file without using MATLAB?

I didn't use it myself but heard of a simple tool (not a text editor) for this so it is definitely possible without setting up a programming environment (by installing octave or python).

A quick search hints that it was possible with total commander. (A lightweight tool with an easy point and click interface)

I would not be surprised if this still works, but I can't guarantee it.

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

You can try to turn support on in spring's converter

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // add converter suport Content-Type: 'application/x-www-form-urlencoded'
        converters.stream()
                .filter(AllEncompassingFormHttpMessageConverter.class::isInstance)
                .map(AllEncompassingFormHttpMessageConverter.class::cast)
                .findFirst()
                .ifPresent(converter -> converter.addSupportedMediaTypes(MediaType.APPLICATION_FORM_URLENCODED_VALUE));
    }

}

In which conda environment is Jupyter executing?

If the above ans doesn't work then try running conda install ipykernel in new env and then run jupyter notebook from any env, you will be able to see or switch between those kernels.

How to convert UTF8 string to byte array?

JavaScript Strings are stored in UTF-16. To get UTF-8, you'll have to convert the String yourself.

One way is to mix encodeURIComponent(), which will output UTF-8 bytes URL-encoded, with unescape, as mentioned on ecmanaut.

var utf8 = unescape(encodeURIComponent(str));

var arr = [];
for (var i = 0; i < utf8.length; i++) {
    arr.push(utf8.charCodeAt(i));
}

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

For someone looking to solve same by using maven. Add below dependency in POM:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>7.0.0.jre8</version>
</dependency>

And use below code for connection:

String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";

try {
    System.out.print("Connecting to SQL Server ... ");
    try (Connection connection = DriverManager.getConnection(connectionUrl))        {
        System.out.println("Done.");
    }
} catch (Exception e) {
    System.out.println();
    e.printStackTrace();
}

Look for this link for other CRUD type of queries.

How to center cards in bootstrap 4?

You can also use Bootstrap 4 flex classes

Like: .align-item-center and .justify-content-center

We can use these classes identically for all device view.

Like: .align-item-sm-center, .align-item-md-center, .justify-content-xl-center, .justify-content-lg-center, .justify-content-xs-center

.text-center class is used to align text in center.

Superscript in Python plots

You just need to have the full expression inside the $. Basically, you need "meters $10^1$". You don't need usetex=True to do this (or most any mathematical formula).

You may also want to use a raw string (e.g. r"\t", vs "\t") to avoid problems with things like \n, \a, \b, \t, \f, etc.

For example:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r'This is an expression $e^{\sin(\omega\phi)}$',
       xlabel='meters $10^1$', ylabel=r'Hertz $(\frac{1}{s})$')
plt.show()

enter image description here

If you don't want the superscripted text to be in a different font than the rest of the text, use \mathregular (or equivalently \mathdefault). Some symbols won't be available, but most will. This is especially useful for simple superscripts like yours, where you want the expression to blend in with the rest of the text.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r'This is an expression $\mathregular{e^{\sin(\omega\phi)}}$',
       xlabel='meters $\mathregular{10^1}$',
       ylabel=r'Hertz $\mathregular{(\frac{1}{s})}$')
plt.show()

enter image description here

For more information (and a general overview of matplotlib's "mathtext"), see: http://matplotlib.org/users/mathtext.html

How can I delay a :hover effect in CSS?

div {
     background: #dbdbdb;
    -webkit-transition: .5s all;   
    -webkit-transition-delay: 5s; 
    -moz-transition: .5s all;   
    -moz-transition-delay: 5s; 
    -ms-transition: .5s all;   
    -ms-transition-delay: 5s; 
    -o-transition: .5s all;   
    -o-transition-delay: 5s; 
    transition: .5s all;   
    transition-delay: 5s; 
}

div:hover {
    background:#5AC900;
    -webkit-transition-delay: 0s;
    -moz-transition-delay: 0s;
    -ms-transition-delay: 0s;
    -o-transition-delay: 0s;
    transition-delay: 0s;
}

This will add a transition delay, which will be applicable to almost every browser..

Pagination on a list using ng-repeat

I know this thread is old now but I am answering it to keep things a bit updated.

With Angular 1.4 and above you can directly use limitTo filter which apart from accepting the limit parameter also accepts a begin parameter.

Usage: {{ limitTo_expression | limitTo : limit : begin}}

So now you may not need to use any third party library to achieve something like pagination. I have created a fiddle to illustrate the same.

Python convert set to string and vice versa

The question is little unclear because the title of the question is asking about string and set conversion but then the question at the end asks how do I serialize ? !

let me refresh the concept of Serialization is the process of encoding an object, including the objects it refers to, as a stream of byte data.

If interested to serialize you can use:

json.dumps  -> serialize
json.loads  -> deserialize

If your question is more about how to convert set to string and string to set then use below code (it's tested in Python 3)

String to Set

set('abca')

Set to String

''.join(some_var_set)

example:

def test():
    some_var_set=set('abca')
    print("here is the set:",some_var_set,type(some_var_set))
    some_var_string=''.join(some_var_set)    
    print("here is the string:",some_var_string,type(some_var_string))

test()

iPad Multitasking support requires these orientations

as Michael said,

Check the "Requires full screen" of the target of xcodeproj, if you don't need to support multitasking.

or Check the following device orientations

  • Portrait
  • Upside Down
  • Landscape Left
  • Landscape Right

In this case, we need to support launch storyboard.

What is the role of the package-lock.json?

It stores an exact, versioned dependency tree rather than using starred versioning like package.json itself (e.g. 1.0.*). This means you can guarantee the dependencies for other developers or prod releases, etc. It also has a mechanism to lock the tree but generally will regenerate if package.json changes.

From the npm docs:

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

This file is intended to be committed into source repositories, and serves various purposes:

Describe a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.

Provide a facility for users to "time-travel" to previous states of node_modules without having to commit the directory itself.

To facilitate greater visibility of tree changes through readable source control diffs.

And optimize the installation process by allowing npm to skip repeated metadata resolutions for previously-installed packages."

Edit

To answer jrahhali's question below about just using the package.json with exact version numbers. Bear in mind that your package.json contains only your direct dependencies, not the dependencies of your dependencies (sometimes called nested dependencies). This means with the standard package.json you can't control the versions of those nested dependencies, referencing them directly or as peer dependencies won't help as you also don't control the version tolerance that your direct dependencies define for these nested dependencies.

Even if you lock down the versions of your direct dependencies you cannot 100% guarantee that your full dependency tree will be identical every time. Secondly you might want to allow non-breaking changes (based on semantic versioning) of your direct dependencies which gives you even less control of nested dependencies plus you again can't guarantee that your direct dependencies won't at some point break semantic versioning rules themselves.

The solution to all this is the lock file which as described above locks in the versions of the full dependency tree. This allows you to guarantee your dependency tree for other developers or for releases whilst still allowing testing of new dependency versions (direct or indirect) using your standard package.json.

NB. The previous shrink wrap json did pretty much the same thing but the lock file renames it so that it's function is clearer. If there's already a shrink wrap file in the project then this will be used instead of any lock file.

d3.select("#element") not working when code above the html element

<script>$(function(){var svg = d3.select("#chart").append("svg:svg");});</script>
<div id="chart"></div>

In other words, it's not happening because you can't query against something that doesn't exist yet-- so just do it after the page loads (here via jquery).

Btw, its recommended that you place your JS files before the close of your body tag.

How to run SQL script in MySQL?

So many ways to do it.

From Workbench: File > Run SQL Script -- then follow prompts

From Windows Command Line:
   Option 1: mysql -u usr -p
             mysql> source file_path.sql
   Option 2: mysql -u usr -p '-e source file_path.sql'
   Option 3: mysql -u usr -p < file_path.sql
   Option 4: put multiple 'source' statements inside of file_path.sql (I do this to drop and recreate schemas/databases which requires multiple files to be run)
             mysql -u usr -p < file_path.sql

If you get errors from the command line, make sure you have previously run

cd {!!>>mysqld.exe home directory here<<!!}
mysqld.exe --initialize 

This must be run from within the mysqld.exe directory, hence the CD.

Hope this is helpful and not just redundant.

How to check Spark Version

You can get the spark version by using the following command:

spark-submit --version

spark-shell --version

spark-sql --version

You can visit the below site to know the spark-version used in CDH 5.7.0

http://www.cloudera.com/documentation/enterprise/release-notes/topics/cdh_rn_new_in_cdh_57.html#concept_m3k_rxh_1v

Convert string to ASCII value python

It is not at all obvious why one would want to concatenate the (decimal) "ascii values". What is certain is that concatenating them without leading zeroes (or some other padding or a delimiter) is useless -- nothing can be reliably recovered from such an output.

>>> tests = ["hi", "Hi", "HI", '\x0A\x29\x00\x05']
>>> ["".join("%d" % ord(c) for c in s) for s in tests]
['104105', '72105', '7273', '104105']

Note that the first 3 outputs are of different length. Note that the fourth result is the same as the first.

>>> ["".join("%03d" % ord(c) for c in s) for s in tests]
['104105', '072105', '072073', '010041000005']
>>> [" ".join("%d" % ord(c) for c in s) for s in tests]
['104 105', '72 105', '72 73', '10 41 0 5']
>>> ["".join("%02x" % ord(c) for c in s) for s in tests]
['6869', '4869', '4849', '0a290005']
>>>

Note no such problems.

Getting value from table cell in JavaScript...not jQuery

The code yo have provided runs fine. Remember that if you have your code in the header, you need to wait for the dom to be loaded first. In jQuery it would just be as simple as putting your code inside $(function(e){...});

In normal javascript use window.onLoad(..) or the like... or have the script after the table defnition (yuck!). The snippet you provided runs fine when I have it that way for the following:

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title></title>
</head>
<body>
  <table id='ddReferences'>
    <tr>
      <td>dfsdf</td> 
      <td>sdfs</td>
      <td>frtyr</td>
      <td>hjhj</td>
    </tr>
  </table>

<script>
var refTab = document.getElementById("ddReferences")
var  ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; row = refTab.rows[i]; i++ ) {
   row = refTab.rows[i];
   for ( var j = 0; col = row.cells[j]; j++ ) {
      alert(col.firstChild.nodeValue);
   }
}

</script>
</body>
</html>

Calculate AUC in R?

Along the lines of erik's response, you should also be able to calculate the ROC directly by comparing all possible pairs of values from pos.scores and neg.scores:

score.pairs <- merge(pos.scores, neg.scores)
names(score.pairs) <- c("pos.score", "neg.score")
sum(score.pairs$pos.score > score.pairs$neg.score) / nrow(score.pairs)

Certainly less efficient than the sample approach or the pROC::auc, but more stable than the former and requiring less installation than the latter.

Related: when I tried this it gave similar results to pROC's value, but not exactly the same (off by 0.02 or so); the result was closer to the sample approach with very high N. If anyone has ideas why that might be I'd be interested.

How to import Maven dependency in Android Studio/IntelliJ?

As of version 0.8.9, Android Studio supports the Maven Central Repository by default. So to add an external maven dependency all you need to do is edit the module's build.gradle file and insert a line into the dependencies section like this:

dependencies {

    // Remote binary dependency
    compile 'net.schmizz:sshj:0.10.0'

}

You will see a message appear like 'Sync now...' - click it and wait for the maven repo to be downloaded along with all of its dependencies. There will be some messages in the status bar at the bottom telling you what's happening regarding the download. After it finishes this, the imported JAR file along with its dependencies will be listed in the External Repositories tree in the Project Browser window, as shown below.

enter image description here

Some further explanations here: http://developer.android.com/sdk/installing/studio-build.html

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors(); in the configure method. The method looks like that:

protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests() // authorize
                .anyRequest().authenticated() // all requests are authenticated
                .and()
                .httpBasic();

        http.cors();
}

What's the difference between equal?, eql?, ===, and ==?

I love jtbandes answer, but since it is pretty long, I will add my own compact answer:

==, ===, eql?, equal?
are 4 comparators, ie. 4 ways to compare 2 objects, in Ruby.
As, in Ruby, all comparators (and most operators) are actually method-calls, you can change, overwrite, and define the semantics of these comparing methods yourself. However, it is important to understand, when Ruby's internal language constructs use which comparator:

== (value comparison)
Ruby uses :== everywhere to compare the values of 2 objects, eg. Hash-values:

{a: 'z'}  ==  {a: 'Z'}    # => false
{a: 1}    ==  {a: 1.0}    # => true

=== (case comparison)
Ruby uses :=== in case/when constructs. The following code snippets are logically identical:

case foo
  when bar;  p 'do something'
end

if bar === foo
  p 'do something'
end

eql? (Hash-key comparison)
Ruby uses :eql? (in combination with the method hash) to compare Hash-keys. In most classes :eql? is identical with :==.
Knowledge about :eql? is only important, when you want to create your own special classes:

class Equ
  attr_accessor :val
  alias_method  :initialize, :val=
  def hash()           self.val % 2             end
  def eql?(other)      self.hash == other.hash  end
end

h = {Equ.new(3) => 3,  Equ.new(8) => 8,  Equ.new(15) => 15}    #3 entries, but 2 are :eql?
h.size            # => 2
h[Equ.new(27)]    # => 15

Note: The commonly used Ruby-class Set also relies on Hash-key-comparison.

equal? (object identity comparison)
Ruby uses :equal? to check if two objects are identical. This method (of class BasicObject) is not supposed to be overwritten.

obj = obj2 = 'a'
obj.equal? obj2       # => true
obj.equal? obj.dup    # => false

How do I check if a list is empty?

What brought me here is a special use-case: I actually wanted a function to tell me if a list is empty or not. I wanted to avoid writing my own function or using a lambda-expression here (because it seemed like it should be simple enough):

foo = itertools.takewhile(is_not_empty, (f(x) for x in itertools.count(1)))

And, of course, there is a very natural way to do it:

foo = itertools.takewhile(bool, (f(x) for x in itertools.count(1)))

Of course, do not use bool in if (i.e., if bool(L):) because it's implied. But, for the cases when "is not empty" is explicitly needed as a function, bool is the best choice.

Is there something like Codecademy for Java

As of right now, I do not know of any. It appears the code academy folks have set their sites on Ruby on Rails. They do not rule Java out of the picture however.

How to get html table td cell value by JavaScript?

Don't use in-line JavaScript, separate your behaviour from your data and it gets much easier to handle. I'd suggest the following:

var table = document.getElementById('tableID'),
    cells = table.getElementsByTagName('td');

for (var i=0,len=cells.length; i<len; i++){
    cells[i].onclick = function(){
        console.log(this.innerHTML);
        /* if you know it's going to be numeric:
        console.log(parseInt(this.innerHTML),10);
        */
    }
}

_x000D_
_x000D_
var table = document.getElementById('tableID'),_x000D_
  cells = table.getElementsByTagName('td');_x000D_
_x000D_
for (var i = 0, len = cells.length; i < len; i++) {_x000D_
  cells[i].onclick = function() {_x000D_
    console.log(this.innerHTML);_x000D_
  };_x000D_
}
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column heading 1</th>_x000D_
      <th>Column heading 2</th>_x000D_
      <th>Column heading 3</th>_x000D_
      <th>Column heading 4</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>43</td>_x000D_
      <td>23</td>_x000D_
      <td>89</td>_x000D_
      <td>5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>3</td>_x000D_
      <td>0</td>_x000D_
      <td>98</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>10</td>_x000D_
      <td>32</td>_x000D_
      <td>7</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS Fiddle proof-of-concept.

A revised approach, in response to the comment (below):

You're missing a semicolon. Also, don't make functions within a loop.

This revision binds a (single) named function as the click event-handler of the multiple <td> elements, and avoids the unnecessary overhead of creating multiple anonymous functions within a loop (which is poor practice due to repetition and the impact on performance, due to memory usage):

function logText() {
  // 'this' is automatically passed to the named
  // function via the use of addEventListener()
  // (later):
  console.log(this.textContent);
}

// using a CSS Selector, with document.querySelectorAll()
// to get a NodeList of <td> elements within the #tableID element:
var cells = document.querySelectorAll('#tableID td');

// iterating over the array-like NodeList, using
// Array.prototype.forEach() and Function.prototype.call():
Array.prototype.forEach.call(cells, function(td) {
  // the first argument of the anonymous function (here: 'td')
  // is the element of the array over which we're iterating.

  // adding an event-handler (the function logText) to handle
  // the click events on the <td> elements:
  td.addEventListener('click', logText);
});

_x000D_
_x000D_
function logText() {_x000D_
  console.log(this.textContent);_x000D_
}_x000D_
_x000D_
var cells = document.querySelectorAll('#tableID td');_x000D_
_x000D_
Array.prototype.forEach.call(cells, function(td) {_x000D_
  td.addEventListener('click', logText);_x000D_
});
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column heading 1</th>_x000D_
      <th>Column heading 2</th>_x000D_
      <th>Column heading 3</th>_x000D_
      <th>Column heading 4</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>43</td>_x000D_
      <td>23</td>_x000D_
      <td>89</td>_x000D_
      <td>5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>3</td>_x000D_
      <td>0</td>_x000D_
      <td>98</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>10</td>_x000D_
      <td>32</td>_x000D_
      <td>7</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS Fiddle proof-of-concept.

References:

How to search by key=>value in a multidimensional array in PHP

if (isset($array[$key]) && $array[$key] == $value)

A minor imporvement to the fast version.

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

What worked for me is using _outline not _outlined after the icon name.

<mat-icon>info</mat-icon>

vs

<mat-icon>info_outline</mat-icon>

Best data type for storing currency values in a MySQL database

Assaf's response of

Depends on how much money you got...

sounds flippant, but actually it's pertinant.

Only today we had an issue where a record failed to be inserted into our Rate table, because one of the columns (GrossRate) is set to Decimal (11,4), and our Product department just got a contract for rooms in some amazing resort in Bora Bora, that sell for several million Pacific Francs per night... something that was never anticpated when the database schema was designed 10 years ago.

Find difference between timestamps in seconds in PostgreSQL

Try: 

SELECT EXTRACT(EPOCH FROM (timestamp_B - timestamp_A))
FROM TableA

Details here: EXTRACT.

Duplicate Symbols for Architecture arm64

For me, I created a method called sampleMethod in ViewController_A and created the same method in ViewController_B too, It caused me this error, then i changed the method name in ViewController_B to secondSampleMethod. It fixed the error.

Seems like a Good feature to reduce the code and not to duplicate the same code in many places.

I tried changing the No Common blocks from Yes to No then enabling testability from Yes to No. It didn't worked. I Checked duplicate files also in build phases, but there is no duplicate files.

How to Deserialize JSON data?

If you use .Net 4.5 you can also use standard .Net json serializer:

using System.Runtime.Serialization.Json;
...    
Stream jsonSource = ...; // serializer will read data stream
var s = new DataContractJsonSerializer(typeof(string[][]));
var j = (string[][])s.ReadObject(jsonSource);

In .Net 4.5 and older you can use JavaScriptSerializer class:

using System.Web.Script.Serialization;
...
JavaScriptSerializer serializer = new JavaScriptSerializer();
string[][] list = serializer.Deserialize<string[][]>(json);

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I am getting similar errors recently because recent JDKs (and browsers, and the Linux TLS stack, etc.) refuse to communicate with some servers in my customer's corporate network. The reason of this is that some servers in this network still have SHA-1 certificates.

Please see: https://www.entrust.com/understanding-sha-1-vulnerabilities-ssl-longer-secure/ https://blog.qualys.com/ssllabs/2014/09/09/sha1-deprecation-what-you-need-to-know

If this would be your current case (recent JDK vs deprecated certificate encription) then your best move is to update your network to the proper encription technology.

In case that you should provide a temporal solution for that, please see another answers to have an idea about how to make your JDK trust or distrust certain encription algorithms:

How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections

Anyway I insist that, in case that I have guessed properly your problem, this is not a good solution to the problem and that your network admin should consider removing these deprecated certificates and get a new one.

Easiest way to compare arrays in C#

I was looking to determine if two sets had equivalent contents, in any order. That meant that, for each element in set A there were equal numbers of elements with that value in both sets. I wanted to account for duplicates (so {1,2,2,3} and {1,2,3,3} should not be considered "the same").

This is what I came up with (note that IsNullOrEmpty is another static extension method that returns true if the enumerable is null or has 0 elements):

    public static bool HasSameContentsAs<T>(this IEnumerable<T> source, IEnumerable<T> target) 
        where T : IComparable
    {
        //If our source is null or empty, then it's just a matter of whether or not the target is too
        if (source.IsNullOrEmpty())
            return target.IsNullOrEmpty();

        //Otherwise, if the target is null/emtpy, they can't be equal
        if (target.IsNullOrEmpty())
            return false;

        //Neither is null or empty, so we'll compare contents.  To account for multiples of 
        //a given value (ex. 1,2,2,3 and 1,1,2,3 are not equal) we'll group the first set
        foreach (var group in source.GroupBy(s => s))
        {
            //If there are a different number of elements in the target set, they don't match
            if (target.Count(t => t.Equals(group.Key)) != group.Count())
                return false;
        }

        //If we got this far, they have the same contents
        return true;
    }

Google Maps: how to get country, state/province/region, city given a lat/long value?

Just try this code this code work with me

var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
 //console.log(lat +"          "+long);
$http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + long + '&key=your key here').success(function (output) {
//console.log( JSON.stringify(output.results[0]));
//console.log( JSON.stringify(output.results[0].address_components[4].short_name));
var results = output.results;
if (results[0]) {
//console.log("results.length= "+results.length);
//console.log("hi "+JSON.stringify(results[0],null,4));
for (var j = 0; j < results.length; j++){
 //console.log("j= "+j);
//console.log(JSON.stringify(results[j],null,4));
for (var i = 0; i < results[j].address_components.length; i++){
 if(results[j].address_components[i].types[0] == "country") {
 //this is the object you are looking for
  country = results[j].address_components[i];
 }
 }
 }
 console.log(country.long_name);
 console.log(country.short_name);
 } else {
 alert("No results found");
 console.log("No results found");
 }
 });
 }, function (err) {
 });

How store a range from excel into a Range variable?

here is an example that allows for performing code on each line of the desired areas (pick either from top & bottom of selection, of from selection

Sub doROWSb()           'WORKS    for do selected rows     SEE FIX ROWS ABOVE  (small ver)
Dim E7 As String    'note:  workcell E7 shows:  BG381
E7 = RANGE("E7")    'see eg below
Dim r As Long       'NOTE: this example has a paste formula(s) down a column(s).  WILL REDUCE 10 HOUR DAYS OF PASTING COLUMNS, DOWN TO 3 MINUTES?
Dim c As Long
Dim rCell As RANGE
'Dim LastRow As Long
r = ActiveCell.row
c = ActiveCell.Column   'might not matter if your code affects whole line anyways, still leave as is

Dim FirstRow As Long    'not in use, Delete if only want last row, note: this code already allows for selection as start
Dim LastRow As Long


If 1 Then     'if you are unable to delete rows not needed, just change 2 lines from: If 1, to if 0 (to go from selection last row, to all rows down from selection)
With Selection
    'FirstRow = .Rows(1).row                 'not used here, Delete if only want last row
    LastRow = .Rows(.Rows.Count).row        'find last row in selection
End With
application.CutCopyMode = False             'if not doing any paste op below
Else
    LastRow = Cells(Rows.Count, 1).End(xlUp).row  'find last row used in sheet
End If
application.EnableEvents = True             'EVENTS  need this?
application.ScreenUpdating = False          'offset-cells(row, col)
'RANGE(E7).Select  'TOP ROW SELECT
RANGE("A1") = vbNullString                  'simple macros on-off switch, vb not here:  If RANGE("A1").Value > 0 Then


For Each rCell In RANGE(Cells(r, c), Cells(LastRow, c)) 'new
    rCell.Select    'make 3 macros for each paste macro below
'your code here:

If 1 Then     'to if 0, if want to paste formulas/formats/all down a column
    Selection.EntireRow.Calculate     'calcs all selected rows, even if just selecting 1 cell in each row (might only be doing 1 row aat here, as part of loop)
Else
'dorows() DO ROWS()
'eg's for paste cells down a column, can make 3 separate macros for each: sub alte() altf & altp
      Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False    'make sub alte ()    add thisworkbook:  application.OnKey "%{e}", "alte"
      'Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False     'make sub altf ()    add thisworkbook:  application.OnKey "%{f}", "altf"
      'Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=False         'amke sub altp ()    add thisworkbook:  application.OnKey "%{p}", "altp"
End If
Next rCell

'application.CutCopyMode = False            'finished - stop copy mode
'RANGE("A2").Select
goBEEPS (2), (0.25)       'beeps secs
application.EnableEvents = True             'EVENTS

'note:  workcell E7 has: SUBSTITUTE(SUBSTITUTE(CELL("address",$BG$369),"$",""),"","")
'other col eg (shows: BG:BG):  =SUBSTITUTE(SUBSTITUTE(CELL("address",$BG2),"$",""),ROW(),"")&":"& SUBSTITUTE(SUBSTITUTE(CELL("address",$BG2),"$",""),ROW(),"")
End Sub


'OTHER:
Sub goBEEPSx(b As Long, t As Double)   'beeps secs as:  goBEEPS (2), (0.25)  OR:  goBEEPS(2, 0.25)
  Dim dt  'as double    'worked wo as double
  Dim x
  For b = b To 1 Step -1
    Beep
    x = Timer
  Do
  DoEvents
  dt = Timer - x
  If dt < 0 Then dt = dt + 86400    '86400 no. seconds in a day, in case hit midnight & timer went down to 0
  Loop Until dt >= t
  Next
End Sub

Using the "start" command with parameters passed to the started program

If you must use double quotation mark at any parameter, you can get error "'c:\somepath' is not recognized a an internal or external command, operable program or batch file". I suggest below solution when using double qoutation mark: https://stackoverflow.com/a/43467194/3835640

Is there any option to limit mongodb memory usage?

I don't think you can configure how much memory MongoDB uses, but that's OK (read below).

To quote from the official source:

Virtual memory size and resident size will appear to be very large for the mongod process. This is benign: virtual memory space will be just larger than the size of the datafiles open and mapped; resident size will vary depending on the amount of memory not used by other processes on the machine.

In other words, Mongo will let other programs use memory if they ask for it.

How to get random value out of an array?

$rand = rand(1,4);

or, for arrays specifically:

$array = array('a value', 'another value', 'just some value', 'not some value');
$rand = $array[ rand(0, count($array)-1) ];

Callback functions in Java

A method is not (yet) a first-class object in Java; you can't pass a function pointer as a callback. Instead, create an object (which usually implements an interface) that contains the method you need and pass that.

Proposals for closures in Java—which would provide the behavior you are looking for—have been made, but none will be included in the upcoming Java 7 release.

Tree view of a directory/folder in Windows?

I recommend WinDirStat.

I frequently use WinDirStat to create screen shots for user documentation of open folders and their contents.

It even uses the correct icons for Windows registered file types.

All I would say is missing is an option to display the files without their icons. I can live without it personally, since I am usually pasting the image into a paint program or Visio to edit it, but it would still be a useful feature.

How to get current relative directory of your Makefile?

Here is one-liner to get absolute path to your Makefile file using shell syntax:

SHELL := /bin/bash
CWD := $(shell cd -P -- '$(shell dirname -- "$0")' && pwd -P)

And here is version without shell based on @0xff answer:

CWD := $(abspath $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST))))))

Test it by printing it, like:

cwd:
        @echo $(CWD)

DateTime.Compare how to check if a date is less than 30 days old?

Compare is unnecessary, Days / TotalDays are unnecessary.

All you need is

if (expireDate < DateTime.Now) {
    // has expired
} else {
    // not expired
}

note this will work if you decide to use minutes or months or even years as your expiry criteria.

Find length (size) of an array in jquery

If length is undefined you can use:

function count(array){

    var c = 0;
    for(i in array) // in returns key, not object
        if(array[i] != undefined)
            c++;

    return c;
}

var total = count(array);

SQLite Reset Primary Key Field

As an alternate option, if you have the Sqlite Database Browser and are more inclined to a GUI solution, you can edit the sqlite_sequence table where field name is the name of your table. Double click the cell for the field seq and change the value to 0 in the dialogue box that pops up.

IntelliJ IDEA generating serialVersionUID

I am using Android Studio 2.1 and I have better consistency of getting the lightbulb by clicking on the class Name and hover over it for a second.

How do I set environment variables from Java?

This is a combination of @paul-blair 's answer converted to Java which includes some cleanups pointed out by paul blair and some mistakes that seem to have been inside @pushy 's code which is made up of @Edward Campbell and anonymous.

I cannot emphasize how much this code should ONLY be used in testing and is extremely hacky. But for cases where you need the environment setup in tests it is exactly what I needed.

This also includes some minor touches of mine that allow the code to work on both Windows running on

java version "1.8.0_92"
Java(TM) SE Runtime Environment (build 1.8.0_92-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.92-b14, mixed mode)

as well as Centos running on

openjdk version "1.8.0_91"
OpenJDK Runtime Environment (build 1.8.0_91-b14)
OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)

The implementation:

/**
 * Sets an environment variable FOR THE CURRENT RUN OF THE JVM
 * Does not actually modify the system's environment variables,
 *  but rather only the copy of the variables that java has taken,
 *  and hence should only be used for testing purposes!
 * @param key The Name of the variable to set
 * @param value The value of the variable to set
 */
@SuppressWarnings("unchecked")
public static <K,V> void setenv(final String key, final String value) {
    try {
        /// we obtain the actual environment
        final Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        final Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
        final boolean environmentAccessibility = theEnvironmentField.isAccessible();
        theEnvironmentField.setAccessible(true);

        final Map<K,V> env = (Map<K, V>) theEnvironmentField.get(null);

        if (SystemUtils.IS_OS_WINDOWS) {
            // This is all that is needed on windows running java jdk 1.8.0_92
            if (value == null) {
                env.remove(key);
            } else {
                env.put((K) key, (V) value);
            }
        } else {
            // This is triggered to work on openjdk 1.8.0_91
            // The ProcessEnvironment$Variable is the key of the map
            final Class<K> variableClass = (Class<K>) Class.forName("java.lang.ProcessEnvironment$Variable");
            final Method convertToVariable = variableClass.getMethod("valueOf", String.class);
            final boolean conversionVariableAccessibility = convertToVariable.isAccessible();
            convertToVariable.setAccessible(true);

            // The ProcessEnvironment$Value is the value fo the map
            final Class<V> valueClass = (Class<V>) Class.forName("java.lang.ProcessEnvironment$Value");
            final Method convertToValue = valueClass.getMethod("valueOf", String.class);
            final boolean conversionValueAccessibility = convertToValue.isAccessible();
            convertToValue.setAccessible(true);

            if (value == null) {
                env.remove(convertToVariable.invoke(null, key));
            } else {
                // we place the new value inside the map after conversion so as to
                // avoid class cast exceptions when rerunning this code
                env.put((K) convertToVariable.invoke(null, key), (V) convertToValue.invoke(null, value));

                // reset accessibility to what they were
                convertToValue.setAccessible(conversionValueAccessibility);
                convertToVariable.setAccessible(conversionVariableAccessibility);
            }
        }
        // reset environment accessibility
        theEnvironmentField.setAccessible(environmentAccessibility);

        // we apply the same to the case insensitive environment
        final Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
        final boolean insensitiveAccessibility = theCaseInsensitiveEnvironmentField.isAccessible();
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        // Not entirely sure if this needs to be casted to ProcessEnvironment$Variable and $Value as well
        final Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
        if (value == null) {
            // remove if null
            cienv.remove(key);
        } else {
            cienv.put(key, value);
        }
        theCaseInsensitiveEnvironmentField.setAccessible(insensitiveAccessibility);
    } catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        throw new IllegalStateException("Failed setting environment variable <"+key+"> to <"+value+">", e);
    } catch (final NoSuchFieldException e) {
        // we could not find theEnvironment
        final Map<String, String> env = System.getenv();
        Stream.of(Collections.class.getDeclaredClasses())
                // obtain the declared classes of type $UnmodifiableMap
                .filter(c1 -> "java.util.Collections$UnmodifiableMap".equals(c1.getName()))
                .map(c1 -> {
                    try {
                        return c1.getDeclaredField("m");
                    } catch (final NoSuchFieldException e1) {
                        throw new IllegalStateException("Failed setting environment variable <"+key+"> to <"+value+"> when locating in-class memory map of environment", e1);
                    }
                })
                .forEach(field -> {
                    try {
                        final boolean fieldAccessibility = field.isAccessible();
                        field.setAccessible(true);
                        // we obtain the environment
                        final Map<String, String> map = (Map<String, String>) field.get(env);
                        if (value == null) {
                            // remove if null
                            map.remove(key);
                        } else {
                            map.put(key, value);
                        }
                        // reset accessibility
                        field.setAccessible(fieldAccessibility);
                    } catch (final ConcurrentModificationException e1) {
                        // This may happen if we keep backups of the environment before calling this method
                        // as the map that we kept as a backup may be picked up inside this block.
                        // So we simply skip this attempt and continue adjusting the other maps
                        // To avoid this one should always keep individual keys/value backups not the entire map
                        LOGGER.info("Attempted to modify source map: "+field.getDeclaringClass()+"#"+field.getName(), e1);
                    } catch (final IllegalAccessException e1) {
                        throw new IllegalStateException("Failed setting environment variable <"+key+"> to <"+value+">. Unable to access field!", e1);
                    }
                });
    }
    LOGGER.info("Set environment variable <"+key+"> to <"+value+">. Sanity Check: "+System.getenv(key));
}

Excel column number from column name

Based on Anastasiya's answer. I think this is the shortest vba command:

Option Explicit

Sub Sample()
    Dim sColumnLetter as String
    Dim iColumnNumber as Integer

    sColumnLetter = "C"
    iColumnNumber = Columns(sColumnLetter).Column

    MsgBox "The column number is " & iColumnNumber
End Sub

Caveat: The only condition for this code to work is that a worksheet is active, because Columns is equivalent to ActiveSheet.Columns. ;)

How to execute XPath one-liners from shell?

Saxon will do this not only for XPath 2.0, but also for XQuery 1.0 and (in the commercial version) 3.0. It doesn't come as a Linux package, but as a jar file. Syntax (which you can easily wrap in a simple script) is

java net.sf.saxon.Query -s:source.xml -qs://element/attribute

2020 UPDATE

Saxon 10.0 includes the Gizmo tool, which can be used interactively or in batch from the command line. For example

java net.sf.saxon.Gizmo -s:source.xml
/>show //element/@attribute
/>quit

close vs shutdown socket?

This is explained in Beej's networking guide. shutdown is a flexible way to block communication in one or both directions. When the second parameter is SHUT_RDWR, it will block both sending and receiving (like close). However, close is the way to actually destroy a socket.

With shutdown, you will still be able to receive pending data the peer already sent (thanks to Joey Adams for noting this).

Multiple selector chaining in jQuery?

You can combine multiple selectors with a comma:

$('#Create .myClass,#Edit .myClass').plugin({options here});

Or if you're going to have a bunch of them, you could add a class to all your form elements and then search within that class. This doesn't get you the supposed speed savings of restricting the search, but I honestly wouldn't worry too much about that if I were you. Browsers do a lot of fancy things to optimize common operations behind your back -- the simple class selector might be faster.

Revert to Eclipse default settings

go to windows>preferences>Java>Editor>Syntax Coloring go all the way down and click on Restore Defaults & Apply and Close

Converting from a string to boolean in Python?

I use

# function
def toBool(x):
    return x in ("True","true",True)

# test cases
[[x, toBool(x)] for x in [True,"True","true",False,"False","false",None,1,0,-1,123]]
"""
Result:
[[True, True],
 ['True', True],
 ['true', True],
 [False, False],
 ['False', False],
 ['false', False],
 [None, False],
 [1, True],
 [0, False],
 [-1, False],
 [123, False]]
"""

Generating Fibonacci Sequence

I've tried this: it might work:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fibonacci</title>
    <style>
        * {
            outline: 0px;
            margin: 0px;
        }

        input[type="number"] {
            color: blue;
            border: 2px solid black;
            width: 99.58vw;
        }
    </style>
</head>

<body>
    <div id="myDiv" style="color: white;background-color: blue;">Numbers Here</div>
    <input type="number" id="input1" oninput="fibonacciProgram(this.value)" placeholder="Type Some Numbers Here">
    <script>
        function fibonacciProgram(numberCount) {
            let resultElement = document.getElementById("myDiv");
            resultElement.innerHTML = " ";
            if (isNaN(numberCount) || numberCount <= 0) {
                resultElement.innerHTML = "please enter a number";
                return;
            }
            let firstBox = 0;
            let secondBox = 1;
            let swichBox;
            let entries = [];
            entries.push(secondBox);
            while (numberCount > 1) {
                swichBox = firstBox + secondBox;
                entries.push(swichBox);
                firstBox = secondBox;
                secondBox = swichBox;
                numberCount--;
            }
            resultElement.innerHTML = entries.join(', ');
        }
    </script>
</body>

</html>

Check if element is in the list (contains)

Declare additional helper function like this:

template <class T, class I >
bool vectorContains(const vector<T>& v, I& t)
{
    bool found = (std::find(v.begin(), v.end(), t) != v.end());
    return found;
}

And use it like this:

void Project::AddPlatform(const char* platform)
{
    if (!vectorContains(platforms, platform))
        platforms.push_back(platform);
}

Snapshot of example can be found here:

https://github.com/tapika/cppscriptcore/blob/b7f3d62747494a52a440482e841ffb016a3fc56e/SolutionProjectModel/Project.cpp#L13

Error in file(file, "rt") : cannot open the connection

I came across a solution based on a few answers popped in the thread. (windows 10)

setwd("D:/path to folder where the files are")
directory <- getwd()
myfile<- "a_file_in_the_folder.txt"
filepath=paste0(directory,"/",myfile[1],sep="")
table <- read.table(table, sep = "\t", header=T, row.names = 1, dec=",")

How to print / echo environment variables?

To bring the existing answers together with an important clarification:

As stated, the problem with NAME=sam echo "$NAME" is that $NAME gets expanded by the current shell before assignment NAME=sam takes effect.

Solutions that preserve the original semantics (of the (ineffective) solution attempt NAME=sam echo "$NAME"):

Use either eval[1] (as in the question itself), or printenv (as added by Aaron McDaid to heemayl's answer), or bash -c (from Ljm Dullaart's answer), in descending order of efficiency:

NAME=sam eval 'echo "$NAME"'  # use `eval` only if you fully control the command string
NAME=sam printenv NAME
NAME=sam bash -c 'echo "$NAME"'

printenv is not a POSIX utility, but it is available on both Linux and macOS/BSD.

What this style of invocation (<var>=<name> cmd ...) does is to define NAME:

  • as an environment variable
  • that is only defined for the command being invoked.

In other words: NAME only exists for the command being invoked, and has no effect on the current shell (if no variable named NAME existed before, there will be none after; a preexisting NAME variable remains unchanged).

POSIX defines the rules for this kind of invocation in its Command Search and Execution chapter.


The following solutions work very differently (from heemayl's answer):

NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"

While they produce the same output, they instead define:

  • a shell variable NAME (only) rather than an environment variable
    • if echo were a command that relied on environment variable NAME, it wouldn't be defined (or potentially defined differently from earlier).
  • that lives on after the command.

Note that every environment variable is also exposed as a shell variable, but the inverse is not true: shell variables are only visible to the current shell and its subshells, but not to child processes, such as external utilities and (non-sourced) scripts (unless they're marked as environment variables with export or declare -x).


[1] Technically, bash is in violation of POSIX here (as is zsh): Since eval is a special shell built-in, the preceding NAME=sam assignment should cause the the variable $NAME to remain in scope after the command finishes, but that's not what happens.
However, when you run bash in POSIX compatibility mode, it is compliant.
dash and ksh are always compliant.
The exact rules are complicated, and some aspects are left up to the implementations to decide; again, see Command Search and Execution.
Also, the usual disclaimer applies: Use eval only on input you fully control or implicitly trust.

Execute function after Ajax call is complete

Try this code:

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
     url: 'api.php',                        
     data: 'id1='+q+'',                                                         
     dataType: 'json',
     async:false,                    
     success: function(data)          
     {   
        id = data[0];              
        vname = data[1];
     },
    complete: function (data) {
      printWithAjax(); 
     }
    });

  }//end of the for statement
  }//end of ajax call function

The "complete" function executes only after the "success" of ajax. So try to call the printWithAjax() on "complete". This should work for you.

GROUP BY without aggregate function

The only real use case for GROUP BY without aggregation is when you GROUP BY more columns than are selected, in which case the selected columns might be repeated. Otherwise you might as well use a DISTINCT.

It's worth noting that other RDBMS's do not require that all non-aggregated columns be included in the GROUP BY. For example in PostgreSQL if the primary key columns of a table are included in the GROUP BY then other columns of that table need not be as they are guaranteed to be distinct for every distinct primary key column. I've wished in the past that Oracle did the same as it would have made for more compact SQL in many cases.

Bootstrap Accordion button toggle "data-parent" not working

Note, not only there is dependency on .panel, it also has dependency on the DOM structure.

Make sure your elements are structured like this:

    <div id="parent-id">
        <div class="panel">
            <a data-toggle="collapse" data-target="#opt1" data-parent="#parent-id">Control</a>
            <div id="opt1" class="collapse">
...

It's basically what @Blazemonger said, but I think the hierarchy of the target element matters too. I didn't finish trying every possibility out, but basically it should work if you follow this hierarchy.

FYI, I had more layers between the control div & content div and that didn't work.

How to dynamically create generic C# object using reflection?

I know this question is resolved but, for the benefit of anyone else reading it; if you have all of the types involved as strings, you could do this as a one liner:

IYourInterface o = (Activator.CreateInstance(Type.GetType("Namespace.TaskA`1[OtherNamespace.TypeParam]") as IYourInterface);

Whenever I've done this kind of thing, I've had an interface which I wanted subsequent code to utilise, so I've casted the created instance to an interface.

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

The command build in pipeline is there to trigger other jobs in jenkins.

Example on github

The job must exist in Jenkins and can be parametrized. As for the branch, I guess you can read it from git

How do I get a platform-dependent new line character?

StringBuilder newLine=new StringBuilder();
newLine.append("abc");
newline.append(System.getProperty("line.separator"));
newline.append("def");
String output=newline.toString();

The above snippet will have two strings separated by a new line irrespective of platforms.

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

You can try using jquery.pep.js:

jquery.pep.js is a lightweight jQuery plugin which turns any DOM element into a draggable object. It works across mostly all browsers, from old to new, from touch to click. I built it to serve a need in which jQuery UI’s draggable was not fulfilling, since it didn’t work on touch devices (without some hackery).

Website, GitHub link

Editor does not contain a main type in Eclipse

I installed Eclipse and created a Java project. Created new Java file outside the 'src' directory and tried to run that. I got the same error "Editor does not contain a main type". I just moved the java file into the 'src' folder and could simply run the program. I couldn't understand what other answers were asking to try. It was so simple.

Invalid application of sizeof to incomplete type with a struct

It means the file containing main doesn't have access to the player structure definition (i.e. doesn't know what it looks like).

Try including it in header.h or make a constructor-like function that allocates it if it's to be an opaque object.

EDIT

If your goal is to hide the implementation of the structure, do this in a C file that has access to the struct:

struct player *
init_player(...)
{
    struct player *p = calloc(1, sizeof *p);

    /* ... */
    return p;
}

However if the implementation shouldn't be hidden - i.e. main should legally say p->canPlay = 1 it would be better to put the definition of the structure in header.h.

Abstract Class:-Real Time Example

Here, Something about abstract class...

  1. Abstract class is an incomplete class so we can't instantiate it.
  2. If methods are abstract, class must be abstract.
  3. In abstract class, we use abstract and concrete method both.
  4. It is illegal to define a class abstract and final both.

Real time example--

If you want to make a new car(WagonX) in which all the another car's properties are included like color,size, engine etc.and you want to add some another features like model,baseEngine in your car.Then simply you create a abstract class WagonX where you use all the predefined functionality as abstract and another functionalities are concrete, which is is defined by you.
Another sub class which extend the abstract class WagonX,By default it also access the abstract methods which is instantiated in abstract class.SubClasses also access the concrete methods by creating the subclass's object.
For reusability the code, the developers use abstract class mostly.

abstract class WagonX
{
   public abstract void model();
   public abstract void color();
   public static void baseEngine()
    {
     // your logic here
    }
   public static void size()
   {
   // logic here
   }
}
class Car extends WagonX
{
public void model()
{
// logic here
}
public void color()
{
// logic here
}
}

adding noise to a signal in python

Awesome answers above. I recently had a need to generate simulated data and this is what I landed up using. Sharing in-case helpful to others as well,

import logging
__name__ = "DataSimulator"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

import numpy as np
import pandas as pd

def generate_simulated_data(add_anomalies:bool=True, random_state:int=42):
    rnd_state = np.random.RandomState(random_state)
    time = np.linspace(0, 200, num=2000)
    pure = 20*np.sin(time/(2*np.pi))

    # concatenate on the second axis; this will allow us to mix different data 
    # distribution
    data = np.c_[pure]
    mu = np.mean(data)
    sd = np.std(data)
    logger.info(f"Data shape : {data.shape}. mu: {mu} with sd: {sd}")
    data_df = pd.DataFrame(data, columns=['Value'])
    data_df['Index'] = data_df.index.values

    # Adding gaussian jitter
    jitter = 0.3*rnd_state.normal(mu, sd, size=data_df.shape[0])
    data_df['with_jitter'] = data_df['Value'] + jitter

    index_further_away = None
    if add_anomalies:
        # As per the 68-95-99.7 rule(also known as the empirical rule) mu+-2*sd 
        # covers 95.4% of the dataset.
        # Since, anomalies are considered to be rare and typically within the 
        # 5-10% of the data; this filtering
        # technique might work 
        #for us(https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule)
        indexes_furhter_away = np.where(np.abs(data_df['with_jitter']) > (mu + 
         2*sd))[0]
        logger.info(f"Number of points further away : 
        {len(indexes_furhter_away)}. Indexes: {indexes_furhter_away}")
        # Generate a point uniformly and embed it into the dataset
        random = rnd_state.uniform(0, 5, 1)
        data_df.loc[indexes_furhter_away, 'with_jitter'] +=  
        random*data_df.loc[indexes_furhter_away, 'with_jitter']
    return data_df, indexes_furhter_away

ASP.NET Button to redirect to another page

You can use PostBackUrl="~/Confirm.aspx"

For example:

In your .aspx file

<asp:Button ID="btnConfirm" runat="server" Text="Confirm" PostBackUrl="~/Confirm.aspx" />

or in your .cs file

btnConfirm.PostBackUrl="~/Confirm.aspx"

pdftk compression option

I didn't see a lot of reduction in file size using qpdf. The best way I found is after pdftk is done use ghostscript to convert pdf to postscript then back to pdf. In PHP you would use exec:

$ps = $save_path.'/psfile.ps';
exec('ps2ps2 ' . $pdf . ' ' . $ps);
unlink($pdf);
exec('ps2pdf ' .$ps . ' ' . $pdf);
unlink($ps);

I used this a few minutes ago to take pdftk output from 490k to 71k.

JavaScript Promises - reject vs. throw

Another important fact is that reject() DOES NOT terminate control flow like a return statement does. In contrast throw does terminate control flow.

Example:

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  throw "err";_x000D_
  console.log("NEVER REACHED");_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

vs

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  reject(); // resolve() behaves similarly_x000D_
  console.log("ALWAYS REACHED"); // "REJECTED" will print AFTER this_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

SyntaxError: missing ; before statement

too many ) parenthesis remove one of them.

Try-catch-finally-return clarification

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

Unknown SSL protocol error in connection

If you meet "Unknown SSL protocol error in connection to bitbucket.org:443" and you are in China, maybe github is been blocked by firewall temporarily. You can try to use VPN, which would work out. Good Luck!

optional parameters in SQL Server stored proc?

Yes, it is. Declare parameter as so:

@Sort varchar(50) = NULL

Now you don't even have to pass the parameter in. It will default to NULL (or whatever you choose to default to).

Check empty string in Swift?

To do the nil check and length simultaneously Swift 2.0 and iOS 9 onwards you could use

if(yourString?.characters.count > 0){}

How to specify function types for void (not Void) methods in Java8?

When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like

  public interface Thunk { void apply(); }

somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.

In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.

Selenium Webdriver submit() vs click()

Also, correct me if I'm wrong, but I believe that submit will wait for a new page to load, whereas click will immediately continue executing code

How can I adjust DIV width to contents

I'd like to add to the other answers this pretty new solution:

If you don't want the element to become inline-block, you can do this:

.parent{
  width: min-content;
}

The support is increasing fast, so when edge decides to implement it, it will be really great: http://caniuse.com/#search=intrinsic

Could not resolve '...' from state ''

I've just had this same issue with Ionic.

It turns out nothing was wrong with my code, I simply had to quit the ionic serve session and run ionic serve again.

After going back into the app, my states worked fine.

I would also suggest pressing save on your app.js file a few times if you are running gulp, to make sure everything gets re-compiled.

Delete all rows with timestamp older than x days

DELETE FROM on_search 
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))

How to set a default value for an existing column

Just Found 3 simple steps to alter already existing column that was null before

update   orders
set BasicHours=0 where BasicHours is null

alter table orders 
add default(0) for BasicHours

alter table orders 
alter  column CleanBasicHours decimal(7,2) not null 

Xcode stuck on Indexing

Close Your Xcode , close any git client(source tree or terminal)if it is opened and finally restart your project.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

Taken from Retrieving File information | Android developers

Retrieving a File's name.

private String queryName(ContentResolver resolver, Uri uri) {
    Cursor returnCursor =
            resolver.query(uri, null, null, null, null);
    assert returnCursor != null;
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    returnCursor.moveToFirst();
    String name = returnCursor.getString(nameIndex);
    returnCursor.close();
    return name;
}

Getting query parameters from react-router hash fragment

"react-router-dom": "^5.0.0",

you do not need to add any additional module, just in your component that has a url address like this:

http://localhost:3000/#/?authority'

you can try the following simple code:

    const search =this.props.location.search;
    const params = new URLSearchParams(search);
    const authority = params.get('authority'); //

Non-recursive depth first search algorithm

Stack<Node> stack = new Stack<>();
stack.add(root);
while (!stack.isEmpty()) {
    Node node = stack.pop();
    System.out.print(node.getData() + " ");

    Node right = node.getRight();
    if (right != null) {
        stack.push(right);
    }

    Node left = node.getLeft();
    if (left != null) {
        stack.push(left);
    }
}

How can I increase the JVM memory?

Right click on project -> Run As -> Run Configurations..-> Select Arguments tab -> In VM Arguments you can increase your JVM memory allocation. Java HotSpot document will help you to setup your VM Argument HERE

I will not prefer to make any changes into eclipse.ini as minor mistake cause lot of issues. It's easier to play with VM Args

Javascript - object key->value

https://jsfiddle.net/sudheernunna/tug98nfm/1/

 var days = {};
days["monday"] = true;
days["tuesday"] = true;
days["wednesday"] = false;
days["thursday"] = true;
days["friday"] = false;
days["saturday"] = true;
days["sunday"] = false;
var userfalse=0,usertrue=0;
for(value in days)
{
   if(days[value]){
   usertrue++;
   }else{
   userfalse++;
   }
    console.log(days[value]);
}
alert("false",userfalse);
alert("true",usertrue);

How do I correctly setup and teardown for my pytest class with tests?

This might help http://docs.pytest.org/en/latest/xunit_setup.html

In my test suite, I group my test cases into classes. For the setup and teardown I need for all the test cases in that class, I use the setup_class(cls) and teardown_class(cls) classmethods.

And for the setup and teardown I need for each of the test case, I use the setup_method(method) and teardown_method(methods)

Example:

lh = <got log handler from logger module>

class TestClass:
    @classmethod
    def setup_class(cls):
        lh.info("starting class: {} execution".format(cls.__name__))

    @classmethod
    def teardown_class(cls):
        lh.info("starting class: {} execution".format(cls.__name__))

    def setup_method(self, method):
        lh.info("starting execution of tc: {}".format(method.__name__))

    def teardown_method(self, method):
        lh.info("starting execution of tc: {}".format(method.__name__))

    def test_tc1(self):
        <tc_content>
        assert 

    def test_tc2(self):
        <tc_content>
        assert

Now when I run my tests, when the TestClass execution is starting, it logs the details for when it is beginning execution, when it is ending execution and same for the methods..

You can add up other setup and teardown steps you might have in the respective locations.

Hope it helps!

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

I don't understand why nobody points to the specific issue and some answers are totally misleading, especially the accepted answer. The issue is that the OP did not pick a rule that could possibly override the margin property that is set by the User Agent (UA) directly on the ul tag. Let's consider all the rules with a margin property used by the OP.

body {

margin:0px;
...
}

The body element is way up in the DOM and the UA rule matches an element below, so the UA wins. It's the way inheritance works. Inheritance is the means by which, in the absence of any specific declarations from any source applied by the CSS cascade, a property value of an element is obtained from its parent element. Specificity on the parent element is useless, because the UA rule matches directly the element.

#mainNav{
    margin:0 auto;
    ...
}

This is a better attempt, a more specific selector #mainNav, which matches the mainNav element lower in the DOM, but the same principle applies, because the ul element is still below this element in the DOM.

#mainNav ul li{
    ...
    margin:0;
    ...
}

This went too far down in the DOM! Now, the selector matches the li element, which is below the ul element.

So, assuming that the UA rule used the selector ul and not !important, which is most likely the case, the solution would have been a simple ul { margin: 0; }, but it would be safer to make it more specific, say #mainNav ul { margin: 0 }.

Using curl POST with variables defined in bash script functions

Here's what actually worked for me, after guidance from answers here:

export BASH_VARIABLE="[1,2,3]"
curl http://localhost:8080/path -d "$(cat <<EOF
{
  "name": $BASH_VARIABLE,
  "something": [
    "value1",
    "value2",
    "value3"
  ]
}
EOF
)" -H 'Content-Type: application/json'

How do I remove a property from a JavaScript object?

There are a lot of good answers here but I just want to chime in that when using delete to remove a property in JavaScript, it is often wise to first check if that property exists to prevent errors.

E.g

var obj = {"property":"value", "property2":"value"};

if (obj && obj.hasOwnProperty("property2")) {
  delete obj.property2;
} else {
  //error handling
}

Due to the dynamic nature of JavaScript there are often cases where you simply don't know if the property exists or not. Checking if obj exists before the && also makes sure you don't throw an error due to calling the hasOwnProperty() function on an undefined object.

Sorry if this didn't add to your specific use case but I believe this to be a good design to adapt when managing objects and their properties.

Check if a variable is of function type

For those who's interested in functional style, or looks for more expressive approach to utilize in meta programming (such as type checking), it could be interesting to see Ramda library to accomplish such task.

Next code contains only pure and pointfree functions:

const R = require('ramda');

const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);

const equalsSyncFunction = isPrototypeEquals(() => {});

const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);

As of ES2017, async functions are available, so we can check against them as well:

const equalsAsyncFunction = isPrototypeEquals(async () => {});

const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);

And then combine them together:

const isFunction = R.either(isSyncFunction, isAsyncFunction);

Of course, function should be protected against null and undefined values, so to make it "safe":

const safeIsFunction = R.unless(R.isNil, isFunction);

And, complete snippet to sum up:

const R = require('ramda');

const isPrototypeEquals = R.pipe(Object.getPrototypeOf, R.equals);

const equalsSyncFunction = isPrototypeEquals(() => {});
const equalsAsyncFunction = isPrototypeEquals(async () => {});

const isSyncFunction = R.pipe(Object.getPrototypeOf, equalsSyncFunction);
const isAsyncFunction = R.pipe(Object.getPrototypeOf, equalsAsyncFunction);

const isFunction = R.either(isSyncFunction, isAsyncFunction);

const safeIsFunction = R.unless(R.isNil, isFunction);

// ---

console.log(safeIsFunction( function () {} ));
console.log(safeIsFunction( () => {} ));
console.log(safeIsFunction( (async () => {}) ));
console.log(safeIsFunction( new class {} ));
console.log(safeIsFunction( {} ));
console.log(safeIsFunction( [] ));
console.log(safeIsFunction( 'a' ));
console.log(safeIsFunction( 1 ));
console.log(safeIsFunction( null ));
console.log(safeIsFunction( undefined ));

However, note the this solution could show less performance than other available options due to extensive usage of higher-order functions.

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

Updating curl worked for us. Somehow yum uses curl for its transactions.

yum update curl --disablerepo=epel

Refresh/reload the content in Div using jquery/ajax

$("#myDiv").load(location.href+" #myDiv>*","");

Make javascript alert Yes/No Instead of Ok/Cancel

In an attempt to solve a similar situation I've come across this example and adapted it. It uses JQUERY UI Dialog as Nikhil D suggested. Here is a look at the code:

HTML:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<input type="button" id="box" value="Confirm the thing?" />
<div id="dialog-confirm"></div>

JavaScript:

$('#box').click(function buttonAction() {
  $("#dialog-confirm").html("Do you want to do the thing?");

  // Define the Dialog and its properties.
  $("#dialog-confirm").dialog({
    resizable: false,
    modal: true,
    title: "Do the thing?",
    height: 250,
    width: 400,
    buttons: {
      "Yes": function() {
        $(this).dialog('close');
        alert("Yes, do the thing");
      },
      "No": function() {
        $(this).dialog('close');
        alert("Nope, don't do the thing");
      }
    }
  });
});

$('#box').click(buttonAction);

I have a few more tweaks I need to do to make this example work for my application. Will update this if I see it fit into the answer. Hope this helps someone.

Does Notepad++ show all hidden characters?

In newer versions of Notepad++ (currently 5.9), this option is under:

View->Show Symbol->Show All Characters

or

View->Show Symbol->Show White Space and Tab

change figure size and figure format in matplotlib

You can change the size of the plot by adding this before you create the figure.

plt.rcParams["figure.figsize"] = [16,9]

How to print the number of characters in each line of a text file

Here is example using xargs:

$ xargs -d '\n' -I% sh -c 'echo % | wc -c' < file

Python: print a generator expression?

You can just wrap the expression in a call to list:

>>> list(x for x in string.letters if x in (y for y in "BigMan on campus"))
['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']

Select a row from html table and send values onclick of a button

check http://jsfiddle.net/Z22NU/12/

function fnselect(){

    alert($("tr.selected td:first" ).html());
}

Watching variables contents in Eclipse IDE

This video does an excellent job of showing you how to set breakpoints and watch variables in the Eclipse Debugger. http://youtu.be/9gAjIQc4bPU

Can I fade in a background image (CSS: background-image) with jQuery?

I know i'm late, but I found a way using jquery which works on every browser(i tested it on chrome, firefox and Ie 9)and th fore-ground elements are always displayed instead of css3 transition property.

create 2 absolute wrapper and using z-index.

First set the elements that have to be in the fore-ground with the highest z-index property value, and the other elemets(all included in the body, so: body{}) with a lower z-index property value than the fore-ground elements'one , at least of 2 number lower.

HTML part:

         <div class="wrapper" id="wrapper1"></div>
         <div class="wrapper" id="wrapper2"></div>

css part:

        .fore-groundElements{              //select all fore-ground elements
                  z-index:0;               //>=0
        }
       .wrapper{
                  background-size: cover;
                  width:100%;
                  height:100%;
                  background-size: 100% 100%;
                  position:absolute;
         }

        #wrapper1{
               z-index:-1; 
        }


        #wrapper2{
                 z-index:-2;
         }
         body{

              height:100%;
              width:100%;
              margin:0px;   
              display:cover;
              z-index:-3                          //<=-3
         }

than the javascript/jquery one:

i needed to change the background image every three second so i used a set timeout.

this is the code:

  $(document).ready(main);

  var main = function(){

             var imgPath=[imagesPath1,..,...];                 // the array in which store the image paths

             var newWrapper;                     // the wrapper to display 
             var currentWrapper;                 //the current displayed wrapper which has to be faded
             var l=2;                             // the next image index  to be displayed, it is set to 2 because the first two position of the array(first two images) start already setted up
             var imgNumber= imgPath.length;        //to know when the images are over and restart the carousel
             var currentImg;                       //the next image path to be displayed


             $('#wrapper1').css("background-image", 'url'+imgPath[0]);         //pre set the first wrapper background images
             $('#wrapper2').css("background-image", 'url'+imgPath[1]);          //pre set the first wrapper background images   

             setInterval(myfunction,3000);                //refresh the background image every three seconds

             function myfunction(){
                    if(l===imgNumber-1){               //restart the carousel if every single image has already been displayed                  
                         l=0;
                     };

             if(l%2==0||l%2==2){                    //set the wrapper that will be displaied after the fadeOut callback function
                  currentWrapper='#wrapper1';         
                  newWrapper='#wrapper2';
             }else{
                  currentWrapper='#wrapper2';
                  newWrapper='#wrapper1';
             };
             currentImg=imgPath[l];
            $(currentWrapper).fadeOut(1000,function(){               //fade out the current wrapper, so now the back-ground wrapper is fully displayed
                  $(newWrapper).css("z-index", "-1");                //move the shown wrapper in the fore-ground
                  $(currentWrapper).css("z-index","-2");             //move the hidden wrapper in the back ground
                  $(currentWrapper).css("background-image",'url'+currentImg);                   // sets up the next image that is now shown in the actually hidden background wrapper
                  $(currentWrapper).show();          //shows the background wrapper, which is not visible yet, and it will be shown the next time the setInterval event will be triggered
                  l++;                         //set the next image index that will be set the next time the setInterval event will be triggered 
             });


         };                   //end of myFunction
  }                          //end of main

i hope that my answer is clear,if you need more explanation comment it.

sorry for my english :)

How do you implement a good profanity filter?

Frankly, I'd let them get the "trick the system" words out and ban them instead, which is just me. But it also makes the programming simpler.

What I'd do is implement a regex filter like so: /[\s]dooby (doo?)[\s]/i or it the word is prefixed on others, /[\s]doob(er|ed|est)[\s]/. These would prevent filtering words like assuaged, which is perfectly valid, but would also require knowledge of the other variants and updating the actual filter if you learn a new one. Obviously these are all examples, but you'd have to decide how to do it yourself.

I'm not about to type out all the words I know, not when I don't actually want to know them.

SQL Query for Logins

Starting with SQL 2008, you should use sys.server_principals instead of sys.syslogins, which has been deprecated.

Possible to make labels appear when hovering over a point in matplotlib?

It seems none of the other answers here actually answer the question. So here is a code that uses a scatter and shows an annotation upon hovering over the scatter points.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))
c = np.random.randint(1,5,size=15)

norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn

fig,ax = plt.subplots()
sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm)

annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)

def update_annot(ind):

    pos = sc.get_offsets()[ind["ind"][0]]
    annot.xy = pos
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), 
                           " ".join([names[n] for n in ind["ind"]]))
    annot.set_text(text)
    annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
    annot.get_bbox_patch().set_alpha(0.4)


def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = sc.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()

fig.canvas.mpl_connect("motion_notify_event", hover)

plt.show()

enter image description here

Because people also want to use this solution for a line plot instead of a scatter, the following would be the same solution for plot (which works slightly differently).

_x000D_
_x000D_
import matplotlib.pyplot as plt_x000D_
import numpy as np; np.random.seed(1)_x000D_
_x000D_
x = np.sort(np.random.rand(15))_x000D_
y = np.sort(np.random.rand(15))_x000D_
names = np.array(list("ABCDEFGHIJKLMNO"))_x000D_
_x000D_
norm = plt.Normalize(1,4)_x000D_
cmap = plt.cm.RdYlGn_x000D_
_x000D_
fig,ax = plt.subplots()_x000D_
line, = plt.plot(x,y, marker="o")_x000D_
_x000D_
annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",_x000D_
                    bbox=dict(boxstyle="round", fc="w"),_x000D_
                    arrowprops=dict(arrowstyle="->"))_x000D_
annot.set_visible(False)_x000D_
_x000D_
def update_annot(ind):_x000D_
    x,y = line.get_data()_x000D_
    annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])_x000D_
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), _x000D_
                           " ".join([names[n] for n in ind["ind"]]))_x000D_
    annot.set_text(text)_x000D_
    annot.get_bbox_patch().set_alpha(0.4)_x000D_
_x000D_
_x000D_
def hover(event):_x000D_
    vis = annot.get_visible()_x000D_
    if event.inaxes == ax:_x000D_
        cont, ind = line.contains(event)_x000D_
        if cont:_x000D_
            update_annot(ind)_x000D_
            annot.set_visible(True)_x000D_
            fig.canvas.draw_idle()_x000D_
        else:_x000D_
            if vis:_x000D_
                annot.set_visible(False)_x000D_
                fig.canvas.draw_idle()_x000D_
_x000D_
fig.canvas.mpl_connect("motion_notify_event", hover)_x000D_
_x000D_
plt.show()
_x000D_
_x000D_
_x000D_

In case someone is looking for a solution for lines in twin axes, refer to How to make labels appear when hovering over a point in multiple axis?

In case someone is looking for a solution for bar plots, please refer to e.g. this answer.

Alter table add multiple columns ms sql

Alter table Hotels 
Add  
{ 
 HasPhotoInReadyStorage  bit, 
 HasPhotoInWorkStorage  bit, 
 HasPhotoInMaterialStorage bit, 
 HasHotelPhotoInReadyStorage  bit, 
 HasHotelPhotoInWorkStorage  bit, 
 HasHotelPhotoInMaterialStorage bit, 
 HasReporterData  bit, 
 HasMovieInReadyStorage  bit, 
 HasMovieInWorkStorage  bit, 
 HasMovieInMaterialStorage bit 
}; 

Above you are using {, }.

Also, you are missing commas:

ALTER TABLE Regions 
ADD ( HasPhotoInReadyStorage  bit, 
 HasPhotoInWorkStorage  bit, 
 HasPhotoInMaterialStorage bit <**** comma needed here
 HasText  bit); 

You need to remove the brackets and make sure all columns have a comma where necessary.

How to add header row to a pandas DataFrame

You can use names directly in the read_csv

names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

Get user info via Google API

Add this to the scope - https://www.googleapis.com/auth/userinfo.profile

And after authorization is done, get the information from - https://www.googleapis.com/oauth2/v1/userinfo?alt=json

It has loads of stuff - including name, public profile url, gender, photo etc.

Link to the issue number on GitHub within a commit message

they have an nice write up about the new issues 2.0 on their blog https://github.blog/2011-04-09-issues-2-0-the-next-generation/

synonyms include

  • fixes #xxx
  • fixed #xxx
  • fix #xxx
  • closes #xxx
  • close #xxx
  • closed #xxx

using any of the keywords in a commit message will make your commit either mentioned or close an issue.

Get selected value from combo box in C# WPF

Solving this problem is simple. All I did was to add "SelectedValuePath" to my XAML code and bind it to my model property that I want to return with the combobox.

<ComboBox SelectedValuePath="_Department"
          DisplayMemberPath="_Department"
          Height="23"
          HorizontalAlignment="Left"
          ItemsSource="{Binding}"
          Margin="-58,1,0,5"
          Name="_DepartmentComboBox"
          VerticalAlignment="Center"
          Width="268"/>