Programs & Examples On #Null object pattern

A pattern where a specific object is used to represent a null, rather than a true programmatic null, in order to avoid various complications that arise from using an actual null. When using this tag on implementation heavy questions - tag the code language the implementation is written in.

How to Free Inode Usage?

We faced similar issue recently, In case if a process refers to a deleted file, the Inode shall not be released, so you need to check lsof /, and kill/ restart the process will release the inodes.

Correct me if am wrong here.

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

There is also another possible source of this error. In some J2EE / web containers (in my experience under Jboss 7.x and Tomcat 7.x) You have to add each class You want to use as a hibernate Entity into the file persistence.xml as

<class>com.yourCompanyName.WhateverEntityClass</class>

In case of jboss this concerns every entity class (local - i.e. within the project You are developing or in a library). In case of Tomcat 7.x this concerns only entity classes within libraries.

Using Mockito's generic "any()" method

As I needed to use this feature for my latest project (at one point we updated from 1.10.19), just to keep the users (that are already using the mockito-core version 2.1.0 or greater) up to date, the static methods from the above answers should be taken from ArgumentMatchers class:

import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.any;

Please keep this in mind if you are planning to keep your Mockito artefacts up to date as possibly starting from version 3, this class may no longer exist:

As per 2.1.0 and above, Javadoc of org.mockito.Matchers states:

Use org.mockito.ArgumentMatchers. This class is now deprecated in order to avoid a name clash with Hamcrest * org.hamcrest.Matchers class. This class will likely be removed in version 3.0.

I have written a little article on mockito wildcards if you're up for further reading.

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

jQuery Form Validation before Ajax submit

function validateForm()
{
    var a=document.forms["Form"]["firstname"].value;
    var b=document.forms["Form"]["midname"].value;
    var c=document.forms["Form"]["lastname"].value;
    var d=document.forms["Form"]["tribe"].value;
    if (a==null || a=="",b==null || b=="",c==null || c=="",d==null || d=="")
    {
        alert("Please Fill All Required Field");
        return false;
    }
    else{

        $.ajax({
        type: 'post',
        url: 'add.php',
        data: $('form').serialize(),
        success: function () {
          alert('Patient added');
          document.getElementById("form").reset();
        }
      });

    }
}

  $(function () {

    $('form').on('submit', function (e) {
      e.preventDefault();

      validateForm();


    });
  });

How do I properly escape quotes inside HTML attributes?

You really should only allow untrusted data into a whitelist of good attributes like: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width

You really want to keep untrusted data out of javascript handlers as well as id or name attributes (they can clobber other elements in the DOM).

Also, if you are putting untrusted data into a SRC or HREF attribute, then its really a untrusted URL so you should validate the URL, make sure its NOT a javascript: URL, and then HTML entity encode.

More details on all of there here: https://www.owasp.org/index.php/Abridged_XSS_Prevention_Cheat_Sheet

How can I open an Excel file in Python?

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

Now you can use the power of pandas DataFrames!

Using global variables in a function

If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces.

Say you've got a module like this:

# sample.py
myGlobal = 5

def func1():
    myGlobal = 42

def func2():
    print myGlobal

func1()
func2()

You might expecting this to print 42, but instead it prints 5. As has already been mentioned, if you add a 'global' declaration to func1(), then func2() will print 42.

def func1():
    global myGlobal
    myGlobal = 42

What's going on here is that Python assumes that any name that is assigned to, anywhere within a function, is local to that function unless explicitly told otherwise. If it is only reading from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope).

When you assign 42 to the name myGlobal, therefore, Python creates a local variable that shadows the global variable of the same name. That local goes out of scope and is garbage-collected when func1() returns; meanwhile, func2() can never see anything other than the (unmodified) global name. Note that this namespace decision happens at compile time, not at runtime -- if you were to read the value of myGlobal inside func1() before you assign to it, you'd get an UnboundLocalError, because Python has already decided that it must be a local variable but it has not had any value associated with it yet. But by using the 'global' statement, you tell Python that it should look elsewhere for the name instead of assigning to it locally.

(I believe that this behavior originated largely through an optimization of local namespaces -- without this behavior, Python's VM would need to perform at least three name lookups each time a new name is assigned to inside a function (to ensure that the name didn't already exist at module/builtin level), which would significantly slow down a very common operation.)

How to get the total number of rows of a GROUP BY query?

The method I ended up using is very simple:

$query = 'SELECT a, b, c FROM tbl WHERE oele = 2 GROUP BY boele';
$nrows = $db->query("SELECT COUNT(1) FROM ($query) x")->fetchColumn();

Might not be the most efficient, but it seems to be foolproof, because it actually counts the original query's results.

Javascript: The prettiest way to compare one value against multiple values

Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):

(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)

if (~[foo, bar].indexOf(foobar)) {
    // pretty
}

HTML if image is not found

I added a parent div around the image and used the following onerror event handler to hide the original image because in IE there was still an ugly image-not-found image shown after using the alt attribute:

<div style=" width:300px; height:150px; float:left; margin-left:5px; margin-top:50px;">
        <img src='@Url.Content("~/Images/Logo-Left.png")' onerror="this.parentElement.innerHTML = '';" />
</div>

How to split the name string in mysql?

First Create Procedure as Below:

CREATE DEFINER=`root`@`%` PROCEDURE `sp_split`(str nvarchar(6500), dilimiter varchar(15), tmp_name varchar(50))
BEGIN

    declare end_index   int;
    declare part        nvarchar(6500);
    declare remain_len  int;

    set end_index      = INSTR(str, dilimiter);

    while(end_index   != 0) do

        /* Split a part */
        set part       = SUBSTRING(str, 1, end_index - 1);

        /* insert record to temp table */
        call `sp_split_insert`(tmp_name, part);

        set remain_len = length(str) - end_index;
        set str = substring(str, end_index + 1, remain_len);

        set end_index  = INSTR(str, dilimiter);

    end while;

    if(length(str) > 0) then

        /* insert record to temp table */
        call `sp_split_insert`(tmp_name, str);

    end if;

END

After that create procedure as below:

CREATE DEFINER=`root`@`%` PROCEDURE `sp_split_insert`(tb_name varchar(255), tb_value nvarchar(6500))
BEGIN
    SET @sql = CONCAT('Insert Into ', tb_name,'(item) Values(?)'); 
    PREPARE s1 from @sql;
    SET @paramA = tb_value;
    EXECUTE s1 USING @paramA;
END

How call test

CREATE DEFINER=`root`@`%` PROCEDURE `test_split`(test_text nvarchar(255))
BEGIN

    create temporary table if not exists tb_search
        (
            item nvarchar(6500)
        );

    call sp_split(test_split, ',', 'tb_search');

    select * from tb_search where length(trim(item)) > 0;

    drop table tb_search;

END


call `test_split`('Apple,Banana,Mengo');

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

