Programs & Examples On #Admin generator

A tool of Symfony PHP framework that allows automatic generation of administrator sections in a web application

Peak-finding algorithm for Python/SciPy

I'm looking at a similar problem, and I've found some of the best references come from chemistry (from peaks finding in mass-spec data). For a good thorough review of peaking finding algorithms read this. This is one of the best clearest reviews of peak finding techniques that I've run across. (Wavelets are the best for finding peaks of this sort in noisy data.).

It looks like your peaks are clearly defined and aren't hidden in the noise. That being the case I'd recommend using smooth savtizky-golay derivatives to find the peaks (If you just differentiate the data above you'll have a mess of false positives.). This is a very effective technique and is pretty easy to implemented (you do need a matrix class w/ basic operations). If you simply find the zero crossing of the first S-G derivative I think you'll be happy.

The Use of Multiple JFrames: Good or Bad Practice?

The multiple JFrame approach has been something I've implemented since I began programming Swing apps. For the most part, I did it in the beginning because I didn't know any better. However, as I matured in my experience and knowledge as a developer and as began to read and absorb the opinions of so many more experienced Java devs online, I made an attempt to shift away from the multiple JFrame approach (both in current projects and future projects) only to be met with... get this... resistance from my clients! As I began implementing modal dialogs to control "child" windows and JInternalFrames for separate components, my clients began to complain! I was quite surprised, as I was doing what I thought was best-practice! But, as they say, "A happy wife is a happy life." Same goes for your clients. Of course, I am a contractor so my end-users have direct access to me, the developer, which is obviously not a common scenario.

So, I'm going to explain the benefits of the multiple JFrame approach, as well as myth-bust some of the cons that others have presented.

  1. Ultimate flexibility in layout - By allowing separate JFrames, you give your end-user the ability to spread out and control what's on his/her screen. The concept feels "open" and non-constricting. You lose this when you go towards one big JFrame and a bunch of JInternalFrames.
  2. Works well for very modularized applications - In my case, most of my applications have 3 - 5 big "modules" that really have nothing to do with each other whatsoever. For instance, one module might be a sales dashboard and one might be an accounting dashboard. They don't talk to each other or anything. However, the executive might want to open both and them being separate frames on the taskbar makes his life easier.
  3. Makes it easy for end-users to reference outside material - Once, I had this situation: My app had a "data viewer," from which you could click "Add New" and it would open a data entry screen. Initially, both were JFrames. However, I wanted the data entry screen to be a JDialog whose parent was the data viewer. I made the change, and immediately I received a call from an end-user who relied heavily on the fact that he could minimize or close the viewer and keep the editor open while he referenced another part of the program (or a website, I don't remember). He's not on a multi-monitor, so he needed the entry dialog to be first and something else to be second, with the data viewer completely hidden. This was impossible with a JDialog and certainly would've been impossible with a JInternalFrame as well. I begrudgingly changed it back to being separate JFrames for his sanity, but it taught me an important lesson.
  4. Myth: Hard to code - This is not true in my experience. I don't see why it would be any easier to create a JInternalFrame than a JFrame. In fact, in my experience, JInternalFrames offer much less flexibility. I have developed a systematic way of handling the opening & closing of JFrames in my apps that really works well. I control the frame almost completely from within the frame's code itself; the creation of the new frame, SwingWorkers that control the retrieval of data on background threads and the GUI code on EDT, restoring/bringing to front the frame if the user tries to open it twice, etc. All you need to open my JFrames is call a public static method open() and the open method, combined with a windowClosing() event handles the rest (is the frame already open? is it not open, but loading? etc.) I made this approach a template so it's not difficult to implement for each frame.
  5. Myth/Unproven: Resource Heavy - I'd like to see some facts behind this speculative statement. Although, perhaps, you could say a JFrame needs more space than a JInternalFrame, even if you open up 100 JFrames, how many more resources would you really be consuming? If your concern is memory leaks because of resources: calling dispose() frees all resources used by the frame for garbage collection (and, again I say, a JInternalFrame should invoke exactly the same concern).

I've written a lot and I feel like I could write more. Anyways, I hope I don't get down-voted simply because it's an unpopular opinion. The question is clearly a valuable one and I hope I've provided a valuable answer, even if it isn't the common opinion.

A great example of multiple frames/single document per frame (SDI) vs single frame/multiple documents per frame (MDI) is Microsoft Excel. Some of MDI benefits:

  • it is possible to have a few windows in non rectangular shape - so they don't hide desktop or other window from another process (e.g. web browser)
  • it is possible to open a window from another process over one Excel window while writing in second Excel window - with MDI, trying to write in one of internal windows will give focus to the entire Excel window, hence hiding window from another process
  • it is possible to have different documents on different screens, which is especially useful when screens do not have the same resolution

SDI (Single-Document Interface, i.e., every window can only have a single document):

enter image description here

MDI (Multiple-Document Interface, i.e., every window can have multiple documents):

enter image description here

How to use Selenium with Python?

You just need to get selenium package imported, that you can do from command prompt using the command

pip install selenium

When you have to use it in any IDE just import this package, no other documentation required to be imported

For Eg :

import selenium 
print(selenium.__filepath__)

This is just a general command you may use in starting to check the filepath of selenium

jQuery count number of divs with a certain class?

<!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <style type="text/css">
            .test {
                background: #ff4040;
                color: #fff;
                display: block;
                font-size: 15px;
            }
        </style>
    </head>
    <body>
        <div class="test"> one </div>
        <div class="test"> two </div>
        <div class="test"> three </div>
        <div class="test"> four </div>
        <div class="test"> five </div>
        <div class="test"> six </div>
        <div class="test"> seven </div>
        <div class="test"> eight </div>
        <div class="test"> nine </div>
        <div class="test"> ten </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function () {
            //get total length by class
            var numItems = $('.test').length;
            //get last three count
            var numItems3=numItems-3;         


            var i = 0;
            $('.test').each(function(){
                i++;
                if(i>numItems3)
                {

                    $(this).attr("class","");
                }
            })
        });
    </script>
    </body>
    </html>

Creating a simple XML file using python

These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.

The available options for that are:

  • ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
  • cElementTree (Optimized C implementation of ElementTree. Also offered in the standard library since 2.5)
  • LXML (Based on libxml2. Offers a rich superset of the ElementTree API as well XPath, CSS Selectors, and more)

Here's an example of how to generate your example document using the in-stdlib cElementTree:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

I've tested it and it works, but I'm assuming whitespace isn't significant. If you need "prettyprint" indentation, let me know and I'll look up how to do that. (It may be an LXML-specific option. I don't use the stdlib implementation much)

For further reading, here are some useful links:

As a final note, either cElementTree or LXML should be fast enough for all your needs (both are optimized C code), but in the event you're in a situation where you need to squeeze out every last bit of performance, the benchmarks on the LXML site indicate that:

  • LXML clearly wins for serializing (generating) XML
  • As a side-effect of implementing proper parent traversal, LXML is a bit slower than cElementTree for parsing.

Check if ADODB connection is open

This topic is old but if other people like me search a solution, this is a solution that I have found:

Public Function DBStats() As Boolean
    On Error GoTo errorHandler
        If Not IsNull(myBase.Version) Then 
            DBStats = True
        End If
        Exit Function
    errorHandler:
        DBStats = False  
End Function

So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":

Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false

Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false

cancelling a handler.postdelayed process

Hope this gist help https://gist.github.com/imammubin/a587192982ff8db221da14d094df6fb4

MainActivity as Screen Launcher with handler & runnable function, the Runnable run to login page or feed page with base preference login user with firebase.

How to add a new project to Github using VS Code

  1. create a new github repository.
  2. Goto the command line in VS code.(ctrl+`)
  3. Type following commands.

git init

git commit -m "first commit"

git remote add origin https://github.com/userName/repoName.git

git push -u origin master

-

PHP How to find the time elapsed since a date time?

Improvisation to the function "humanTiming" by arnorhs. It would calculate a "fully stretched" translation of time string to human readable text version. For example to say it like "1 week 2 days 1 hour 28 minutes 14 seconds"

function humantime ($oldtime, $newtime = null, $returnarray = false)    {
    if(!$newtime) $newtime = time();
    $time = $newtime - $oldtime; // to get the time since that moment
    $tokens = array (
            31536000 => 'year',
            2592000 => 'month',
            604800 => 'week',
            86400 => 'day',
            3600 => 'hour',
            60 => 'minute',
            1 => 'second'
    );
    $htarray = array();
    foreach ($tokens as $unit => $text) {
            if ($time < $unit) continue;
            $numberOfUnits = floor($time / $unit);
            $htarray[$text] = $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
            $time = $time - ( $unit * $numberOfUnits );
    }
    if($returnarray) return $htarray;
    return implode(' ', $htarray);
}

Using CookieContainer with WebClient class

This one is just extension of article you found.


public class WebClientEx : WebClient
{
    public WebClientEx(CookieContainer container)
    {
        this.container = container;
    }

    public CookieContainer CookieContainer
        {
            get { return container; }
            set { container= value; }
        }

    private CookieContainer container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest r = base.GetWebRequest(address);
        var request = r as HttpWebRequest;
        if (request != null)
        {
            request.CookieContainer = container;
        }
        return r;
    }

    protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
    {
        WebResponse response = base.GetWebResponse(request, result);
        ReadCookies(response);
        return response;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);
        ReadCookies(response);
        return response;
    }

    private void ReadCookies(WebResponse r)
    {
        var response = r as HttpWebResponse;
        if (response != null)
        {
            CookieCollection cookies = response.Cookies;
            container.Add(cookies);
        }
    }
}

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

First off, if you're using savefig, be aware that it will override the figure's background color when saving unless you specify otherwise (e.g. fig.savefig('blah.png', transparent=True)).

However, to remove the axes' and figure's background on-screen, you'll need to set both ax.patch and fig.patch to be invisible.

E.g.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

for item in [fig, ax]:
    item.patch.set_visible(False)

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

(Of course, you can't tell the difference on SO's white background, but everything is transparent...)

If you don't want to show anything other than the line, turn the axis off as well using ax.axis('off'):

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

fig.patch.set_visible(False)
ax.axis('off')

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

In that case, though, you may want to make the axes take up the full figure. If you manually specify the location of the axes, you can tell it to take up the full figure (alternately, you can use subplots_adjust, but this is simpler for the case of a single axes).

import matplotlib.pyplot as plt

fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.plot(range(10))

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

adding css class to multiple elements

.button input,
.button a {
    ...
}

What design patterns are used in Spring framework?

Service Locator Pattern - ServiceLocatorFactoryBean keeps information of all the beans in the context. When client code asks for a service (bean) using name, it simply locates that bean in the context and returns it. Client code does not need to write spring related code to locate a bean.

Using CSS to insert text

Just code it like this:

.OwnerJoe {
  //other things here
  &:before{
    content: "Joe's Task: ";
  }
}

How do I redirect to another webpage?

Standard "vanilla" JavaScript way to redirect a page

window.location.href = 'newPage.html';

Or more simply: (since window is Global)

location.href = 'newPage.html';

If you are here because you are losing HTTP_REFERER when redirecting, keep reading:

(Otherwise ignore this last part)


The following section is for those using HTTP_REFERER as one of many security measures (although it isn't a great protective measure). If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).

Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise, you can almost always simply use window.location.href.

Testing against HTTP_REFERER (URL pasting, session, etc.) can help tell whether a request is legitimate. (Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments)


Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)

Usage: redirect('anotherpage.aspx');

function redirect (url) {
    var ua        = navigator.userAgent.toLowerCase(),
        isIE      = ua.indexOf('msie') !== -1,
        version   = parseInt(ua.substr(4, 2), 10);

    // Internet Explorer 8 and lower
    if (isIE && version < 9) {
        var link = document.createElement('a');
        link.href = url;
        document.body.appendChild(link);
        link.click();
    }

    // All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
    else { 
        window.location.href = url; 
    }
}

How do I get the value of text input field using JavaScript?

simple js

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
}

Reverse ip, find domain names on ip address

From about section of Reverse IP Domain Check tool on yougetsignal:

A reverse IP domain check takes a domain name or IP address pointing to a web server and searches for other sites known to be hosted on that same web server. Data is gathered from search engine results, which are not guaranteed to be complete.

How do I calculate tables size in Oracle

select segment_name as tablename, sum(bytes/ (1024 * 1024 * 1024)) as tablesize_in_GB
From dba_segments /* if looking at tables not owned by you else use user_segments */
where segment_name = 'TABLE_WHOSE_SIZE_I_WANT_TO_KNOW'
and   OWNER = 'WHO OWNS THAT TABLE' /* if user_segments is used delete this line */ 
group by segment_name ;

How to use new PasswordEncoder from Spring Security

Here is the implementation of BCrypt which is working for me.

in spring-security.xml

<authentication-manager >
    <authentication-provider ref="authProvider"></authentication-provider>  
    </authentication-manager>
<beans:bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
  <beans:property name="userDetailsService" ref="userDetailsServiceImpl" />
  <beans:property name="passwordEncoder" ref="encoder" />
</beans:bean>
<!-- For hashing and salting user passwords -->
    <beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

In java class

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(yourpassword);

For more detailed example of spring security Click Here

Hope this will help.

Thanks

Map<String, String>, how to print both the "key string" and "value string" together

Inside of your loop, you have the key, which you can use to retrieve the value from the Map:

for (String key: mss1.keySet()) {
    System.out.println(key + ": " + mss1.get(key));
}

Is the NOLOCK (Sql Server hint) bad practice?

With NOLOCK hint, the transaction isolation level for the SELECT statement is READ UNCOMMITTED. This means that the query may see dirty and inconsistent data.

This is not a good idea to apply as a rule. Even if this dirty read behavior is OK for your mission critical web based application, a NOLOCK scan can cause 601 error which will terminate the query due to data movement as a result of lack of locking protection.

I suggest reading When Snapshot Isolation Helps and When It Hurts - the MSDN recommends using READ COMMITTED SNAPSHOT rather than SNAPSHOT under most circumstances.

How to declare a Fixed length Array in TypeScript

The Tuple approach :

This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.

Syntax example :

// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]> 

This is the safest approach, considering it prevents accessing indexes out of the boundaries.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
  Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
  & { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }

Tests :

var myFixedLengthArray: FixedLengthArray< [string, string, string]>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? INVALID INDEX ERROR

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR

(*) This solution requires the noImplicitAny typescript configuration directive to be enabled in order to work (commonly recommended practice)


The Array(ish) approach :

This solution behaves as an augmentation of the Array type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.

Syntax example :

let foo: FixedLengthArray<string, 3> 

Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' |  'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
  Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
  & {
    readonly length: L 
    [ I : number ] : T
    [Symbol.iterator]: () => IterableIterator<T>   
  }

Tests :

var myFixedLengthArray: FixedLengthArray<string,3>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? SHOULD FAIL

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL

How to rename a directory/folder on GitHub website?

There is no way to do this in the GitHub web application. I believe to only way to do this is in the command line using git mv <old name> <new name> or by using a Git client(like SourceTree).

How to resize a VirtualBox vmdk file

Use these simple steps to resize the vmdk

  1. Go to File -> Virtual Media Player

enter image description here

  1. Select vdi file and click properties

enter image description here

Here you can increase or decrease the vdi size.

How to get label text value form a html page?

You can use textContent attribute to retrieve data from a label.

 <script>
       var datas = document.getElementById("excel-data-div").textContent;
    </script>


<label id="excel-data-div" style="display: none;">
     Sample text
</label>

How do I copy directories recursively with gulp?

Turns out that to copy a complete directory structure gulp needs to be provided with a base for your gulp.src() method.

So gulp.src( [ files ], { "base" : "." }) can be used in the structure above to copy all the directories recursively.

If, like me, you may forget this then try:

gulp.copy=function(src,dest){
    return gulp.src(src, {base:"."})
        .pipe(gulp.dest(dest));
};

Difference between Select Unique and Select Distinct

  1. Unique was the old syntax while Distinct is the new syntax,which is now the Standard sql.
  2. Unique creates a constraint that all values to be inserted must be different from the others. An error can be witnessed if one tries to enter a duplicate value. Distinct results in the removal of the duplicate rows while retrieving data.
  3. Example: SELECT DISTINCT names FROM student ;

    CREATE TABLE Persons ( Id varchar NOT NULL UNIQUE, Name varchar(20) );

Chmod 777 to a folder and all contents

If you are going for a console command it would be:

chmod -R 777 /www/store. The -R (or --recursive) options make it recursive.

Or if you want to make all the files in the current directory have all permissions type:

chmod -R 777 ./

If you need more info about chmod command see: File permission

Print range of numbers on same line

Though the answer has been given for the question. I would like to add, if in case we need to print numbers without any spaces then we can use the following code

        for i in range(1,n):
            print(i,end="")

Determining type of an object in ruby

you could also try: instance_of?

p 1.instance_of? Fixnum    #=> True
p "1".instance_of? String  #=> True
p [1,2].instance_of? Array #=> True

Python equivalent to 'hold on' in Matlab

The hold on feature is switched on by default in matplotlib.pyplot. So each time you evoke plt.plot() before plt.show() a drawing is added to the plot. Launching plt.plot() after the function plt.show() leads to redrawing the whole picture.

how to bind datatable to datagridview in c#

On the DataGridView, set the DataPropertyName of the columns to your column names of your DataTable.

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

I have faced the same issue. After done some research i found fix for me and it may useful. The issue is not only related to re-installation as of my observation, it depends on access permissions also.

Step 1: Repair the particular COM object.

Step 2: Component Services > Computers > My Computer > DCOM Config > Select your COM object > Right click > Properties > Security tab > Access Permissions > Choose Customize > Click EDIT > Select IIS_USER (If not exists create with complete rights) and give complete access and click OK.

Move to Identity tab > You can select "Interactive user" or "This user" > Click Apply and OK. If you choose "This user", we have to give Administrative privileged user to that server

Step 3: Open IIS Manager > Restart the Application Pools.

Note: If required please restart the server

executing a function in sql plus

declare
  x number;
begin
  x := myfunc(myargs);
end;

Alternatively:

select myfunc(myargs) from dual;

How to get just the date part of getdate()?

try this:

select convert (date ,getdate())

or

select CAST (getdate() as DATE)

or

select convert(varchar(10), getdate(),121)

Manually adding a Userscript to Google Chrome

The best thing to do is to install the Tampermonkey extension.

This will allow you to easily install Greasemonkey scripts, and to easily manage them. Also it makes it easier to install userscripts directly from sites like OpenUserJS, MonkeyGuts, etc.

Finally, it unlocks most all of the GM functionality that you don't get by installing a GM script directly with Chrome. That is, more of what GM on Firefox can do, is available with Tampermonkey.


But, if you really want to install a GM script directly, it's easy a right pain on Chrome these days...

Chrome After about August, 2014:

You can still drag a file to the extensions page and it will work... Until you restart Chrome. Then it will be permanently disabled. See Continuing to "protect" Chrome users from malicious extensions for more information. Again, Tampermonkey is the smart way to go. (Or switch browsers altogether to Opera or Firefox.)

Chrome 21+ :

Chrome is changing the way extensions are installed. Userscripts are pared-down extensions on Chrome but. Starting in Chrome 21, link-click behavior is disabled for userscripts. To install a user script, drag the **.user.js* file into the Extensions page (chrome://extensions in the address input).

Older Chrome versions:

Merely drag your **.user.js* files into any Chrome window. Or click on any Greasemonkey script-link.

You'll get an installation warning:
Initial warning

Click Continue.


You'll get a confirmation dialog:
confirmation dialog

Click Add.


Notes:

  1. Scripts installed this way have limitations compared to a Greasemonkey (Firefox) script or a Tampermonkey script. See Cross-browser user-scripting, Chrome section.

Controlling the Script and name:

By default, Chrome installs scripts in the Extensions folder1, full of cryptic names and version numbers. And, if you try to manually add a script under this folder tree, it will be wiped the next time Chrome restarts.

To control the directories and filenames to something more meaningful, you can:

  1. Create a directory that's convenient to you, and not where Chrome normally looks for extensions. For example, Create: C:\MyChromeScripts\.

  2. For each script create its own subdirectory. For example, HelloWorld.

  3. In that subdirectory, create or copy the script file. For example, Save this question's code as: HelloWorld.user.js.

  4. You must also create a manifest file in that subdirectory, it must be named: manifest.json.

    For our example, it should contain:

    {
        "manifest_version": 2,
        "content_scripts": [ {
            "exclude_globs":    [  ],
            "include_globs":    [ "*" ],
            "js":               [ "HelloWorld.user.js" ],
            "matches":          [   "https://stackoverflow.com/*",
                                    "https://stackoverflow.com/*"
                                ],
            "run_at": "document_end"
        } ],
        "converted_from_user_script": true,
        "description":  "My first sensibly named script!",
        "name":         "Hello World",
        "version":      "1"
    }
    

    The manifest.json file is automatically generated from the meta-block by Chrome, when an user script is installed. The values of @include and @exclude meta-rules are stored in include_globs and exclude_globs, @match (recommended) is stored in the matches list. "converted_from_user_script": true is required if you want to use any of the supported GM_* methods.

  5. Now, in Chrome's Extension manager (URL = chrome://extensions/), Expand "Developer mode".

  6. Click the Load unpacked extension... button.

  7. For the folder, paste in the folder for your script, In this example it is: C:\MyChromeScripts\HelloWorld.

  8. Your script is now installed, and operational!

  9. If you make any changes to the script source, hit the Reload link for them to take effect:

    Reload link




1 The folder defaults to:

Windows XP:
  Chrome  : %AppData%\..\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions\
  Chromium: %AppData%\..\Local Settings\Application Data\Chromium\User Data\Default\Extensions\

Windows Vista/7/8:
  Chrome  : %LocalAppData%\Google\Chrome\User Data\Default\Extensions\
  Chromium: %LocalAppData%\Chromium\User Data\Default\Extensions\

Linux:
  Chrome  : ~/.config/google-chrome/Default/Extensions/
  Chromium: ~/.config/chromium/Default/Extensions/

Mac OS X:
  Chrome  : ~/Library/Application Support/Google/Chrome/Default/Extensions/
  Chromium: ~/Library/Application Support/Chromium/Default/Extensions/

Although you can change it by running Chrome with the --user-data-dir= option.

How to convert CLOB to VARCHAR2 inside oracle pl/sql

ALTER TABLE TABLE_NAME ADD (COLUMN_NAME_NEW varchar2(4000 char));
update TABLE_NAME set COLUMN_NAME_NEW = COLUMN_NAME;

ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME;
ALTER TABLE TABLE_NAME rename column COLUMN_NAME_NEW to COLUMN_NAME;

How to set cookies in laravel 5 independently inside controller

If you want to set cookie and get it outside of request, Laravel is not your friend.

Laravel cookies are part of Request, so if you want to do this outside of Request object, use good 'ole PHP setcookie(..) and $_COOKIE to get it.

Get all column names of a DataTable into string array using (LINQ/Predicate)

List<String> lsColumns = new List<string>();

if(dt.Rows.Count>0)
{
    var count = dt.Rows[0].Table.Columns.Count;

    for (int i = 0; i < count;i++ )
    {
        lsColumns.Add(Convert.ToString(dt.Rows[0][i]));
    }
}

What is a simple command line program or script to backup SQL server databases?

SET NOCOUNT ON;
declare @PATH VARCHAR(200)='D:\MyBackupFolder\'
 -- path where you want to take backups
IF OBJECT_ID('TEMPDB..#back') IS NOT NULL

DROP TABLE #back

CREATE TABLE #back
(
RN INT IDENTITY (1,1),
DatabaseName NVARCHAR(200)

)

INSERT INTO #back 
SELECT       'MyDatabase1'
UNION SELECT 'MyDatabase2'
UNION SELECT 'MyDatabase3'
UNION SELECT 'MyDatabase4'

-- your databases List

DECLARE @COUNT INT =0 ,  @RN INT =1, @SCRIPT NVARCHAR(MAX)='',  @DBNAME VARCHAR(200)

PRINT '---------------------FULL BACKUP SCRIPT-------------------------'+CHAR(10)
SET @COUNT = (SELECT COUNT(*) FROM #back)
PRINT 'USE MASTER'+CHAR(10)
WHILE(@COUNT > = @RN)
BEGIN

SET @DBNAME =(SELECT DatabaseName FROM #back WHERE RN=@RN)
SET @SCRIPT ='BACKUP DATABASE ' +'['+@DBNAME+']'+CHAR(10)+'TO DISK =N'''+@PATH+@DBNAME+ N'_Backup_'
+ REPLACE ( REPLACE ( REPLACE ( REPLACE ( CAST ( CAST ( GETDATE () AS DATETIME2 ) AS VARCHAR ( 100 )), '-' , '_' ), ' ' , '_' ), '.' , '_' ), ':' , '' )+'.bak'''+CHAR(10)+'WITH COMPRESSION, STATS = 10'+CHAR(10)+'GO'+CHAR(10)
PRINT @SCRIPT
SET @RN=@RN+1
END

 PRINT '---------------------DIFF BACKUP SCRIPT-------------------------'+CHAR(10)

  SET  @COUNT  =0 SET  @RN  =1 SET @SCRIPT ='' SET @DBNAME =''
 SET @COUNT = (SELECT COUNT(*) FROM #back)
PRINT 'USE MASTER'+CHAR(10)
WHILE(@COUNT > = @RN)
BEGIN
SET @DBNAME =(SELECT DatabaseName FROM #back WHERE RN=@RN)
SET @SCRIPT ='BACKUP DATABASE ' +'['+@DBNAME+']'+CHAR(10)+'TO DISK =N'''+@PATH+@DBNAME+ N'_Backup_'
+ REPLACE ( REPLACE ( REPLACE ( REPLACE ( CAST ( CAST ( GETDATE () AS DATETIME2 ) AS VARCHAR ( 100 )), '-' , '_' ), ' ' , '_' ), '.' , '_' ), ':' , '' )+'.diff'''+CHAR(10)+'WITH DIFFERENTIAL, COMPRESSION, STATS = 10'+CHAR(10)+'GO'+CHAR(10)
PRINT @SCRIPT
SET @RN=@RN+1
END

How do you change video src using jQuery?

Try $("#divVideo video")[0].load(); after you changed the src attribute.

Definition of "downstream" and "upstream"

In terms of source control, you're "downstream" when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.

When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.

Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to "upstream". That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them "upstream" to the original source, they shouldn't have to deal with the same issue in the next release.

Converting string "true" / "false" to boolean value

If you're using the variable result:

result = result == "true";

Unzip a file with php

PHP has its own inbuilt class that can be used to unzip or extracts contents from a zip file. The class is ZipArchive. Below is the simple and basic PHP code that will extract a zip file and place it in a specific directory:

<?php
$zip_obj = new ZipArchive;
$zip_obj->open('dummy.zip');
$zip_obj->extractTo('directory_name/sub_dir');
?>

If you want some advance features then below is the improved code that will check if the zip file exists or not:

<?php
$zip_obj = new ZipArchive;
if ($zip_obj->open('dummy.zip') === TRUE) {
   $zip_obj->extractTo('directory/sub_dir');
   echo "Zip exists and successfully extracted";
}
else {
   echo "This zip file does not exists";
}
?>

Source: How to unzip or extract zip files in PHP?

How to delete from a table where ID is in a list of IDs?

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

Mockito. Verify method arguments

I have used Mockito.verify in this way

@UnitTest
public class JUnitServiceTest
{
    @Mock
    private MyCustomService myCustomService;


    @Test
    public void testVerifyMethod()
    {
       Mockito.verify(myCustomService, Mockito.never()).mymethod(parameters); // method will never call (an alternative can be pick to use times(0))
       Mockito.verify(myCustomService, Mockito.times(2)).mymethod(parameters); // method will call for 2 times
       Mockito.verify(myCustomService, Mockito.atLeastOnce()).mymethod(parameters); // method will call atleast 1 time
       Mockito.verify(myCustomService, Mockito.atLeast(2)).mymethod(parameters); // method will call atleast 2 times
       Mockito.verify(myCustomService, Mockito.atMost(3)).mymethod(parameters); // method will call at most 3 times
       Mockito.verify(myCustomService, Mockito.only()).mymethod(parameters); //   no other method called except this
    }
}

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

Difference between Spring MVC and Struts MVC

Spring provides a very clean division between controllers, JavaBean models, and views.

Facebook Access Token for Pages

See here if you want to grant a Facebook App permanent access to a page (even when you / the app owner are logged out):

http://developers.facebook.com/docs/opengraph/using-app-tokens/

"An App Access Token does not expire unless you refresh the application secret through your app settings."

Eclipse "this compilation unit is not on the build path of a java project"

Had the same problem (but with Maven). The reason was incorrect choice of executor: my project used global settings that are not avilable from Embedded installation of Maven. Changed it to external (Window -> Preferences -> Maven -> Installations) and that fixed the problem.

Visual Studio 2017 - Git failed with a fatal error

I once had such an error from Git while I was trying to synchronise a repository (I tried to send my commits while having pending changes from my coworker):

Git failed with a fatal error. pull --verbose --progress --no-edit --no-stat --recurse-submodules=no origin

It turned out that after pressing the Commit all button to create a local commit, Visual Studio had left one file uncommitted and this elaborated error message actually meant: "Commit all your changes".

That missing file was Entity Framework 6 model, and it is often shown as uncommitted file although you haven't changed a thing in it.

You can do commit all or undo all changes that are not committed.

Forwarding port 80 to 8080 using NGINX

NGINX supports WebSockets by allowing a tunnel to be setup between a client and a backend server. In order for NGINX to send the Upgrade request from the client to the backend server, Upgrade and Connection headers must be set explicitly. For example:

# WebSocket proxying
map $http_upgrade $connection_upgrade {
    default         upgrade;
    ''              close;
}


server {
    listen 80;

    # The host name to respond to
    server_name cdn.domain.com;

    location / {
        # Backend nodejs server
        proxy_pass          http://127.0.0.1:8080;
        proxy_http_version  1.1;
        proxy_set_header    Upgrade     $http_upgrade;
        proxy_set_header    Connection  $connection_upgrade;
    }
}

Source: http://nginx.com/blog/websocket-nginx/

How to insert an element after another element in JavaScript without using a library?

The method node.after (doc) inserts a node after another node.

For two DOM nodes node1 and node2,

node1.after(node2) inserts node2 after node1.

This method is not available in older browsers, so usually a polyfill is needed.

Laravel - Return json along with http status code

I prefer the response helper myself:

    return response()->json(['message' => 'Yup. This request succeeded.'], 200);

Check whether a value exists in JSON object

var JSON = [{"name":"cat"}, {"name":"dog"}];

The JSON variable refers to an array of object with one property called "name". I don't know of the best way but this is what I do?

var hasMatch =false;

for (var index = 0; index < JSON.length; ++index) {

 var animal = JSON[index];

 if(animal.Name == "dog"){
   hasMatch = true;
   break;
 }
}

How can I add new dimensions to a Numpy array?

Pythonic

X = X[:, :, None]

which is equivalent to

X = X[:, :, numpy.newaxis] and X = numpy.expand_dims(X, axis=-1)

But as you are explicitly asking about stacking images, I would recommend going for stacking the list of images np.stack([X1, X2, X3]) that you may have collected in a loop.

If you do not like the order of the dimensions you can rearrange with np.transpose()

How to implement a simple scenario the OO way

The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).

Custom CSS Scrollbar for Firefox

I thought I would share my findings in case someone is considering a JQuery plugin to do the job.

I gave JQuery Custom Scrollbar a go. It's pretty fancy and does some smooth scrolling (with scrolling inertia) and has loads of parameters you can tweak, but it ended up being a bit too CPU intensive for me (and it adds a fair amount to the DOM).

Now I'm giving Perfect Scrollbar a go. It's simple and lightweight (6KB) and it's doing a decent job so far. It's not CPU intensive at all (as far as I can tell) and adds very little to your DOM. It's only got a couple of parameters to tweak (wheelSpeed and wheelPropagation), but it's all I need and it handles updates to the scrolling content nicely (such as loading images).

P.S. I did have a quick look at JScrollPane, but @simone is right, it's a bit dated now and a PITA.

How to count the number of occurrences of a character in an Oracle varchar value?

Here's an idea: try replacing everything that is not a dash char with empty string. Then count how many dashes remained.

select length(regexp_replace('123-345-566', '[^-]', '')) from dual

How to avoid HTTP error 429 (Too Many Requests) python

Another workaround would be to spoof your IP using some sort of Public VPN or Tor network. This would be assuming the rate-limiting on the server at IP level.

There is a brief blog post demonstrating a way to use tor along with urllib2:

http://blog.flip-edesign.com/?p=119

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

Is __init__.py not required for packages in Python 3.3+

If you have setup.py in your project and you use find_packages() within it, it is necessary to have an __init__.py file in every directory for packages to be automatically found.

Packages are only recognized if they include an __init__.py file

UPD: If you want to use implicit namespace packages without __init__.py you just have to use find_namespace_packages() instead

Docs

What are the obj and bin folders (created by Visual Studio) used for?

One interesting fact about the obj directory: If you have publishing set up in a web project, the files that will be published are staged to obj\Release\Package\PackageTmp. If you want to publish the files yourself rather than use the integrated VS feature, you can grab the files that you actually need to deploy here, rather than pick through all the digital debris in the bin directory.

Zabbix server is not running: the information displayed may not be current

To solve the problem zabbix server is not running you have to :

First - Check that all of the database parameters in zabbix.conf.php ( /etc/zabbix/web/zabbix.conf.php) and zabbix_server.conf ( /etc/zabbix/zabbix_server.conf) to be the same. Including:
• DBHost
• DBName
• DBUser
• DBPassword

Second- Change SElinux parameters:

#setsebool -P httpd_can_network_connect on
#setsebool -P httpd_can_connect_zabbix 1
#setsebool -P zabbix_can_network 1

After all, restart all services:

#service zabbix-server restart
#service httpd restart

worth a try.

How to convert current date to epoch timestamp?

Short-hand to convert python date/datetime to Epoch (without microseconds)

int(current_date.strftime("%s")) # 2020-01-14  ---> 1578956400
int(current_datetime.strftime("%s")) # 2020-01-14 16:59:30.251176 -----> 1579017570

Class constants in python

Since Horse is a subclass of Animal, you can just change

print(Animal.SIZES[1])

with

print(self.SIZES[1])

Still, you need to remember that SIZES[1] means "big", so probably you could improve your code by doing something like:

class Animal:
    SIZE_HUGE="Huge"
    SIZE_BIG="Big"
    SIZE_MEDIUM="Medium"
    SIZE_SMALL="Small"

class Horse(Animal):
    def printSize(self):
        print(self.SIZE_BIG)

Alternatively, you could create intermediate classes: HugeAnimal, BigAnimal, and so on. That would be especially helpful if each animal class will contain different logic.

Datatables on-the-fly resizing

This did the trick for me.

$('#dataTable').resize()

auto refresh for every 5 mins

Refresh document every 300 seconds using HTML Meta tag add this inside the head tag of the page

 <meta http-equiv="refresh" content="300">

Using Script:

            setInterval(function() {
                  window.location.reload();
                }, 300000); 

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

During the creation of S3Client you can specify the endpoint mapping to a particular region. If default of s3.amazonaws.com then bucket will be created in us-east-1 which is North Virginia.

More details on S3 endpoints and regions in AWS docs: http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region.

So, always make sure about the endpoint/region while creating the S3Client and access S3 resouces using the same client in the same region.

If the bucket is created from AWS S3 Console, then check the region from the console for that bucket then create a S3 Client in that region using the endpoint details mentioned in the above link.

IN vs ANY operator in PostgreSQL

(Neither IN nor ANY is an "operator". A "construct" or "syntax element".)

Logically, quoting the manual:

IN is equivalent to = ANY.

But there are two syntax variants of IN and two variants of ANY. Details:

IN taking a set is equivalent to = ANY taking a set, as demonstrated here:

But the second variant of each is not equivalent to the other. The second variant of the ANY construct takes an array (must be an actual array type), while the second variant of IN takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:

ANY is more versatile

The ANY construct is far more versatile, as it can be combined with various operators, not just =. Example:

SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');

For a big number of values, providing a set scales better for each:

Related:

Inversion / opposite / exclusion

"Find rows where id is in the given array":

SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);

Inversion: "Find rows where id is not in the array":

SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}');  -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));

All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[].

Rows with id IS NULL do not pass either of these expressions. To include NULL values additionally:

SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;

How to generate Javadoc HTML files in Eclipse?

  1. Project > Generate Javadoc....

  2. In the Javadoc command: field, browse to find javadoc.exe (usually at [path_to_jdk_directory]\bin\javadoc.exe).

  3. Check the box next to the project/package/file for which you are creating the Javadoc.

  4. In the Destination: field, browse to find the desired destination (for example, the root directory of the current project).

  5. Click Finish.

You should now be able to find the newly generated Javadoc in the destination folder. Open index.html.

What is the 'dynamic' type in C# 4.0 used for?

Another use case for dynamic typing is for virtual methods that experience a problem with covariance or contravariance. One such example is the infamous Clone method that returns an object of the same type as the object it is called on. This problem is not completely solved with a dynamic return because it bypasses static type checking, but at least you don't need to use ugly casts all the time as per when using plain object. Otherwise to say, the casts become implicit.

public class A
{
    // attributes and constructor here
    public virtual dynamic Clone()
    {
        var clone = new A();
        // Do more cloning stuff here
        return clone;
    }
}

public class B : A
{
    // more attributes and constructor here
    public override dynamic Clone()
    {
        var clone = new B();    
        // Do more cloning stuff here
        return clone;
    }
}    

public class Program
{
    public static void Main()
    {
        A a = new A().Clone();  // No cast needed here
        B b = new B().Clone();  // and here
        // do more stuff with a and b
    }
}

What killed my process and why?

This looks like a good article on the subject: Taming the OOM killer.

The gist is that Linux overcommits memory. When a process asks for more space, Linux will give it that space, even if it is claimed by another process, under the assumption that nobody actually uses all of the memory they ask for. The process will get exclusive use of the memory it has allocated when it actually uses it, not when it asks for it. This makes allocation quick, and might allow you to "cheat" and allocate more memory than you really have. However, once processes start using this memory, Linux might realize that it has been too generous in allocating memory it doesn't have, and will have to kill off a process to free some up. The process to be killed is based on a score taking into account runtime (long-running processes are safer), memory usage (greedy processes are less safe), and a few other factors, including a value you can adjust to make a process less likely to be killed. It's all described in the article in a lot more detail.

Edit: And here is another article that explains pretty well how a process is chosen (annotated with some kernel code examples). The great thing about this is that it includes some commentary on the reasoning behind the various badness() rules.

Looping through array and removing items, without breaking for loop

Here is a simple linear time solution to this simple linear time problem.

When I run this snippet, with n = 1 million, each call to filterInPlace() takes .013 to .016 seconds. A quadratic solution (e.g. the accepted answer) would take a million times that, or so.

_x000D_
_x000D_
// Remove from array every item such that !condition(item).
function filterInPlace(array, condition) {
   var iOut = 0;
   for (var i = 0; i < array.length; i++)
     if (condition(array[i]))
       array[iOut++] = array[i];
   array.length = iOut;
}

// Try it out.  A quadratic solution would take a very long time.
var n = 1*1000*1000;
console.log("constructing array...");
var Auction = {auctions: []};
for (var i = 0; i < n; ++i) {
  Auction.auctions.push({seconds:1});
  Auction.auctions.push({seconds:2});
  Auction.auctions.push({seconds:0});
}
console.log("array length should be "+(3*n)+": ", Auction.auctions.length)
filterInPlace(Auction.auctions, function(auction) {return --auction.seconds >= 0; })
console.log("array length should be "+(2*n)+": ", Auction.auctions.length)
filterInPlace(Auction.auctions, function(auction) {return --auction.seconds >= 0; })
console.log("array length should be "+n+": ", Auction.auctions.length)
filterInPlace(Auction.auctions, function(auction) {return --auction.seconds >= 0; })
console.log("array length should be 0: ", Auction.auctions.length)
_x000D_
_x000D_
_x000D_

Note that this modifies the original array in place rather than creating a new array; doing it in place like this can be advantageous, e.g. in the case that the array is the program's single memory bottleneck; in that case, you don't want to create another array of the same size, even temporarily.

How to set or change the default Java (JDK) version on OS X?

Consider the following approach only to change the JDK for each and specific tab of your terminal (i.e: iTerm).

Having in the /Library/Java/JavaVirtualMachines path the two following jdks

  • openjdk8u275-b01
  • openjdk-11.0.9.1+1

And in the .bash_profile file the following:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/openjdk-11.0.9.1+1/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH

If you open Iterm with a first Tab A and execute the following:

javac -version
javac 11.0.9.1

java -version
openjdk version "11.0.9.1" 2020-11-04
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.9.1+1)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.9.1+1, mixed mode)

The output is correct and expected

But if you open a second Tab B and override that JDK do the following:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/openjdk8u275-b01/Contents/Home/
export PATH=$JAVA_HOME/bin:$PATH

Then

javac -version
javac 1.8.0_275

java -version
openjdk version "1.8.0_275"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_275-b01)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.275-b01, mixed mode)

It works fine. Of course if the Tab B is closed or you open a new Tab C all work according the .bash_profile settings

add/remove active class for ul list with jquery?

you can use siblings and removeClass method

$('.nav-link li').click(function() {
    $(this).addClass('active').siblings().removeClass('active');
});

Change background image opacity

What I did is:

<div id="bg-image"></div>
<div class="container">
    <h1>Hello World!</h1>
</div>

CSS:

html {
    height: 100%;
    width: 100%;
}
body {
    height: 100%;
    width: 100%;
}
#bg-image {
    height: 100%;
    width: 100%;
    position: absolute;
    background-image: url(images/background.jpg);
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    opacity: 0.3;
}

"Could not get any response" response when using postman with subdomain

None of these solutions works for me. Postman is not sending any request to the server because postman is not finding the host. So, if you modify your /etc/hosts to 127.0.0.1 localhost 127.0.0.1 subdomain.localhost

It works for me.

How to manage exceptions thrown in filters in Spring?

After reading through different methods suggested in the above answers, I decided to handle the authentication exceptions by using a custom filter. I was able to handle the response status and codes using an error response class using the following method.

I created a custom filter and modified my security config by using the addFilterAfter method and added after the CorsFilter class.

@Component
public class AuthFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    //Cast the servlet request and response to HttpServletRequest and HttpServletResponse
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    // Grab the exception from the request attribute
    Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
    //Set response content type to application/json
    httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

    //check if exception is not null and determine the instance of the exception to further manipulate the status codes and messages of your exception
    if(exception!=null && exception instanceof AuthorizationParameterNotFoundException){
        ErrorResponse errorResponse = new ErrorResponse(exception.getMessage(),"Authetication Failed!");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(convertObjectToJson(errorResponse));
        writer.flush();
        return;
    }
    // If exception instance cannot be determined, then throw a nice exception and desired response code.
    else if(exception!=null){
            ErrorResponse errorResponse = new ErrorResponse(exception.getMessage(),"Authetication Failed!");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write(convertObjectToJson(errorResponse));
            writer.flush();
            return;
        }
        else {
        // proceed with the initial request if no exception is thrown.
            chain.doFilter(httpServletRequest,httpServletResponse);
        }
    }

public String convertObjectToJson(Object object) throws JsonProcessingException {
    if (object == null) {
        return null;
    }
    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(object);
}
}

SecurityConfig class

    @Configuration
    public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    AuthFilter authenticationFilter;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(authenticationFilter, CorsFilter.class).csrf().disable()
                .cors(); //........
        return http;
     }
   }

ErrorResponse class

public class ErrorResponse  {
private final String message;
private final String description;

public ErrorResponse(String description, String message) {
    this.message = message;
    this.description = description;
}

public String getMessage() {
    return message;
}

public String getDescription() {
    return description;
}}

Two dimensional array in python

There aren't multidimensional arrays as such in Python, what you have is a list containing other lists.

>>> arr = [[]]
>>> len(arr)
1

What you have done is declare a list containing a single list. So arr[0] contains a list but arr[1] is not defined.

You can define a list containing two lists as follows:

arr = [[],[]]

Or to define a longer list you could use:

>>> arr = [[] for _ in range(5)]
>>> arr
[[], [], [], [], []]

What you shouldn't do is this:

arr = [[]] * 3

As this puts the same list in all three places in the container list:

>>> arr[0].append('test')
>>> arr
[['test'], ['test'], ['test']]

Bootstrap select dropdown list placeholder

<option value="" defaultValue disabled> Something </option>

you can replace defaultValue with selected but that would give warning.

NodeJS w/Express Error: Cannot GET /

I was facing the same problem as mentioned in the question. The following steps solved my problem.

I upgraded the nodejs package link with following steps

  1. Clear NPM's cache:

    npm cache clean -f
    
  2. Install a little helper called 'n'

    npm install -g n  
    

Then I went to node.js website, downloaded the latest node js package, installed it, and my problem was solved.

How can I download HTML source in C#

You can get it with:

var html = new System.Net.WebClient().DownloadString(siteUrl)

How can I declare dynamic String array in Java

The Array.newInstance(Class<?> componentType, int length) method is to be used to create an array with dynamically length.

Multi-dimensional arrays can be created similarly with the Array.newInstance(Class<?> componentType, int... dimensions) method.

How do you scroll up/down on the console of a Linux VM

In some VPS hostings (like linode) you have to click Ctrl+A and then ESC. Exit with double ESC too.

ES6 export default with multiple functions referring to each other

One alternative is to change up your module. Generally if you are exporting an object with a bunch of functions on it, it's easier to export a bunch of named functions, e.g.

export function foo() { console.log('foo') }, 
export function bar() { console.log('bar') },
export function baz() { foo(); bar() }

In this case you are export all of the functions with names, so you could do

import * as fns from './foo';

to get an object with properties for each function instead of the import you'd use for your first example:

import fns from './foo';

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

If you are having an issue retrieving the password using the keychain wrapper, use this code:

NSData *pass =[keychain objectForKey:(__bridge id)(kSecValueData)];
NSString *passworddecoded = [[NSString alloc] initWithData:pass
                                           encoding:NSUTF8StringEncoding];

Read from file in eclipse

There's nothing wrong with your code, the following works fine for me when I have the file.txt in the user.dir directory.

import java.io.File;
import java.util.Scanner;

public class testme {
    public static void main(String[] args) {
        System.out.println(System.getProperty("user.dir"));
        File file = new File("file.txt");
        try {
            Scanner scanner = new Scanner(file);
        } catch (Exception e) {
        System.out.println(e);
        }
    }
}

Don't trust Eclipse with where it says the file is. Go out to the actual filesystem with Windows Explorer or equivalent and check.

Based on your edit, I think we need to see your import statements as well.

SQL Server : Arithmetic overflow error converting expression to data type int

SELECT                          
    DATEPART(YEAR, dateTimeStamp) AS [Year]                         
    , DATEPART(MONTH, dateTimeStamp) AS [Month]                         
    , COUNT(*) AS NumStreams                        
    , [platform] AS [Platform]                      
    , deliverableName AS [Deliverable Name]                     
    , SUM(billableDuration) AS NumSecondsDelivered

Assuming that your quoted text is the exact text, one of these columns can't do the mathematical calculations that you want. Double click on the error and it will highlight the line that's causing the problems (if it's different than what's posted, it may not be up there); I tested your code with the variables and there was no problem, meaning that one of these columns (which we don't know more specific information about) is creating this error.

One of your expressions needs to be casted/converted to an int in order for this to go through, which is the meaning of Arithmetic overflow error converting expression to data type int.

How do you uninstall the package manager "pip", if installed from source?

I was using above command but it was not working. This command worked for me:

python -m pip uninstall pip setuptools

String, StringBuffer, and StringBuilder

Note that if you are using Java 5 or newer, you should use StringBuilder instead of StringBuffer. From the API documentation:

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

In practice, you will almost never use this from multiple threads at the same time, so the synchronization that StringBuffer does is almost always unnecessary overhead.

How to insert text into the textarea at the current cursor position?


_x000D_
_x000D_
function insertAtCaret(text) {_x000D_
  const textarea = document.querySelector('textarea')_x000D_
  textarea.setRangeText(_x000D_
    text,_x000D_
    textarea.selectionStart,_x000D_
    textarea.selectionEnd,_x000D_
    'end'_x000D_
  )_x000D_
}_x000D_
_x000D_
setInterval(() => insertAtCaret('Hello'), 3000)
_x000D_
<textarea cols="60">Stack Overflow Stack Exchange Starbucks Coffee</textarea>
_x000D_
_x000D_
_x000D_

What is the error "Every derived table must have its own alias" in MySQL?

I arrived here because I thought I should check in SO if there are adequate answers, after a syntax error that gave me this error, or if I could possibly post an answer myself.

OK, the answers here explain what this error is, so not much more to say, but nevertheless I will give my 2 cents using my words:

This error is caused by the fact that you basically generate a new table with your subquery for the FROM command.

That's what a derived table is, and as such, it needs to have an alias (actually a name reference to it).

So given the following hypothetical query:

SELECT id, key1
FROM (
    SELECT t1.ID id, t2.key1 key1, t2.key2 key2, t2.key3 key3
    FROM table1 t1 
    LEFT JOIN table2 t2 ON t1.id = t2.id
    WHERE t2.key3 = 'some-value'
) AS tt

So, at the end, the whole subquery inside the FROM command will produce the table that is aliased as tt and it will have the following columns id, key1, key2, key3.

So, then with the initial SELECT from that table we finally select the id and key1 from the tt.

PostgreSQL function for last inserted ID

Postgres has an inbuilt mechanism for the same, which in the same query returns the id or whatever you want the query to return. here is an example. Consider you have a table created which has 2 columns column1 and column2 and you want column1 to be returned after every insert.

# create table users_table(id serial not null primary key, name character varying);
CREATE TABLE
#insert into users_table(name) VALUES ('Jon Snow') RETURNING id;?
 id 
----
  1
(1 row)

# insert into users_table(name) VALUES ('Arya Stark') RETURNING id;?
 id 
----
  2
(1 row)

How to enter ssh password using bash?

Create a new keypair: (go with the defaults)

ssh-keygen

Copy the public key to the server: (password for the last time)

ssh-copy-id [email protected]

From now on the server should recognize your key and not ask you for the password anymore:

ssh [email protected]

Plot 3D data in R

Not sure why the code above did not work for the library rgl, but the following link has a great example with the same library. Run the code in R and you will obtain a beautiful 3d plot that you can turn around in all angles.

http://statisticsr.blogspot.de/2008/10/some-r-functions.html

########################################################################
## another example of 3d plot from my personal reserach, use rgl library
########################################################################
# 3D visualization device system

library(rgl);
data(volcano)
dim(volcano)

peak.height <- volcano;
ppm.index <- (1:nrow(volcano));
sample.index <- (1:ncol(volcano));

zlim <- range(peak.height)
zlen <- zlim[2] - zlim[1] + 1
colorlut <- terrain.colors(zlen) # height color lookup table
col <- colorlut[(peak.height-zlim[1]+1)] # assign colors to heights for each point
open3d()

ppm.index1 <- ppm.index*zlim[2]/max(ppm.index);
sample.index1 <- sample.index*zlim[2]/max(sample.index)

title.name <- paste("plot3d ", "volcano", sep = "");
surface3d(ppm.index1, sample.index1, peak.height, color=col, back="lines", main = title.name);
grid3d(c("x", "y+", "z"), n =20)

sample.name <- paste("col.", 1:ncol(volcano), sep="");
sample.label <- as.integer(seq(1, length(sample.name), length = 5));

axis3d('y+',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3);
axis3d('y',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3)
axis3d('z',pos=c(0, 0, NA))

ppm.label <- as.integer(seq(1, length(ppm.index), length = 10));
axes3d('x', at=c(ppm.index1[ppm.label], 0, 0), abs(round(ppm.index[ppm.label], 2)), cex = 0.3);

title3d(main = title.name, sub = "test", xlab = "ppm", ylab = "samples", zlab = "peak")
rgl.bringtotop();

Is it possible to use a div as content for Twitter's Popover

Why so complicated? just put this :

data-html='true'

How do you display a Toast from a background thread on Android?

  1. Get UI Thread Handler instance and use handler.sendMessage();
  2. Call post() method handler.post();
  3. runOnUiThread()
  4. view.post()

SVN change username

If your protocol is http and you are using Subversion 1.7, you can switch the user at anytime by simply using the global --username option on any command.

When Ingo's method didn't work for me, this was what I found that worked.

How to write a JSON file in C#?

Update 2020: It's been 7 years since I wrote this answer. It still seems to be getting a lot of attention. In 2013 Newtonsoft Json.Net was THE answer to this problem. Now it's still a good answer to this problem but it's no longer the the only viable option. To add some up-to-date caveats to this answer:

  • .Net Core now has the spookily similar System.Text.Json serialiser (see below)
  • The days of the JavaScriptSerializer have thankfully passed and this class isn't even in .Net Core. This invalidates a lot of the comparisons ran by Newtonsoft.
  • It's also recently come to my attention, via some vulnerability scanning software we use in work that Json.Net hasn't had an update in some time. Updates in 2020 have dried up and the latest version, 12.0.3, is over a year old.
  • The speed tests quoted below are comparing an older version of Json.Nt (version 6.0 and like I said the latest is 12.0.3) with an outdated .Net Framework serialiser.

Are Json.Net's days numbered? It's still used a LOT and it's still used by MS librarties. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.


Update since .Net Core 3.0

A new kid on the block since writing this is System.Text.Json which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. as below, I'd advise you to test this yourself .


I would recommend Json.Net, see example below:

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

string json = JsonConvert.SerializeObject(_data.ToArray());

//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);

Or the slightly more efficient version of the above code (doesn't use a string as a buffer):

//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
     JsonSerializer serializer = new JsonSerializer();
     //serialize object directly into file stream
     serializer.Serialize(file, _data);
}

Documentation: Serialize JSON to a file


Why? Here's a feature comparison between common serialisers as well as benchmark tests .

Below is a graph of performance taken from the linked article:

enter image description here

This separate post, states that:

Json.NET has always been memory efficient, streaming the reading and writing large documents rather than loading them entirely into memory, but I was able to find a couple of key places where object allocations could be reduced...... (now) Json.Net (6.0) allocates 8 times less memory than JavaScriptSerializer


Benchmarks appear to be Json.Net 5, the current version (on writing) is 10. What version of standard .Net serialisers used is not mentioned

These tests are obviously from the developers who maintain the library. I have not verified their claims. If in doubt test them yourself.

.NET 4.0 has a new GAC, why?

Yes since there are 2 distinct Global Assembly Cache (GAC), you will have to manage each of them individually.

In .NET Framework 4.0, the GAC went through a few changes. The GAC was split into two, one for each CLR.

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. There was no need in the previous two framework releases to split GAC. The problem of breaking older applications in Net Framework 4.0.

To avoid issues between CLR 2.0 and CLR 4.0 , the GAC is now split into private GAC’s for each runtime.The main change is that CLR v2.0 applications now cannot see CLR v4.0 assemblies in the GAC.

Source

Why?

It seems to be because there was a CLR change in .NET 4.0 but not in 2.0 to 3.5. The same thing happened with 1.1 to 2.0 CLR. It seems that the GAC has the ability to store different versions of assemblies as long as they are from the same CLR. They do not want to break old applications.

See the following information in MSDN about the GAC changes in 4.0.

For example, if both .NET 1.1 and .NET 2.0 shared the same GAC, then a .NET 1.1 application, loading an assembly from this shared GAC, could get .NET 2.0 assemblies, thereby breaking the .NET 1.1 application

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. As a result of this, there was no need in the previous two framework releases to split the GAC. The problem of breaking older (in this case, .NET 2.0) applications resurfaces in Net Framework 4.0 at which point CLR 4.0 released. Hence, to avoid interference issues between CLR 2.0 and CLR 4.0, the GAC is now split into private GACs for each runtime.

As the CLR is updated in future versions you can expect the same thing. If only the language changes then you can use the same GAC.

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

For future readers, one easy way is as follows if they wish to export in bulk using bash,

akshay@ideapad:/tmp$ mysql -u someuser -p test -e "select * from offices"
Enter password: 
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+
| officeCode | city          | phone            | addressLine1             | addressLine2 | state      | country   | postalCode | territory |
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+
| 1          | San Francisco | +1 650 219 4782  | 100 Market Street        | Suite 300    | CA         | USA       | 94080      | NA        |
| 2          | Boston        | +1 215 837 0825  | 1550 Court Place         | Suite 102    | MA         | USA       | 02107      | NA        |
| 3          | NYC           | +1 212 555 3000  | 523 East 53rd Street     | apt. 5A      | NY         | USA       | 10022      | NA        |
| 4          | Paris         | +33 14 723 4404  | 43 Rue Jouffroy D'abbans | NULL         | NULL       | France    | 75017      | EMEA      |
| 5          | Tokyo         | +81 33 224 5000  | 4-1 Kioicho              | NULL         | Chiyoda-Ku | Japan     | 102-8578   | Japan     |
| 6          | Sydney        | +61 2 9264 2451  | 5-11 Wentworth Avenue    | Floor #2     | NULL       | Australia | NSW 2010   | APAC      |
| 7          | London        | +44 20 7877 2041 | 25 Old Broad Street      | Level 7      | NULL       | UK        | EC2N 1HN   | EMEA      |
+------------+---------------+------------------+--------------------------+--------------+------------+-----------+------------+-----------+

If you're exporting by non-root user then set permission like below

root@ideapad:/tmp# mysql -u root -p
MariaDB[(none)]> UPDATE mysql.user SET File_priv = 'Y' WHERE user='someuser' AND host='localhost';

Restart or Reload mysqld

akshay@ideapad:/tmp$ sudo su
root@ideapad:/tmp#  systemctl restart mariadb

Sample code snippet

akshay@ideapad:/tmp$ cat test.sh 
#!/usr/bin/env bash

user="someuser"
password="password"
database="test"

mysql -u"$user" -p"$password" "$database" <<EOF
SELECT * 
INTO OUTFILE '/tmp/csvs/offices.csv' 
FIELDS TERMINATED BY '|' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\n'
FROM offices;
EOF

Execute

akshay@ideapad:/tmp$ mkdir -p /tmp/csvs
akshay@ideapad:/tmp$ chmod +x test.sh
akshay@ideapad:/tmp$ ./test.sh 
akshay@ideapad:/tmp$ cat /tmp/csvs/offices.csv 
"1"|"San Francisco"|"+1 650 219 4782"|"100 Market Street"|"Suite 300"|"CA"|"USA"|"94080"|"NA"
"2"|"Boston"|"+1 215 837 0825"|"1550 Court Place"|"Suite 102"|"MA"|"USA"|"02107"|"NA"
"3"|"NYC"|"+1 212 555 3000"|"523 East 53rd Street"|"apt. 5A"|"NY"|"USA"|"10022"|"NA"
"4"|"Paris"|"+33 14 723 4404"|"43 Rue Jouffroy D'abbans"|\N|\N|"France"|"75017"|"EMEA"
"5"|"Tokyo"|"+81 33 224 5000"|"4-1 Kioicho"|\N|"Chiyoda-Ku"|"Japan"|"102-8578"|"Japan"
"6"|"Sydney"|"+61 2 9264 2451"|"5-11 Wentworth Avenue"|"Floor #2"|\N|"Australia"|"NSW 2010"|"APAC"
"7"|"London"|"+44 20 7877 2041"|"25 Old Broad Street"|"Level 7"|\N|"UK"|"EC2N 1HN"|"EMEA"

Adjust plot title (main) position

To summarize and explain visually how it works. Code construction is as follows:

par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)

explanation:

par(mar = c(low, left, top, right)) - margins of the graph area.

title("text" - title text
      adj  = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
      line = positive values move title text up, negative - down)

enter image description here

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I think that error from Nginx is indicating that the connection was closed by your nodejs server (i.e., "upstream"). How is nodejs configured?

Adding images or videos to iPhone Simulator

This is MUCH easier with the new iOS Simulator that comes with Xcode 6+ (iOS Simulator 8.1 and above.) Now all you have to do is drag one or more photos onto the iOS Simulator window, and instead of opening Safari, the Photos app opens, and instantly adds all dragged-in photos to the device.

Visual Studio C# IntelliSense not automatically displaying

I simply closed all pages of visual studio and reopened ..it worked.

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

How does Google reCAPTCHA v2 work behind the scenes?

A new paper has been released with several tests against reCAPTCHA:

https://www.blackhat.com/docs/asia-16/materials/asia-16-Sivakorn-Im-Not-a-Human-Breaking-the-Google-reCAPTCHA-wp.pdf

Some highlights:

  • By keeping a cookie active for +9 days (by browsing sites with Google resources), you can then pass reCAPTCHA by only clicking the checkbox;
  • There are no restrictions based on requests per IP;
  • The browser's user agent must be real, and Google run tests against your environment to ensure it matches the user agent;
  • Google tests if the browser can render a Canvas;
  • Screen resolution and mouse events don't affect the results;

Google has already fixed the cookie vulnerability and is probably restricting some behaviors based on IPs.

Another interesting finding is that Google runs a VM in JavaScript that obfuscates much of reCAPTCHA code and behavior. This VM is known as botguard and is used to protect other services besides reCAPTCHA:

https://github.com/neuroradiology/InsideReCaptcha

UPDATE 2017

A recent paper (from August) was published on WOOT 2017 achieving 85% accuracy in solving noCAPTCHA reCAPTCHA audio challenges:

http://uncaptcha.cs.umd.edu/papers/uncaptcha_woot17.pdf

UPDATE 2018

Google is introducing reCAPTCHA v3, which looks like a "human score prediction engine" that is calibrated per website. It can be installed into different pages of a website (working like a Google Analytics script) to help reCAPTCHA and the website owner to understand the behaviour of humans vs. bots before filling a reCAPTCHA.

https://www.google.com/recaptcha/intro/v3beta.html

How to dockerize maven project? and how many ways to accomplish it?

There may be many ways.. But I implemented by following two ways

Given example is of maven project.

1. Using Dockerfile in maven project

Use the following file structure:

Demo
+-- src
|    +-- main
|    ¦   +-- java
|    ¦       +-- org
|    ¦           +-- demo
|    ¦               +-- Application.java
|    ¦   
|    +-- test
|
+---- Dockerfile
+---- pom.xml

And update the Dockerfile as:

FROM java:8
EXPOSE 8080
ADD /target/demo.jar demo.jar
ENTRYPOINT ["java","-jar","demo.jar"]

Navigate to the project folder and type following command you will be ab le to create image and run that image:

$ mvn clean
$ mvn install
$ docker build -f Dockerfile -t springdemo .
$ docker run -p 8080:8080 -t springdemo

Get video at Spring Boot with Docker

2. Using Maven plugins

Add given maven plugin in pom.xml

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.5</version>
        <configuration>
            <imageName>springdocker</imageName>
            <baseImage>java</baseImage>
            <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
            <resources>
                <resource>
                    <targetPath>/</targetPath>
                    <directory>${project.build.directory}</directory>
                    <include>${project.build.finalName}.jar</include>
                </resource>
            </resources>
        </configuration>
    </plugin>

Navigate to the project folder and type following command you will be able to create image and run that image:

$ mvn clean package docker:build
$ docker images
$ docker run -p 8080:8080 -t <image name>

In first example we are creating Dockerfile and providing base image and adding jar an so, after doing that we will run docker command to build an image with specific name and then run that image..

Whereas in second example we are using maven plugin in which we providing baseImage and imageName so we don't need to create Dockerfile here.. after packaging maven project we will get the docker image and we just need to run that image..

How to read a text file in project's root directory?

In this code you access to root directory project:

 string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);

then:

StreamReader r = new StreamReader(_filePath + "/cities2.json"))

Update multiple columns in SQL

If you need to re-type this several times, you can do like I did once. Get your columns` names into rows in excel sheet (write down at the end of each column name (=) which is easy in notepad++) on the right side make a column to copy and paste your value that will correspond to the new entries at each column. Then on the right of them in an independent column put the commas as designed

Then you will have to copy your values into the middle column each time then just paste then and run

I do not know an easier solution

Get google map link with latitude/longitude

See documentation on how to search using latitude/longitude here.

For location specified as: +38° 34' 24.00", -109° 32' 57.00

https://maps.google.com/maps?q=%2B38%C2%B0+34'+24.00%22,+-109%C2%B0+32'+57.00&ie=UTF-8

Note that the plus signs (%2B) and degree symbols(%C2%B0) need to be properly encoded.

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

Best way to remove the last character from a string built with stringbuilder

I recommend, you change your loop algorithm:

  • Add the comma not AFTER the item, but BEFORE
  • Use a boolean variable, that starts with false, do suppress the first comma
  • Set this boolean variable to true after testing it

Can a unit test project load the target application's app.config file?

Your unit tests are considered as an environment that runs your code to test it. Just like any normal environment, you have i.e. staging/production. You may need to add a .config file for your test project as well. A workaround is to create a class library and convert it to Test Project by adding necessary NuGet packages such as NUnit and NUnit Adapter. it works perfectly fine with both Visual Studio Test Runner and Resharper and you have your app.config file in your test project. enter image description here

enter image description here

enter image description here

enter image description here

And finally debugged my test and value from App.config:

enter image description here

curl_init() function not working

Seems you haven't installed the Curl on your server.
Check the PHP version of your server and run the following command to install the curl.

sudo apt-get install php7.2-curl

Then restart the apache service by using the following command.

sudo service apache2 restart

Replace 7.2 with your PHP version.

How to check if an excel cell is empty using Apache POI?

Gagravarr's answer is quite good!


Check if an excel cell is empty

But if you assume that a cell is also empty if it contains an empty String (""), you need some additional code. This can happen, if a cell was edited and then not cleared properly (for how to clear a cell properly, see further below).

I wrote myself a helper to check if an XSSFCell is empty (including an empty String).

 /**
 * Checks if the value of a given {@link XSSFCell} is empty.
 * 
 * @param cell
 *            The {@link XSSFCell}.
 * @return {@code true} if the {@link XSSFCell} is empty. {@code false}
 *         otherwise.
 */
public static boolean isCellEmpty(final XSSFCell cell) {
    if (cell == null) { // use row.getCell(x, Row.CREATE_NULL_AS_BLANK) to avoid null cells
        return true;
    }

    if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
        return true;
    }

    if (cell.getCellType() == Cell.CELL_TYPE_STRING && cell.getStringCellValue().trim().isEmpty()) {
        return true;
    }

    return false;
}

Pay attention for newer POI Version

They first changed getCellType() to getCellTypeEnum() as of Version 3.15 Beta 3 and then moved back to getCellType() as of Version 4.0.

  • Version >= 3.15 Beta 3:

    • Use CellType.BLANK and CellType.STRING instead of Cell.CELL_TYPE_BLANK and Cell.CELL_TYPE_STRING
  • Version >= 3.15 Beta 3 && Version < 4.0

    • Use Cell.getCellTypeEnum() instead of Cell.getCellType()

But better double check yourself, because they planned to change it back in future releases.


Example

This JUnit test shows the case in which the additional empty check is needed.

Scenario: the content of a cell is changed within a Java program. Later on, in the same Java program, the cell is checked for emptiness. The test will fail if the isCellEmpty(XSSFCell cell) function doesn't check for empty Strings.

@Test
public void testIsCellEmpty_CellHasEmptyString_ReturnTrue() {
    // Arrange
    XSSFCell cell = new XSSFWorkbook().createSheet().createRow(0).createCell(0);

    boolean expectedValue = true;
    boolean actualValue;

    // Act
    cell.setCellValue("foo");
    cell.setCellValue("bar");
    cell.setCellValue(" ");
    actualValue = isCellEmpty(cell);

    // Assert
    Assert.assertEquals(expectedValue, actualValue);
}

In addition: Clear a cell properly

Just in case if someone wants to know, how to clear the content of a cell properly. There are two ways to archive that (I would recommend way 1).

// way 1
public static void clearCell(final XSSFCell cell) {
    cell.setCellType(Cell.CELL_TYPE_BLANK);
}

// way 2
public static void clearCell(final XSSFCell cell) {
    String nullString = null;
    cell.setCellValue(nullString); 
}

Why way 1? Explicit is better than implicit (thanks, Python)

Way 1: sets the cell type explicitly back to blank.
Way 2: sets the cell type implicitly back to blank due to a side effect when setting a cell value to a null String.


Useful sources

Regards winklerrr

Does Typescript support the ?. operator? (And, what's it called?)

Edit Nov. 13, 2019!

As of November 5, 2019 TypeScript 3.7 has shipped and it now supports ?. the optional chaining operator !!!

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining


For Historical Purposes Only:

Edit: I have updated the answer thanks to fracz comment.

TypeScript 2.0 released !. It's not the same as ?.(Safe Navigator in C#)

See this answer for more details:

https://stackoverflow.com/a/38875179/1057052

This will only tell the compiler that the value is not null or undefined. This will not check if the value is null or undefined.

TypeScript Non-null assertion operator

// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
    // Throw exception if e is null or invalid entity
}

function processEntity(e?: Entity) {
    validateEntity(e);
    let s = e!.name;  // Assert that e is non-null and access name
}

How to rename a file using svn?

It can be if you created new directory at the disk BEFORE create/commit it in the SVN. All that you need is just create it in SVN and do move after:

$ svn mv etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/
svn: E155010: Path '/home/dyr/svn/nagioscore/etc/nagios/hosts/us0101/ccs' is not a directory

$ svn status
?       etc/nagios/hosts/us0101/ccs

$ rm -rvf etc/nagios/hosts/us0101/ccs
removed directory 'etc/nagios/hosts/us0101/ccs'

$ svn mkdir etc/nagios/hosts/us0101/ccs
A         etc/nagios/hosts/us0101/ccs

$ svn move etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
A         etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
D         etc/nagios/hosts/us0101/cs/us0101ccs001.cfg

$ svn status
A       etc/nagios/hosts/us0101/ccs
A  +    etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
        > moved from etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
D       etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
        > moved to etc/nagios/hosts/us0101/ccs/us0101accs001.cfg

How to edit a JavaScript alert box title?

Override the javascript window.alert() function.

window.alert = function(title, message){
    var myElementToShow = document.getElementById("someElementId");
    myElementToShow.innerHTML = title + "</br>" + message; 
}

With this you can create your own alert() function. Create a new 'cool' looking dialog (from some div elements).

Tested working in chrome and webkit, not sure of others.

How can I make a div not larger than its contents?

You want a block element that has what CSS calls shrink-to-fit width and the spec does not provide a blessed way to get such a thing. In CSS2, shrink-to-fit is not a goal, but means to deal with a situation where browser "has to" get a width out of thin air. Those situations are:

  • float
  • absolutely positioned element
  • inline-block element
  • table element

when there are no width specified. I heard they think of adding what you want in CSS3. For now, make do with one of the above.

The decision not to expose the feature directly may seem strange, but there is a good reason. It is expensive. Shrink-to-fit means formatting at least twice: you cannot start formatting an element until you know its width, and you cannot calculate the width w/o going through entire content. Plus, one does not need shrink-to-fit element as often as one may think. Why do you need extra div around your table? Maybe table caption is all you need.

Unloading classes in java?

You can unload a ClassLoader but you cannot unload specific classes. More specifically you cannot unload classes created in a ClassLoader that's not under your control.

If possible, I suggest using your own ClassLoader so you can unload.

How to display default text "--Select Team --" in combo box on pageload in WPF?

Based on IceForge's answer I prepared a reusable solution:

xaml style:

<Style x:Key="ComboBoxSelectOverlay" TargetType="TextBlock">
    <Setter Property="Grid.ZIndex" Value="10"/>
    <Setter Property="Foreground" Value="{x:Static SystemColors.GrayTextBrush}"/>
    <Setter Property="Margin" Value="6,4,10,0"/>
    <Setter Property="IsHitTestVisible" Value="False"/>
    <Setter Property="Visibility" Value="Hidden"/>
    <Style.Triggers>
        <DataTrigger Binding="{Binding}" Value="{x:Null}">
            <Setter Property="Visibility" Value="Visible"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

example of use:

<Grid>
     <ComboBox x:Name="cmb"
               ItemsSource="{Binding Teams}" 
               SelectedItem="{Binding SelectedTeam}"/>
     <TextBlock DataContext="{Binding ElementName=cmb,Path=SelectedItem}"
               Text=" -- Select Team --" 
               Style="{StaticResource ComboBoxSelectOverlay}"/>
</Grid>

Private Variables and Methods in Python

The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)

class Foo:
    def __init__(self):
        self.__privateField = 4;
        print self.__privateField # yields 4 no problem

foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'

It will be accessible through _Foo__privateField instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.

How to handle change of checkbox using jQuery?

$("input[type=checkbox]").on("change", function() { 

    if (this.checked) {

      //do your stuff

     }
});

How to delete large data of table in SQL without log?

Another use:

SET ROWCOUNT 1000 -- Buffer

DECLARE @DATE AS DATETIME = dateadd(MONTH,-7,GETDATE())

DELETE LargeTable  WHERE readTime < @DATE
WHILE @@ROWCOUNT > 0
BEGIN
   DELETE LargeTable  WHERE readTime < @DATE
END
SET ROWCOUNT 0

Optional;

If transaction log is enabled, disable transaction logs.

ALTER DATABASE dbname SET RECOVERY SIMPLE;

Why do access tokens expire?

This is very much implementation specific, but the general idea is to allow providers to issue short term access tokens with long term refresh tokens. Why?

  • Many providers support bearer tokens which are very weak security-wise. By making them short-lived and requiring refresh, they limit the time an attacker can abuse a stolen token.
  • Large scale deployment don't want to perform a database lookup every API call, so instead they issue self-encoded access token which can be verified by decryption. However, this also means there is no way to revoke these tokens so they are issued for a short time and must be refreshed.
  • The refresh token requires client authentication which makes it stronger. Unlike the above access tokens, it is usually implemented with a database lookup.

How to combine paths in Java?

To enhance JodaStephen's answer, Apache Commons IO has FilenameUtils which does this. Example (on Linux):

assert org.apache.commons.io.FilenameUtils.concat("/home/bob", "work\\stuff.log") == "/home/bob/work/stuff.log"

It's platform independent and will produce whatever separators your system needs.

MySQL select one column DISTINCT, with corresponding other columns

How about

`SELECT 
    my_distinct_column,
    max(col1),
    max(col2),
    max(col3)
    ...
 FROM
    my_table 
 GROUP BY 
    my_distinct_column`

How to clear a notification in Android

   String ns = Context.NOTIFICATION_SERVICE;
  NotificationManager Nmang = (NotificationManager) getApplicationContext()
                                                     .getSystemService(ns);
  Nmang .cancel(getIntent().getExtras().getInt("notificationID"));

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

Try this. It worked for me.

Go to RUN and type gpedit.msc then completely disable Onedrive. Have you noticed that the problem only existed after the last large download from Microsoft? It contained this package. I also removed it from the Start menu.

This appears to be the cause of the issue. Something to do with downloading temporary files, which of course an applet is.

Once done everything went back to normal.

Print a string as hex bytes?

You can use hexdump's

import hexdump
hexdump.dump("Hello World", sep=":")

(append .lower() if you require lower-case). This works for both Python 2 & 3.

C# ListView Column Width Auto

I made a program that cleared and refilled my listview multiple times. For some reason whenever I added columns with width = -2 I encountered a problem with the first column being way too long. What I did to fix this was create this method.

private void ResizeListViewColumns(ListView lv)
{
    foreach(ColumnHeader column in lv.Columns)
    {
        column.Width = -2;
    }
}

The great thing about this method is that you can pretty much put this anywhere to resize all your columns. Just pass in your ListView.

How to wait for a number of threads to complete?

If you make a list of the threads, you can loop through them and .join() against each, and your loop will finish when all the threads have. I haven't tried it though.

http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#join()

How to redirect a page using onclick event in php?

Why do people keep confusing php and javascript?

PHP is SERVER SIDE
JAVASCRIPT (like onclick) is CLIENT SIDE

You will have to use just javascript to redirect. Otherwise if you want PHP involved you can use an AJAX call to log a hit or whatever you like to send back a URL or additional detail.

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

Move the -h and specify that mydir is a directory

attrib /S /D /L -H mydir\*.*

Converting float to char*

char* str=NULL;
int len = asprintf(&str, "%g", float_var);
if (len == -1)
  fprintf(stderr, "Error converting float: %m\n");
else
  printf("float is %s\n", str);
free(str);

PowerShell says "execution of scripts is disabled on this system."

This solved my issue

Open Windows PowerShell Command and run below query to change ExecutionPolicy

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

if it ask for confirm changes press 'Y' and hit enter.

How to use wait and notify in Java without IllegalMonitorStateException?

You can only call notify on objects where you own their monitor. So you need something like

synchronized(threadObject)
{
   threadObject.notify();
}

How do I minimize the command prompt from my bat file

The only way I know is by creating a Windows shortcut to the batch file and then changing its properties to run minimized by default.

What is the difference between npm install and npm run build?

The main difference is ::

npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json

npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).