I had the same issue. After much searching I decided to reconfigure my server in Eclipse. (ie clean it as suggested by Benson Go to Project Explorer, Servers and Delete (ensure you also delete contents on disk) Then go to Windows->Preferences->Server->Runtime Environments Remove the Tomcat server and then add it back in.

This cleans up the server.xml, webxml, context.xml files. It basically rewrites them. Something in one of mine (or multiple things) were awry and this fixes it. A bit simpler than trying to find the offending tags/lines

How do you fadeIn and animate at the same time?

$('.tooltip').animate({ opacity: 1, top: "-10px" }, 'slow');

However, this doesn't appear to work on display: none elements (as fadeIn does). So, you might need to put this beforehand:

$('.tooltip').css('display', 'block');
$('.tooltip').animate({ opacity: 0 }, 0);

What is the meaning of # in URL and how can I use that?

It specifies an "Anchor", or a position on the page, and allows you to "jump" or "scroll" to that position on the page.

Please see this page for more details.

How to find the operating system version using JavaScript?

I started to write a Script to read OS and browser version that can be tested on Fiddle. Feel free to use and extend.
Breaking Change:
Since September 2020 the new Edge gets detected. So 'Microsoft Edge' is the new version based on Chromium and the old Edge is now detected as 'Microsoft Legacy Edge'!

/**
 * JavaScript Client Detection
 * (C) viazenetti GmbH (Christian Ludwig)
 */
(function (window) {
    {
        var unknown = '-';

        // screen
        var screenSize = '';
        if (screen.width) {
            width = (screen.width) ? screen.width : '';
            height = (screen.height) ? screen.height : '';
            screenSize += '' + width + " x " + height;
        }

        // browser
        var nVer = navigator.appVersion;
        var nAgt = navigator.userAgent;
        var browser = navigator.appName;
        var version = '' + parseFloat(navigator.appVersion);
        var majorVersion = parseInt(navigator.appVersion, 10);
        var nameOffset, verOffset, ix;

        // Opera
        if ((verOffset = nAgt.indexOf('Opera')) != -1) {
            browser = 'Opera';
            version = nAgt.substring(verOffset + 6);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // Opera Next
        if ((verOffset = nAgt.indexOf('OPR')) != -1) {
            browser = 'Opera';
            version = nAgt.substring(verOffset + 4);
        }
        // Legacy Edge
        else if ((verOffset = nAgt.indexOf('Edge')) != -1) {
            browser = 'Microsoft Legacy Edge';
            version = nAgt.substring(verOffset + 5);
        } 
        // Edge (Chromium)
        else if ((verOffset = nAgt.indexOf('Edg')) != -1) {
            browser = 'Microsoft Edge';
            version = nAgt.substring(verOffset + 4);
        }
        // MSIE
        else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
        }
        // Chrome
        else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
            browser = 'Chrome';
            version = nAgt.substring(verOffset + 7);
        }
        // Safari
        else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
            browser = 'Safari';
            version = nAgt.substring(verOffset + 7);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // Firefox
        else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
            browser = 'Firefox';
            version = nAgt.substring(verOffset + 8);
        }
        // MSIE 11+
        else if (nAgt.indexOf('Trident/') != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(nAgt.indexOf('rv:') + 3);
        }
        // Other browsers
        else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
            browser = nAgt.substring(nameOffset, verOffset);
            version = nAgt.substring(verOffset + 1);
            if (browser.toLowerCase() == browser.toUpperCase()) {
                browser = navigator.appName;
            }
        }
        // trim the version string
        if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);

        majorVersion = parseInt('' + version, 10);
        if (isNaN(majorVersion)) {
            version = '' + parseFloat(navigator.appVersion);
            majorVersion = parseInt(navigator.appVersion, 10);
        }

        // mobile version
        var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);

        // cookie
        var cookieEnabled = (navigator.cookieEnabled) ? true : false;

        if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
            document.cookie = 'testcookie';
            cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
        }

        // system
        var os = unknown;
        var clientStrings = [
            {s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/},
            {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
            {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
            {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
            {s:'Windows Vista', r:/Windows NT 6.0/},
            {s:'Windows Server 2003', r:/Windows NT 5.2/},
            {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
            {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
            {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
            {s:'Windows 98', r:/(Windows 98|Win98)/},
            {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
            {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
            {s:'Windows CE', r:/Windows CE/},
            {s:'Windows 3.11', r:/Win16/},
            {s:'Android', r:/Android/},
            {s:'Open BSD', r:/OpenBSD/},
            {s:'Sun OS', r:/SunOS/},
            {s:'Chrome OS', r:/CrOS/},
            {s:'Linux', r:/(Linux|X11(?!.*CrOS))/},
            {s:'iOS', r:/(iPhone|iPad|iPod)/},
            {s:'Mac OS X', r:/Mac OS X/},
            {s:'Mac OS', r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
            {s:'QNX', r:/QNX/},
            {s:'UNIX', r:/UNIX/},
            {s:'BeOS', r:/BeOS/},
            {s:'OS/2', r:/OS\/2/},
            {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
        ];
        for (var id in clientStrings) {
            var cs = clientStrings[id];
            if (cs.r.test(nAgt)) {
                os = cs.s;
                break;
            }
        }

        var osVersion = unknown;

        if (/Windows/.test(os)) {
            osVersion = /Windows (.*)/.exec(os)[1];
            os = 'Windows';
        }

        switch (os) {
            case 'Mac OS':
            case 'Mac OS X':
            case 'Android':
                osVersion = /(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'iOS':
                osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
                osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
                break;
        }
        
        // flash (you'll need to include swfobject)
        /* script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" */
        var flashVersion = 'no check';
        if (typeof swfobject != 'undefined') {
            var fv = swfobject.getFlashPlayerVersion();
            if (fv.major > 0) {
                flashVersion = fv.major + '.' + fv.minor + ' r' + fv.release;
            }
            else  {
                flashVersion = unknown;
            }
        }
    }

    window.jscd = {
        screen: screenSize,
        browser: browser,
        browserVersion: version,
        browserMajorVersion: majorVersion,
        mobile: mobile,
        os: os,
        osVersion: osVersion,
        cookies: cookieEnabled,
        flashVersion: flashVersion
    };
}(this));

alert(
    'OS: ' + jscd.os +' '+ jscd.osVersion + '\n' +
    'Browser: ' + jscd.browser +' '+ jscd.browserMajorVersion +
      ' (' + jscd.browserVersion + ')\n' + 
    'Mobile: ' + jscd.mobile + '\n' +
    'Flash: ' + jscd.flashVersion + '\n' +
    'Cookies: ' + jscd.cookies + '\n' +
    'Screen Size: ' + jscd.screen + '\n\n' +
    'Full User Agent: ' + navigator.userAgent
);

C# Timer or Thread.Sleep

I agree as well, using a timer is the best option. I have tried a solution similar to yours in the past and started having issues where the loop would misfire, and I would have to wait for another Thread.Sleep() before it would fire again. Also, it did cause all sorts of issues with stopping the service, I would get constant errors about how it wasn't responding and had to be closed.

@Prashanth's code should be exactly what you need.

Select multiple columns from a table, but group by one

==EDIT==

I checked your question again and have concluded this can't be done.

ProductName is not unique, It must either be part of the Group By or excluded from your results.

For example how would SQL present these results to you if you Group By only ProductID?

ProductID | ProductName | OrderQuantity 
---------------------------------------
1234      | abc         | 1
1234      | def         | 1
1234      | ghi         | 1
1234      | jkl         | 1

React Router v4 - How to get current route?

If you are using react's templates, where the end of your react file looks like this: export default SomeComponent you need to use the higher-order component (often referred to as an "HOC"), withRouter.

First, you'll need to import withRouter like so:

import {withRouter} from 'react-router-dom';

Next, you'll want to use withRouter. You can do this by change your component's export. It's likely you want to change from export default ComponentName to export default withRouter(ComponentName).

Then you can get the route (and other information) from props. Specifically, location, match, and history. The code to spit out the pathname would be:

console.log(this.props.location.pathname);

A good writeup with additional information is available here: https://reacttraining.com/react-router/core/guides/philosophy

Skip first entry in for loop in python?

Example:

mylist=['one','two','three','four','five']
for i in mylist[1:]:
   print(i)

In python index start from 0, We can use slicing operator to make manipulations in iteration.

for i in range(1,-1):

Why doesn't file_get_contents work?

//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>        
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> 
</script>
</head>
<body>
<?php    
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData   = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>

How do I convert this list of dictionaries to a csv file?

In python 3 things are a little different, but way simpler and less error prone. It's a good idea to tell the CSV your file should be opened with utf8 encoding, as it makes that data more portable to others (assuming you aren't using a more restrictive encoding, like latin1)

import csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
with open('people.csv', 'w', encoding='utf8', newline='') as output_file:
    fc = csv.DictWriter(output_file, 
                        fieldnames=toCSV[0].keys(),

                       )
    fc.writeheader()
    fc.writerows(toCSV)
  • Note that csv in python 3 needs the newline='' parameter, otherwise you get blank lines in your CSV when opening in excel/opencalc.

Alternatively: I prefer use to the csv handler in the pandas module. I find it is more tolerant of encoding issues, and pandas will automatically convert string numbers in CSVs into the correct type (int,float,etc) when loading the file.

import pandas
dataframe = pandas.read_csv(filepath)
list_of_dictionaries = dataframe.to_dict('records')
dataframe.to_csv(filepath)

Note:

  • pandas will take care of opening the file for you if you give it a path, and will default to utf8 in python3, and figure out headers too.
  • a dataframe is not the same structure as what CSV gives you, so you add one line upon loading to get the same thing: dataframe.to_dict('records')
  • pandas also makes it much easier to control the order of columns in your csv file. By default, they're alphabetical, but you can specify the column order. With vanilla csv module, you need to feed it an OrderedDict or they'll appear in a random order (if working in python < 3.5). See: Preserving column order in Python Pandas DataFrame for more.

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

VBA subs are no macros. A VBA sub can be a macro, but it is not a must.

The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.

The more elegant way is, to design and write your own VBA code without using the macro features!

VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.

If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".

In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.

It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.

In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.

Move the mouse pointer to a specific position?

Interesting. This isn't directly possible for the reasons called out earlier (spam clicks and malware injection), but consider this hack, which creates an impression of the same:

Step 1: Hide the cursor

Let's say you've a div, you can use this css property to hide the real cursor:

.your_div {
    cursor: none
}

Step 2: Introduce a pseudo cursor

Simply create an image, a cursor look-alike,mouse cursor imageand place it within your webpage, with position:absolute.

Step 3: Track actual mouse movement

This is easy. Check internet on how to get real mouse location (X & Y coordinates).

Step 4: Move the pseudo cursor

As the actual cursor move, move your pseudo cursor by same X & Y difference. Similarly, you can always generate a click event at any location on your webpage with javascript magic (just search the internet on how-to).

Now at this point, you can control the pesudo cursor the way you want, and your user will get the impression that the real cursor is moving.


Fair Warning: Do not do it. No one wants their cursor or computer controlled this way, unless if you've some specific use-case, or if you are determined to flee your users away.

Get single row result with Doctrine NativeQuery

->getSingleScalarResult() will return a single value, instead of an array.

MySQL - Replace Character in Columns

maybe I'd go by this.

 SQL = SELECT REPLACE(myColumn, '""', '\'') FROM myTable

I used singlequotes because that's the one that registers string expressions in MySQL, or so I believe.

Hope that helps.

How can I add a class to a DOM element in JavaScript?

Here is working source code using a function approach.

<html>
    <head>
        <style>
            .news{padding:10px; margin-top:2px;background-color:red;color:#fff;}
        </style>
    </head>

    <body>
    <div id="dd"></div>
        <script>
            (function(){
                var countup = this;
                var newNode = document.createElement('div');
                newNode.className = 'textNode news content';
                newNode.innerHTML = 'this created div contains a class while created!!!';
                document.getElementById('dd').appendChild(newNode);
            })();
        </script>
    </body>
</html>

Automatically start a Windows Service on install

You can use the GetServices method of ServiceController class to get an array of all the services. Then, find your service by checking the ServiceName property of each service. When you've found your service, call the Start method to start it.

You should also check the Status property to see what state it is already in before calling start (it may be running, paused, stopped, etc..).

JavaScript: How to find out if the user browser is Chrome?

To know the names of different desktop browsers (Firefox, IE, Opera, Edge, Chrome). Except Safari.

function getBrowserName() {
  var browserName = '';
  var userAgent = navigator.userAgent;
  (typeof InstallTrigger !== 'undefined') && (browserName = 'Firefox');
  ( /* @cc_on!@*/ false || !!document.documentMode) && (browserName = 'IE');
  (!!window.chrome && userAgent.match(/OPR/)) && (browserName = 'Opera');
  (!!window.chrome && userAgent.match(/Edge/)) && (browserName = 'Edge');
  (!!window.chrome && !userAgent.match(/(OPR|Edge)/)) && (browserName = 'Chrome');

  /**
   * Expected returns
   * Firefox, Opera, Edge, Chrome
   */
  return browserName;
}

Works in the following browser versions:

Opera - 58.0.3135.79
Firefox - 65.0.2 (64-bit)
IE - 11.413.15063 (JS Fiddle no longer supports IE just paste in Console)
Edge - 44.17763.1.0
Chrome - 72.0.3626.121 (Official Build) (64-bit)

View the gist here and the fiddle here

The original code snippet no longer worked for Chrome and I forgot where I found it. It had safari before but I no longer have access to safari so I cannot verify anymore.

Only the Firefox and IE codes were part of the original snippet.

The checking for Opera, Edge, and Chrome is straight forward. They have differences in the userAgent. OPR only exists in Opera. Edge only exists in Edge. So to check for Chrome these string shouldn't be there.

As for the Firefox and IE, I cannot explain what they do.

I'll be adding this functionality to a package i'm writing

How to get rid of underline for Link component of React Router?

Working for me, just add className="nav-link" and activeStyle{{textDecoration:'underline'}}

<NavLink className="nav-link" to="/" exact activeStyle= 
  {{textDecoration:'underline'}}>My Record</NavLink>

Run C++ in command prompt - Windows

Open cmd and go In Directory where file is saved. Then, For compile, g++ FileName. cpp Or gcc FileName. cpp

For Run, FileName. exe

This Is For Compile & Run Program.

Make sure, gcc compiler installed in PC or Laptop. And also path variable must be set.

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

I know this is going to be a late answer, however here is the most correct answer.

In MySQL database, change your timestamp default value into CURRENT_TIMESTAMP. If you have old records with the fake value, you will have to manually fix them.

DTO pattern: Best way to copy properties between two objects

Wouldn't lambdaj's project function do what you are looking for?

It'll look something like this:

List<UserDTO> userNDtos = project(users, UserDTO.class, on(User.class).getUserName(), on(User.class).getFullName(), .....);

(Define the constructor for UserDTO accordingly...)

Also see here for examples...

How to make PDF file downloadable in HTML link?

Instead of linking to the .PDF file, instead do something like

<a href="pdf_server.php?file=pdffilename">Download my eBook</a>

which outputs a custom header, opens the PDF (binary safe) and prints the data to the user's browser, then they can choose to save the PDF despite their browser settings. The pdf_server.php should look like this:

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
} 
fclose($fp); 

PS: and obviously run some sanity checks on the "file" variable to prevent people from stealing your files such as don't accept file extensions, deny slashes, add .pdf to the value

Python - converting a string of numbers into a list of int

Split on commas, then map to integers:

map(int, example_string.split(','))

Or use a list comprehension:

[int(s) for s in example_string.split(',')]

The latter works better if you want a list result, or you can wrap the map() call in list().

This works because int() tolerates whitespace:

>>> example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
>>> list(map(int, example_string.split(',')))  # Python 3, in Python 2 the list() call is redundant
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
>>> [int(s) for s in example_string.split(',')]
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]

Splitting on just a comma also is more tolerant of variable input; it doesn't matter if 0, 1 or 10 spaces are used between values.

How do I cast a JSON Object to a TypeScript class?

I ran into a similar need. I wanted something that will give me easy transformation from/to JSON that is coming from a REST api call to/from specific class definition. The solutions that I've found were insufficient or meant to rewrite my classes' code and adding annotations or similars.

I wanted something like GSON is used in Java to serialize/deserialize classes to/from JSON objects.

Combined with a later need, that the converter will function in JS as well, I ended writing my own package.

It has though, a little bit of overhead. But when started it is very convenient in adding and editing.

You initialize the module with :

  1. conversion schema - allowing to map between fields and determine how the conversion will be done
  2. Classes map array
  3. Conversion functions map - for special conversions.

Then in your code, you use the initialized module like :

const convertedNewClassesArray : MyClass[] = this.converter.convert<MyClass>(jsonObjArray, 'MyClass');

const convertedNewClass : MyClass = this.converter.convertOneObject<MyClass>(jsonObj, 'MyClass');

or , to JSON :

const jsonObject = this.converter.convertToJson(myClassInstance);

Use this link to the npm package and also a detailed explanation to how to work with the module: json-class-converter

Also wrapped it for
Angular use in : angular-json-class-converter

How to split a string to 2 strings in C

For purposes such as this, I tend to use strtok_r() instead of strtok().

For example ...

int main (void) {
char str[128];
char *ptr;

strcpy (str, "123456 789asdf");
strtok_r (str, " ", &ptr);

printf ("'%s'  '%s'\n", str, ptr);
return 0;
}

This will output ...

'123456' '789asdf'

If more delimiters are needed, then loop.

Hope this helps.

Installing Bootstrap 3 on Rails App

I think the most up to date gem for the new bootstrap version is form anjlab.

But I don't know if it currently works good with other gems like simple_form when you do rails generate simple_form:install --bootstrap, etc. you may have to edit some initializers or configurations to fit the new bootstrap version.

syntaxerror: unexpected character after line continuation character in python

The filename should be a string. In other names it should be within quotes.

f = open("D\\python\\HW\\2_1 - Copy.cp","r")
lines = f.readlines()
for i in lines:
    thisline = i.split(" ");

You can also open the file using with

with open("D\\python\\HW\\2_1 - Copy.cp","r") as f:
    lines = f.readlines()
    for i in lines:
        thisline = i.split(" ");

There is no need to add the semicolon(;) in python. It's ugly.

Android : change button text and background color

Just complementing @Jonsmoke's answer.

For API level 21 and above you can use :

android:backgroundTint="@android:color/white"

in XML for the button layout.

For API level below 21 use an AppCompatButton using app namespace instead of android for backgroundTint.

For example:

<android.support.v7.widget.AppCompatButton
    android:id="@+id/my_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="My Button"
    app:backgroundTint="@android:color/white" />

Using sudo with Python script

  • Use -S option in the sudo command which tells to read the password from 'stdin' instead of the terminal device.

  • Tell Popen to read stdin from PIPE.

  • Send the Password to the stdin PIPE of the process by using it as an argument to communicate method. Do not forget to add a new line character, '\n', at the end of the password.

sp = Popen(cmd , shell=True, stdin=PIPE)
out, err = sp.communicate(_user_pass+'\n')   

Jquery- Get the value of first td in table

This should work:

$(".hit").click(function(){    
   var value=$(this).closest('tr').children('td:first').text();
   alert(value);    
});

Explanation:

  • .closest('tr') gets the nearest ancestor that is a <tr> element (so in this case the row where the <a> element is in).
  • .children('td:first') gets all the children of this element, but with the :first selector we reduce it to the first <td> element.
  • .text() gets the text inside the element

As you can see from the other answers, there is more than only one way to do this.

Sort a List of objects by multiple fields

Your Comparator would look like this:

public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
    public int compare(GraduationCeremony o1, GraduationCeremony o2) {
        int value1 = o1.campus.compareTo(o2.campus);
        if (value1 == 0) {
            int value2 = o1.faculty.compareTo(o2.faculty);
            if (value2 == 0) {
                return o1.building.compareTo(o2.building);
            } else {
                return value2;
            }
        }
        return value1;
    }
}

Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).

Is it better to use std::memcpy() or std::copy() in terms to performance?

Just a minor addition: The speed difference between memcpy() and std::copy() can vary quite a bit depending on if optimizations are enabled or disabled. With g++ 6.2.0 and without optimizations memcpy() clearly wins:

Benchmark             Time           CPU Iterations
---------------------------------------------------
bm_memcpy            17 ns         17 ns   40867738
bm_stdcopy           62 ns         62 ns   11176219
bm_stdcopy_n         72 ns         72 ns    9481749

When optimizations are enabled (-O3), everything looks pretty much the same again:

Benchmark             Time           CPU Iterations
---------------------------------------------------
bm_memcpy             3 ns          3 ns  274527617
bm_stdcopy            3 ns          3 ns  272663990
bm_stdcopy_n          3 ns          3 ns  274732792

The bigger the array the less noticeable the effect gets, but even at N=1000 memcpy() is about twice as fast when optimizations aren't enabled.

Source code (requires Google Benchmark):

#include <string.h>
#include <algorithm>
#include <vector>
#include <benchmark/benchmark.h>

constexpr int N = 10;

void bm_memcpy(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    memcpy(r.data(), a.data(), N * sizeof(int));
  }
}

void bm_stdcopy(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    std::copy(a.begin(), a.end(), r.begin());
  }
}

void bm_stdcopy_n(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    std::copy_n(a.begin(), N, r.begin());
  }
}

BENCHMARK(bm_memcpy);
BENCHMARK(bm_stdcopy);
BENCHMARK(bm_stdcopy_n);

BENCHMARK_MAIN()

/* EOF */

Prevent BODY from scrolling when a modal is opened

The best solution is the css-only body{overflow:hidden} solution used by most of these answers. Some answers provide a fix that also prevent the "jump" caused by the disappearing scrollbar; however, none were too elegant. So, I wrote these two functions, and they seem to work pretty well.

var $body = $(window.document.body);

function bodyFreezeScroll() {
    var bodyWidth = $body.innerWidth();
    $body.css('overflow', 'hidden');
    $body.css('marginRight', ($body.css('marginRight') ? '+=' : '') + ($body.innerWidth() - bodyWidth))
}

function bodyUnfreezeScroll() {
    var bodyWidth = $body.innerWidth();
    $body.css('marginRight', '-=' + (bodyWidth - $body.innerWidth()))
    $body.css('overflow', 'auto');
}

Check out this jsFiddle to see it in use.

Difference between request.getSession() and request.getSession(true)

request.getSession() or request.getSession(true) both will return a current session only . if current session will not exist then it will create a new session.

Plot multiple boxplot in one graph

You should get your data in a specific format by melting your data (see below for how melted data looks like) before you plot. Otherwise, what you have done seems to be okay.

require(reshape2)
df <- read.csv("TestData.csv", header=T)
# melting by "Label". `melt is from the reshape2 package. 
# do ?melt to see what other things it can do (you will surely need it)
df.m <- melt(df, id.var = "Label")
> df.m # pasting some rows of the melted data.frame

#     Label variable      value
# 1    Good       F1 0.64778924
# 2    Good       F1 0.54608791
# 3    Good       F1 0.46134200
# 4    Good       F1 0.79421221
# 5    Good       F1 0.56919951
# 6    Good       F1 0.73568570
# 7    Good       F1 0.65094207
# 8    Good       F1 0.45749702
# 9    Good       F1 0.80861929
# 10   Good       F1 0.67310067
# 11   Good       F1 0.68781739
# 12   Good       F1 0.47009455
# 13   Good       F1 0.95859182
# 14   Good       F1 1.00000000
# 15   Good       F1 0.46908343
# 16    Bad       F1 0.57875528
# 17    Bad       F1 0.28938046
# 18    Bad       F1 0.68511766

require(ggplot2)
ggplot(data = df.m, aes(x=variable, y=value)) + geom_boxplot(aes(fill=Label))

boxplot_ggplot2

Edit: I realise that you might need to facet. Here's an implementation of that as well:

p <- ggplot(data = df.m, aes(x=variable, y=value)) + 
             geom_boxplot(aes(fill=Label))
p + facet_wrap( ~ variable, scales="free")

ggplot2_faceted

Edit 2: How to add x-labels, y-labels, title, change legend heading, add a jitter?

p <- ggplot(data = df.m, aes(x=variable, y=value)) 
p <- p + geom_boxplot(aes(fill=Label))
p <- p + geom_jitter()
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p 

ggplot2_geom_plot

Edit 3: How to align geom_point() points to the center of box-plot? It could be done using position_dodge. This should work.

require(ggplot2)
p <- ggplot(data = df.m, aes(x=variable, y=value)) 
p <- p + geom_boxplot(aes(fill = Label))
# if you want color for points replace group with colour=Label
p <- p + geom_point(aes(y=value, group=Label), position = position_dodge(width=0.75))
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p 

ggplot2_position_dodge_geom_point

Autoincrement VersionCode with gradle extra properties

Define versionName in AndroidManifest.xml

android:versionName="5.1.5"

Inside android{...} block in build.gradle of app level :

defaultConfig {
        applicationId "com.example.autoincrement"
        minSdkVersion 18
        targetSdkVersion 23
        multiDexEnabled true
        def version = getIncrementationVersionName()
        versionName version
}

Outside android{...} block in build.gradle of app level :

def getIncrementedVersionName() {
    List<String> runTasks = gradle.startParameter.getTaskNames();

    //find version name in manifest
    def manifestFile = file('src/main/AndroidManifest.xml')
    def matcher = Pattern.compile('versionName=\"(\\d+)\\.(\\d+)\\.(\\d+)\"').matcher(manifestFile.getText())
    matcher.find()

    //extract versionName parts
    def firstPart = Integer.parseInt(matcher.group(1))
    def secondPart = Integer.parseInt(matcher.group(2))
    def thirdPart = Integer.parseInt(matcher.group(3))

    //check is runTask release or not
    // if release - increment version
    for (String item : runTasks) {
        if (item.contains("assemble") && item.contains("Release")) {
            thirdPart++
            if (thirdPart == 10) {
                thirdPart = 0;
                secondPart++
                if (secondPart == 10) {
                    secondPart = 0;
                    firstPart++
                }
            }
        }
    }

    def versionName = firstPart + "." + secondPart + "." + thirdPart

    // update manifest
    def manifestContent = matcher.replaceAll('versionName=\"' + versionName + '\"')
    manifestFile.write(manifestContent)

    println "incrementVersionName = " + versionName

    return versionName
}

After create singed APK :

android:versionName="5.1.6"

Note : If your versionName different from my, you need change regex and extract parts logic.

How to remove all event handlers from an event

Stephen has right. It is very easy:

public event EventHandler<Cles_graph_doivent_etre_redessines> les_graph_doivent_etre_redessines;
public void remove_event()
{
    if (this.les_graph_doivent_etre_redessines != null)
    {
        foreach (EventHandler<Cles_graph_doivent_etre_redessines> F_les_graph_doivent_etre_redessines in this.les_graph_doivent_etre_redessines.GetInvocationList())
        {
            this.les_graph_doivent_etre_redessines -= F_les_graph_doivent_etre_redessines;
        }
    }
}

How to find the cumulative sum of numbers in a list?

Without having to use Numpy, you can loop directly over the array and accumulate the sum along the way. For example:

a=range(10)
i=1
while((i>0) & (i<10)):
    a[i]=a[i-1]+a[i]
    i=i+1
print a

Results in:

[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]

Is it possible to specify the schema when connecting to postgres with JDBC?

As of version 9.4, you can use the currentSchema parameter in your connection string.

For example:

jdbc:postgresql://localhost:5432/mydatabase?currentSchema=myschema

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

Not really a technical solution, but SQL Server 2017 flat file import is totally revamped, and imported my large-ish file with 5 clicks, handled encoding / field length issues without any input from me

enter image description here

Save ArrayList to SharedPreferences

Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple.

TinyDB tinydb = new TinyDB(context);

to put

tinydb.putList("MyUsers", mUsersArray);

to get

tinydb.getList("MyUsers");

UPDATE

Some useful examples and troubleshooting might be found here: Android Shared Preference TinyDB putListObject frunction

Filter element based on .data() key/value

We can make a plugin pretty easily:

$.fn.filterData = function(key, value) {
    return this.filter(function() {
        return $(this).data(key) == value;
    });
};

Usage (checking a radio button):

$('input[name=location_id]').filterData('my-data','data-val').prop('checked',true);

Unpivot with column name

Another way around using cross join would be to specify column names inside cross join

select name, Subject, Marks 
from studentmarks
Cross Join (
values (Maths,'Maths'),(Science,'Science'),(English,'English')
) un(Marks, Subject)
where marks is not null;

How do I check if the mouse is over an element in jQuery?

JUST FYI for future finders of this.

I made a jQuery plugin that can do this and a lot more. In my plugin, to get all elements the cursor is currently hovered over, simply do the following:

$.cursor("isHover"); // will return jQ object of all elements the cursor is 
                     // currently over & doesn't require timer

As I mentioned, it also has alot of other uses as you can see in the

jsFiddle found here

Finding repeated words on a string and counting the repetitions

Using java8

private static void findWords(String s, List<String> output, List<Integer> count){
    String[] words = s.split(", ");
    Map<String, Integer> map = new LinkedHashMap<>();
    Arrays.stream(words).forEach(e->map.put(e, map.getOrDefault(e, 0) + 1));
    map.forEach((k,v)->{
        output.add(k);
        count.add(v);
    });
}

Also, use a LinkedHashMap if you want to preserve the order of insertion

private static void findWords(){
    String s = "House, House, House, Dog, Dog, Dog, Dog";
    List<String> output = new ArrayList<>();
    List<Integer> count = new ArrayList<>();
    findWords(s, output, count);
    System.out.println(output);
    System.out.println(count);
}

Output

[House, Dog]
[3, 4]

Integer to hex string in C++

Use <iomanip>'s std::hex. If you print, just send it to std::cout, if not, then use std::stringstream

std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );

You can prepend the first << with << "0x" or whatever you like if you wish.

Other manips of interest are std::oct (octal) and std::dec (back to decimal).

One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfill and setw this to circumvent the problem:

stream << std::setfill ('0') << std::setw(sizeof(your_type)*2) 
       << std::hex << your_int;

So finally, I'd suggest such a function:

template< typename T >
std::string int_to_hex( T i )
{
  std::stringstream stream;
  stream << "0x" 
         << std::setfill ('0') << std::setw(sizeof(T)*2) 
         << std::hex << i;
  return stream.str();
}

How to push a new folder (containing other folders and files) to an existing git repo?

You can directly go to Web IDE and upload your folder there.

Steps:

  1. Go to Web IDE(Mostly located below the clone option).
  2. Create new directory at your path
  3. Upload your files and folders

In some cases you may not be able to directly upload entire folder containing folders, In such cases, you will have to create directory structure yourself.

What are Covering Indexes and Covered Queries in SQL Server?

When I simply recalled that a Clustered Index consists of a key-ordered non-heap list of ALL the columns in the defined table, the lights went on for me. The word "cluster", then, refers to the fact that there is a "cluster" of all the columns, like a cluster of fish in that "hot spot". If there is no index covering the column containing the sought value (the right side of the equation), then the execution plan uses a Clustered Index Seek into the Clustered Index's representation of the requested column because it does not find the requested column in any other "covering" index. The missing will cause a Clustered Index Seek operator in the proposed Execution Plan, where the sought value is within a column inside the ordered list represented by the Clustered Index.

So, one solution is to create a non-clustered index that has the column containing the requested value inside the index. In this way, there is no need to reference the Clustered Index, and the Optimizer should be able to hook that index in the Execution Plan with no hint. If, however, there is a Predicate naming the single column clustering key and an argument to a scalar value on the clustering key, the Clustered Index Seek Operator will still be used, even if there is already a covering index on a second column in the table without an index.

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

UPDATE: this is not the solution but it's a workaround for a problem that can cause the exception presented in the question.

I've solved changing from Release Configuration to Debug Configuration.

JSON serialization/deserialization in ASP.Net Core

You can use Newtonsoft.Json, it's a dependency of Microsoft.AspNet.Mvc.ModelBinding which is a dependency of Microsoft.AspNet.Mvc. So, you don't need to add a dependency in your project.json.

#using Newtonsoft.Json
....
JsonConvert.DeserializeObject(json);

Note, using a WebAPI controller you don't need to deal with JSON.

UPDATE ASP.Net Core 3.0

Json.NET has been removed from the ASP.NET Core 3.0 shared framework.

You can use the new JSON serializer layers on top of the high-performance Utf8JsonReader and Utf8JsonWriter. It deserializes objects from JSON and serializes objects to JSON. Memory allocations are kept minimal and includes support for reading and writing JSON with Stream asynchronously.

To get started, use the JsonSerializer class in the System.Text.Json.Serialization namespace. See the documentation for information and samples.

To use Json.NET in an ASP.NET Core 3.0 project:

    services.AddMvc()
        .AddNewtonsoftJson();

Read Json.NET support in Migrate from ASP.NET Core 2.2 to 3.0 Preview 2 for more information.

python numpy ValueError: operands could not be broadcast together with shapes

Convert the arrays to matrices, and then perform the multiplication.

X = np.matrix(X)

y = np.matrix(y)

X*y

Pushing to Git returning Error Code 403 fatal: HTTP request failed

To resolve such 403 during push error you have to go in .git directory config file and change the given line:

precomposeunicode = true
[remote "origin"]
http://[email protected]:abc/xyz.git

Change the line to this

precomposeunicode = true
[remote "origin"]
ssh://[email protected]/abc/xyz.git

This resolved my issue.

How to print a query string with parameter values when using Hibernate

add following properties and values to your log4j or logback configuration:

org.hibernate.sql=DEBUG
org.hibernate.type.descriptor.sql.BasicBinder=TRACE

In android how to set navigation drawer header image and name programmatically in class file?

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.addHeaderView(yourview);

HTTP status code 0 - Error Domain=NSURLErrorDomain?

The Response was Empty. Most of the case the codes will stats with 1xx, 2xx, 3xx, 4xx, 5xx.

List of HTTP status codes

Excel CSV. file with more than 1,048,576 rows of data

First you want to change the file format from csv to txt. That is simple to do, just edit the file name and change csv to txt. (Windows will give you warning about possibly corrupting the data, but it is fine, just click ok). Then make a copy of the txt file so that now you have two files both with 2 millions rows of data. Then open up the first txt file and delete the second million rows and save the file. Then open the second txt file and delete the first million rows and save the file. Now change the two files back to csv the same way you changed them to txt originally.

How do I specify the exit code of a console application in .NET?

Just an another way:

public static class ApplicationExitCodes
{
    public static readonly int Failure = 1;
    public static readonly int Success = 0;
}

How do I calculate the normal vector of a line segment?

Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.

The matrix representation of the general 2D transformation looks like this:

x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)

where (x,y) are the components of the original vector and (x', y') are the transformed components.

If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:

x' = -y
y' = +x

Same result as given earlier, but with a little more explanation as to where it comes from.

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

How do you save/store objects in SharedPreferences on Android?

An other way to save and restore an object from android sharedpreferences without using the Json format