Ponits to note::

  1. One more thing, npm build and npm run build are two different things, npm run build will do custom work written inside package.json and npm build is a pre-defined script (not available to use directly)

  2. You cannot specify some thing inside custom build script (npm run build) script and expect npm build to do the same. Try following thing to verify in your package.json:

    { "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }

and run npm run build and npm build one by one and you will see the difference. For more about commands kindly follow npm documentation.

Cheers!!

Serialize an object to string

Code Safety Note

Regarding the accepted answer, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible scenarios, while using the latter one fails sometimes.

Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject<T>() that is defined in the derived type's base class: http://ideone.com/1Z5J1. Note that Ideone uses Mono to execute code: the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.

For the sake of completeness I post the full code sample here for future reference, just in case Ideone (where I posted the code) becomes unavailable in the future:

using System;
using System.Xml.Serialization;
using System.IO;

public class Test
{
    public static void Main()
    {
        Sub subInstance = new Sub();
        Console.WriteLine(subInstance.TestMethod());
    }

    public class Super
    {
        public string TestMethod() {
            return this.SerializeObject();
        }
    }

    public class Sub : Super
    {
    }
}

public static class TestExt {
    public static string SerializeObject<T>(this T toSerialize)
    {
        Console.WriteLine(typeof(T).Name);             // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead
        Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringWriter textWriter = new StringWriter();

        // And now...this will throw and Exception!
        // Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType()); 
        // solves the problem
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

How to remove "disabled" attribute using jQuery?

<input type="text" disabled="disabled" class="inputDisabled" value="">
?<button id="edit">Edit</button>????????????????????????????????

$("#edit").click(function(event){
    event.preventDefault();
    $('.inputDisabled').removeAttr("disabled")
});?

http://jsfiddle.net/ZwHfY/

AngularJS open modal on button click

You should take a look at Batarang for AngularJS debugging

As for your issue:

Your scope variable is not directly attached to the modal correctly. Below is the adjusted code. You need to specify when the modal shows using ng-show

<!-- Confirmation Dialog -->
<div class="modal" modal="showModal" ng-show="showModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Delete confirmation</h4>
      </div>
      <div class="modal-body">
        <p>Are you sure?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="cancel()">No</button>
        <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
      </div>
    </div>
  </div>
</div>
<!-- End of Confirmation Dialog -->

How to run Visual Studio post-build events for debug build only

Pre- and Post-Build Events run as a batch script. You can do a conditional statement on $(ConfigurationName).

For instance

if $(ConfigurationName) == Debug xcopy something somewhere

Dynamically create an array of strings with malloc

Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:

char (*orderedIds)[ID_LEN+1]
    = malloc(variableNumberOfElements * sizeof(*orderedIds));

// Clear-up
free(orderedIds);

A more cumbersome, but more general, solution, is to assign an array of pointers, and psuedo-initialising them to point at elements of a raw backing array:

char *raw = malloc(variableNumberOfElements * (ID_LEN + 1));
char **orderedIds = malloc(sizeof(*orderedIds) * variableNumberOfElements);

// Set each pointer to the start of its corresponding section of the raw buffer.
for (i = 0; i < variableNumberOfElements; i++)
{
    orderedIds[i] = &raw[i * (ID_LEN+1)];
}

...

// Clear-up pointer array
free(orderedIds);
// Clear-up raw array
free(raw);

When & why to use delegates?

I've just go my head around these, and so I'll share an example as you already have descriptions but at the moment one advantage I see is to get around the Circular Reference style warnings where you can't have 2 projects referencing each other.

Let's assume an application downloads an XML, and then saves the XML to a database.

I have 2 projects here which build my solution: FTP and a SaveDatabase.

So, our application starts by looking for any downloads and downloading the file(s) then it calls the SaveDatabase project.

Now, our application needs to notify the FTP site when a file is saved to the database by uploading a file with Meta data (ignore why, it's a request from the owner of the FTP site). The issue is at what point and how? We need a new method called NotifyFtpComplete() but in which of our projects should it be saved too - FTP or SaveDatabase? Logically, the code should live in our FTP project. But, this would mean our NotifyFtpComplete will have to be triggered or, it will have to wait until the save is complete, and then query the database to ensure it is in there. What we need to do is tell our SaveDatabase project to call the NotifyFtpComplete() method direct but we can't; we'd get a ciruclar reference and the NotifyFtpComplete() is a private method. What a shame, this would have worked. Well, it can.

During our application's code, we would have passed parameters between methods, but what if one of those parameters was the NotifyFtpComplete method. Yup, we pass the method, with all of the code inside as well. This would mean we could execute the method at any point, from any project. Well, this is what the delegate is. This means, we can pass the NotifyFtpComplete() method as a parameter to our SaveDatabase() class. At the point it saves, it simply executes the delegate.

See if this crude example helps (pseudo code). We will also assume that the application starts with the Begin() method of the FTP class.

class FTP
{
    public void Begin()
    {
        string filePath = DownloadFileFromFtpAndReturnPathName();

        SaveDatabase sd = new SaveDatabase();
        sd.Begin(filePath, NotifyFtpComplete());
    }

    private void NotifyFtpComplete()
    {
        //Code to send file to FTP site
    }
}


class SaveDatabase
{
    private void Begin(string filePath, delegateType NotifyJobComplete())
    {
        SaveToTheDatabase(filePath);

        /* InvokeTheDelegate - 
         * here we can execute the NotifyJobComplete
         * method at our preferred moment in the application,
         * despite the method being private and belonging
         * to a different class.
         */
        NotifyJobComplete.Invoke();
    }
}

So, with that explained, we can do it for real now with this Console Application using C#

using System;

namespace ConsoleApplication1
{
    /* I've made this class private to demonstrate that 
    * the SaveToDatabase cannot have any knowledge of this Program class.
    */
    class Program
    {
        static void Main(string[] args)
        {
            //Note, this NotifyDelegate type is defined in the SaveToDatabase project
            NotifyDelegate nofityDelegate = new NotifyDelegate(NotifyIfComplete);

            SaveToDatabase sd = new SaveToDatabase();            
            sd.Start(nofityDelegate);
            Console.ReadKey();
        }

        /* this is the method which will be delegated -
         * the only thing it has in common with the NofityDelegate
         * is that it takes 0 parameters and that it returns void.
         * However, it is these 2 which are essential.
         * It is really important to notice that it writes
         * a variable which, due to no constructor,
         * has not yet been called (so _notice is not initialized yet).
         */ 
    private static void NotifyIfComplete()
    {
        Console.WriteLine(_notice);
    }

    private static string _notice = "Notified";
    }


    public class SaveToDatabase
    {
        public void Start(NotifyDelegate nd)
        {
            /* I shouldn't write to the console from here, 
             * just for demonstration purposes
             */
            Console.WriteLine("SaveToDatabase Complete");
            Console.WriteLine(" ");
            nd.Invoke();
        }
    }
    public delegate void NotifyDelegate();
}

I suggest you step through the code and see when _notice is called and when the method (delegate) is called as this, I hope, will make things very clear.

However, lastly, we can make it more useful by changing the delegate type to include a parameter.

using System.Text;

namespace ConsoleApplication1
{
    /* I've made this class private to demonstrate that the SaveToDatabase
     * cannot have any knowledge of this Program class.
     */
    class Program
    {
        static void Main(string[] args)
        {
            SaveToDatabase sd = new SaveToDatabase();
            /* Please note, that although NotifyIfComplete()
         * takes a string parameter, we do not declare it,
         * all we want to do is tell C# where the method is
         * so it can be referenced later,
         * we will pass the parameter later.
         */
            var notifyDelegateWithMessage = new NotifyDelegateWithMessage(NotifyIfComplete);

            sd.Start(notifyDelegateWithMessage );

            Console.ReadKey();
        }

        private static void NotifyIfComplete(string message)
        {
            Console.WriteLine(message);
        }
    }


    public class SaveToDatabase
    {
        public void Start(NotifyDelegateWithMessage nd)
        {
                        /* To simulate a saving fail or success, I'm just going
         * to check the current time (well, the seconds) and
         * store the value as variable.
         */
            string message = string.Empty;
            if (DateTime.Now.Second > 30)
                message = "Saved";
            else
                message = "Failed";

            //It is at this point we pass the parameter to our method.
            nd.Invoke(message);
        }
    }

    public delegate void NotifyDelegateWithMessage(string message);
}

Select last row in MySQL

You can combine two queries suggested by @spacepille into single query that looks like this:

SELECT * FROM `table_name` WHERE id=(SELECT MAX(id) FROM `table_name`);

It should work blazing fast, but on INNODB tables it's fraction of milisecond slower than ORDER+LIMIT.

Press Enter to move to next control

private void txt_invoice_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
            txt_date.Focus();
    }

    private void txt_date_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
            txt_patientname.Focus();
    }

}

How to change facebook login button with my custom image

I got it working with a call to something as simple as

function fb_login() {
  FB.login( function() {}, { scope: 'email,public_profile' } );
}

I don't know if facebook will ever be able to block this circumvention, but for now I can use whatever HTML or image I want to call fb_login and it works fine.

Reference: Facebook API Docs

Hide/Show components in react native

I would vouch for using the opacity-method if you do not want to remove the component from your page, e.g. hiding a WebView.

<WebView
   style={{opacity: 0}} // Hide component
   source={{uri: 'https://www.google.com/'}}
 />

This is useful if you need to submit a form to a 3rd party website.

PHP - how to create a newline character?

Use the PHP nl2br to get the newlines in a text string..

$text = "Manu is a good boy.(Enter)He can code well.

echo nl2br($text);

Result.

Manu is a good boy.

He can code well.

Preventing multiple clicks on button

We can use on and off click for preventing Multiple clicks. i tried it to my application and it's working as expected.

$(document).ready(function () {     
    $("#disable").on('click', function () {
        $(this).off('click'); 
        // enter code here
    });
})

EnterKey to press button in VBA Userform

Here you can simply use:

SendKeys "{ENTER}" at the end of code linked to the Username field.

And so you can skip pressing ENTER Key once (one time).
And as a result, the next button ("Log In" button here) will be activated. And when you press ENTER once (your desired outcome), It will run code which is linked with "Log In" button.

How to schedule a task to run when shutting down windows

In addition to Dan Williams' answer, if you want to add a Startup/Shutdown script, you need to be looking for Windows Settings under Computer Configuration. If you want to add a Logon/Logoff script, you need to be looking for Windows Settings under User Configuration.

So to reiterate what Dan said with this information included,

For Startup/Shutdown:

  1. Run gpedit.msc (Local Policies)
  2. Computer Configuration -> Windows Settings -> Scripts -> Startup or Shutdown -> Properties -> Add

For Logon/Logoff:

  1. Run gpedit.msc (Local Policies)
  2. User Configuration -> Windows Settings -> Scripts -> Logon or Logoff -> Properties -> Add

Source: http://technet.microsoft.com/en-us/library/cc739591(WS.10).aspx

Get filename from input [type='file'] using jQuery

If selected more 1 file:

$("input[type="file"]").change(function() {
   var files = $("input[type="file"]").prop("files");
   var names = $.map(files, function(val) { return val.name; });
   $(".some_div").text(names);
});

files will be a FileList object. names is an array of strings (file names).

How to find the maximum value in an array?

Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.

int max = array.get(0);

for (int i = 1; i < array.length; i++) {
    if (array.get(i) > max) {
      max = array.get(i);
    }
}

GitHub relative link in Markdown file

You can link to file, but not to folders, and keep in mind that, Github will add /blob/master/ before your relative link(and folders lacks that part so they cannot be linked, neither with HTML <a> tags or Markdown link).

So, if we have a file in myrepo/src/Test.java, it will have a url like:

https://github.com/WesternGun/myrepo/blob/master/src/Test.java

And to link it in the readme file, we can use:

[This is a link](src/Test.java)

or: <a href="src/Test.java">This is a link</a>.

(I guess, master represents the master branch and it differs when the file is in another branch.)

How do you reindex an array in PHP but with indexes starting from 1?

You can reindex an array so the new array starts with an index of 1 like this;

$arr = array(
  '2' => 'red',
  '1' => 'green',
  '0' => 'blue',
);

$arr1 = array_values($arr);   // Reindex the array starting from 0.
array_unshift($arr1, '');     // Prepend a dummy element to the start of the array.
unset($arr1[0]);              // Kill the dummy element.

print_r($arr);
print_r($arr1);

The output from the above is;

Array
(
    [2] => red
    [1] => green
    [0] => blue
)
Array
(
    [1] => red
    [2] => green
    [3] => blue
)

JQuery - Get select value

var nationality = $("#dancerCountry").val(); should work. Are you sure that the element selector is working properly? Perhaps you should try:

var nationality = $('select[name="dancerCountry"]').val();

E: Unable to locate package mongodb-org

I faced same issue but fix it by the changing the package file section command. The whole step that i followed was:

At first try with this command: sudo apt-get install -y mongodb

This is the unofficial mongodb package provided by Ubuntu and it is not maintained by MongoDB and conflict with MongoDB’s offically supported packages.

If the above command not working then you can fix the issue by one of the bellow procedure:

#Step 1:  Import the MongoDB public key
#In Ubuntu 18.*+, you may get invalid signatures. --recv value may need to be updated to EA312927. 
#See here for more details on the invalid signature issue: [https://stackoverflow.com/questions/34733340/mongodb-gpg-invalid-signatures][1]

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

#Step 2: Generate a file with the MongoDB repository url
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

#Step 3: Refresh the local database with the packages
sudo apt-get update

#Step 4: Install the last stable MongoDB version and all the necessary packages on our system
sudo apt-get install mongodb-org

         #Or
# The unofficial mongodb package provided by Ubuntu is not maintained by MongoDB and conflict with MongoDB’s offically supported packages. Use the official MongoDB mongodb-org packages, which are kept up-to-date with the most recent major and minor MongoDB releases.
sudo apt-get install -y mongodb 

Hope this will work for you also. You can follow this MongoDB

Update The above instruction will install mongodb 2.6 version, if you want to install latest version for Uubuntu 12.04 then just replace above step 2 and follow bellow instruction instead of that:

#Step 2: Generate a file with the MongoDB repository url
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb.list

If you are using Ubuntu 14.04 then use bellow step instead of above step 2

#Step 2: Generate a file with the MongoDB repository url
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

Best way to check for IE less than 9 in JavaScript without library

for what it's worth:

    if(  document.addEventListener  ){
        alert("you got IE9 or greater");
    }

This successfully targets IE 9+ because the addEventListener method was supported very early on for every major browser but IE. (Chrome, Firefox, Opera, and Safari) MDN Reference. It is supported currently in IE9 and we can expect it to continue to be supported here on out.

How to convert column with dtype as object to string in Pandas Dataframe

Did you try assigning it back to the column?

df['column'] = df['column'].astype('str') 

Referring to this question, the pandas dataframe stores the pointers to the strings and hence it is of type 'object'. As per the docs ,You could try:

df['column_new'] = df['column'].str.split(',') 

How to convert MySQL time to UNIX timestamp using PHP?

$time_PHP = strtotime( $datetime_SQL );

How to use java.Set

Since it is a HashSet you will need to override hashCode and equals methods. http://preciselyconcise.com/java/collections/d_set.php has an example explaining how to implement hashCode and equals methods

How to disable spring security for particular url

I have a better way:

http
    .authorizeRequests()
    .antMatchers("/api/v1/signup/**").permitAll()
    .anyRequest().authenticated()

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

SELECT * 
FROM table 
WHERE date BETWEEN 
    ADDDATE(LAST_DAY(DATE_SUB(NOW(),INTERVAL 2 MONTH)), INTERVAL 1 DAY) 
    AND DATE_SUB(NOW(),INTERVAL 1 MONTH);

See the docs for info on DATE_SUB, ADDDATE, LAST_DAY and other useful datetime functions.

Should a function have only one return statement?

I believe that multiple returns are usually good (in the code that I write in C#). The single-return style is a holdover from C. But you probably aren't coding in C.

There is no law requiring only one exit point for a method in all programming languages. Some people insist on the superiority of this style, and sometimes they elevate it to a "rule" or "law" but this belief is not backed up by any evidence or research.

More than one return style may be a bad habit in C code, where resources have to be explicitly de-allocated, but languages such as Java, C#, Python or JavaScript that have constructs such as automatic garbage collection and try..finally blocks (and using blocks in C#), and this argument does not apply - in these languages, it is very uncommon to need centralised manual resource deallocation.

There are cases where a single return is more readable, and cases where it isn't. See if it reduces the number of lines of code, makes the logic clearer or reduces the number of braces and indents or temporary variables.

Therefore, use as many returns as suits your artistic sensibilities, because it is a layout and readability issue, not a technical one.

I have talked about this at greater length on my blog.

Reading CSV files using C#

To complete the previous answers, one may need a collection of objects from his CSV File, either parsed by the TextFieldParser or the string.Split method, and then each line converted to an object via Reflection. You obviously first need to define a class that matches the lines of the CSV file.

I used the simple CSV Serializer from Michael Kropat found here: Generic class to CSV (all properties) and reused his methods to get the fields and properties of the wished class.

I deserialize my CSV file with the following method:

public static IEnumerable<T> ReadCsvFileTextFieldParser<T>(string fileFullPath, string delimiter = ";") where T : new()
{
    if (!File.Exists(fileFullPath))
    {
        return null;
    }

    var list = new List<T>();
    var csvFields = GetAllFieldOfClass<T>();
    var fieldDict = new Dictionary<int, MemberInfo>();

    using (TextFieldParser parser = new TextFieldParser(fileFullPath))
    {
        parser.SetDelimiters(delimiter);

        bool headerParsed = false;

        while (!parser.EndOfData)
        {
            //Processing row
            string[] rowFields = parser.ReadFields();
            if (!headerParsed)
            {
                for (int i = 0; i < rowFields.Length; i++)
                {
                    // First row shall be the header!
                    var csvField = csvFields.Where(f => f.Name == rowFields[i]).FirstOrDefault();
                    if (csvField != null)
                    {
                        fieldDict.Add(i, csvField);
                    }
                }
                headerParsed = true;
            }
            else
            {
                T newObj = new T();
                for (int i = 0; i < rowFields.Length; i++)
                {
                    var csvFied = fieldDict[i];
                    var record = rowFields[i];

                    if (csvFied is FieldInfo)
                    {
                        ((FieldInfo)csvFied).SetValue(newObj, record);
                    }
                    else if (csvFied is PropertyInfo)
                    {
                        var pi = (PropertyInfo)csvFied;
                        pi.SetValue(newObj, Convert.ChangeType(record, pi.PropertyType), null);
                    }
                    else
                    {
                        throw new Exception("Unhandled case.");
                    }
                }
                if (newObj != null)
                {
                    list.Add(newObj);
                }
            }
        }
    }
    return list;
}

public static IEnumerable<MemberInfo> GetAllFieldOfClass<T>()
{
    return
        from mi in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
        where new[] { MemberTypes.Field, MemberTypes.Property }.Contains(mi.MemberType)
        let orderAttr = (ColumnOrderAttribute)Attribute.GetCustomAttribute(mi, typeof(ColumnOrderAttribute))
        orderby orderAttr == null ? int.MaxValue : orderAttr.Order, mi.Name
        select mi;            
}

Jenkins - How to access BUILD_NUMBER environment variable

To Answer your first question, Jenkins variables are case sensitive. However, if you are writing a windows batch script, they are case insensitive, because Windows doesn't care about the case.

Since you are not very clear about your setup, let's make the assumption that you are using an ant build step to fire up your ant task. Have a look at the Jenkins documentation (same page that Adarsh gave you, but different chapter) for an example on how to make Jenkins variables available to your ant task.

EDIT:

Hence, I will need to access the environmental variable ${BUILD_NUMBER} to construct the URL.

Why don't you use $BUILD_URL then? Isn't it available in the extended email plugin?

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

<script type="text/javascript">
    function lnkLogout_Confirm()
    {
        var bResponse = confirm('Are you sure you want to exit?');

        if (bResponse === true) {
            ////console.log("lnkLogout_Confirm clciked.");
            var url = '@Url.Action("Login", "Login")';
            window.location.href = url;
        }
        return bResponse;
    }

</script>

Xampp Access Forbidden php

A. #LoadModule vhost_alias_module modules/mod_vhost_alias.so
B. <Directory />
    AllowOverride none
    Require all denied
</Directory>

Replace with:

A. LoadModule vhost_alias_module modules/mod_vhost_alias.so
B:
<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

From E:\xamp**apache\conf/httpd.conf**

"Uncaught Error: [$injector:unpr]" with angular after deployment

If you follow your link, it tells you that the error results from the $injector not being able to resolve your dependencies. This is a common issue with angular when the javascript gets minified/uglified/whatever you're doing to it for production.

The issue is when you have e.g. a controller;

angular.module("MyApp").controller("MyCtrl", function($scope, $q) {
  // your code
})

The minification changes $scope and $q into random variables that doesn't tell angular what to inject. The solution is to declare your dependencies like this:

angular.module("MyApp")
  .controller("MyCtrl", ["$scope", "$q", function($scope, $q) {
  // your code
}])

That should fix your problem.

Just to re-iterate, everything I've said is at the link the error message provides to you.

java : non-static variable cannot be referenced from a static context Error

You probably want to add "static" to the declaration of con2.

In Java, things (both variables and methods) can be properties of the class (which means they're shared by all objects of that type), or they can be properties of the object (a different one in each object of the same class). The keyword "static" is used to indicate that something is a property of the class.

"Static" stuff exists all the time. The other stuff only exists after you've created an object, and even then each individual object has its own copy of the thing. And the flip side of this is key in this case: static stuff can't access non-static stuff, because it doesn't know which object to look in. If you pass it an object reference, it can do stuff like "thingie.con2", but simply saying "con2" is not allowed, because you haven't said which object's con2 is meant.

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

There is no overload for DateTime values, but you can get the long value Ticks that is what the values contain, compare them and then create a new DateTime value from the result:

new DateTime(Math.Min(Date1.Ticks, Date2.Ticks))

(Note that the DateTime structure also contains a Kind property, that is not retained in the new value. This is normally not a problem; if you compare DateTime values of different kinds the comparison doesn't make sense anyway.)

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to pass optional arguments to a method in C++?

With the introduction of std::optional in C++17 you can pass optional arguments:

#include <iostream>
#include <string>
#include <optional>

void myfunc(const std::string& id, const std::optional<std::string>& param = std::nullopt)
{
    std::cout << "id=" << id << ", param=";

    if (param)
        std::cout << *param << std::endl;
    else
        std::cout << "<parameter not set>" << std::endl;
}

int main() 
{
    myfunc("first");
    myfunc("second" , "something");
}

Output:

id=first param=<parameter not set>
id=second param=something

See https://en.cppreference.com/w/cpp/utility/optional

Extract string between two strings in java

Your pattern is fine. But you shouldn't be split()ting it away, you should find() it. Following code gives the output you are looking for:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

How do I float a div to the center?

Try margin: 0 auto, the div will need a fixed with.

Using JavaMail with TLS

Good post, the line

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

is mandatory if the SMTP server uses SSL Authentication, like the GMail SMTP server does. However if the server uses Plaintext Authentication over TLS, it should not be present, because Java Mail will complain about the initial connection being plaintext.

Also make sure you are using the latest version of Java Mail. Recently I used some old Java Mail jars from a previous project and could not make the code work, because the login process was failing. After I have upgraded to the latest version of Java Mail, the reason of the error became clear: it was a javax.net.ssl.SSLHandshakeException, which was not thrown up in the old version of the lib.

no operator "<<" matches these operands

If you want to use std::string reliably, you must #include <string>.

How to do a logical OR operation for integer comparison in shell scripting?

If a bash script

If [[ $input -gt number  ||  $input  -lt number  ]]
then 
    echo .........
else
    echo .........

fi

exit

Unable to launch the IIS Express Web server

Before you try anything else, make sure you 1. restart visual studio (mostly for refreshing memory resident options from files) and 2. restart your system (mostly for invalid file locking). If your problem is such temporary or self-fixed those will do without changing anything. It worked for me with PC restart. Also if you work on a multi-user project make sure you have the latest workable version - someone else may had check in something invalid by mistake at e.g. the project file and you mess with your system for no reason. If those won't work, then you probably need to alter some setting(s) that are stuck, missing or need modification - there are plenty propositions on other answers.

List of all unique characters in a string?

Store Unique characters in list

Method 1:

uniue_char = list(set('aaabcabccd'))
#['a', 'b', 'c', 'd']

Method 2: By Loop ( Complex )

uniue_char = []
for c in 'aaabcabccd':
    if not c in uniue_char:
        uniue_char.append(c)
print(uniue_char)
#['a', 'b', 'c', 'd']

Android camera intent

It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.

Request this permission on the AndroidManifest.xml:

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

On your Activity, start by defining this:

static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;

Then fire this Intent in an onClick:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
    // Create the File where the photo should go
    File photoFile = null;
    try {
        photoFile = createImageFile();
    } catch (IOException ex) {
        // Error occurred while creating the File
        Log.i(TAG, "IOException");
    }
    // Continue only if the File was successfully created
    if (photoFile != null) {
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
    }
}

Add the following support method:

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  // prefix
            ".jpg",         // suffix
            storageDir      // directory
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

Then receive the result:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        try {
            mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
            mImageView.setImageBitmap(mImageBitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.

How to copy a file from remote server to local machine?

For example, your remote host is example.com and remote login name is user1:

scp [email protected]:/path/to/file /path/to/store/file

c# dictionary How to add multiple values for single key?

Instead of using a Dictionary, why not convert to an ILookup?

var myData = new[]{new {a=1,b="frog"}, new {a=1,b="cat"}, new {a=2,b="giraffe"}};
ILookup<int,string> lookup = myData.ToLookup(x => x.a, x => x.b);
IEnumerable<string> allOnes = lookup[1]; //enumerable of 2 items, frog and cat

An ILookup is an immutable data structure that allows multiple values per key. Probably not much use if you need to add items at different times, but if you have all your data up-front, this is definitely the way to go.

Get the device width in javascript

Ya mybe u can use document.documentElement.clientWidth to get the device width of client and keep tracking the device width by put on setInterval

just like

setInterval(function(){
        width = document.documentElement.clientWidth;
        console.log(width);
    }, 1000);

How do I get the height and width of the Android Navigation Bar programmatically?

I think better answer is here because it allows you to get even cutout height too.

Take your root view, and add setOnApplyWindowInsetsListener (or you can override onApplyWindowInsets from it), and take insets.getSystemWindowInsets from it.

In my camera activity, i add padding equal to the systemWindowInsetBottom to my bottom layout. And finally, it fix cutout issue.

Camera activity insets

with appcompat it is like this

ViewCompat.setOnApplyWindowInsetsListener(mCameraSourcePreview, (v, insets) -> {
    takePictureLayout.setPadding(0,0,0,insets.getSystemWindowInsetBottom());
    return insets.consumeSystemWindowInsets();
});

without appcompat, this:

mCameraSourcePreview.setOnApplyWindowInsetsListener((v, insets) -> { ... })

Run javascript script (.js file) in mongodb including another file inside js

Another way is to pass the file into mongo in your terminal prompt.

$ mongo < myjstest.js

This will start a mongo session, run the file, then exit. Not sure about calling a 2nd file from the 1st however. I haven't tried it.

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.

Example:

myvar1 = userInput['param1']
myvar2 = userInput['param2']

to:

myvar = userInput

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

Can you check if every number exists? If yes you may try this:

S = sum of all numbers in the bag (S < 5050)
Z = sum of the missing numbers 5050 - S

if the missing numbers are x and y then:

x = Z - y and
max(x) = Z - 1

So you check the range from 1 to max(x) and find the number

What are the true benefits of ExpandoObject?

The real benefit for me is the totally effortless data binding from XAML:

public dynamic SomeData { get; set; }

...

SomeData.WhatEver = "Yo Man!";

...

 <TextBlock Text="{Binding SomeData.WhatEver}" />