private static ExampleObject getObject(Context c,String db_name){
            SharedPreferences sharedPreferences = c.getSharedPreferences(db_name, Context.MODE_PRIVATE);
            ExampleObject o = new ExampleObject();
            Field[] fields = o.getClass().getFields();
            try {
                for (Field field : fields) {
                    Class<?> type = field.getType();
                    try {
                        final String name = field.getName();
                        if (type == Character.TYPE || type.equals(String.class)) {
                            field.set(o,sharedPreferences.getString(name, ""));
                        } else if (type.equals(int.class) || type.equals(Short.class))
                            field.setInt(o,sharedPreferences.getInt(name, 0));
                        else if (type.equals(double.class))
                            field.setDouble(o,sharedPreferences.getFloat(name, 0));
                        else if (type.equals(float.class))
                            field.setFloat(o,sharedPreferences.getFloat(name, 0));
                        else if (type.equals(long.class))
                            field.setLong(o,sharedPreferences.getLong(name, 0));
                        else if (type.equals(Boolean.class))
                            field.setBoolean(o,sharedPreferences.getBoolean(name, false));
                        else if (type.equals(UUID.class))
                            field.set(
                                    o,
                                    UUID.fromString(
                                            sharedPreferences.getString(
                                                    name,
                                                    UUID.nameUUIDFromBytes("".getBytes()).toString()
                                            )
                                    )
                            );

                    } catch (IllegalAccessException e) {
                        Log.e(StaticConfig.app_name, "IllegalAccessException", e);
                    } catch (IllegalArgumentException e) {
                        Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
                    }
                }
            } catch (Exception e) {
                System.out.println("Exception: " + e);
            }
            return o;
        }
        private static void setObject(Context context, Object o, String db_name) {
            Field[] fields = o.getClass().getFields();
            SharedPreferences sp = context.getSharedPreferences(db_name, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            for (Field field : fields) {
                Class<?> type = field.getType();
                try {
                    final String name = field.getName();
                    if (type == Character.TYPE || type.equals(String.class)) {
                        Object value = field.get(o);
                        if (value != null)
                            editor.putString(name, value.toString());
                    } else if (type.equals(int.class) || type.equals(Short.class))
                        editor.putInt(name, field.getInt(o));
                    else if (type.equals(double.class))
                        editor.putFloat(name, (float) field.getDouble(o));
                    else if (type.equals(float.class))
                        editor.putFloat(name, field.getFloat(o));
                    else if (type.equals(long.class))
                        editor.putLong(name, field.getLong(o));
                    else if (type.equals(Boolean.class))
                        editor.putBoolean(name, field.getBoolean(o));
                    else if (type.equals(UUID.class))
                        editor.putString(name, field.get(o).toString());

                } catch (IllegalAccessException e) {
                    Log.e(StaticConfig.app_name, "IllegalAccessException", e);
                } catch (IllegalArgumentException e) {
                    Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
                }
            }

            editor.apply();
        }

Adjusting HttpWebRequest Connection Timeout in C#

Sorry for tacking on to an old thread, but I think something that was said above may be incorrect/misleading.

From what I can tell .Timeout is NOT the connection time, it is the TOTAL time allowed for the entire life of the HttpWebRequest and response. Proof:

I Set:

.Timeout=5000
.ReadWriteTimeout=32000

The connect and post time for the HttpWebRequest took 26ms

but the subsequent call HttpWebRequest.GetResponse() timed out in 4974ms thus proving that the 5000ms was the time limit for the whole send request/get response set of calls.

I didn't verify if the DNS name resolution was measured as part of the time as this is irrelevant to me since none of this works the way I really need it to work--my intention was to time out quicker when connecting to systems that weren't accepting connections as shown by them failing during the connect phase of the request.

For example: I'm willing to wait 30 seconds on a connection request that has a chance of returning a result, but I only want to burn 10 seconds waiting to send a request to a host that is misbehaving.

Python: Ignore 'Incorrect padding' error when base64 decoding

You can simply use base64.urlsafe_b64decode(data) if you are trying to decode a web image. It will automatically take care of the padding.

What exactly does an #if 0 ..... #endif block do?

I'd like to add on for the #else case:

#if 0
   /* Code here will NOT be complied. */
#else
   /* Code will be compiled. */
#endif


#if 1
   /* Code will be complied. */
#else
   /* Code will NOT be compiled. */
#endif

How to line-break from css, without using <br />?

You can use white-space: pre; to make elements act like <pre>, which preserves newlines. Example:

_x000D_
_x000D_
p {_x000D_
  white-space: pre;_x000D_
}
_x000D_
<p>hello _x000D_
How are you</p>
_x000D_
_x000D_
_x000D_

Note for IE that this only works in IE8+.

SQL Server tables: what is the difference between @, # and ##?

I would focus on the differences between #table and @table. ##table is a global temporary table and for the record in over 10 years of using SQL Server I have yet to come across a valid use case. I'm sure that some exist but the nature of the object makes it highly unusable IMHO.

The response to @whiner by @marc_s is absolutely true: it is a prevalent myth that table variables always live in memory. It is actually quite common for a table variable to go to disk and operate just like a temp table.

Anyway I suggest reading up on the set of differences by following the links pointed out by @Astander. Most of the difference involve limitations on what you can't do with @table variables.

how to convert 2d list to 2d numpy array?

I am using large data sets exported to a python file in the form

XVals1 = [.........] 
XVals2 = [.........] 

Each list is of identical length. I use

>>> a1 = np.array(SV.XVals1)

>>> a2 = np.array(SV.XVals2)

Then

>>> A = np.matrix([a1,a2])

JQuery Validate Dropdown list

Easiest way to get it done is by adding required into your select

Select the best option
<br/>

<select name="dd1" id="dd1" required>
<option value="none">None</option>
<option value="o1">option 1</option>
<option value="o2">option 2</option>
<option value="o3">option 3</option>
</select> 

<br/><br/>?

Process.start: how to get the output?

The solution that worked for me in win and linux is the folling

// GET api/values
        [HttpGet("cifrado/{xml}")]
        public ActionResult<IEnumerable<string>> Cifrado(String xml)
        {
            String nombreXML = DateTime.Now.ToString("ddMMyyyyhhmmss").ToString();
            String archivo = "/app/files/"+nombreXML + ".XML";
            String comando = " --armor --recipient [email protected]  --encrypt " + archivo;
            try{
                System.IO.File.WriteAllText(archivo, xml);                
                //String comando = "C:\\GnuPG\\bin\\gpg.exe --recipient [email protected] --armor --encrypt C:\\Users\\Administrador\\Documents\\pruebas\\nuevo.xml ";
                ProcessStartInfo startInfo = new ProcessStartInfo() {FileName = "/usr/bin/gpg",  Arguments = comando }; 
                Process proc = new Process() { StartInfo = startInfo, };
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.Start();
                proc.WaitForExit();
                Console.WriteLine(proc.StandardOutput.ReadToEnd());
                return new string[] { "Archivo encriptado", archivo + " - "+ comando};
            }catch (Exception exception){
                return new string[] { archivo, "exception: "+exception.ToString() + " - "+ comando };
            }
        }

split python source code into multiple files?

Python has importing and namespacing, which are good. In Python you can import into the current namespace, like:

>>> from test import disp
>>> disp('World!')

Or with a namespace:

>>> import test
>>> test.disp('World!')

How to write and read java serialized objects into a file

if you serialize the whole list you also have to de-serialize the file into a list when you read it back. This means that you will inevitably load in memory a big file. It can be expensive. If you have a big file, and need to chunk it line by line (-> object by object) just proceed with your initial idea.

Serialization:

LinkedList<YourObject> listOfObjects = <something>;
try {
    FileOutputStream file = new FileOutputStream(<filePath>);
    ObjectOutputStream writer = new ObjectOutputStream(file);
    for (YourObject obj : listOfObjects) {
        writer.writeObject(obj);
    }
    writer.close();
    file.close();
} catch (Exception ex) {
    System.err.println("failed to write " + filePath + ", "+ ex);
}

De-serialization:

try {
    FileInputStream file = new FileInputStream(<filePath>);
    ObjectInputStream reader = new ObjectInputStream(file);
    while (true) {
        try { 
            YourObject obj = (YourObject)reader.readObject();
            System.out.println(obj)
        } catch (Exception ex) {
            System.err.println("end of reader file ");
            break;
        }
    }
} catch (Exception ex) {
    System.err.println("failed to read " + filePath + ", "+ ex);
}

pandas resample documentation

There's more to it than this, but you're probably looking for this list:

B   business day frequency
C   custom business day frequency (experimental)
D   calendar day frequency
W   weekly frequency
M   month end frequency
BM  business month end frequency
MS  month start frequency
BMS business month start frequency
Q   quarter end frequency
BQ  business quarter endfrequency
QS  quarter start frequency
BQS business quarter start frequency
A   year end frequency
BA  business year end frequency
AS  year start frequency
BAS business year start frequency
H   hourly frequency
T   minutely frequency
S   secondly frequency
L   milliseconds
U   microseconds

Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases

Custom date format with jQuery validation plugin

nickf's answer is good, but note that the validation plug-in already includes validators for several other date formats, in the additional-methods.js file. Before you write your own, make sure that someone hasn't already done it.

Align printf output in Java

Here's a potential solution that will set the width of the bookType column (i.e. format of the bookTypes value) based on the longest bookTypes value.

public class Test {
    public static void main(String[] args) {
        String[] bookTypes = { "Newspaper", "Paper Back", "Hardcover book", "Electronic book", "Magazine" };
        double[] costs = { 1.0, 7.5, 10.0, 2.0, 3.0 };

        // Find length of longest bookTypes value.
        int maxLengthItem = 0;
        boolean firstValue = true;
        for (String bookType : bookTypes) {
            maxLengthItem = (firstValue) ? bookType.length() : Math.max(maxLengthItem, bookType.length());
            firstValue = false;
        }

        // Display rows of data
        for (int i = 0; i < bookTypes.length; i++) {
            // Use %6.2 instead of %.2 so that decimals line up, assuming max
            // book cost of $999.99. Change 6 to a different number if max cost
            // is different
            String format = "%d. %-" + Integer.toString(maxLengthItem) + "s \t\t $%9.2f\n";
            System.out.printf(format, i + 1, bookTypes[i], costs[i]);
        }
    }
}

How to insert a new key value pair in array in php?

To add:

$arr["key"] = "value";

Then simply return $arr

Can't return directly like this way return $arr["key"] = "value";

What is the best open-source java charting library? (other than jfreechart)

There is JChart which is all open source. I'm not sure exactly what you are graphing and how you are graphing it (servlets, swing, etc) so I would say just look at a couple different ones and see which works for you.

http://sourceforge.net/projects/jchart/

I've also used JGraph but I've only used their commercial version. They do offer an open source version however:

http://www.jgraph.com/jgraph.html

WSDL vs REST Pros and Cons

This probably really belongs as comments in several of the above posts, but I don't yet have the rep to do that, so here goes.

I think it is interesting that a lot of the pros and cons often cited for SOAP and REST have (IMO) very little to do with the actual values or limits of the two technologies. Probably the most cited pro for REST is that it is "light-weight" or tends to be more "human readable". At one level this is certainly true, REST does have a lower barrier to entry - there is less required structure than SOAP (though I agree with those who have said that good tooling is largely the answer here - too bad much of the SOAP tooling is pretty dreadful).

Beyond that initial entry cost however, I think the REST impression comes from a combination of the form of the request URLs and the complexity of the data exchanged by most REST services. REST tends to encourage simpler, more human readable request URLs and the data tends to be more digestable as well. To what extent however are these inherent to REST and to what extent are they merely accidental. The simpler URL structure is a direct result of the architecture - but it could be equally well applied to SOAP based services. The more digestable data is more likely to be a result of the lack of any defined structure. This means you'd better keep your data formats simple or you are going to be in for a lot of work. So here SOAP's additional structure, which should be a benefit is actually enabling sloppy design and that sloppy design then gets used as a dig against the technology.

So for use in the exchange of structured data between computer systems I'm not sure that REST is inherently better than SOAP (or visa-versa), they are just different. I think the comparison above of REST vs SOAP to dynamic vs. static typing is a good one. Where dyanmic languages tend to run in to trouble is in long term maintenance and upkeep of a system (and by long term I'm not talking a year or 2, I'm talking 5 or 10). It will be interesting to see if REST runs into the same challenges over time. I tend to think it will so if I were building a distributed, information processing system I would gravitate to SOAP as the communication mechanism (also because of the tranmission and application protocol layering and flexibility that it affords as has been mentioned above).

In other places though REST seems more appropriate. AJAX between the client and its server (regardless of payload) is one major example. I don't have much care for the longevity of this type of connection and ease of use and flexibility are at a premimum. Similarly if I needed quick access to some external service and I didn't think I was going to care about the maintainability of the interaction over time (again I'm assuming this is where REST is going to end up costing me more, one way or another), then I might choose REST just so I could get in and out quickly.

Anyway, they are both viable technologies and depending on what tradeoffs you want to make for a given application they can serve you well (or poorly).

Construct pandas DataFrame from list of tuples of (row,col,values)

You can pivot your DataFrame after creating:

>>> df = pd.DataFrame(data)
>>> df.pivot(index=0, columns=1, values=2)
# avg DataFrame
1      c1     c2
0               
r1  avg11  avg12
r2  avg21  avg22
>>> df.pivot(index=0, columns=1, values=3)
# stdev DataFrame
1        c1       c2
0                   
r1  stdev11  stdev12
r2  stdev21  stdev22

Converting strings to floats in a DataFrame

NOTE: pd.convert_objects has now been deprecated. You should use pd.Series.astype(float) or pd.to_numeric as described in other answers.

This is available in 0.11. Forces conversion (or set's to nan) This will work even when astype will fail; its also series by series so it won't convert say a complete string column

In [10]: df = DataFrame(dict(A = Series(['1.0','1']), B = Series(['1.0','foo'])))

In [11]: df
Out[11]: 
     A    B
0  1.0  1.0
1    1  foo

In [12]: df.dtypes
Out[12]: 
A    object
B    object
dtype: object

In [13]: df.convert_objects(convert_numeric=True)
Out[13]: 
   A   B
0  1   1
1  1 NaN

In [14]: df.convert_objects(convert_numeric=True).dtypes
Out[14]: 
A    float64
B    float64
dtype: object

Why doesn't calling a Python string method do anything unless you assign its output?

This is because strings are immutable in Python.

Which means that X.replace("hello","goodbye") returns a copy of X with replacements made. Because of that you need replace this line:

X.replace("hello", "goodbye")

with this line:

X = X.replace("hello", "goodbye")

More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace,strip,translate,lower/upper,join,...

You must assign their output to something if you want to use it and not throw it away, e.g.

X  = X.strip(' \t')
X2 = X.translate(...)
Y  = X.lower()
Z  = X.upper()
A  = X.join(':')
B  = X.capitalize()
C  = X.casefold()

and so on.

Get total of Pandas column

As other option, you can do something like below

Group   Valuation   amount
    0   BKB Tube    156
    1   BKB Tube    143
    2   BKB Tube    67
    3   BAC Tube    176
    4   BAC Tube    39
    5   JDK Tube    75
    6   JDK Tube    35
    7   JDK Tube    155
    8   ETH Tube    38
    9   ETH Tube    56

Below script, you can use for above data

import pandas as pd    
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()

How to input a string from user into environment variable from batch file

A rather roundabout way, just for completeness:

 for /f "delims=" %i in ('type CON') do set inp=%i

Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.

Proper way to set response status and JSON content in a REST API made with nodejs and express

I don't see anyone mentioned the fact that the order of method calls on res object is important. I'm new to nodejs and didn't realize at first that res.json() does more than just setting the body of the response. It actually tries to infer the response status as well. So, if done like so:

res.json({"message": "Bad parameters"})
res.status(400)

The second line would be of no use, because based on the correctly built json express/nodejs will already infer the success status(200).

How to "comment-out" (add comment) in a batch/cmd?

You can use :: or rem for comments.

When commenting, use :: as it's 3 times faster. An example is shown here

Only if comments are in if, use rem, as the colons could make errors, because they are a label.

Mercurial — revert back to old version and continue from there

After using hg update -r REV it wasn't clear in the answer about how to commit that change so that you can then push.

If you just try to commit after the update, Mercurial doesn't think there are any changes.

I had to first make a change to any file (say in a README) so Mercurial recognized that I made a new change, then I could commit that.

This then created two heads as mentioned.

To get rid of the other head before pushing, I then followed the No-Op Merges step to remedy that situation.

I was then able to push.

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

This happened to me when deleting some Equinox package from my plugins directory, make sure this is not the case.

git with IntelliJ IDEA: Could not read from remote repository

I tried Native option but does not work for me, finally regenerate ssh key in old way and add -m option in ssh-keygen command. also IDEA works with build-in option as fine.

ssh-keygen -m PEM -t rsa -b 4096 -C "email@..."

How to loop through all but the last item of a list?

This answers what the OP should have asked, i.e. traverse a list comparing consecutive elements (excellent SilentGhost answer), yet generalized for any group (n-gram): 2, 3, ... n:

zip(*(l[start:] for start in range(0, n)))

Examples:

l = range(0, 4)  # [0, 1, 2, 3]

list(zip(*(l[start:] for start in range(0, 2)))) # == [(0, 1), (1, 2), (2, 3)]
list(zip(*(l[start:] for start in range(0, 3)))) # == [(0, 1, 2), (1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 4)))) # == [(0, 1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 5)))) # == []

Explanations:

  • l[start:] generates a a list/generator starting from index start
  • *list or *generator: passes all elements to the enclosing function zip as if it was written zip(elem1, elem2, ...)

Note:

AFAIK, this code is as lazy as it can be. Not tested.

How to extract numbers from a string in Python?

I'd use a regexp :

>>> import re
>>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30')
['42', '32', '30']

This would also match 42 from bla42bla. If you only want numbers delimited by word boundaries (space, period, comma), you can use \b :

>>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')
['42', '32', '30']

To end up with a list of numbers instead of a list of strings:

>>> [int(s) for s in re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')]
[42, 32, 30]

How to compare two maps by their values

This question is old, but still relevant.

If you want to compare two maps by their values matching their keys, you can do as follows:

public static <K, V> boolean mapEquals(Map<K, V> leftMap, Map<K, V> rightMap) {
    if (leftMap == rightMap) return true;
    if (leftMap == null || rightMap == null || leftMap.size() != rightMap.size()) return false;
    for (K key : leftMap.keySet()) {
        V value1 = leftMap.get(key);
        V value2 = rightMap.get(key);
        if (value1 == null && value2 == null)
            continue;
        else if (value1 == null || value2 == null)
            return false;
        if (!value1.equals(value2))
            return false;
    }
    return true;
}

HTML/CSS: Making two floating divs the same height

I needed to do something similar, here is my implementation. To recap the purpose, it is to have 2 elements take up the width of a given parent container, and the height to only be as high as it needs to be. Essentially height equaling max height of largest amount of content, but the other container being flush.

html

<div id="ven">
<section>some content</section>
<section>some content</section>
</div>

css

#ven {
height: 100%;
}
#ven section {
width: 50%;
float: left;
height: 100%;
}

What is the difference between call and apply?

While this is an old topic, I just wanted to point out that .call is slightly faster than .apply. I can't tell you exactly why.

See jsPerf, http://jsperf.com/test-call-vs-apply/3


[UPDATE!]

Douglas Crockford mentions briefly the difference between the two, which may help explain the performance difference... http://youtu.be/ya4UHuXNygM?t=15m52s

Apply takes an array of arguments, while Call takes zero or more individual parameters! Ah hah!

.apply(this, [...])

.call(this, param1, param2, param3, param4...)

How to change icon on Google map marker

try this

var locations = [
        ['San Francisco: Power Outage', 37.7749295, -122.4194155,'http://labs.google.com/ridefinder/images/mm_20_purple.png'],
        ['Sausalito', 37.8590937, -122.4852507,'http://labs.google.com/ridefinder/images/mm_20_red.png'],
        ['Sacramento', 38.5815719, -121.4943996,'http://labs.google.com/ridefinder/images/mm_20_green.png'],
        ['Soledad', 36.424687, -121.3263187,'http://labs.google.com/ridefinder/images/mm_20_blue.png'],
        ['Shingletown', 40.4923784, -121.8891586,'http://labs.google.com/ridefinder/images/mm_20_yellow.png']
    ];



//inside the loop
marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                map: map,
                icon: locations[i][3]
            });

What's wrong with foreign keys?

I'm sure there are plenty of applications where you can get away with it, but it's not the best idea. You can't always count on your application to properly manage your database, and frankly managing the database should not be of very much concern to your application.

If you are using a relational database then it seems you ought to have some relationships defined in it. Unfortunately this attitude (you don't need foreign keys) seems to be embraced by a lot of application developers who would rather not be bothered with silly things like data integrity (but need to because their companies don't have dedicated database developers). Usually in databases put together by these types you are lucky just to have primary keys ;)

Fatal error: unexpectedly found nil while unwrapping an Optional values

Nil Coalescing Operator can be used as well.

rowName = rowName != nil ?rowName!.stringFromCamelCase():""

JBoss default password

If you are using Talend MDM Server, the login is: login: admin password: talend

See more: http://wiki.glitchdata.com/index.php?title=TOS:_Accessing_the_Talend_MDM_Server

This differs from the default JBoss login of admin/admin The password setup file is also login-config.xml in this case.

Simple prime number generator in Python

re is powerful:

import re


def isprime(n):
    return re.compile(r'^1?$|^(11+)\1+$').match('1' * n) is None

print [x for x in range(100) if isprime(x)]

###########Output#############
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

What does java:comp/env/ do?

After several attempts and going deep in Tomcat's source code I found out that the simple property useNaming="false" did the trick!! Now Tomcat resolves names java:/liferay instead of java:comp/env/liferay

How to play .mp4 video in videoview in android?

In Kotlin you can do as

 val videoView = findViewById<VideoView>(R.id.videoView)

       // If url is from raw
   /* val url = "android.resource://" + packageName
        .toString() + "/" + R.raw.video*/

    // If url is from network
    val url = "http://www.servername.com/projects/projectname/videos/1361439400.mp4"

    val video =
        Uri.parse(url)
    videoView.setVideoURI(video)
    videoView.setOnPreparedListener{
        videoView.start()
    }

How to find array / dictionary value using key?

It's as simple as this :

$array[$key];

How can I transition height: 0; to height: auto; using CSS?

My workaround is to transition max-height to the exact content height for a nice smooth animation, then use a transitionEnd callback to set max-height to 9999px so the content can resize freely.

_x000D_
_x000D_
var content = $('#content');_x000D_
content.inner = $('#content .inner'); // inner div needed to get size of content when closed_x000D_
_x000D_
// css transition callback_x000D_
content.on('transitionEnd webkitTransitionEnd transitionend oTransitionEnd msTransitionEnd', function(e){_x000D_
    if(content.hasClass('open')){_x000D_
        content.css('max-height', 9999); // try setting this to 'none'... I dare you!_x000D_
    }_x000D_
});_x000D_
_x000D_
$('#toggle').on('click', function(e){_x000D_
    content.toggleClass('open closed');_x000D_
    content.contentHeight = content.outerHeight();_x000D_
    _x000D_
    if(content.hasClass('closed')){_x000D_
        _x000D_
        // disable transitions & set max-height to content height_x000D_
        content.removeClass('transitions').css('max-height', content.contentHeight);_x000D_
        setTimeout(function(){_x000D_
            _x000D_
            // enable & start transition_x000D_
            content.addClass('transitions').css({_x000D_
                'max-height': 0,_x000D_
                'opacity': 0_x000D_
            });_x000D_
            _x000D_
        }, 10); // 10ms timeout is the secret ingredient for disabling/enabling transitions_x000D_
        // chrome only needs 1ms but FF needs ~10ms or it chokes on the first animation for some reason_x000D_
        _x000D_
    }else if(content.hasClass('open')){  _x000D_
        _x000D_
        content.contentHeight += content.inner.outerHeight(); // if closed, add inner height to content height_x000D_
        content.css({_x000D_
            'max-height': content.contentHeight,_x000D_
            'opacity': 1_x000D_
        });_x000D_
        _x000D_
    }_x000D_
});
_x000D_
.transitions {_x000D_
    transition: all 0.5s ease-in-out;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
body {_x000D_
    font-family:Arial;_x000D_
    line-height: 3ex;_x000D_
}_x000D_
code {_x000D_
    display: inline-block;_x000D_
    background: #fafafa;_x000D_
    padding: 0 1ex;_x000D_
}_x000D_
#toggle {_x000D_
    display:block;_x000D_
    padding:10px;_x000D_
    margin:10px auto;_x000D_
    text-align:center;_x000D_
    width:30ex;_x000D_
}_x000D_
#content {_x000D_
    overflow:hidden;_x000D_
    margin:10px;_x000D_
    border:1px solid #666;_x000D_
    background:#efefef;_x000D_
    opacity:1;_x000D_
}_x000D_
#content .inner {_x000D_
    padding:10px;_x000D_
    overflow:auto;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
<div id="content" class="open">_x000D_
    <div class="inner">_x000D_
        <h3>Smooth CSS Transitions Between <code>height: 0</code> and <code>height: auto</code></h3>_x000D_
        <p>A clever workaround is to use <code>max-height</code> instead of <code>height</code>, and set it to something bigger than your content. Problem is the browser uses this value to calculate transition duration. So if you set it to <code>max-height: 1000px</code> but the content is only 100px high, the animation will be 10x too fast.</p>_x000D_
        <p>Another option is to measure the content height with JS and transition to that fixed value, but then you have to keep track of the content and manually resize it if it changes.</p>_x000D_
        <p>This solution is a hybrid of the two - transition to the measured content height, then set it to <code>max-height: 9999px</code> after the transition for fluid content sizing.</p>_x000D_
    </div>_x000D_
</div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<button id="toggle">Challenge Accepted!</button>
_x000D_
_x000D_
_x000D_

Error: Unable to run mksdcard SDK tool

In case of lubuntu 14.04 use

sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6

P.S-no need to restart the system.

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

I had a little different problem. In Project - Properties - Libraries - JRE library, I had the wrong JRE lib version. Remove and set the actual one, and voila - all Access restriction... warnings are away.

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

Here's where it gets confusing, the text states "If the balance factor of R is 1, it means the insertion occurred on the (external) right side of that node and a left rotation is needed". But from m understanding the text said (as I quoted) that if the balance factor was within [-1, 1] then there was no need for balancing?

R is the right-hand child of the current node N.

If balance(N) = +2, then you need a rotation of some sort. But which rotation to use? Well, it depends on balance(R): if balance(R) = +1 then you need a left-rotation on N; but if balance(R) = -1 then you will need a double-rotation of some sort.

Get the last item in an array

This method will not mess with your prototype. It also guards against 0 length arrays, along with null/undefined arrays. You can even override the default value if the returned default value might match an item in your array.

_x000D_
_x000D_
const items = [1,2,3]_x000D_
const noItems = []_x000D_
_x000D_
/**_x000D_
 * Returns the last item in an array._x000D_
 * If the array is null, undefined, or empty, the default value is returned._x000D_
 */_x000D_
function arrayLast (arrayOrNull, defVal = undefined) {_x000D_
  if (!arrayOrNull || arrayOrNull.length === 0) {_x000D_
    return defVal_x000D_
  }_x000D_
  return arrayOrNull[arrayOrNull.length - 1]_x000D_
}_x000D_
_x000D_
console.log(arrayLast(items))_x000D_
console.log(arrayLast(noItems))_x000D_
console.log(arrayLast(null))_x000D_
_x000D_
console.log(arrayLast(items, 'someDefault'))_x000D_
console.log(arrayLast(noItems, 'someDefault'))_x000D_
console.log(arrayLast(null, 'someDefault'))
_x000D_
_x000D_
_x000D_

Select top 10 records for each category

Might the UNION operator work for you? Have one SELECT for each section, then UNION them together. Guess it would only work for a fixed number of sections though.

Android : difference between invisible and gone?

when you make it Gone every time of compilation of program the component gets initialized that means you are removing the component from layout and when you make it invisible the component it will take the same space in the layout but every time you dont need to initialize it.

if you set Visibility=Gone then you have to initialize the component..like

eg Button _mButton = new Button(this);

_mButton = (Button)findViewByid(R.id.mButton);

so it will take more time as compared to Visibility = invisible.

How to add a new line of text to an existing file in Java?

you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append) constructor.

output = new BufferedWriter(new FileWriter(my_file_name, true));

should do the trick

Select every Nth element in CSS

As the name implies, :nth-child() allows you to construct an arithmetic expression using the n variable in addition to constant numbers. You can perform addition (+), subtraction (-) and coefficient multiplication (an where a is an integer, including positive numbers, negative numbers and zero).

Here's how you would rewrite the above selector list:

div:nth-child(4n)

For an explanation on how these arithmetic expressions work, see my answer to this question, as well as the spec.

Note that this answer assumes that all of the child elements within the same parent element are of the same element type, div. If you have any other elements of different types such as h1 or p, you will need to use :nth-of-type() instead of :nth-child() to ensure you only count div elements:

<body>
  <h1></h1>
  <div>1</div>  <div>2</div>
  <div>3</div>  <div>4</div>
  <h2></h2>
  <div>5</div>  <div>6</div>
  <div>7</div>  <div>8</div>
  <h2></h2>
  <div>9</div>  <div>10</div>
  <div>11</div> <div>12</div>
  <h2></h2>
  <div>13</div> <div>14</div>
  <div>15</div> <div>16</div>
</body>

For everything else (classes, attributes, or any combination of these), where you're looking for the nth child that matches an arbitrary selector, you will not be able to do this with a pure CSS selector. See my answer to this question.


By the way, there's not much of a difference between 4n and 4n + 4 with regards to :nth-child(). If you use the n variable, it starts counting at 0. This is what each selector would match:

:nth-child(4n)

4(0) = 0
4(1) = 4
4(2) = 8
4(3) = 12
4(4) = 16
...

:nth-child(4n+4)

4(0) + 4 = 0  + 4 = 4
4(1) + 4 = 4  + 4 = 8
4(2) + 4 = 8  + 4 = 12
4(3) + 4 = 12 + 4 = 16
4(4) + 4 = 16 + 4 = 20
...

As you can see, both selectors will match the same elements as above. In this case, there is no difference.

How to prevent form from being submitted?

The following works as of now (tested in chrome and firefox):

<form onsubmit="event.preventDefault(); return validateMyForm();">

where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()

How to set up a Web API controller for multipart/form-data

check ur WebApiConfig and add this

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

How to delete the first row of a dataframe in R?

I am not expert, but this may work as well,

dat <- dat[2:nrow(dat), ]

Java ArrayList - Check if list is empty

Your original problem was that you were checking if the list was null, which it would never be because you instantiated it with List<Integer> numbers = new ArrayList<Integer>();. However, you have updated your code to use the List.isEmpty() method to properly check if the list is empty.

The problem now is that you are never actually sending an empty list to giveList(). In your do-while loop, you add any input number to the list, even if it is -1. To prevent -1 being added, change the do-while loop to only add numbers if they are not -1. Then, the list will be empty if the user's first input number is -1.

do {
    number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number (-1 to stop)"));
    /* Change this line */
    if (number != -1) numbers.add(number);
} while (number != -1);

React JS get current date

OPTION 1: if you want to make a common utility function then you can use this

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

Can I add jars to maven 2 build classpath without installing them?

A strange solution I found:

using Eclipse

  • create simple (non-maven) java project
  • add a Main class
  • add all the jars to the classpath
  • export Runnable JAR (it's important, because no other way here to do it)
  • select Extract required libraries into generated JAR
  • decide the licence issues
  • tadammm...install the generated jar to your m2repo
  • add this single dependency to your other projects.

cheers, Balint

How to delete/remove nodes on Firebase

As others have noted the call to .remove() is asynchronous. We should all be aware nothing happens 'instantly', even if it is at the speed of light.

What you mean by 'instantly' is that the next line of code should be able to execute after the call to .remove(). With asynchronous operations the next line may be when the data has been removed, it may not - it is totally down to chance and the amount of time that has elapsed.

.remove() takes one parameter a callback function to help deal with this situation to perform operations after we know that the operation has been completed (with or without an error). .push() takes two params, a value and a callback just like .remove().

Here is your example code with modifications:

ref = new Firebase("myfirebase.com")

ref.push({key:val}, function(error){
  //do stuff after push completed
});

// deletes all data pushed so far
ref.remove(function(error){
  //do stuff after removal
});

Android notification is not showing

I had the same issue with my Android app. I was trying out notifications and found that notifications were showing on my Android emulator which ran a Android 7.0 (Nougat) system, whereas it wasn't running on my phone which had Android 8.1 (Oreo).

After reading the documentation, I found that Android had a feature called notification channel, without which notifications won't show up on Oreo devices. Below is the link to official Android documentation on notification channels.

How to return a custom object from a Spring Data JPA GROUP BY query

This SQL query return List< Object[] > would.

You can do it this way:

 @RestController
 @RequestMapping("/survey")
 public class SurveyController {

   @Autowired
   private SurveyRepository surveyRepository;

     @RequestMapping(value = "/find", method =  RequestMethod.GET)
     public Map<Long,String> findSurvey(){
       List<Object[]> result = surveyRepository.findSurveyCount();
       Map<Long,String> map = null;
       if(result != null && !result.isEmpty()){
          map = new HashMap<Long,String>();
          for (Object[] object : result) {
            map.put(((Long)object[0]),object[1]);
          }
       }
     return map;
     }
 }

Add a scrollbar to a <textarea>

textarea {
    overflow-y: scroll; /* Vertical scrollbar */
    overflow: scroll; /* Horizontal and vertical scrollbar*/
}

How to filter array in subdocument with MongoDB

Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output

db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})

Result:

{
  "_id": ObjectId("..."),
  "list": [{a: 1}]
}

rails 3 validation on uniqueness on multiple attributes

Dont work for me, need to put scope in plural

validates_uniqueness_of :teacher_id, :scopes => [:semester_id, :class_id]

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

The reason is, in state you defined:

this.state = { fields: {} }

fields as a blank object, so during the first rendering this.state.fields.name will be undefined, and the input field will get its value as:

value={undefined}

Because of that, the input field will become uncontrolled.

Once you enter any value in input, fields in state gets changed to:

this.state = { fields: {name: 'xyz'} }

And at that time the input field gets converted into a controlled component; that's why you are getting the error:

A component is changing an uncontrolled input of type text to be controlled.

Possible Solutions:

1- Define the fields in state as:

this.state = { fields: {name: ''} }

2- Or define the value property by using Short-circuit evaluation like this:

value={this.state.fields.name || ''}   // (undefined || '') = ''

Oracle PL/SQL - How to create a simple array variable?

Sample programs as follows and provided on link also https://oracle-concepts-learning.blogspot.com/

plsql table or associated array.

        DECLARE 
            TYPE salary IS TABLE OF NUMBER INDEX BY VARCHAR2(20); 
            salary_list salary; 
            name VARCHAR2(20); 
        BEGIN 
           -- adding elements to the table 
           salary_list('Rajnish') := 62000; salary_list('Minakshi') := 75000; 
           salary_list('Martin') := 100000; salary_list('James') := 78000; 
           -- printing the table name := salary_list.FIRST; WHILE name IS NOT null 
            LOOP 
               dbms_output.put_line ('Salary of ' || name || ' is ' || 
               TO_CHAR(salary_list(name))); 
               name := salary_list.NEXT(name); 
            END LOOP; 
        END; 
        /

Finding which process was killed by Linux OOM killer

Now dstat provides the feature to find out in your running system which process is candidate for getting killed by oom mechanism

dstat --top-oom
 --out-of-memory---
  kill score
 java           77
 java           77
 java           77

and as per man page

  --top-oom
          show process that will be killed by OOM the first

HashSet vs LinkedHashSet

HashSet:

The underlined data structure is Hashtable. Duplicate objects are not allowed.insertion order is not preserved and it is based on hash code of objects. Null insertion is possible(only once). It implements Serializable, Clonable but not RandomAccess interface. HashSet is best choose if frequent operation is search operation.

In HashSet duplicates are not allowed.if users are trying to insert duplicates when we won't get any compile or runtime exceptions. add method returns simply false.

Constructors:

HashSet h=new HashSet(); creates an empty HashSet object with default initial capacity 16 and default fill ratio(Load factor) is 0.75 .

HashSet h=new HashSet(int initialCapacity); creates an empty HashSet object with specified initialCapacity and default fill ration is 0.75.

HashSet h=new HashSet(int initialCapacity, float fillRatio);

HashSet h=new HashSet(Collection c); creates an equivalent HashSet object for the given collection. This constructor meant for inter conversion between collection object.

LinkedHashSet:

It is a child class of HashSet. it is exactly same as HashSet including(Constructors and Methods) except the following differences.

Differences HashSet:

  1. The underlined data structure is Hashtable.
  2. Insertion order is not preserved.
  3. introduced 1.2 version.

LinkedHashSet:

  1. The underlined data structure is a combination of LinkedList and Hashtable.
  2. Insertion order is preserved.
  3. Indroduced in 1.4 version.

Convert int to ASCII and back in Python

Use hex(id)[2:] and int(urlpart, 16). There are other options. base32 encoding your id could work as well, but I don't know that there's any library that does base32 encoding built into Python.

Apparently a base32 encoder was introduced in Python 2.4 with the base64 module. You might try using b32encode and b32decode. You should give True for both the casefold and map01 options to b32decode in case people write down your shortened URLs.

Actually, I take that back. I still think base32 encoding is a good idea, but that module is not useful for the case of URL shortening. You could look at the implementation in the module and make your own for this specific case. :-)

Copying PostgreSQL database to another server

You don't need to create an intermediate file. You can do

pg_dump -C -h localhost -U localuser dbname | psql -h remotehost -U remoteuser dbname

or

pg_dump -C -h remotehost -U remoteuser dbname | psql -h localhost -U localuser dbname

using psql or pg_dump to connect to a remote host.

With a big database or a slow connection, dumping a file and transfering the file compressed may be faster.

As Kornel said there is no need to dump to a intermediate file, if you want to work compressed you can use a compressed tunnel

pg_dump -C dbname | bzip2 | ssh  remoteuser@remotehost "bunzip2 | psql dbname"

or

pg_dump -C dbname | ssh -C remoteuser@remotehost "psql dbname"

but this solution also requires to get a session in both ends.

Note: pg_dump is for backing up and psql is for restoring. So, the first command in this answer is to copy from local to remote and the second one is from remote to local. More -> https://www.postgresql.org/docs/9.6/app-pgdump.html

How to clear Tkinter Canvas?

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

How can I list (ls) the 5 last modified files in a directory?

ls -t list files by creation time not last modified time. Use ls -ltc if you want to list files by last modified time from last to first(top to bottom). Thus to list the last n: ls -ltc | head ${n}

Swift - how to make custom header for UITableView?

If you are using custom cell as header, add the following.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let headerView = UIView()
        let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
        headerView.addSubview(headerCell)
        return headerView
    }

If you want to have simple view, add the following.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView:UIView =  UIView()
    return headerView
}

NSAttributedString add text alignment

In swift 4:

    let paraStyle = NSMutableParagraphStyle.init()
    paraStyle.alignment = .left

    let str = "Test Message"
    let attribute = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 12)]

    let attrMessage = NSMutableAttributedString(string: str, attributes: attribute)


    attrMessage.addAttribute(kCTParagraphStyleAttributeName as NSAttributedStringKey, value: paraStyle, range: NSMakeRange(0, str.count))

Using request.setAttribute in a JSP page

The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.

Running multiple AsyncTasks at the same time -- not possible?

Just to include the latest update (UPDATE 4) in @Arhimed 's immaculate answer in the very good summary of @sulai:

void doTheTask(AsyncTask task) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // Android 4.4 (API 19) and above
        // Parallel AsyncTasks are possible, with the thread-pool size dependent on device
        // hardware
        task.execute(params);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Android 3.0 to
        // Android 4.3
        // Parallel AsyncTasks are not possible unless using executeOnExecutor
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    } else { // Below Android 3.0
        // Parallel AsyncTasks are possible, with fixed thread-pool size
        task.execute(params);
    }
}

Shorter syntax for casting from a List<X> to a List<Y>?

In case when X derives from Y you can also use ToList<T> method instead of Cast<T>

listOfX.ToList<Y>()

How to access a property of an object (stdClass Object) member/element of an array?

To access an array member you use $array['KEY'];

To access an object member you use $obj->KEY;

To access an object member inside an array of objects:
$array[0] // Get the first object in the array
$array[0]->KEY // then access its key

You may also loop over an array of objects like so:

foreach ($arrayOfObjs as $key => $object) {
    echo $object->object_property;
}

Think of an array as a collection of things. It's a bag where you can store your stuff and give them a unique id (key) and access them (or take the stuff out of the bag) using that key. I want to keep things simple here, but this bag can contain other bags too :)

Update (this might help someone understand better):

An array contains 'key' and 'value' pairs. Providing a key for an array member is optional and in this case it is automatically assigned a numeric key which starts with 0 and keeps on incrementing by 1 for each additional member. We can retrieve a 'value' from the array by it's 'key'.

So we can define an array in the following ways (with respect to keys):

First method:

$colorPallete = ['red', 'blue', 'green'];

The above array will be assigned numeric keys automatically. So the key assigned to red will be 0, for blue 1 and so on.

Getting values from the above array:

$colorPallete[0]; // will output 'red'
$colorPallete[1]; // will output 'blue'
$colorPallete[2]; // will output 'green'

Second method:

$colorPallete = ['love' => 'red', 'trust' => 'blue', 'envy' => 'green']; // we expliicitely define the keys ourself.

Getting values from the above array:

$colorPallete['love']; // will output 'red'
$colorPallete['trust']; // will output 'blue'
$colorPallete['envy']; // will output 'green'

Directory.GetFiles: how to get only filename, not full path?

You can use System.IO.Path.GetFileName to do this.

E.g.,

string[] files = Directory.GetFiles(dir);
foreach(string file in files)
    Console.WriteLine(Path.GetFileName(file));

While you could use FileInfo, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles unless you need the additional functionality of the FileInfo class.

Difference between Activity and FragmentActivity

FragmentActivity is part of the support library, while Activity is the framework's default class. They are functionally equivalent.

You should always use FragmentActivity and android.support.v4.app.Fragment instead of the platform default Activity and android.app.Fragment classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.

Phone number formatting an EditText in Android

You can accept only numbers and phone number type using java code

 EditText number1 = (EditText) layout.findViewById(R.id.edittext); 
    number1.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_CLASS_PHONE);
     number1.setKeyListener(DigitsKeyListener.getInstance("0123456789”));
      number1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(14)}); // 14 is max digits

This code will avoid lot of validations after reading input

Error: Selection does not contain a main type

I had this issue because the tutorial code I was trying to run wasn't in the correct package even though I had typed in the package name at the top of each class.

I right-clicked each class, Refactor and Move To and accepted the package name suggestion.

Then as usual, Run As... Java Application.

And it worked :)

How do I resolve this "ORA-01109: database not open" error?

alter pluggable database orclpdb open;`

worked for me.

orclpdb is the name of pluggable database which may be different based on the individual.

Vendor code 17002 to connect to SQLDeveloper

Listed are the steps that could rectify the error:

  1. Press Windows+R
  2. Type services.msc and strike Enter
  3. Find all services
  4. Starting with ora start these services and wait!!
  5. When your server specific service is initialized (in my case it was orcl)
  6. Now run mysql or whatever you are using and start coding.P

Mockito: InvalidUseOfMatchersException

Inspite of using all the matchers, I was getting the same issue:

"org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
1 matchers expected, 3 recorded:"

It took me little while to figure this out that the method I was trying to mock was a static method of a class(say Xyz.class) which contains only static method and I forgot to write following line:

PowerMockito.mockStatic(Xyz.class);

May be it will help others as it may also be the cause of the issue.

Why doesn't RecyclerView have onItemClickListener()?

use PlaceHolderView

@Layout(R.layout.item_view_1)
public class View1{

    @View(R.id.txt)
    public TextView txt;

    @Resolve
    public void onResolved() {
        txt.setText(String.valueOf(System.currentTimeMillis() / 1000));
    }

    @Click(R.id.btn)
    public void onClick(){
        txt.setText(String.valueOf(System.currentTimeMillis() / 1000));
    }
}

Java: How to convert String[] to List or Set

If you really want to use a set:

String[] strArray = {"foo", "foo", "bar"};  
Set<String> mySet = new HashSet<String>(Arrays.asList(strArray));
System.out.println(mySet);

output:

[foo, bar]

Java 8 Iterable.forEach() vs foreach loop

forEach() can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.

For example ArrayList.forEach(action) may be simply implemented as

for(int i=0; i<size; i++)
    action.accept(elements[i])

as opposed to the for-each loop which requires a lot of scaffolding

Iterator iter = list.iterator();
while(iter.hasNext())
    Object next = iter.next();
    do something with `next`

However, we also need to account for two overhead costs by using forEach(), one is making the lambda object, the other is invoking the lambda method. They are probably not significant.

see also http://journal.stuffwithstuff.com/2013/01/13/iteration-inside-and-out/ for comparing internal/external iterations for different use cases.

Reverse of JSON.stringify?

Check this out.
http://jsfiddle.net/LD55x/

Code:

var myobj = {};
myobj.name="javascriptisawesome";
myobj.age=25;
myobj.mobile=123456789;
debugger;
var str = JSON.stringify(myobj);
alert(str);
var obj = JSON.parse(str);
alert(obj);

Where will log4net create this log file?

if you want to choose dynamically the path to the log file use the method written in this link: method to dynamic choose the log file path.

if you want you can set the path to where your app EXE file exists like this -

var logFileLocation = System.IO.Path.GetDirectoryName
(System.Reflection.Assembly.GetEntryAssembly().Location);

and then send this 'logFileLocation' to the method written in the link above like this:

Initialize(logFileLocation);

and you are ready to go! :)

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Below is the exact code you need to make your sheet look exactly as it is in the attached PDF:

try
        {
            Excel.Application application;
            Excel.Workbook workBook;
            Excel.Worksheet workSheet;
            object misValue = System.Reflection.Missing.Value;

            application = new Excel.ApplicationClass();
            workBook = application.Workbooks.Add(misValue);
            workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(1);

            int i = 1;
            workSheet.Cells[i, 2] = "MSS Close Sheet"; 
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;               
            i++;
            workSheet.Cells[i, 2] = "MSS - " + dpsNoTextBox.Text;
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            i++;
            workSheet.Cells[i, 2] = customerNameTextBox.Text;
            i++;                
            workSheet.Cells[i, 2] = "Opening Date : ";
            workSheet.Cells[i, 3] = openingDateTextBox.Value.ToShortDateString();
            i++;
            workSheet.Cells[i, 2] = "Closing Date : ";
            workSheet.Cells[i, 3] = closingDateTextBox.Value.ToShortDateString();
            i++;
            i++;
            i++;

            workSheet.Cells[i, 1] = "SL. No";
            workSheet.Cells[i, 2] = "Month";
            workSheet.Cells[i, 3] = "Amount Deposited";
            workSheet.Cells[i, 4] = "Fine";
            workSheet.Cells[i, 5] = "Cumulative Total";
            workSheet.Cells[i, 6] = "Profit + Cumulative Total";
            workSheet.Cells[i, 7] = "Profit @ " + profitRateComboBox.Text;
            WorkSheet.Cells[i, 1].EntireRow.Font.Bold = true;
            i++;



            /////////////////////////////////////////////////////////
            foreach (RecurringDeposit rd in RecurringDepositList)
            {
                workSheet.Cells[i, 1] = rd.SN.ToString();
                workSheet.Cells[i, 2] = rd.MonthYear;
                workSheet.Cells[i, 3] = rd.InstallmentSize.ToString();
                workSheet.Cells[i, 4] = "";
                workSheet.Cells[i, 5] = rd.CumulativeTotal.ToString();
                workSheet.Cells[i, 6] = rd.ProfitCumulative.ToString();
                workSheet.Cells[i, 7] = rd.Profit.ToString();
                i++;
            }
            //////////////////////////////////////////////////////


            ////////////////////////////////////////////////////////
            workSheet.Cells[i, 2] = "Total (" + RecurringDepositList.Count + " months installment)";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = totalAmountDepositedTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "a) Total Amount Deposited";
            workSheet.Cells[i, 3] = totalAmountDepositedTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "b) Fine";
            workSheet.Cells[i, 3] = "";
            i++;

            workSheet.Cells[i, 2] = "c) Total Pft Paid";
            workSheet.Cells[i, 3] = totalProfitPaidTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Sub Total";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (totalAmountDepositedTextBox.Value + totalProfitPaidTextBox.Value).ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Deduction";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            i++;

            workSheet.Cells[i, 2] = "a) Excise Duty";
            workSheet.Cells[i, 3] = "0";
            i++;

            workSheet.Cells[i, 2] = "b) Income Tax on Pft. @ " + incomeTaxPercentageTextBox.Text;
            workSheet.Cells[i, 3] = "0";
            i++;

            workSheet.Cells[i, 2] = "c) Account Closing Charge ";
            workSheet.Cells[i, 3] = closingChargeCommaNumberTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "d) Outstanding on BAIM(FO) ";
            workSheet.Cells[i, 3] = baimFOLowerTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Total Deduction ";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (incomeTaxDeductionTextBox.Value + closingChargeCommaNumberTextBox.Value + baimFOTextBox.Value).ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Client Paid ";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = customerPayableNumberTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "e) Current Balance ";
            workSheet.Cells[i, 3] = currentBalanceCommaNumberTextBox.Value.ToString("0.00");
            workSheet.Cells[i, 5] = "Exp. Pft paid on MSS A/C(PL67054)";
            workSheet.Cells[i, 6] = plTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "e) Total Paid ";
            workSheet.Cells[i, 3] = customerPayableNumberTextBox.Value.ToString("0.00");
            workSheet.Cells[i, 5] = "IT on Pft (BDT16216)";
            workSheet.Cells[i, 6] = incomeTaxDeductionTextBox.Value.ToString("0.00");
            i++;

            workSheet.Cells[i, 2] = "Difference";
            WorkSheet.Cells[i, 2].Style.Font.Bold = true;
            workSheet.Cells[i, 3] = (currentBalanceCommaNumberTextBox.Value - customerPayableNumberTextBox.Value).ToString("0.00");
            workSheet.Cells[i, 5] = "Account Closing Charge";
            workSheet.Cells[i, 6] = closingChargeCommaNumberTextBox.Value;
            i++;

            ///////////////////////////////////////////////////////////////

            workBook.SaveAs("D:\\" + dpsNoTextBox.Text.Trim() + "-" + customerNameTextBox.Text.Trim() + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            workBook.Close(true, misValue, misValue);
            application.Quit();

            releaseObject(workSheet);
            releaseObject(workBook);
            releaseObject(application);

Validating a Textbox field for only numeric input.

I know this is an old question but I figured out I should pitch my answer anyways.

The following snippet iterates through each character of the text and uses the IsNumber() method, which returns true if the character is a number and false the other way, to check if all the characters are numbers. If all are numbers, the method returns true. If not it returns false.

using System;

private bool ValidateText(string text){
    char[] characters = text.ToCharArray();

    foreach(char c in characters){
        if(!char.IsNumber(c))
            return false;
    }
    return true;
}

How to remove class from all elements jquery

$(".edgetoedge>li").removeClass("highlight");

Is there a way to make npm install (the command) to work behind proxy?

When in doubt, try all these commands, as I do:

npm config set registry http://registry.npmjs.org/
npm config set proxy http://myusername:[email protected]:8080
npm config set https-proxy http://myusername:[email protected]:8080
npm config set strict-ssl false
set HTTPS_PROXY=http://myusername:[email protected]:8080
set HTTP_PROXY=http://myusername:[email protected]:8080
export HTTPS_PROXY=http://myusername:[email protected]:8080
export HTTP_PROXY=http://myusername:[email protected]:8080
export http_proxy=http://myusername:[email protected]:8080

npm --proxy http://myusername:[email protected]:8080 \
--without-ssl --insecure -g install

=======

UPDATE

Put your settings into ~/.bashrc or ~/.bash_profile so you don't have to worry about your settings everytime you open a new terminal window!

If your company is like mine, I have to change my password pretty often. So I added the following into my ~/.bashrc or ~/.bash_profile so that whenever I open a terminal, I know my npm is up to date!

  1. Simply paste the following code at the bottom of your ~/.bashrc file:

    ######################
    # User Variables (Edit These!)
    ######################
    username="myusername"
    password="mypassword"
    proxy="mycompany:8080"
    
    ######################
    # Environement Variables
    # (npm does use these variables, and they are vital to lots of applications)
    ######################
    export HTTPS_PROXY="http://$username:$password@$proxy"
    export HTTP_PROXY="http://$username:$password@$proxy"
    export http_proxy="http://$username:$password@$proxy"
    export https_proxy="http://$username:$password@$proxy"
    export all_proxy="http://$username:$password@$proxy"
    export ftp_proxy="http://$username:$password@$proxy"
    export dns_proxy="http://$username:$password@$proxy"
    export rsync_proxy="http://$username:$password@$proxy"
    export no_proxy="127.0.0.10/8, localhost, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16"
    
    ######################
    # npm Settings
    ######################
    npm config set registry http://registry.npmjs.org/
    npm config set proxy "http://$username:$password@$proxy"
    npm config set https-proxy "http://$username:$password@$proxy"
    npm config set strict-ssl false
    echo "registry=http://registry.npmjs.org/" > ~/.npmrc
    echo "proxy=http://$username:$password@$proxy" >> ~/.npmrc
    echo "strict-ssl=false" >> ~/.npmrc
    echo "http-proxy=http://$username:$password@$proxy" >> ~/.npmrc
    echo "http_proxy=http://$username:$password@$proxy" >> ~/.npmrc
    echo "https_proxy=http://$username:$password@$proxy" >> ~/.npmrc
    echo "https-proxy=http://$username:$password@$proxy" >> ~/.npmrc
    
    ######################
    # WGET SETTINGS
    # (Bonus Settings! Not required for npm to work, but needed for lots of other programs)
    ######################
    echo "https_proxy = http://$username:$password@$proxy/" > ~/.wgetrc
    echo "http_proxy = http://$username:$password@$proxy/" >> ~/.wgetrc
    echo "ftp_proxy = http://$username:$password@$proxy/" >> ~/.wgetrc
    echo "use_proxy = on" >> ~/.wgetrc
    
    ######################
    # CURL SETTINGS
    # (Bonus Settings! Not required for npm to work, but needed for lots of other programs)
    ######################
    echo "proxy=http://$username:$password@$proxy" > ~/.curlrc
    
  2. Then edit the "username", "password", and "proxy" fields in the code you pasted.

  3. Open a new terminal

  4. Check your settings by running npm config list and cat ~/.npmrc

  5. Try to install your module using

    • npm install __, or
    • npm --without-ssl --insecure install __, or
    • override your proxy settings by using npm --without-ssl --insecure --proxy http://username:password@proxy:8080 install __.
    • If you want the module to be available globally, add option -g

Deserializing a JSON into a JavaScript object

I think this should help:

Also documentations also prove that you can use require() for json files: https://www.bennadel.com/blog/2908-you-can-use-require-to-load-json-javascript-object-notation-files-in-node-js.htm

var jsonfile = require("./path/to/jsonfile.json");
node = jsonfile.adjacencies.nodeTo;
node2 = jsonfile.adjacencies.nodeFrom;
node3 = jsonfile.adjacencies.data.$color;
//other things.

Convert datetime to Unix timestamp and convert it back in python

solution is

import time
import datetime
d = datetime.date(2015,1,5)

unixtime = time.mktime(d.timetuple())

Convert List<String> to List<Integer> directly

No, you need to loop over the array

for(String s : strList) intList.add(Integer.valueOf(s));

How to run Rake tasks from within Rake tasks?

I would suggest not to create general debug and release tasks if the project is really something that gets compiled and so results in files. You should go with file-tasks which is quite doable in your example, as you state, that your output goes into different directories. Say your project just compiles a test.c file to out/debug/test.out and out/release/test.out with gcc you could setup your project like this:

WAYS = ['debug', 'release']
FLAGS = {}
FLAGS['debug'] = '-g'
FLAGS['release'] = '-O'
def out_dir(way)
  File.join('out', way)
end
def out_file(way)
  File.join(out_dir(way), 'test.out')
end
WAYS.each do |way|
  desc "create output directory for #{way}"
  directory out_dir(way)

  desc "build in the #{way}-way"
  file out_file(way) => [out_dir(way), 'test.c'] do |t|
    sh "gcc #{FLAGS[way]} -c test.c -o #{t.name}"
  end
end
desc 'build all ways'
task :all => WAYS.map{|way|out_file(way)}

task :default => [:all]

This setup can be used like:

rake all # (builds debug and release)
rake debug # (builds only debug)
rake release # (builds only release)

This does a little more as asked for, but shows my points:

  1. output directories are created, as necessary.
  2. the files are only recompiled if needed (this example is only correct for the simplest of test.c files).
  3. you have all tasks readily at hand if you want to trigger the release build or the debug build.
  4. this example includes a way to also define small differences between debug and release-builds.
  5. no need to reenable a build-task that is parametrized with a global variable, because now the different builds have different tasks. the codereuse of the build-task is done by reusing the code to define the build-tasks. see how the loop does not execute the same task twice, but instead created tasks, that can later be triggered (either by the all-task or be choosing one of them on the rake commandline).

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

What you are looking for is called reverse geocoding. Google provides a server-side reverse geocoding service through the Google Geocoding API, which you should be able to use for your project.

This is how a response to the following request would look like:

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false

Response:

{
  "status": "OK",
  "results": [ {
    "types": [ "street_address" ],
    "formatted_address": "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
    "address_components": [ {
      "long_name": "275-291",
      "short_name": "275-291",
      "types": [ "street_number" ]
    }, {
      "long_name": "Bedford Ave",
      "short_name": "Bedford Ave",
      "types": [ "route" ]
    }, {
      "long_name": "New York",
      "short_name": "New York",
      "types": [ "locality", "political" ]
    }, {
      "long_name": "Brooklyn",
      "short_name": "Brooklyn",
      "types": [ "administrative_area_level_3", "political" ]
    }, {
      "long_name": "Kings",
      "short_name": "Kings",
      "types": [ "administrative_area_level_2", "political" ]
    }, {
      "long_name": "New York",
      "short_name": "NY",
      "types": [ "administrative_area_level_1", "political" ]
    }, {
      "long_name": "United States",
      "short_name": "US",
      "types": [ "country", "political" ]
    }, {
      "long_name": "11211",
      "short_name": "11211",
      "types": [ "postal_code" ]
    } ],
    "geometry": {
      "location": {
        "lat": 40.7142298,
        "lng": -73.9614669
      },
      "location_type": "RANGE_INTERPOLATED",
      "viewport": {
        "southwest": {
          "lat": 40.7110822,
          "lng": -73.9646145
        },
        "northeast": {
          "lat": 40.7173774,
          "lng": -73.9583193
        }
      }
    }
  },

  ... Additional results[] ...

You can also opt to receive the response in xml instead of json, by simply substituting json for xml in the request URI:

http://maps.googleapis.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false

As far as I know, Google will also return the same name for address components, especially for high-level names like country names and city names. Nevertheless, keep in mind that while the results are very accurate for most applications, you could still find the occasional spelling mistake or ambiguous result.

"Post Image data using POSTMAN"

Follow the below steps:

  1. No need to give any type of header.
  2. Select body > form-data and do same as shown in the image. 1

  3. Now in your Django view.py

def post(self, request, *args, **kwargs):
    image = request.FILES["image"]
    data = json.loads(request.data['data'])
    ...
    return Response(...)
  1. You can access all the keys (id, uid etc..) from the data variable.

How different is Objective-C from C++?

Objective-C is a more perfect superset of C. In C and Objective-C implicit casting from void* to a struct pointer is allowed.

Foo* bar = malloc(sizeof(Foo));

C++ will not compile unless the void pointer is explicitly cast:

Foo* bar = (Foo*)malloc(sizeof(Foo));

The relevance of this to every day programming is zero, just a fun trivia fact.

How to move Docker containers between different hosts?

You cannot move a running docker container from one host to another.

You can commit the changes in your container to an image with docker commit, move the image onto a new host, and then start a new container with docker run. This will preserve any data that your application has created inside the container.

Nb: It does not preserve data that is stored inside volumes; you need to move data volumes manually to new host.

Deleting Elements in an Array if Element is a Certain value VBA

Deleting Elements in an Array if Element is a Certain value VBA

to delete elements in an Array wih certain condition, you can code like this

For i = LBound(ArrValue, 2) To UBound(ArrValue, 2)
    If [Certain condition] Then
        ArrValue(1, i) = "-----------------------"
    End If
Next i

StrTransfer = Replace(Replace(Replace(join(Application.Index(ArrValue(), 1, 0), ","), ",-----------------------,", ",", , , vbBinaryCompare), "-----------------------,", "", , , vbBinaryCompare), ",-----------------------", "", , , vbBinaryCompare)
ResultArray = join( Strtransfer, ",")

I often manipulate 1D-Array with Join/Split but if you have to delete certain value in Multi Dimension I suggest you to change those Array into 1D-Array like this

strTransfer = Replace(Replace(Replace(Replace(Names.Add("A", MultiDimensionArray), Chr(34), ""), "={", ""), "}", ""), ";", ",")
'somecode to edit Array like 1st code on top of this comment
'then loop through this strTransfer to get right value in right dimension
'with split function.

pthread function from a class

The above answers are good, but in my case, 1st approach that converts the function to be a static didn't work. I was trying to convert exiting code to move into thread function but that code had lots to references to non-static class members already. The second solution of encapsulating into C++ object works, but has 3-level wrappers to run a thread.

I had an alternate solution that uses existing C++ construct - 'friend' function, and it worked perfect for my case. An example of how I used 'friend' (will use the above same example for names showing how it can be converted into a compact form using friend)

    class MyThreadClass
    {
    public:
       MyThreadClass() {/* empty */}
       virtual ~MyThreadClass() {/* empty */}

       bool Init()
       {
          return (pthread_create(&_thread, NULL, &ThreadEntryFunc, this) == 0);
       }

       /** Will not return until the internal thread has exited. */
       void WaitForThreadToExit()
       {
          (void) pthread_join(_thread, NULL);
       }

    private:
       //our friend function that runs the thread task
       friend void* ThreadEntryFunc(void *);

       pthread_t _thread;
    };

    //friend is defined outside of class and without any qualifiers
    void* ThreadEntryFunc(void *obj_param) {
    MyThreadClass *thr  = ((MyThreadClass *)obj_param); 

    //access all the members using thr->

    return NULL;
    }

Ofcourse, we can use boost::thread and avoid all these, but I was trying to modify the C++ code to not use boost (the code was linking against boost just for this purpose)

How to use mouseover and mouseout in Angular 6

<div (mouseenter)="changeText=true" (mouseout)="changeText=false">
  <span *ngIf="!changeText">Hide</span>
  <span *ngIf="changeText">Show</span>
</div>

and if you want to use in *ngFor then assign the object value of hover data and then check its id and show hover info/icon or anything like that:-

 <div (mouseenter)="hoverCard(d)" (mouseleave)="hoverCard(null)" *ngFor="let d of data" class="col-lg-3 col-md-4 col-sm-6 mt-4">
   <a *ngIf="hoverData && hoverData.id == d.id" class="text-right"><i class="fas fa-edit"></i>Hover Text</a>
    Normal Text
  </div>

in TS File

  hoverData!:Data|null;

  hoverCard(d: Data|null){
    this.hoverData = sCatg;
  }

Invalid self signed SSL cert - "Subject Alternative Name Missing"

on MAC starting from chrome Version 67.0.3396.99 my self-signed certificate stopped to work.

regeneration with all what written here didn't work.

UPDATE

had a chance to confirm that my approach works today :). If it doesn't work for you make sure your are using this approach

v3.ext
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = <specify-the-same-common-name-that-you-used-while-generating-csr-in-the-last-step>
$

copied from here https://ksearch.wordpress.com/2017/08/22/generate-and-import-a-self-signed-ssl-certificate-on-mac-osx-sierra/

END UPDATE

finally was able to see green Secure only when removed my cert from system, and added it to local keychain. (if there is one - drop it first). Not sure if it maters but in my case I downloaded certificate via chrome, and verified that create date is today - so it is the one I've just created.

hope it will be helpful for someone spend like a day on it.

never update chrome!

Count unique values with pandas per groups

IIUC you want the number of different ID for every domain, then you can try this:

output = df.drop_duplicates()
output.groupby('domain').size()

output:

    domain
facebook.com    1
google.com      1
twitter.com     2
vk.com          3
dtype: int64

You could also use value_counts, which is slightly less efficient.But the best is Jezrael's answer using nunique:

%timeit df.drop_duplicates().groupby('domain').size()
1000 loops, best of 3: 939 µs per loop
%timeit df.drop_duplicates().domain.value_counts()
1000 loops, best of 3: 1.1 ms per loop
%timeit df.groupby('domain')['ID'].nunique()
1000 loops, best of 3: 440 µs per loop

What does Maven do, in theory and in practice? When is it worth to use it?

From the Sonatype doc:

The answer to this question depends on your own perspective. The great majority of Maven users are going to call Maven a “build tool”: a tool used to build deployable artifacts from source code. Build engineers and project managers might refer to Maven as something more comprehensive: a project management tool. What is the difference? A build tool such as Ant is focused solely on preprocessing, compilation, packaging, testing, and distribution. A project management tool such as Maven provides a superset of features found in a build tool. In addition to providing build capabilities, Maven can also run reports, generate a web site, and facilitate communication among members of a working team.

I'd strongly recommend looking at the Sonatype doc and spending some time looking at the available plugins to understand the power of Maven.

Very briefly, it operates at a higher conceptual level than (say) Ant. With Ant, you'd specify the set of files and resources that you want to build, then specify how you want them jarred together, and specify the order that should occur in (clean/compile/jar). With Maven this is all implicit. Maven expects to find your files in particular places, and will work automatically with that. Consequently setting up a project with Maven can be a lot simpler, but you have to play by Maven's rules!

Need to combine lots of files in a directory

you could use powershell script like this

$sb = new-object System.Text.StringBuilder

foreach ($file in Get-ChildItem -path 'C:\temp\xx\') {
    $content = Get-Content -Path $file.fullname
    $sb.Append($content)
}
Out-File -FilePath 'C:\temp\xx\c.txt' -InputObject $sb.toString()

Why does visual studio 2012 not find my tests?

This sometimes works.

Check that the processor architecture under Test menu matches the one you use to build the solution.

Test -> Test Settings -> Default Processor Architecture -> x86 / x64

As mentioned in other posts, make sure you have the Test Explorer window open. Test -> Windows -> Test Explorer

Then rebuilding the project with the tests should make the tests appear in Test Explorer.

Edit: As Ourjamie pointed out below, doing a clean build may also help. In addition to that, here is one more thing I encountered:

The "Build" checkbox was unticked in Configuration Manager for a new test project I had created under the solution.

Go to Build -> Configuration Manager. Make sure your test project has build checkbox checked for all solution configurations and solution platforms.

How to create text file and insert data to that file on Android

Check the android documentation. It's in fact not much different than standard java io file handling so you could also check that documentation.

An example from the android documentation:

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

How to declare a variable in a template in Angular

I liked the approach of creating a directive to do this (good call @yurzui).

I ended up finding a Medium article Angular "let" Directive which explains this problem nicely and proposes a custom let directive which ended up working great for my use case with minimal code changes.

Here's the gist (at the time of posting) with my modifications:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'

interface LetContext <T> {
  appLet: T | null
}

@Directive({
  selector: '[appLet]',
})
export class LetDirective <T> {
  private _context: LetContext <T> = { appLet: null }

  constructor(_viewContainer: ViewContainerRef, _templateRef: TemplateRef <LetContext <T> >) {
    _viewContainer.createEmbeddedView(_templateRef, this._context)
  }

  @Input()
  set appLet(value: T) {
    this._context.appLet = value
  }
}

My main changes were:

  • changing the prefix from 'ng' to 'app' (you should use whatever your app's custom prefix is)
  • changing appLet: T to appLet: T | null

Not sure why the Angular team hasn't just made an official ngLet directive but whatevs.

Original source code credit goes to @AustinMatherne

Loop through an array of strings in Bash?

I loop through an array of my projects for a git pull update:

#!/bin/sh
projects="
web
ios
android
"
for project in $projects do
    cd  $HOME/develop/$project && git pull
end

Get the selected option id with jQuery

$('#my_select option:selected').attr('id');

Using an HTTP PROXY - Python

Just wanted to mention, that you also may have to set the https_proxy OS environment variable in case https URLs need to be accessed. In my case it was not obvious to me and I tried for hours to discover this.

My use case: Win 7, jython-standalone-2.5.3.jar, setuptools installation via ez_setup.py

How to enable PHP's openssl extension to install Composer?

I am using WAMP server. Actually its files showed that openssl is opened. But manually I went to the folder and edited php.ini. Then I found it has not opened openssl.I uncommented it and it worked after after WAMP restart.

how to initialize a char array?

memset(msg, 0, 65546)

Check if number is decimal

A total cludge.. but hey it works !

$numpart = explode(".", $sumnum); 

if ((exists($numpart[1]) && ($numpart[1] > 0 )){
//    it's a decimal that is greater than zero
} else {
// its not a decimal, or the decimal is zero
}

How to load a jar file at runtime

Reloading existing classes with existing data is likely to break things.

You can load new code into new class loaders relatively easily:

ClassLoader loader = URLClassLoader.newInstance(
    new URL[] { yourURL },
    getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();

Class loaders no longer used can be garbage collected (unless there is a memory leak, as is often the case with using ThreadLocal, JDBC drivers, java.beans, etc).

If you want to keep the object data, then I suggest a persistence mechanism such as Serialisation, or whatever you are used to.

Of course debugging systems can do fancier things, but are more hacky and less reliable.

It is possible to add new classes into a class loader. For instance, using URLClassLoader.addURL. However, if a class fails to load (because, say, you haven't added it), then it will never load in that class loader instance.

Putting images with options in a dropdown list

folks, I got this Bootstrap dropdown working. I modified the click event slightly in order to keep the currently-selected image. And as you see, the USD currency is the default selected :

<div class="btn-group" style="margin:10px;">    <!-- CURRENCY, BOOTSTRAP DROPDOWN -->
                <!--<a class="btn btn-primary" href="javascript:void(0);">Currency</a>-->                    
                <a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#"><img src="../../Images/flag-usd-small.png"> USD <span class="caret"></span></a>
                <ul class="dropdown-menu">
                    <li><a href="javascript:void(0);">
                        <img src="../../Images/flag-aud-small.png" /> AUD</a>
                    </li>
                    <li><a href="javascript:void(0);">
                        <img src="../../Images/flag-cad-small.png" /> CAD</a>
                    </li>
                    <li><a href="javascript:void(0);">
                        <img src="../../Images/flag-cny-small.png" /> CNY</a>
                    </li>
                    <li><a href="javascript:void(0);">
                        <img src="../../Images/flag-gbp-small.png" /> GBP</a>
                    </li>
                    <li><a href="javascript:void(0);">
                        <img src="../../Images/flag-usd-small.png" /> USD</a>
                    </li>
                </ul>
            </div>


/* BOOTSTRAP DROPDOWN MENU - Update selected item text and image */
$(".dropdown-menu li a").click(function () {
    var selText = $(this).text();
    var imgSource = $(this).find('img').attr('src');
    var img = '<img src="' + imgSource + '"/>';        
    $(this).parents('.btn-group').find('.dropdown-toggle').html(img + ' ' + selText + ' <span class="caret"></span>');
});

Adjust width and height of iframe to fit with content in it

<iframe src="..." style="border:none; width:100%; height: 100vh;"></iframe>

Force browser to refresh css, javascript, etc

General solution

Pressing Ctrl + F5 (or Ctrl + Shift + R) to force a cache reload. I believe Macs use Cmd + Shift + R.

PHP

In PHP, you can disable the cache by setting the expiration date to a time in the past with headers:

header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

Chrome

Chrome's cache can be disabled by opening the developer tools with F12, clicking on the gear icon in the lower right corner and selecting Disable cache in the settings dialog, like this:

enter image description here
Image taken from this answer.

Firefox

Type about:config into the URL bar then find the entry titled network.http.use-cache. Set this to false.

How do I compare strings in GoLang?

== is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString do not contain "a", but "a\n" (if you look closely, you'll see the extra line break in your example output).

You can use the strings.TrimRight function to remove trailing whitespaces from your input:

if strings.TrimRight(input, "\n") == "a" {
    // ...
}

CSS background image alt attribute

This article from W3C tells you what they think you should do https://www.w3.org/WAI/GL/wiki/ARIATechnique_usingImgRole_with_aria-label_forCSS-backgroundImage

and has examples here http://mars.dequecloud.com/demo/ImgRole.htm

among which

<a href="http://www.facebook.com">
 <span class="fb_logo" role="img" aria-label="Connect via Facebook">
 </span>
</a>

Still, if, like in the above example, the element containing the background image is just an empty container, I personally prefer to put the text in there and hide it using CSS; right where you show the image instead:

<a href="http://www.facebook.com"><span class="fb_logo">
  Connect via Facebook
</span></a>

.fb_logo {
  height: 37px; width: 37px;
  background-image: url('../gfx/logo-facebook.svg');
  color:transparent; overflow:hidden; /* hide the text */
}

HTML form with two submit buttons and two "target" attributes

This works for me:

<input type='submit' name='self' value='This window' onclick='this.form.target="_self";' />

<input type='submit' name='blank' value='New window' onclick='this.form.target="_blank";' />

How do I set a Windows scheduled task to run in the background?

Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start

Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

remap is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:

:map and :noremap are recursive and non-recursive versions of the various mapping commands. For example, if we run:

:map j gg           (moves cursor to first line)
:map Q j            (moves cursor to first line)
:noremap W j        (moves cursor down one line)

Then:

  • j will be mapped to gg.
  • Q will also be mapped to gg, because j will be expanded for the recursive mapping.
  • W will be mapped to j (and not to gg) because j will not be expanded for the non-recursive mapping.

Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.

For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map and :noremap), one that works in normal mode (:nmap and :nnoremap), one in visual mode (:vmap and :vnoremap) and so on.

For more guidance on this, see:

:help :map
:help :noremap
:help recursive_mapping
:help :map-modes