Programs & Examples On #Detours

This tag is about the Microsoft Detours library for intercepting arbitrary Win32 binary functions on x86, x64, and ARM machines.

window.print() not working in IE

For Firefox use

iframewin.print()

for IE use

iframedocument.execCommand('print', false, null);

see also Unable to print an iframe on IE using JavaScript, prints parent page instead

How to enable curl in xampp?

It should be available in php.ini file. You need to un-comment the line for curl extension:

  ;extension=php_curl.dll
  ^----- remove semi-colon

How do I install cURL on cygwin?

I just copied the folder "curl-7.43.0" from zip file that I downloaded from curl website curl.haxx.se into cygwin64 folder on drive C:. And then I have used it with prefix curl in cygwin command terminal.

My actual download location from softpedia, I have used Softpedia Mirror (US)

GROUP_CONCAT comma separator - MySQL

Or, if you are doing a split - join:

GROUP_CONCAT(split(thing, " "), '----') AS thing_name,

You may want to inclue WITHIN RECORD, like this:

GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,

from BigQuery API page

Why doesn't [01-12] range work as expected?

Use this:

0?[1-9]|1[012]
  • 07: valid
  • 7: valid
  • 0: not match
  • 00 : not match
  • 13 : not match
  • 21 : not match

To test a pattern as 07/2018 use this:

/^(0?[1-9]|1[012])\/([2-9][0-9]{3})$/

(Date range between 01/2000 to 12/9999 )

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {
  len=strlen(arr); 
  count++; 
}

How can you make a custom keyboard in Android?

One of the best well-documented example I found.

http://www.fampennings.nl/maarten/android/09keyboard/index.htm

KeyboardView related XML file and source code are provided.

How do I print an IFrame from javascript in Safari/Chrome

I used Andrew's script but added a piece before the printPage() function is called. The iframe needs focus, otherwise it will still print the parent frame in IE.

function printIframe(id)
{
    var iframe = document.frames ? document.frames[id] : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;
    iframe.focus();
    ifWin.printPage();
    return false;
}

Don't thank me though, it was Andrew who wrote this. I just made a tweak =P

Get difference between 2 dates in JavaScript?

var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10); 

alert(diffDays )

Find which rows have different values for a given column in Teradata SQL

Join the table with itself and give it two different aliases (A and B in the following example). This allows to compare different rows of the same table.

SELECT DISTINCT A.Id
FROM
    Address A
    INNER JOIN Address B
        ON A.Id = B.Id AND A.[Adress Code] < B.[Adress Code]
WHERE
    A.Address <> B.Address

The "less than" comparison < ensures that you get 2 different addresses and you don't get the same 2 address codes twice. Using "not equal" <> instead, would yield the codes as (1, 2) and (2, 1); each one of them for the A alias and the B alias in turn.

The join clause is responsible for the pairing of the rows where as the where-clause tests additional conditions.


The query above works with any address codes. If you want to compare addresses with specific address codes, you can change the query to

SELECT A.Id
FROM
    Address A
    INNER JOIN Address B
        ON A.Id = B.Id
WHERE                     
    A.[Adress Code] = 1 AND
    B.[Adress Code] = 2 AND
    A.Address <> B.Address

I imagine that this might be useful to find customers having a billing address (Adress Code = 1 as an example) differing from the delivery address (Adress Code = 2) .

MySQL INNER JOIN select only one row from second table

Matei Mihai given a simple and efficient solution but it will not work until put a MAX(date) in SELECT part so this query will become:

SELECT u.*, p.*, max(date)
FROM payments p
JOIN users u ON u.id=p.user_id AND u.package = 1
GROUP BY u.id

And order by will not make any difference in grouping but it can order the final result provided by group by. I tried it and it worked for me.

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

How can I get the source directory of a Bash script from within the script itself?

How to obtain the full file path, full directory, and base filename of any script being run itself

For many cases, all you need to acquire is the full path to the script you just called. This can be easily accomplished using realpath. Note that realpath is part of GNU coreutils. If you don't have it already installed (it comes default on Ubuntu), you can install it with sudo apt update && sudo apt install coreutils.

get_script_path.sh:

#!/bin/bash

FULL_PATH_TO_SCRIPT="$(realpath "$0")"

# You can then also get the full path to the directory, and the base
# filename, like this:
SCRIPT_DIRECTORY="$(dirname "$FULL_PATH_TO_SCRIPT")"
SCRIPT_FILENAME="$(basename "$FULL_PATH_TO_SCRIPT")"

# Now print it all out
echo "FULL_PATH_TO_SCRIPT = \"$FULL_PATH_TO_SCRIPT\""
echo "SCRIPT_DIRECTORY    = \"$SCRIPT_DIRECTORY\""
echo "SCRIPT_FILENAME     = \"$SCRIPT_FILENAME\""

Example output:

~/GS/dev/eRCaGuy_hello_world/bash$ ./get_script_path.sh 
FULL_PATH_TO_SCRIPT = "/home/gabriel/GS/dev/eRCaGuy_hello_world/bash/get_script_path.sh"
SCRIPT_DIRECTORY    = "/home/gabriel/GS/dev/eRCaGuy_hello_world/bash"
SCRIPT_FILENAME     = "get_script_path.sh"

Note that realpath also successfully walks down symbolic links to determine and point to their targets rather than pointing to the symbolic link.

The code above is now part of my eRCaGuy_hello_world repo in this file here: bash/get_script_path.sh.

References:

  1. How to retrieve absolute path given relative

Best way to update data with a RecyclerView adapter

@inmyth's answer is correct, just modify the code a bit, to handle empty list.

public class NewsAdapter extends RecyclerView.Adapter<...> {    
    ...
    private static List mFeedsList;
    ...    
    public void swap(List list){
            if (mFeedsList != null) {
                mFeedsList.clear();
                mFeedsList.addAll(list);
            }
            else {
                mFeedsList = list;
            }
            notifyDataSetChanged();
    }

I am using Retrofit to fetch the list, on Retrofit's onResponse() use,

adapter.swap(feedList);

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

Check for the presence of words like "ad", "banner" or "popup" within your file. I removed these and it worked. Based on this post here: Failed to load resource under Chrome it seems like Ad Block Plus was the culprit in my case.

To add server using sp_addlinkedserver

I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. @Domnic answer didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.

An extended answer for remote IP db connections:

Step 1: Link servers

EXEC sp_addlinkedserver @server='SRV_NAME',
   @srvproduct=N'',
   @provider=N'SQLNCLI',   
   @datasrc=N'aaa.bbb.ccc.ddd';

EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'

...where SRV_NAME is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd is the ip address of the remote server hosting your SQLserver DB.

Step 2: Run your queries For instance:

SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table

...and that's it!

Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin

Find out the history of SQL queries

For recent SQL:

select * from v$sql

For history:

select * from dba_hist_sqltext

Validate phone number using angular js

<div ng-class="{'has-error': userForm.mobileno.$error.pattern ,'has-success': userForm.mobileno.$valid}">

              <input type="text" name="mobileno" ng-model="mobileno" ng-pattern="/^[7-9][0-9]{9}$/"  required>

Here "userForm" is my form name.

Bloomberg BDH function with ISIN

To download ISIN code data the only place I see this is on the ISIN organizations website, www.isin.org. try http://isin.org, they should have a function where you can easily download.

Check whether a string is not null and not empty

test equals with an empty string and null in the same conditional:

if(!"".equals(str) && str != null) {
    // do stuff.
}

Does not throws NullPointerException if str is null, since Object.equals() returns false if arg is null.

the other construct str.equals("") would throw the dreaded NullPointerException. Some might consider bad form using a String literal as the object upon wich equals() is called but it does the job.

Also check this answer: https://stackoverflow.com/a/531825/1532705

OkHttp Post Body as JSON

Just use JSONObject.toString(); method. And have a look at OkHttp's tutorial:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json); // new
  // RequestBody body = RequestBody.create(JSON, json); // old
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

Creating a SearchView that looks like the material design guidelines

Another way you can achieve the desired effect is to use this Material Search View library. It handles search history automatically and it's possible to provide search suggestions to the view as well.

Sample: (It's shown in Portuguese, but it also works in english and italian).

Sample

Setup

Before you can use this lib, you have to implement a class named MsvAuthority inside the br.com.mauker package on your app module, and it should have a public static String variable called CONTENT_AUTHORITY. Give it the value you want and don't forget to add the same name on your manifest file. The lib will use this file to set the Content Provider authority.

Example:

MsvAuthority.java

package br.com.mauker;

public class MsvAuthority {
    public static final String CONTENT_AUTHORITY = "br.com.mauker.materialsearchview.searchhistorydatabase";
}

AndroidManifest.xml

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

    <application ... >
        <provider
        android:name="br.com.mauker.materialsearchview.db.HistoryProvider"
        android:authorities="br.com.mauker.materialsearchview.searchhistorydatabase"
        android:exported="false"
        android:protectionLevel="signature"
        android:syncable="true"/>
    </application>

</manifest>

Usage

To use it, add the dependency:

compile 'br.com.mauker.materialsearchview:materialsearchview:1.2.0'

And then, on your Activity layout file, add the following:

<br.com.mauker.materialsearchview.MaterialSearchView
    android:id="@+id/search_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

After that, you'll just need to get the MaterialSearchView reference by using getViewById(), and open it up or close it using MaterialSearchView#openSearch() and MaterialSearchView#closeSearch().

P.S.: It's possible to open and close the view not only from the Toolbar. You can use the openSearch() method from basically any Button, such as a Floating Action Button.

// Inside onCreate()
MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
Button bt = (Button) findViewById(R.id.button);

bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            searchView.openSearch();
        }
    });

You can also close the view using the back button, doing the following:

@Override
public void onBackPressed() {
    if (searchView.isOpen()) {
        // Close the search on the back button press.
        searchView.closeSearch();
    } else {
        super.onBackPressed();
    }
}

For more information on how to use the lib, check the github page.

Oracle SQL Developer spool output?

I was trying things to duplicate the spools you get from sqlplus. I found the following and hope it helps:

Create your sql script file ie:

Please note the echo and serveroutput.

Test_Spool.SQL

Spool 'c:\temp\Test1.txt';
set echo on;
set serveroutput on;
declare
sqlresult varchar2(60);

begin
  select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
  dbms_output.put_line('The date is ' || sqlresult);
end;

/

Spool off;
set serveroutput off;
set echo off;

Run the script from another worksheet:

@TEST_Spool.SQL

My output from the Test1.txt

set serveroutput on
declare
sqlresult varchar2(60);

begin
  select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
  dbms_output.put_line('The date is ' || sqlresult);
end;

anonymous block completed

The date is 2016-04-07 09:21:32

Spool of

HTTP response code for POST when resource already exists

I know it's been ages but I will leave an answer here which I see fit.

I think the best will be to use HTTP_306_RESERVED.

Tainted canvases may not be exported

In the img tag set crossorigin to Anonymous.

<img crossorigin="anonymous"></img>

Reduce left and right margins in matplotlib plot

inspired by Sammys answer above:

margins = {  #     vvv margin in inches
    "left"   :     1.5 / figsize[0],
    "bottom" :     0.8 / figsize[1],
    "right"  : 1 - 0.3 / figsize[0],
    "top"    : 1 - 1   / figsize[1]
}
fig.subplots_adjust(**margins)

Where figsize is the tuple that you used in fig = pyplot.figure(figsize=...)

How to create a fix size list in python?

It's not really the python way to initialize lists like this. Anyway, you can initialize a list like this:

>>> l = [None] * 4
>>> l
[None, None, None, None]

Concatenating strings doesn't work as expected

std::string a = "Hello ";
a += "World";

List directory in Go

We can get a list of files inside a folder on the file system using various golang standard library functions.

  1. filepath.Walk
  2. ioutil.ReadDir
  3. os.File.Readdir

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "path/filepath"
)

func main() {
    var (
        root  string
        files []string
        err   error
    )

    root := "/home/manigandan/golang/samples"
    // filepath.Walk
    files, err = FilePathWalkDir(root)
    if err != nil {
        panic(err)
    }
    // ioutil.ReadDir
    files, err = IOReadDir(root)
    if err != nil {
        panic(err)
    }
    //os.File.Readdir
    files, err = OSReadDir(root)
    if err != nil {
        panic(err)
    }

    for _, file := range files {
        fmt.Println(file)
    }
}
  1. Using filepath.Walk

The path/filepath package provides a handy way to scan all the files in a directory, it will automatically scan each sub-directories in the directory.

func FilePathWalkDir(root string) ([]string, error) {
    var files []string
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if !info.IsDir() {
            files = append(files, path)
        }
        return nil
    })
    return files, err
}
  1. Using ioutil.ReadDir

ioutil.ReadDir reads the directory named by dirname and returns a list of directory entries sorted by filename.

func IOReadDir(root string) ([]string, error) {
    var files []string
    fileInfo, err := ioutil.ReadDir(root)
    if err != nil {
        return files, err
    }

    for _, file := range fileInfo {
        files = append(files, file.Name())
    }
    return files, nil
}
  1. Using os.File.Readdir

Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.

func OSReadDir(root string) ([]string, error) {
    var files []string
    f, err := os.Open(root)
    if err != nil {
        return files, err
    }
    fileInfo, err := f.Readdir(-1)
    f.Close()
    if err != nil {
        return files, err
    }

    for _, file := range fileInfo {
        files = append(files, file.Name())
    }
    return files, nil
}

Benchmark results.

benchmark score

Get more details on this Blog Post

Case Statement Equivalent in R

As of data.table v1.13.0 you can use the function fcase() (fast-case) to do SQL-like CASE operations (also similar to dplyr::case_when()):

require(data.table)

dt <- data.table(name = c('cow','pig','eagle','pigeon','cow','eagle'))
dt[ , category := fcase(name %in% c('cow', 'pig'), 'mammal',
                        name %in% c('eagle', 'pigeon'), 'bird') ]

Add click event on div tag using javascript

Just add the onclick-attribute:

<div class="drill_cursor" onclick='alert("youClickedMe!");'>
....
</div>

It's javascript, but it's automatically bound using an html-attribute instead of manually binding it within <script> tags - maybe it does what you want.

While it might be good enough for very small projects or test pages, you should definitly consider using addEventListener (as pointed out by other answers), if you expect the code to grow and stay maintainable.

C++ wait for user input

Several ways to do so, here are some possible one-line approaches:

  1. Use getch() (need #include <conio.h>).

  2. Use getchar() (expected for Enter, need #include <iostream>).

  3. Use cin.get() (expected for Enter, need #include <iostream>).

  4. Use system("pause") (need #include <iostream>).

    PS: This method will also print Press any key to continue . . . on the screen. (seems perfect choice for you :))


Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.

How to create timer events using C++ 11?

If you are on Windows, you can use the CreateThreadpoolTimer function to schedule a callback without needing to worry about thread management and without blocking the current thread.

template<typename T>
static void __stdcall timer_fired(PTP_CALLBACK_INSTANCE, PVOID context, PTP_TIMER timer)
{
    CloseThreadpoolTimer(timer);
    std::unique_ptr<T> callable(reinterpret_cast<T*>(context));
    (*callable)();
}

template <typename T>
void call_after(T callable, long long delayInMs)
{
    auto state = std::make_unique<T>(std::move(callable));
    auto timer = CreateThreadpoolTimer(timer_fired<T>, state.get(), nullptr);
    if (!timer)
    {
        throw std::runtime_error("Timer");
    }

    ULARGE_INTEGER due;
    due.QuadPart = static_cast<ULONGLONG>(-(delayInMs * 10000LL));

    FILETIME ft;
    ft.dwHighDateTime = due.HighPart;
    ft.dwLowDateTime = due.LowPart;

    SetThreadpoolTimer(timer, &ft, 0 /*msPeriod*/, 0 /*msWindowLength*/);
    state.release();
}

int main()
{
    auto callback = []
    {
        std::cout << "in callback\n";
    };

    call_after(callback, 1000);
    std::cin.get();
}

Convert UTC date time to local date time

This is an universal solution:

function convertUTCDateToLocalDate(date) {
    var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);

    var offset = date.getTimezoneOffset() / 60;
    var hours = date.getHours();

    newDate.setHours(hours - offset);

    return newDate;   
}

Usage:

var date = convertUTCDateToLocalDate(new Date(date_string_you_received));

Display the date based on the client local setting:

date.toLocaleString();

Delete all rows in table

Truncate table is faster than delete * from XXX. Delete is slow because it works one row at a time. There are a few situations where truncate doesn't work, which you can read about on MSDN.

newline in <td title="">

Using &#xA; Works in Chrome to create separate lines in a tooltip.

React - How to force a function component to render?

Update react v16.8 (16 Feb 2019 realease)

Since react 16.8 released with hooks, function components are now have the ability to hold persistent state. With that ability you can now mimic a forceUpdate:

_x000D_
_x000D_
function App() {_x000D_
  const [, updateState] = React.useState();_x000D_
  const forceUpdate = React.useCallback(() => updateState({}), []);_x000D_
  console.log("render");_x000D_
  return (_x000D_
    <div>_x000D_
      <button onClick={forceUpdate}>Force Render</button>_x000D_
    </div>_x000D_
  );_x000D_
}_x000D_
_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>_x000D_
<div id="root"/>
_x000D_
_x000D_
_x000D_

Note that this approach should be re-considered and in most cases when you need to force an update you probably doing something wrong.


Before react 16.8.0

No you can't, State-Less function components are just normal functions that returns jsx, you don't have any access to the React life cycle methods as you are not extending from the React.Component.

Think of function-component as the render method part of the class components.

Changing CSS Values with Javascript

I don't know why the other solutions go through the whole list of stylesheets for the document. Doing so creates a new entry in each stylesheet, which is inefficient. Instead, we can simply append a new stylesheet and simply add our desired CSS rules there.

style=document.createElement('style');
document.head.appendChild(style);
stylesheet=style.sheet;
function css(selector,property,value)
{
    try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }
    catch(err){}
}

Note that we can override even inline styles set directly on elements by adding " !important" to the value of the property, unless there already exist more specific "!important" style declarations for that property.

Spring Boot Java Config Set Session Timeout

  • Spring Boot version 1.0: server.session.timeout=1200
  • Spring Boot version 2.0: server.servlet.session.timeout=10m
    NOTE: If a duration suffix is not specified, seconds will be used.

implement time delay in c

In standard C (C99), you can use time() to do this, something like:

#include <time.h>
:
void waitFor (unsigned int secs) {
    unsigned int retTime = time(0) + secs;   // Get finishing time.
    while (time(0) < retTime);               // Loop until it arrives.
}

By the way, this assumes time() returns a 1-second resolution value. I don't think that's mandated by the standard so you may have to adjust for it.


In order to clarify, this is the only way I'm aware of to do this with ISO C99 (and the question is tagged with nothing more than "C" which usually means portable solutions are desirable although, of course, vendor-specific solutions may still be given).

By all means, if you're on a platform that provides a more efficient way, use it. As several comments have indicated, there may be specific problems with a tight loop like this, with regard to CPU usage and battery life.

Any decent time-slicing OS would be able to drop the dynamic priority of a task that continuously uses its full time slice but the battery power may be more problematic.

However C specifies nothing about the OS details in a hosted environment, and this answer is for ISO C and ISO C alone (so no use of sleep, select, Win32 API calls or anything like that).

And keep in mind that POSIX sleep can be interrupted by signals. If you are going to go down that path, you need to do something like:

int finishing = 0; // set finishing in signal handler 
                   // if you want to really stop.

void sleepWrapper (unsigned int secs) {
    unsigned int left = secs;
    while ((left > 0) && (!finishing)) // Don't continue if signal has
        left = sleep (left);           //   indicated exit needed.
}

Android - border for button

create drawable/button_green.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
  <gradient
    android:startColor="#003000"
    android:centerColor="#006000"
    android:endColor="#003000"
    android:angle="270" />
  <corners android:radius="5dp" />
  <stroke android:width="2px" android:color="#007000" />
</shape>

and point it out as @drawable/button_green:

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@drawable/button_green"
        android:text="Button" />

convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

How to perform keystroke inside powershell?

function Do-SendKeys {
    param (
        $SENDKEYS,
        $WINDOWTITLE
    )
    $wshell = New-Object -ComObject wscript.shell;
    IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
    Sleep 1
    IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'

How do I draw a circle in iOS Swift?

Here is my version using Swift 5 and Core Graphics.

I have created a class to draw two circles. The first circle is created using addEllipse(). It puts the ellipse into a square, thus creating a circle. I find it surprising that there is no function addCircle(). The second circle is created using addArc() of 2pi radians

import UIKit

@IBDesignable
class DrawCircles: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {

        guard let context = UIGraphicsGetCurrentContext() else {
            print("could not get graphics context")
            return
        }

        context.setLineWidth(2)

        context.setStrokeColor(UIColor.blue.cgColor)

        context.addEllipse(in: CGRect(x: 30, y: 30, width: 50.0, height: 50.0))

        context.strokePath()

        context.setStrokeColor(UIColor.red.cgColor)

        context.beginPath() // this prevents a straight line being drawn from the current point to the arc

        context.addArc(center: CGPoint(x:100, y: 100), radius: 20, startAngle: 0, endAngle: 2.0*CGFloat.pi, clockwise: false)

        context.strokePath()
    }
}

in your ViewController's didViewLoad() add the following:

let myView = DrawCircles(frame: CGRect(x: 50, y: 50, width: 300, height: 300))

self.view.addSubview(myView)

When it runs it should look like this. I hope you like my solution!

enter image description here

compareTo() vs. equals()

String.equals() requires invoking instanceof operator while compareTo() requires not. My colleague has noted large performance drop-down caused by excessive numbers of instanceof calls in equals() method, however my test has proved compareTo() to be only slightly faster.

I was using, however, Java 1.6. On other versions (or other JDK vendors) the difference could be larger.

The test compared each-to-each string in 1000 element arrays, repeated 10 times.

$.ajax( type: "POST" POST method to php

You need to use data: {title: title} to POST it correctly.

In the PHP code you need to echo the value instead of returning it.

Saving numpy array to txt file row wise

I know this is old, but none of these answers solved the root problem of numpy not saving the array row-wise. I found that this one liner did the trick for me:

b = np.matrix(a)
np.savetxt("file", b)

Compare object instances for equality by their attributes

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

    def __repr__(self):
        return str(self.value)

    def __eq__(self,other):
        return self.value == other.value

node1 = Node(1)
node2 = Node(1)

print(f'node1 id:{id(node1)}')
print(f'node2 id:{id(node2)}')
print(node1 == node2)
>>> node1 id:4396696848
>>> node2 id:4396698000
>>> True

How do I set a column value to NULL in SQL Server Management Studio?

If you are using the table interface you can type in NULL (all caps)

otherwise you can run an update statement where you could:

Update table set ColumnName = NULL where [Filter for record here]

Matrix Transpose in Python

def transpose(matrix):
   x=0
   trans=[]
   b=len(matrix[0])
   while b!=0:
       trans.append([])
       b-=1
   for list in matrix:
       for element in list:
          trans[x].append(element)
          x+=1
       x=0
   return trans

How to make a <svg> element expand or contract to its parent container?

For your iphone You could use in your head balise :

"width=device-width"

How to assign execute permission to a .sh file in windows to be executed in linux

This is not possible. Linux permissions and windows permissions do not translate. They are machine specific. It would be a security hole to allow permissions to be set on files before they even arrive on the target system.

Calculate time difference in minutes in SQL Server

Apart from the DATEDIFF you can also use the TIMEDIFF function or the TIMESTAMPDIFF.

EXAMPLE

SET @date1 = '2010-10-11 12:15:35', @date2 = '2010-10-10 00:00:00';

SELECT 
TIMEDIFF(@date1, @date2) AS 'TIMEDIFF',
TIMESTAMPDIFF(hour, @date1, @date2) AS 'Hours',
TIMESTAMPDIFF(minute, @date1, @date2) AS 'Minutes',
TIMESTAMPDIFF(second, @date1, @date2) AS 'Seconds';

RESULTS

TIMEDIFF : 36:15:35
Hours : -36
Minutes : -2175
Seconds : -130535

How do I find the maximum of 2 numbers?

Just for the fun of it, after the party has finished and the horse bolted.

The answer is: max() !

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

Similarity String Comparison in Java

This is typically done using an edit distance measure. Searching for "edit distance java" turns up a number of libraries, like this one.

Init method in Spring Controller (annotation version)

public class InitHelloWorld implements BeanPostProcessor {

   public Object postProcessBeforeInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("BeforeInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

   public Object postProcessAfterInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("AfterInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

}

Sequence contains more than one element

The problem is that you are using SingleOrDefault. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault which will succeed no matter how many elements are in the collection.

What's the best way to break from nested loops in JavaScript?

If you use Coffeescript, there is a convenient "do" keyword that makes it easier to define and immediately execute an anonymous function:

do ->
  for a in first_loop
    for b in second_loop
      if condition(...)
        return

...so you can simply use "return" to get out of the loops.

Finding the average of a list

numbers = [0,1,2,3]

numbers[0] = input("Please enter a number")

numbers[1] = input("Please enter a second number")

numbers[2] = input("Please enter a third number")

numbers[3] = input("Please enter a fourth number")

print (numbers)

print ("Finding the Avarage")

avarage = int(numbers[0]) + int(numbers[1]) + int(numbers[2]) + int(numbers [3]) / 4

print (avarage)

When do you use Git rebase instead of Git merge?

Before merge/rebase:

A <- B <- C    [master]
^
 \
  D <- E       [branch]

After git merge master:

A <- B <- C
^         ^
 \         \
  D <- E <- F

After git rebase master:

A <- B <- C <- D' <- E'

(A, B, C, D, E and F are commits)

This example and much more well illustrated information about Git can be found in Git The Basics Tutorial.

How to use SortedMap interface in Java?

I would use TreeMap, which implements SortedMap. It is designed exactly for that.

Example:

Map<Integer, String> map = new TreeMap<Integer, String>();

// Add Items to the TreeMap
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Iterate over them
for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " => " + entry.getValue());
}

See the Java tutorial page for SortedMap.
And here a list of tutorials related to TreeMap.

Unable to add window -- token null is not valid; is your activity running?

In my case, I was inflating a PopupMenu at the very beginning of the activity i.e on onCreate()... I fixed it by putting it in a Handler

  new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                PopupMenu popuMenu=new PopupMenu(SplashScreen.this,binding.progressBar);
                popuMenu.inflate(R.menu.bottom_nav_menu);
                popuMenu.show();
            }
        },100);

Dynamically replace img src attribute with jQuery

This is what you wanna do:

var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);

How to get host name with port from a http or https request

You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.

StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
int idx = (((uri != null) && (uri.length() > 0)) ? url.indexOf(uri) : url.length());
String host = url.substring(0, idx); //base url
idx = host.indexOf("://");
if(idx > 0) {
  host = host.substring(idx); //remove scheme if present
}

Displaying better error message than "No JSON object could be decoded"

For my particular version of this problem, I went ahead and searched the function declaration of load_json_file(path) within the packaging.py file, then smuggled a print line into it:

def load_json_file(path):
    data = open(path, 'r').read()
    print data
    try:
        return Bunch(json.loads(data))
    except ValueError, e:
        raise MalformedJsonFileError('%s when reading "%s"' % (str(e),
                                                               path))

That way it would print the content of the json file before entering the try-catch, and that way – even with my barely existing Python knowledge – I was able to quickly figure out why my configuration couldn't read the json file.
(It was because I had set up my text editor to write a UTF-8 BOM … stupid)

Just mentioning this because, while maybe not a good answer to the OP's specific problem, this was a rather quick method in determining the source of a very oppressing bug. And I bet that many people will stumble upon this article who are searching a more verbose solution for a MalformedJsonFileError: No JSON object could be decoded when reading …. So that might help them.

Difference between SurfaceView and View?

Views are all drawn on the same GUI thread which is also used for all user interaction.

So if you need to update GUI rapidly or if the rendering takes too much time and affects user experience then use SurfaceView.

Remove All Event Listeners of Specific Type

If your only goal by removing the listeners is to stop them from running, you can add an event listener to the window capturing and canceling all events of the given type:

window.addEventListener(type, function (event) {
    event.stopPropagation();
}, true);

Passing in true for the third parameter causes the event to be captured on the way down. Stopping propagation means that the event never reaches the listeners that are listening for it.

Keep in mind though that this has very limited use as you can't add new listeners for the given type (they will all be blocked). There are ways to get around this somewhat, e.g., by firing a new kind of event that only your listeners would know to listen for. Here is how you can do that:

window.addEventListener('click', function (event) {
    // (note: not cross-browser)
    var event2 = new CustomEvent('click2', {detail: {original: event}});
    event.target.dispatchEvent(event2);
    event.stopPropagation();
}, true);

element.addEventListener('click2', function(event) {
    event = event.detail && event.detail.original ?
        event.detail.original :
        event;
    // ... do something with event ...
});

However, note that this may not work as well for fast events like mousemove, given that the re-dispatching of the event introduces a delay.

Better would be to just keep track of the listeners added in the first place, as outlined in Martin Wantke's answer, if you need to do this.

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Use DateFormat. (Sorry, but the brevity of the question does not warrant a longer or more detailed answer.)

Apply CSS styles to an element depending on its child elements

As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.

It'd be wonderful if you could do something like div[div.a] or div:containing[div.a] as you said, but this isn't possible.

You may want to consider looking at jQuery. Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.

If you use jQuery, something along the lines of this would may work (untested but the theory is there):

$('div:has(div.a)').css('border', '1px solid red');

or

$('div:has(div.a)').addClass('redBorder');

combined with a CSS class:

.redBorder
{
    border: 1px solid red;
}

Here's the documentation for the jQuery "has" selector.

How to replace (null) values with 0 output in PIVOT

If you have a situation where you are using dynamic columns in your pivot statement you could use the following:

DECLARE @cols               NVARCHAR(MAX)
DECLARE @colsWithNoNulls    NVARCHAR(MAX)
DECLARE @query              NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(Name) 
            FROM Hospital
            WHERE Active = 1 AND StateId IS NOT NULL
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @colsWithNoNulls = STUFF(
            (
                SELECT distinct ',ISNULL(' + QUOTENAME(Name) + ', ''No'') ' + QUOTENAME(Name)
                FROM Hospital
                WHERE Active = 1 AND StateId IS NOT NULL
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

EXEC ('
        SELECT Clinician, ' + @colsWithNoNulls + '
        FROM
        (
            SELECT DISTINCT p.FullName AS Clinician, h.Name, CASE WHEN phl.personhospitalloginid IS NOT NULL THEN ''Yes'' ELSE ''No'' END AS HasLogin
            FROM Person p
            INNER JOIN personlicense pl ON pl.personid = p.personid
            INNER JOIN LicenseType lt on lt.licensetypeid = pl.licensetypeid
            INNER JOIN licensetypegroup ltg ON ltg.licensetypegroupid = lt.licensetypegroupid
            INNER JOIN Hospital h ON h.StateId = pl.StateId
            LEFT JOIN PersonHospitalLogin phl ON phl.personid = p.personid AND phl.HospitalId = h.hospitalid
            WHERE ltg.Name = ''RN'' AND
                pl.licenseactivestatusid = 2 AND
                h.Active = 1 AND
                h.StateId IS NOT NULL
        ) AS Results
        PIVOT
        (
            MAX(HasLogin)
            FOR Name IN (' + @cols + ')
        ) p
')

Sorting list based on values from another list

Also, if you don't mind using numpy arrays (or in fact already are dealing with numpy arrays...), here is another nice solution:

people = ['Jim', 'Pam', 'Micheal', 'Dwight']
ages = [27, 25, 4, 9]

import numpy
people = numpy.array(people)
ages = numpy.array(ages)
inds = ages.argsort()
sortedPeople = people[inds]

I found it here: http://scienceoss.com/sort-one-list-by-another-list/

What is a good alternative to using an image map generator?

Why don't you use a combination of HTML/CSS instead? Image maps are obsolete.

This btw is Search Engine Optimised as well :)

Source code follows:

_x000D_
_x000D_
.image-map {
  background: url('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
  width: 272px;
  height: 92px;
  display: block;
  position: relative;
  margin-top:10px;
  float: left;
}

.image-map > a.map {
  position: absolute;
  display: block;
  border: 1px solid green;
}
_x000D_
<div class="image-map">
    <a class="map" rel="G" style="top: 0px; left: 0px; width: 70px; height: 95px;" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 70px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 120px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="g" style="top: 0px; left: 170px; width: 40px; height: 95px" href="#"></a>
    <a class="map" rel="l" style="top: 0px; left: 210px; width: 20px; height: 95px" href="#"></a>
    <a class="map" rel="e" style="top: 0px; left: 230px; width: 40px; height: 95px" href="#"></a>
</div>
_x000D_
_x000D_
_x000D_

EDIT:

After the numerous negative points this answer has received I have to come back and say that I can clearly see that you don't agree with my answer, but I personally still believe that is a better option than image maps.

Sure it cannot do polygons, it might have issues on manual page zoom, but personally I feel image maps are obsolete although still on the html5 specification. (It makes make more sense nowadays to try and replicate them using html5 canvas instead)

However I guess the target audience for this question does not agree with me.

You could also check this Are HTML Image Maps still used? and see the most highly voted answer just for reference.

Undo a Git merge that hasn't been pushed yet

With modern Git, you can:

git merge --abort

Older syntax:

git reset --merge

Old-school:

git reset --hard

But actually, it is worth noticing that git merge --abort is only equivalent to git reset --merge given that MERGE_HEAD is present. This can be read in the Git help for merge command.

git merge --abort is equivalent to git reset --merge when MERGE_HEAD is present.

After a failed merge, when there is no MERGE_HEAD, the failed merge can be undone with git reset --merge, but not necessarily with git merge --abort, so they are not only old and new syntax for the same thing.

Personally I find git reset --merge much more powerful and useful in everyday work, so that's the one I always use.

Adding an onclick event to a table row

I try to figure out how to get a better result with pure JS and i get something this:

DEMO: https://jsfiddle.net/f5r3emjt/1/

const tbody = document.getElementById("tbody");
let rowSelected;

tbody.onclick = (e) => {
  for (let i = 0; i < e.path.length; ++i) {
    if (e.path[i].tagName == "TR") {
      selectRow(e.path[i]);
      break;
    }
  }
};

function selectRow(r) {
  if (rowSelected !== undefined) rowSelected.style.backgroundColor = "white";

  rowSelected = r;
  rowSelected.style.backgroundColor = "dodgerblue";
}

And now you can use the variable rowSelected in other function like you want or call another function after set the style

Cannot push to Git repository on Bitbucket

If you are using SourceTree (I'm using 2.4.1), I found a simpler way to generate an SSH key and add it to my Bitbucket settings. This solved the problem for me.

  1. In SourceTree, go to Preferences.
  2. Go to the Accounts tab and select your account.
  3. There should be an option to generate and copy an SSH key to clipboard.
  4. Once you have copied that, go to Bitbucket in your browser. Go to [avatar] -> Bitbucket settings.
  5. Go to SSH keys.
  6. Click Add key
  7. Paste in the key you copied.

I received a confirmation email from Bitbucket that an SSH key had been added to my account.

For reference, on macOS, using Terminal, you can use the following command to see the keys generated for your device. This is where the key you generated is stored.

ls -la ~/.ssh

As others have stated, this documentation helped me: Use the SSH protocol with Bitbucket Cloud

Parser Error when deploy ASP.NET application

I have solved it this way.

Go to your project file let's say project/name/bin and delete everything within the bin folder. (this will then give you another error which you can solve this way)

then in your visual studio right click project's References folder, to open NuGet Package Manager.

Go to browse and install "DotNetCompilerPlatform".

Split string on whitespace in Python

Another method through re module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.

>>> import re
>>> s = "many   fancy word \nhello    \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']

Above regex would match one or more non-space characters.

Javascript: How to check if a string is empty?

But for a better check:

if(str === null || str === '')
{
    //enter code here
}

How can you create pop up messages in a batch script?

msg * "Enter Your Message"

Does this help ?

javascript regex : only english letters allowed

_x000D_
_x000D_
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
_x000D_
_x000D_

Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w covers a-zA-Z and some other word characters. It all depends on what you need specifically.

Android SDK location

press WIN+R and from the run dialog run dialog Execute the following: **%appdata%..\Local\Android**

You should now be presented with Folder Explorer displaying the parent directory of the SDK.

Setting focus to iframe contents

document.getElementsByName("iframe_name")[0].contentWindow.document.body.focus();

Where does Vagrant download its .box files to?

The actual .box file is deleted by Vagrant once the download and box installation is complete. As mentioned in other answers, whilst downloading, the .box file is stored as:

~/.vagrant.d/tmp/boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

where the file name is 'box' followed by a 40 byte hexadecimal hash. A temporary file on my system for example, is:

~/.vagrant.d/tmp/boxc74a85fe4af3197a744851517c6af4d4959db77f

As far as I can tell, this file is never saved with a *.box extension, which explains why the searches above failed to locate it. There are two ways to retrieve the actual box file:

  1. Download the .box file from vagrantcloud.com

    1. Find the box you're interested in on the atlas. For example, https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1
    2. Replace the domain name with vagrantcloud.com. So https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1 becomes https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box.
    3. Add /providers/virtualbox.box to the end of that URL. So https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1 becomes https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box
    4. Save the .box file
    5. Use the .box as you wish, for example, hosting it yourself and pointing config.vm.box_url to the URL. OR
  2. Get the .box directly from Vagrant

    This requires you to modify the ruby source to prevent Vagrant from deleting the box after successful download.

    1. Locate the box_add.rb file in your Vagrant installation directory. On my system it's located at /Applications/Vagrant/embedded/gems/gems/vagrant-1.5.2/lib/vagrant/action/builtin/box_add.rb
    2. Find the box_add function. Within the box_add function, there is a block that reads:

      ensure # Make sure we delete the temporary file after we add it, # unless we were interrupted, in which case we keep it around # so we can resume the download later. if !@download_interrupted @logger.debug("Deleting temporary box: #{box_url}") begin box_url.delete if box_url rescue Errno::ENOENT # Not a big deal, the temp file may not actually exist end end

    3. Comment this block out.
    4. Add another box using vagrant add box <boxname>.
    5. Wait for it to download. You can watch it save in the ~/.vagrant.d/tmp/ directory as a boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX file.
    6. Rename the the file to something more useful. Eg, mv boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX trusty64.box.

Why would you want this?

For me, this has been useful to retrieve the .box file so it can be hosted on local, fast infrastructure as opposed to downloading from HashiCorp's Atlas box catalog or another box provider.

This really should be part of the default Vagrant functionality as it has a very definitive use case.

MySQL/Writing file error (Errcode 28)

For xampp users: on my experience, the problem was caused by a file, named '0' and located in the 'mysql' folder. The size was tooooo huge (mine exploded to about 256 Gb). Its removal fixed the problem.

Visual Studio 2017: Display method references

For display references on the top of method you have to enabled the CodeLens option in Visual Studio Professional and Visual Studio Enterprise.

Use below steps to enabled it.

1. Go to Tools and then select Options :

enter image description here

2. Then Select Text Editor -> All Languages -> CodeLens

enter image description here

3. Click on check box to Enable Code Lens: enter image description here

Now you can see the references on the top of methods.

This will not work for VS - Community Edition.

Cheers!

Log all requests from the python-requests module

Just improving this answer

This is how it worked for me:

import logging
import sys    
import requests
import textwrap
    
root = logging.getLogger('httplogger')


def logRoundtrip(response, *args, **kwargs):
    extra = {'req': response.request, 'res': response}
    root.debug('HTTP roundtrip', extra=extra)
    

class HttpFormatter(logging.Formatter):

    def _formatHeaders(self, d):
        return '\n'.join(f'{k}: {v}' for k, v in d.items())

    def formatMessage(self, record):
        result = super().formatMessage(record)
        if record.name == 'httplogger':
            result += textwrap.dedent('''
                ---------------- request ----------------
                {req.method} {req.url}
                {reqhdrs}

                {req.body}
                ---------------- response ----------------
                {res.status_code} {res.reason} {res.url}
                {reshdrs}

                {res.text}
            ''').format(
                req=record.req,
                res=record.res,
                reqhdrs=self._formatHeaders(record.req.headers),
                reshdrs=self._formatHeaders(record.res.headers),
            )

        return result

formatter = HttpFormatter('{asctime} {levelname} {name} {message}', style='{')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
root.addHandler(handler)
root.setLevel(logging.DEBUG)


session = requests.Session()
session.hooks['response'].append(logRoundtrip)
session.get('http://httpbin.org')

How do I download a file with Angular2 or greater

This answer suggests that you cannot download files directly with AJAX, primarily for security reasons. So I'll describe what I do in this situation,

01. Add href attribute in your anchor tag inside the component.html file,
eg:-

<div>
       <a [href]="fileUrl" mat-raised-button (click)='getGenaratedLetterTemplate(element)'> GENARATE </a>
</div>

02. Do all following steps in your component.ts to bypass the security level and bring the save as popup dialog,
eg:-

import { environment } from 'environments/environment';
import { DomSanitizer } from '@angular/platform-browser';
export class ViewHrApprovalComponent implements OnInit {
private apiUrl = environment.apiUrl;
  fileUrl
 constructor(
    private sanitizer: DomSanitizer,
    private letterService: LetterService) {}
getGenaratedLetterTemplate(letter) {

    this.data.getGenaratedLetterTemplate(letter.letterId).subscribe(
      // cannot download files directly with AJAX, primarily for security reasons);
    console.log(this.apiUrl + 'getGeneratedLetter/' + letter.letterId);
    this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.apiUrl + 'getGeneratedLetter/' + letter.letterId);
  }

Note: This answer will work if you are getting an error "OK" with status code 200

Pandas - Plotting a stacked Bar Chart

That should help

df.groupby(['NFF', 'ABUSE']).size().unstack().plot(kind='bar', stacked=True)

WinForms DataGridView font size

    private void UpdateFont()
    {
        //Change cell font
        foreach(DataGridViewColumn c in dgAssets.Columns)
        {
            c.DefaultCellStyle.Font = new Font("Arial", 8.5F, GraphicsUnit.Pixel);
        }
    }

Eclipse and Windows newlines

To recursively remove the carriage returns (\r) from the CVS/* files in all child directories, run the following in a unix shell:

find ./ -wholename "\*CVS/[RE]\*" -exec dos2unix -q -o {} \;

How do I display local image in markdown?

The following works with a relative path to an image into a subfolder next to the document (currently only tested on a Windows System):

![image info](./pictures/image.png)

How do you find the row count for all your tables in Postgres

I usually don't rely on statistics, especially in PostgreSQL.

SELECT table_name, dsql2('select count(*) from '||table_name) as rownum
FROM information_schema.tables
WHERE table_type='BASE TABLE'
    AND table_schema='livescreen'
ORDER BY 2 DESC;
CREATE OR REPLACE FUNCTION dsql2(i_text text)
  RETURNS int AS
$BODY$
Declare
  v_val int;
BEGIN
  execute i_text into v_val;
  return v_val;
END; 
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

Writing numerical values on the plot with Matplotlib

Use pyplot.text() (import matplotlib.pyplot as plt)

import matplotlib.pyplot as plt

x=[1,2,3]
y=[9,8,7]

plt.plot(x,y)
for a,b in zip(x, y): 
    plt.text(a, b, str(b))
plt.show()

How to list the certificates stored in a PKCS12 keystore with keytool?

You can list down the entries (certificates details) with the keytool and even you don't need to mention the store type.

keytool -list -v -keystore cert.p12 -storepass <password>

 Keystore type: PKCS12
 Keystore provider: SunJSSE

 Your keystore contains 1 entry
 Alias name: 1
 Creation date: Jul 11, 2020
 Entry type: PrivateKeyEntry
 Certificate chain length: 2

Removing carriage return and new-line from the end of a string in c#

This should work ...

var tst = "12345\n\n\r\n\r\r";
var res = tst.TrimEnd( '\r', '\n' );

git remove merge commit from history

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

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

git revert -m 1 <SHA of merge>

-m 1 specifies which parent line to choose

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


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

git rebase -i <SHA before branching out>

and delete (remove lines) corresponding to purple commits.

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

git undo all uncommitted or unsaved changes

I'm using source tree.... You can do revert all uncommitted changes with 2 easy steps:

1) just need to reset the workspace file status

enter image description here 2) select all unstage files (command +a), right click and select remove

enter image description here

It's that simple :D

Npm Error - No matching version found for

try

npm install --force
npm install --legacy-peer-deps

Getting mouse position in c#

You should use System.Windows.Forms.Cursor.Position: "A Point that represents the cursor's position in screen coordinates."

Connect Android Studio with SVN

  1. Run Android Studio.
  2. From the menu bar, select Android Studio
  3. Under IDE Settings, click Plugins and then select Search Subversion Integration
  4. Check SubVersion.
  5. Restart Android Studio.

Change div height on button click

_x000D_
_x000D_
var ww1 = "";_x000D_
var ww2 = 0;_x000D_
var myVar1 ;_x000D_
var myVar2 ;_x000D_
function wm1(){_x000D_
  myVar1 =setInterval(w1, 15);_x000D_
}_x000D_
function wm2(){_x000D_
  myVar2 =setInterval(w2, 15);_x000D_
}_x000D_
function w1(){_x000D_
 ww1=document.getElementById('chartdiv').style.height;_x000D_
 ww2= ww1.replace("px", ""); _x000D_
    if(parseFloat(ww2) <= 200){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)+5) + 'px';_x000D_
    }else{_x000D_
      clearInterval(myVar1);_x000D_
    }_x000D_
}_x000D_
function w2(){_x000D_
 ww1=document.getElementById('chartdiv').style.height;_x000D_
 ww2= ww1.replace("px", ""); _x000D_
    if(parseFloat(ww2) >= 50){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)-5) + 'px';_x000D_
    }else{_x000D_
      clearInterval(myVar2);_x000D_
    }_x000D_
}
_x000D_
<html>_x000D_
  <head>    _x000D_
  </head>_x000D_
_x000D_
<body >_x000D_
    <button type="button" onClick = "wm1()">200px</button>_x000D_
    <button type="button" onClick = "wm2()">50px</button>_x000D_
    <div id="chartdiv" style="width: 100%; height: 50px; background-color:#ccc"></div>_x000D_
  _x000D_
  <div id="demo"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

HTML Button Close Window

I know this thread has been answered, but another solution that may be useful for some, particularly to those with multiple pages where they want to have this button, is to give the input an id and place the code in a JavaScript file. You can then place the code for the button on multiple pages, taking up less space in your code.

For the button:

    <input type="button" id="cancel_edit" value="Cancel"></input>

in the JavaScript file:

    $("#cancel_edit").click(function(){
        window.open('','_parent',''); 
        window.close(); 
    });

Check if current directory is a Git repository

Not sure if there is a publicly accessible/documented way to do this (there are some internal git functions which you can use/abuse in the git source itself)

You could do something like;

if ! git ls-files >& /dev/null; then
  echo "not in git"
fi

Regex to remove all special characters from string?

public static string Letters(this string input)
{
    return string.Concat(input.Where(x => char.IsLetter(x) && !char.IsSymbol(x) && !char.IsWhiteSpace(x)));
}

How can I remove a style added with .css() function?

you remove style using

removeAttr( 'style' );

What is cURL in PHP?

cURL

  • cURL is a way you can hit a URL from your code to get a HTML response from it.
  • It's used for command line cURL from the PHP language.
  • cURL is a library that lets you make HTTP requests in PHP.

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().

Sample Code

// error reporting
error_reporting(E_ALL);
ini_set("display_errors", 1);

//setting url
$url = 'http://example.com/api';

//data
$data = array("message" => "Hello World!!!");

try {
    $ch = curl_init($url);
    $data_string = json_encode($data);

    if (FALSE === $ch)
        throw new Exception('failed to initialize');

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

        $output = curl_exec($ch);

    if (FALSE === $output)
        throw new Exception(curl_error($ch), curl_errno($ch));

    // ...process $output now
} catch(Exception $e) {

    trigger_error(sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage()),
        E_USER_ERROR);
}

For more information, please check -

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

NEW WAY SINCE VERSION 0.7.7

Since Version 0.7.7 there is a new way to create an aggregated report:

You create a separate 'report' project which collects all the necessary reports (Any goal in the aggregator project is executed before its modules therefore it can't be used).

aggregator pom
  |- parent pom
  |- module a
  |- module b
  |- report module 

The root pom looks like this (don't forget to add the new report module under modules):

<build>
<plugins>
  <plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.8</version>
    <executions>
      <execution>
        <id>prepare-agent</id>
        <goals>
          <goal>prepare-agent</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>

The poms from each sub module doesn't need to be changed at all. The pom from the report module looks like this:

<!-- Add all sub modules as dependencies here -->
<dependencies>
  <dependency>
    <module a>
  </dependency>
  <dependency>
    <module b>
  </dependency>
 ...

  <build>
    <plugins>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>0.7.8</version>
        <executions>
          <execution>
            <id>report-aggregate</id>
            <phase>verify</phase>
            <goals>
              <goal>report-aggregate</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

A full exmple can be found here.

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

Please note that in upcoming version of C# which is 8, the answers are not true.

All the reference types are non-nullable by default and you can actually do the following:

public string? MyNullableString; 
this.MyNullableString = null; //Valid

However,

public string MyNonNullableString; 
this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning. 

The important thing here is to show the intent of your code. If the "intent" is that the reference type can be null, then mark it so otherwise assigning null value to non-nullable would result in compiler warning.

More info

PHP - Session destroy after closing browser

There's one more "hack" by using HTTP Referer (we asume that browser window was closed current referer's domain name and curent page's domain name do not match):

session_start();
$_SESSION['somevariable'] = 'somevalue';

if(parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST) != $_SERVER["SERVER_NAME"]){
    session_destroy();
}

This also has some drawbacks, but it helped me few times.

Factory Pattern. When to use factory methods?

Consider a scenario when you have to design an Order and Customer class. For simplicity and initial requirements you do not feel need of factory for Order class and fill your application with many 'new Order()' statements. Things are working well.

Now a new requirement comes into picture that Order object cannot be instantiated without Customer association (new dependency). Now You have following considerations.

1- You create constructor overload which will work only for new implementations. (Not acceptable). 2- You change Order() signatures and change each and every invokation. (Not a good practice and real pain).

Instead If you have created a factory for Order Class you only have to change one line of code and you are good to go. I suggest Factory class for almost every aggregate association. Hope that helps.

How to send email to multiple recipients with addresses stored in Excel?

You have to loop through every cell in the range "D3:D6" and construct your To string. Simply assigning it to a variant will not solve the purpose. EmailTo becomes an array if you assign the range directly to it. You can do this as well but then you will have to loop through the array to create your To string

Is this what you are trying? (TRIED AND TESTED)

Option Explicit

Sub Mail_workbook_Outlook_1()
     'Working in 2000-2010
     'This example send the last saved version of the Activeworkbook
    Dim OutApp As Object
    Dim OutMail As Object
    Dim emailRng As Range, cl As Range
    Dim sTo As String

    Set emailRng = Worksheets("Selections").Range("D3:D6")

    For Each cl In emailRng 
        sTo = sTo & ";" & cl.Value
    Next

    sTo = Mid(sTo, 2)

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = sTo
        .CC = "[email protected];[email protected]"
        .BCC = ""
        .Subject = "RMA #" & Worksheets("RMA").Range("E1")
        .Body = "Attached to this email is RMA #" & _
        Worksheets("RMA").Range("E1") & _
        ". Please follow the instructions for your department included in this form."
        .Attachments.Add ActiveWorkbook.FullName
         'You can add other files also like this
         '.Attachments.Add ("C:\test.txt")

        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Twig for loop for arrays with keys

I found the answer :

{% for key,value in array_path %}
    Key : {{ key }}
    Value : {{ value }}
{% endfor %}

Can a foreign key be NULL and/or duplicate?

Can a Foreign key be NULL?

Existing answers focused on single column scenario. If we consider multi column foreign key we have more options using MATCH [SIMPLE | PARTIAL | FULL] clause defined in SQL Standard:

PostgreSQL-CREATE TABLE

A value inserted into the referencing column(s) is matched against the values of the referenced table and referenced columns using the given match type. There are three match types: MATCH FULL, MATCH PARTIAL, and MATCH SIMPLE (which is the default). MATCH FULL will not allow one column of a multicolumn foreign key to be null unless all foreign key columns are null; if they are all null, the row is not required to have a match in the referenced table. MATCH SIMPLE allows any of the foreign key columns to be null; if any of them are null, the row is not required to have a match in the referenced table. MATCH PARTIAL is not yet implemented.

(Of course, NOT NULL constraints can be applied to the referencing column(s) to prevent these cases from arising.)

Example:

CREATE TABLE A(a VARCHAR(10), b VARCHAR(10), d DATE , UNIQUE(a,b));
INSERT INTO A(a, b, d) 
VALUES (NULL, NULL, NOW()),('a', NULL, NOW()),(NULL, 'b', NOW()),('c', 'b', NOW());

CREATE TABLE B(id INT PRIMARY KEY, ref_a VARCHAR(10), ref_b VARCHAR(10));

-- MATCH SIMPLE - default behaviour nulls are allowed
ALTER TABLE B ADD CONSTRAINT B_Fk FOREIGN KEY (ref_a, ref_b) 
REFERENCES A(a,b) MATCH SIMPLE;

INSERT INTO B(id, ref_a, ref_b) VALUES (1, NULL, 'b');  

-- (NULL/'x') 'x' value does not exists in A table, but insert is valid
INSERT INTO B(id, ref_a, ref_b) VALUES (2, NULL, 'x');  

ALTER TABLE B DROP CONSTRAINT IF EXISTS B_Fk; -- cleanup

-- MATCH PARTIAL - not implemented
ALTER TABLE B ADD CONSTRAINT B_Fk FOREIGN KEY (ref_a, ref_b) 
REFERENCES A(a,b) MATCH PARTIAL;
-- ERROR:  MATCH PARTIAL not yet implemented

DELETE FROM B; ALTER TABLE B DROP CONSTRAINT IF EXISTS B_Fk; -- cleanup

-- MATCH FULL nulls are not allowed
ALTER TABLE B ADD CONSTRAINT B_Fk FOREIGN KEY (ref_a, ref_b) 
REFERENCES A(a,b) MATCH FULL;

-- FK is defined, inserting NULL as part of FK
INSERT INTO B(id, ref_a, ref_b) VALUES (1, NULL, 'b');
-- ERROR:  MATCH FULL does not allow mixing of null and nonnull key values.

-- FK is defined, inserting all NULLs - valid
INSERT INTO B(id, ref_a, ref_b) VALUES (1, NULL, NULL);

db<>fiddle demo

Text inset for UITextField?

Swift

 class TextField: UITextField {

    let inset: CGFloat = 8

    // placeholder position
    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: inset, dy: inset)
    }

    // text position
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: inset, dy: inset)
    }
}

Switch between python 2.7 and python 3.5 on Mac OS X

I just follow up the answer from @John Wilkey.

My alias python used to represent python2.7 (located in /usr/bin). However the default python_path is now preceded by /usr/local/bin for python3; hence when typing python, I didn't get either the python version.

I tried make a link in /usr/local/bin for python2:

ln -s /usr/bin/python /usr/local/bin/

It works when calling python for python2.

How to compile without warnings being treated as errors?

Solution:

CFLAGS=-Wno-error ./configure

AngularJS event on window innerWidth size change

I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/

Ive refactored the code to make it simpler for this.

// In your controller
var w = angular.element($window);
$scope.$watch(
  function () {
    return $window.innerWidth;
  },
  function (value) {
    $scope.windowWidth = value;
  },
  true
);

w.bind('resize', function(){
  $scope.$apply();
});

You can then reference to windowWidth from the html

<span ng-bind="windowWidth"></span>

Have a variable in images path in Sass?

We can use relative path instead of absolute path:

$assetPath: '~src/assets/images/';
$logo-img: '#{$assetPath}logo.png';
@mixin logo {
  background-image: url(#{$logo-img});
}

.logo {
    max-width: 65px;
    @include logo;
 }

go get results in 'terminal prompts disabled' error for github private repo

If you configure your gitconfig with this option, you will later have a problem cloning other repos of GitHub

git config --global --add url. "[email protected]". Instead, "https://github.com/"

Instead, I recommend that you use this option

echo "export GIT_TERMINAL_PROMPT=1" >> ~/.bashrc || ~/.zshrc

and do not forget to generate an access token from your private repository. When prompted to enter your password, just paste the access token. Happy clone :)

How to turn off INFO logging in Spark?

In Spark 2.0 you can also configure it dynamically for your application using setLogLevel:

    from pyspark.sql import SparkSession
    spark = SparkSession.builder.\
        master('local').\
        appName('foo').\
        getOrCreate()
    spark.sparkContext.setLogLevel('WARN')

In the pyspark console, a default spark session will already be available.

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I know this thread is a year old now but having experienced the same problem I managed to solve the problem by setting a target server for my project.

i.e. right-click on your project and select 'Properties' -> 'Targeted Runtimes' and select the server you going to run your web app on (Tomcat 6 or 7).

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

If you're still facing the issue even after replacing doGet() with doPost() and changing the form method="post". Try clearing the cache of the browser or hit the URL in another browser or incognito/private mode. It may works!

For best practices, please follow this link. https://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

Why is width: 100% not working on div {display: table-cell}?

Putting display:table; inside .outer-wrapper seemed to work...

JSFiddle Link


EDIT: Two Wrappers Using Display Table Cell

I would comment on your answer but i have too little rep :( anyways...

Going off your answer, seems like all you need to do is add display:table; inside .outer-wrapper (Dejavu?), and you can get rid of table-wrapper whole-heartedly.

JSFiddle

But yeah, the position:absolute lets you place the div over the img, I read too quickly and thought that you couldn't use position:absolute at all, but seems like you figured it out already. Props!

I'm not going to post the source code, after all its 99% timshutes's work, so please refer to his answer, or just use my jsfiddle link

Update: One Wrapper Using Flexbox

It's been a while, and all the cool kids are using flexbox:

<div style="display: flex; flex-direction: column; justify-content: center; align-items: center;">
    stuff to be centered
</div>

Full JSFiddle Solution

Browser Support (source): IE 11+, FireFox 42+, Chrome 46+, Safari 8+, iOS 8.4+ (-webkit- prefix), Android 4.1+ (-webkit- prefix)

CSS Tricks: a Guide to Flexbox

How to Center in CSS: input how you want your content to be centered, and it outputs how to do it in html and css. The future is here!

How to read a HttpOnly cookie using JavaScript

Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.

But more importantly why do you want to read an HTTPOnly cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly flag and "secure flag" (which forces the cookie to be sent over https) should always be set.

If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.

People have too much faith in the HTTPOnly flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

Jdk 9 and 10 solution

<plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven-compiler.version}</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
                <debug>true</debug>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.ow2.asm</groupId>
                    <artifactId>asm</artifactId>
                    <version>6.2</version>
                </dependency>
            </dependencies>
        </plugin>

and make sure your maven is pointing to JDK 10 or 9. mvn -v

Apache Maven 3.5.3 (3383c37e1f9e9b3bc3df5050c29c8aff9f295297; 2018-02-24T14:49:05-05:00)
Maven home: C:\devplay\apache-maven-3.5.3\bin\..
Java version: 10.0.1, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk-10.0.1
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

How to scroll to top of long ScrollView layout?

@SuppressWarnings({ "deprecation", "unchecked" })
public void swipeTopToBottom(AppiumDriver<MobileElement> driver) 
                    throws InterruptedException {
       Dimension dimensions = driver.manage().window().getSize();
        Double screenHeightStart = dimensions.getHeight() * 0.30;
        int scrollStart = screenHeightStart.intValue();
        System.out.println("s="+scrollStart);
        Double screenHeightEnd = dimensions.getHeight()*0.90;
        int scrollEnd = screenHeightEnd.intValue();
        driver.swipe(0,scrollStart,0,scrollEnd,2000);
        CommonUtils.threadWait(driver, 3000);
    }

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

Even after this my code is working fine , so i just removed all warning messages with this statement at line 1 .

<?php error_reporting(E_ERROR); ?>

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

HTML Table cellspacing or padding just top / bottom

There is css:

table { border-spacing: 40px 10px; }

for 40px wide and 10px high

How do I find out what all symbols are exported from a shared object?

The cross-platform way (not only cross-platform itself, but also working, at the very least, with both *.so and *.dll) is using reverse-engineering framework radare2. E.g.:

$ rabin2 -s glew32.dll | head -n 5 
[Symbols]
vaddr=0x62afda8d paddr=0x0005ba8d ord=000 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_multisample
vaddr=0x62afda8e paddr=0x0005ba8e ord=001 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_tbuffer
vaddr=0x62afda8f paddr=0x0005ba8f ord=002 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_texture_compression_FXT1
vaddr=0x62afdab8 paddr=0x0005bab8 ord=003 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_AMD_blend_minmax_factor

As a bonus, rabin2 recognizes C++ name mangling, for example (and also with .so file):

$ rabin2 -s /usr/lib/libabw-0.1.so.1.0.1 | head -n 5
[Symbols]
vaddr=0x00027590 paddr=0x00027590 ord=124 fwd=NONE sz=430 bind=GLOBAL type=FUNC name=libabw::AbiDocument::isFileFormatSupported
vaddr=0x0000a730 paddr=0x0000a730 ord=125 fwd=NONE sz=58 bind=UNKNOWN type=FUNC name=boost::exception::~exception
vaddr=0x00232680 paddr=0x00032680 ord=126 fwd=NONE sz=16 bind=UNKNOWN type=OBJECT name=typeinfoforboost::exception_detail::clone_base
vaddr=0x00027740 paddr=0x00027740 ord=127 fwd=NONE sz=235 bind=GLOBAL type=FUNC name=libabw::AbiDocument::parse

Works with object files too:

$ g++ test.cpp -c -o a.o
$ rabin2 -s a.o | head -n 5
Warning: Cannot initialize program headers
Warning: Cannot initialize dynamic strings
Warning: Cannot initialize dynamic section
[Symbols]
vaddr=0x08000149 paddr=0x00000149 ord=006 fwd=NONE sz=1 bind=LOCAL type=OBJECT name=std::piecewise_construct
vaddr=0x08000149 paddr=0x00000149 ord=007 fwd=NONE sz=1 bind=LOCAL type=OBJECT name=std::__ioinit
vaddr=0x080000eb paddr=0x000000eb ord=017 fwd=NONE sz=73 bind=LOCAL type=FUNC name=__static_initialization_and_destruction_0
vaddr=0x08000134 paddr=0x00000134 ord=018 fwd=NONE sz=21 bind=LOCAL type=FUNC name=_GLOBAL__sub_I__Z4funcP6Animal

How to execute UNION without sorting? (SQL)

The sort is used to eliminate the duplicates, and is implicit for DISTINCT and UNION queries (but not UNION ALL) - you could still specify the columns you'd prefer to order by if you need them sorted by specific columns.

For example, if you wanted to sort by the result sets, you could introduce an additional column, and sort by that first:

SELECT foo, bar, 1 as ResultSet
FROM Foo
WHERE bar = 1
UNION
SELECT foo, bar, 2 as ResultSet
FROM Foo
WHERE bar = 3
UNION
SELECT foo, bar, 3 as ResultSet
FROM Foo
WHERE bar = 2
ORDER BY ResultSet

How do I use hexadecimal color strings in Flutter?

In Flutter it create a color from RGB with alpha, use

return new Container(
  color: new Color.fromRGBO(0, 0, 0, 0.5),
);

How to use hex-color:

return new Container(
  color: new Color(0xFF4286f4),
);
//0xFF -> the opacity (FF for opaque)
//4286f4 -> the hex-color

Hex-color with opacity:

return new Container(
  color: new Color(0xFF4286f4).withOpacity(0.5),
);

// or change the "FF" value

100% — FF
 95% — F2
 90% — E6
 85% — D9
 80% — CC
 75% — BF
 70% — B3
 65% — A6
 60% — 99
 55% — 8C
 50% — 80
 45% — 73
 40% — 66
 35% — 59
 30% — 4D
 25% — 40
 20% — 33
 15% — 26
 10% — 1A
 5% — 0D
 0% — 00

For more follow official link https://api.flutter.dev/flutter/dart-ui/Color-class.html

Name does not exist in the current context

Same issue happened with me when i mistakenly added some text in front of the top directive of the master page all the controls across all the page included in my project started showing, does not exist in the current context. After spending much time across the forum and self analysis, i found the mistakenly added text and removed but it does not solved the problem. Then i had to click on each error to open the associated page so that VS can load the page and recognize it, once the code was loaded in VS, error from those particular page started disappearing because VS recognized it. clicking on each error, loading each page in VS editor did the trick for me and you have to do it only once because later it will be automatically recognized by VS. I would say it is a Visual Studio Glitch.

Does a finally block always get executed in Java?

Finally block always execute whether exception handle or not .if any exception occurred before try block then finally block will not execute.

What is the difference between Promises and Observables?

Promise:

  • Provide a single future value;
  • Not lazy;
  • Not cancellable;

Observable:

  • Emits multiple values over time;
  • Lazy;
  • Cancellable;
  • Supports map, filter, reduce and similar operators

You can use promises instead of observables when calling HTTP in Angular if you wish.

Extracting Ajax return data in jQuery

Change the .find to .filter...

How to run a task when variable is undefined in ansible?

From the ansible docs: If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:

tasks:

- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
  when: foo is defined

- fail: msg="Bailing out. this play requires 'bar'"
  when: bar is not defined

So in your case, when: deployed_revision is not defined should work

How to Alter Constraint

You can not alter constraints ever but you can drop them and then recreate.

Have look on this

ALTER TABLE your_table DROP CONSTRAINT ACTIVEPROG_FKEY1;

and then recreate it with ON DELETE CASCADE like this

ALTER TABLE your_table
add CONSTRAINT ACTIVEPROG_FKEY1 FOREIGN KEY(ActiveProgCode) REFERENCES PROGRAM(ActiveProgCode)
    ON DELETE CASCADE;

hope this help

How can I download a file from a URL and save it in Rails?

An even shorter version:

require 'open-uri'
download = open('http://example.com/image.png')
IO.copy_stream(download, '~/image.png')

To keep the same filename:

IO.copy_stream(download, "~/#{download.base_uri.to_s.split('/')[-1]}")

@RequestParam in Spring MVC handling optional parameters

You need to give required = false for name and password request parameters as well. That's because, when you provide just the logout parameter, it actually expects for name and password as well as they are still mandatory.

It worked when you just gave name and password because logout wasn't a mandatory parameter thanks to required = false already given for logout.

Is it possible to use pip to install a package from a private GitHub repository?

You can also install a private repository dependency via git+https://github.com/... URL by providing login credentials (login and password, or deploy token) for curl with the .netrc file:

echo "machine github.com login ei-grad password mypasswordshouldbehere" > ~/.netrc
pip install "git+https://github.com/ei-grad/my_private_repo.git#egg=my_private_repo"

Using floats with sprintf() in embedded C

Isn't something like this really easier:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char str[10];
float adc_read = 678.0123;

dtostrf( adc_read, 3, 4, temp );
sprintf(str,"adc_read = %10s \n", temp);
printf(temp);

Convert Year/Month/Day to Day of Year in Python

Just subtract january 1 from the date:

import datetime
today = datetime.datetime.now()
day_of_year = (today - datetime.datetime(today.year, 1, 1)).days + 1

Batch file to perform start, run, %TEMP% and delete all

The following batch commands are used to delete all your temp, recent and prefetch files on your System.

Save the following code as "Clear.bat" on your local system

*********START CODE************

@ECHO OFF

del /s /f /q %userprofile%\Recent\*.*

del /s /f /q C:\Windows\Prefetch\*.*

del /s /f /q C:\Windows\Temp\*.*

del /s /f /q %USERPROFILE%\appdata\local\temp\*.*


/Below command to Show the folder after deleted files

Explorer %userprofile%\Recent

Explorer C:\Windows\Prefetch

Explorer C:\Windows\Temp

Explorer %USERPROFILE%\appdata\local\temp


*********END CODE************

How can I tell if a VARCHAR variable contains a substring?

    IF CHARINDEX('TextToSearch',@TextWhereISearch, 0) > 0 => TEXT EXISTS

    IF PATINDEX('TextToSearch', @TextWhereISearch) > 0 => TEXT EXISTS

    Additionally we can also use LIKE but I usually don't use LIKE.

How to convert a byte array to Stream

Easy, simply wrap a MemoryStream around it:

Stream stream = new MemoryStream(buffer);

HTML meta tag for content language

Html5 also recommend to use <html lang="es-ES"> The small letter lang tag only specifies: language code The large letter specifies: country code

This is really useful for ie.Chrome, when the browser is proposing to translate web content(ie google translate)

Getting all types that implement an interface

I see so many overcomplicated answers here and people always tell me that I tend to overcomplicate things. Also using IsAssignableFrom method for the purpose of solving OP problem is wrong!

Here is my example, it selects all assemblies from the app domain, then it takes flat list of all available types and checks every single type's list of interfaces for match:

public static IEnumerable<Type> GetImplementingTypes(this Type itype) 
    => AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes())
           .Where(t => t.GetInterfaces().Contains(itype));

SVG gradient using CSS

Here is how to set a linearGradient on a target element:

<style type="text/css">
    path{fill:url('#MyGradient')}
</style>
<defs>
    <linearGradient id="MyGradient">
        <stop offset="0%" stop-color="#e4e4e3" ></stop>
        <stop offset="80%" stop-color="#fff" ></stop>
    </linearGradient>
</defs>

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

You can use a while loop.

Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
    Map.Entry<String, String> entry = iterator.next();
    if(entry.getKey().equals("test")) {
        iterator.remove();
    } 
}

How to POST request using RestSharp

As of 2017 I post to a rest service and getting the results from it like that:

        var loginModel = new LoginModel();
        loginModel.DatabaseName = "TestDB";
        loginModel.UserGroupCode = "G1";
        loginModel.UserName = "test1";
        loginModel.Password = "123";

        var client = new RestClient(BaseUrl);

        var request = new RestRequest("/Connect?", Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.AddBody(loginModel);

        var response = client.Execute(request);

        var obj = JObject.Parse(response.Content);

        LoginResult result = new LoginResult
        {
            Status = obj["Status"].ToString(),
            Authority = response.ResponseUri.Authority,
            SessionID = obj["SessionID"].ToString()
        };

How do I update a formula with Homebrew?

You will first need to update the local formulas by doing

brew update

and then upgrade the package by doing

brew upgrade formula-name

An example would be if i wanted to upgrade mongodb, i would do something like this, assuming mongodb was already installed :

brew update && brew upgrade mongodb && brew cleanup mongodb

Trim spaces from start and end of string

If using jQuery is an option:

/**
 * Trim the site input[type=text] fields globally by removing any whitespace from the
 * beginning and end of a string on input .blur()
 */
$('input[type=text]').blur(function(){
    $(this).val($.trim($(this).val()));
});

or simply:

$.trim(string);

What's the difference between next() and nextLine() methods from Scanner class?

next() can read the input only till the space. It can't read two words separated by a space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

For reading the entire line you can use nextLine().

How do I close a tkinter window?

def quit()
    root.quit()

or

def quit()
    root.destroy()

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

At least 8 = {8,}:

str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)

array_push() with key value pair

$data['cat'] = 'wagon';

That's all you need to add the key and value to the array.

psql: FATAL: database "<user>" does not exist

Since this question is the first in search results, I'll put a different solution for a different problem here anyway, in order not to have a duplicate title.

The same error message can come up when running a query file in psql without specifying a database. Since there is no use statement in postgresql, we have to specify the database on the command line, for example:

psql -d db_name -f query_file.sql

Typescript sleep

For some reason the above accepted answer does not work in New versions of Angular (V6).

for that use this..

async delay(ms: number) {
    await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}

above worked for me.

Usage:

this.delay(3000);

OR more accurate way

this.delay(3000).then(any=>{
     //your task after delay.
});

Check if a PHP cookie exists and if not set its value

Answer

You can't according to the PHP manual:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

Work around

But you can work around it by also setting $_COOKIE when you call setcookie():

if(!isset($_COOKIE['lg'])) {
    setcookie('lg', 'ro');
    $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];

How to get the selected date value while using Bootstrap Datepicker?

Generally speaking,

$('#startdate').data('date') 

is best because

$('#startdate').val()

not work if you have a datepicker "inline"

Best way to check if a drop down list contains a value?

There are two methods that come to mind:

You could use Contains like so:

if (ddlCustomerNumber.Items.Contains(new 
    ListItem(GetCustomerNumberCookie().ToString())))
{
    // ... code here
}

or modifying your current strategy:

if (ddlCustomerNumber.Items.FindByText(
    GetCustomerNumberCookie().ToString()) != null)
{
    // ... code here
}

EDIT: There's also a DropDownList.Items.FindByValue that works the same way as FindByText, except it searches based on values instead.

get index of DataTable column with name

You can use DataColumn.Ordinal to get the index of the column in the DataTable. So if you need the next column as mentioned use Column.Ordinal + 1:

row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;

How to var_dump variables in twig templates?

The complete recipe here for quicker reference (note that all the steps are mandatory):

1) when instantiating Twig, pass the debug option

$twig = new Twig_Environment(
$loader, ['debug'=>true, 'cache'=>false, /*other options */]
);

2) add the debug extension

$twig->addExtension(new \Twig_Extension_Debug());

3) Use it like @Hazarapet Tunanyan pointed out

{{ dump(MyVar) }}

or

{{ dump() }}

or

{{ dump(MyObject.MyPropertyName) }}

increment date by one month

Just updating the answer with simple method for find the date after no of months. As the best answer marked doesn't give the correct solution.

<?php

    $date = date('2020-05-31');
    $current = date("m",strtotime($date));
    $next = date("m",strtotime($date."+1 month"));
    if($current==$next-1){
        $needed = date('Y-m-d',strtotime($date." +1 month"));
    }else{
        $needed = date('Y-m-d', strtotime("last day of next month",strtotime($date)));
    }
    echo "Date after 1 month from 2020-05-31 would be : $needed";

?>

how to pass this element to javascript onclick function and add a class to that clicked element

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script> 
<script type="text/javascript" src="jquery-2.1.0.js"></script> 
<script type="text/javascript" >
function openOnImageClick(event)
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var target = event.target || event.srcElement; // IE

console.log(target);
console.log(target.src);
 var img = document.createElement('img');
 img.setAttribute('src', target.src);
  img.setAttribute('width', '200');
   img.setAttribute('height', '150');
  document.getElementById("images").appendChild(img);


}


</script>
</head>
<body>

<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>

<div id="images" >
</div>

<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
<img src="sabaLogo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />

</body>
</html> 

submitting a GET form with query string params and hidden params disappear

I had a very similar problem where for the form action, I had something like:

<form action="http://www.example.com/?q=content/something" method="GET">
   <input type="submit" value="Go away..." />&nbsp;
</form>

The button would get the user to the site, but the query info disappeared so the user landed on the home page rather than the desired content page. The solution in my case was to find out how to code the URL without the query that would get the user to the desired page. In this case my target was a Drupal site, so as it turned out /content/something also worked. I also could have used a node number (i.e. /node/123).

how to select first N rows from a table in T-SQL?

You can also use rowcount, but TOP is probably better and cleaner, hence the upvote for Mehrdad

SET ROWCOUNT 10
SELECT * FROM dbo.Orders
WHERE EmployeeID = 5
ORDER BY OrderDate

SET ROWCOUNT 0

What is Bootstrap?

Bootstrap is an HTML, CSS, JS framework with many components that let you create beautiful and modern web sites or web applications very fast.

The following websites contain examples, elements and reusable components that you can integrate into your project using bootstrap framework

bootsnipp.com

startbootstrap.com

bootdey.com

How do I use arrays in C++?

Assignment

For no particular reason, arrays cannot be assigned to one another. Use std::copy instead:

#include <algorithm>

// ...

int a[8] = {2, 3, 5, 7, 11, 13, 17, 19};
int b[8];
std::copy(a + 0, a + 8, b);

This is more flexible than what true array assignment could provide because it is possible to copy slices of larger arrays into smaller arrays. std::copy is usually specialized for primitive types to give maximum performance. It is unlikely that std::memcpy performs better. If in doubt, measure.

Although you cannot assign arrays directly, you can assign structs and classes which contain array members. That is because array members are copied memberwise by the assignment operator which is provided as a default by the compiler. If you define the assignment operator manually for your own struct or class types, you must fall back to manual copying for the array members.

Parameter passing

Arrays cannot be passed by value. You can either pass them by pointer or by reference.

Pass by pointer

Since arrays themselves cannot be passed by value, usually a pointer to their first element is passed by value instead. This is often called "pass by pointer". Since the size of the array is not retrievable via that pointer, you have to pass a second parameter indicating the size of the array (the classic C solution) or a second pointer pointing after the last element of the array (the C++ iterator solution):

#include <numeric>
#include <cstddef>

int sum(const int* p, std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

int sum(const int* p, const int* q)
{
    return std::accumulate(p, q, 0);
}

As a syntactic alternative, you can also declare parameters as T p[], and it means the exact same thing as T* p in the context of parameter lists only:

int sum(const int p[], std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

You can think of the compiler as rewriting T p[] to T *p in the context of parameter lists only. This special rule is partly responsible for the whole confusion about arrays and pointers. In every other context, declaring something as an array or as a pointer makes a huge difference.

Unfortunately, you can also provide a size in an array parameter which is silently ignored by the compiler. That is, the following three signatures are exactly equivalent, as indicated by the compiler errors:

int sum(const int* p, std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[], std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[8], std::size_t n)   // the 8 has no meaning here

Pass by reference

Arrays can also be passed by reference:

int sum(const int (&a)[8])
{
    return std::accumulate(a + 0, a + 8, 0);
}

In this case, the array size is significant. Since writing a function that only accepts arrays of exactly 8 elements is of little use, programmers usually write such functions as templates:

template <std::size_t n>
int sum(const int (&a)[n])
{
    return std::accumulate(a + 0, a + n, 0);
}

Note that you can only call such a function template with an actual array of integers, not with a pointer to an integer. The size of the array is automatically inferred, and for every size n, a different function is instantiated from the template. You can also write quite useful function templates that abstract from both the element type and from the size.

Python popen command. Wait until the command is finished

You can you use subprocess to achieve this.

import subprocess

#This command could have multiple commands separated by a new line \n
some_command = "export PATH=$PATH://server.sample.mo/app/bin \n customupload abc.txt"

p = subprocess.Popen(some_command, stdout=subprocess.PIPE, shell=True)

(output, err) = p.communicate()  

#This makes the wait possible
p_status = p.wait()

#This will give you the output of the command being executed
print "Command output: " + output

what is an illegal reflective access

Apart from an understanding of the accesses amongst modules and their respective packages. I believe the crux of it lies in the Module System#Relaxed-strong-encapsulation and I would just cherry-pick the relevant parts of it to try and answer the question.

What defines an illegal reflective access and what circumstances trigger the warning?

To aid in the migration to Java-9, the strong encapsulation of the modules could be relaxed.

  • An implementation may provide static access, i.e. by compiled bytecode.

  • May provide a means to invoke its run-time system with one or more packages of one or more of its modules open to code in all unnamed modules, i.e. to code on the classpath. If the run-time system is invoked in this way, and if by doing so some invocations of the reflection APIs succeed where otherwise they would have failed.

In such cases, you've actually ended up making a reflective access which is "illegal" since in a pure modular world you were not meant to do such accesses.

How it all hangs together and what triggers the warning in what scenario?

This relaxation of the encapsulation is controlled at runtime by a new launcher option --illegal-access which by default in Java9 equals permit. The permit mode ensures

The first reflective-access operation to any such package causes a warning to be issued, but no warnings are issued after that point. This single warning describes how to enable further warnings. This warning cannot be suppressed.

The modes are configurable with values debug(message as well as stacktrace for every such access), warn(message for each such access), and deny(disables such operations).


Few things to debug and fix on applications would be:-

  • Run it with --illegal-access=deny to get to know about and avoid opening packages from one module to another without a module declaration including such a directive(opens) or explicit use of --add-opens VM arg.
  • Static references from compiled code to JDK-internal APIs could be identified using the jdeps tool with the --jdk-internals option

The warning message issued when an illegal reflective-access operation is detected has the following form:

WARNING: Illegal reflective access by $PERPETRATOR to $VICTIM

where:

$PERPETRATOR is the fully-qualified name of the type containing the code that invoked the reflective operation in question plus the code source (i.e., JAR-file path), if available, and

$VICTIM is a string that describes the member being accessed, including the fully-qualified name of the enclosing type

Questions for such a sample warning: = JDK9: An illegal reflective access operation has occurred. org.python.core.PySystemState

Last and an important note, while trying to ensure that you do not face such warnings and are future safe, all you need to do is ensure your modules are not making those illegal reflective accesses. :)

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Can I run multiple programs in a Docker container?

They can be in separate containers, and indeed, if the application was also intended to run in a larger environment, they probably would be.

A multi-container system would require some more orchestration to be able to bring up all the required dependencies, though in Docker v0.6.5+, there is a new facility to help with that built into Docker itself - Linking. With a multi-machine solution, its still something that has to be arranged from outside the Docker environment however.

With two different containers, the two parts still communicate over TCP/IP, but unless the ports have been locked down specifically (not recommended, as you'd be unable to run more than one copy), you would have to pass the new port that the database has been exposed as to the application, so that it could communicate with Mongo. This is again, something that Linking can help with.

For a simpler, small installation, where all the dependencies are going in the same container, having both the database and Python runtime started by the program that is initially called as the ENTRYPOINT is also possible. This can be as simple as a shell script, or some other process controller - Supervisord is quite popular, and a number of examples exist in the public Dockerfiles.

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

I had this same problem because I bought a CSS template and it grabbed a javascript an external javascript file through http://whatever.js.com/javascript.js. I went to that page in my browser and then changed it to https://whatever... using SSL and it worked, so in my HTML javascript tag I just changed the URL to use https instead of http and it worked.

Toggle show/hide on click with jQuery

The toggle-event is deprecated in version 1.8, and removed in version 1.9

Try this...

$('#myelement').toggle(
   function () {
      $('#another-element').show("slide", {
          direction: "right"
      }, 1000);
   },
   function () {
      $('#another-element').hide("slide", {
          direction: "right"
      }, 1000);
});

Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed, jQuery docs.

The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element, jQuery docs

You toggle between visibility using show and hide with click. You can put condition on visibility if element is visible then hide else show it. Note you will need jQuery UI to use addition effects with show / hide like direction.

Live Demo

$( "#myelement" ).click(function() {     
    if($('#another-element:visible').length)
        $('#another-element').hide("slide", { direction: "right" }, 1000);
    else
        $('#another-element').show("slide", { direction: "right" }, 1000);        
});

Or, simply use toggle instead of click. By using toggle you wont need a condition (if-else) statement. as suggested by T.J.Crowder.

Live Demo

$( "#myelement" ).click(function() {     
   $('#another-element').toggle("slide", { direction: "right" }, 1000);
});

Textarea Auto height

I used jQuery AutoSize. When I tried using Elastic it frequently gave me bogus heights (really tall textarea's). jQuery AutoSize has worked well and hasn't had this issue.

How does paintComponent work?

Calling object.paintComponent(g) is an error.

Instead this method is called automatically when the panel is created. The paintComponent() method can also be called explicitly by the repaint() method defined in Component class.

The effect of calling repaint() is that Swing automatically clears the graphic on the panel and executes the paintComponent method to redraw the graphics on this panel.

Concatenate multiple node values in xpath

I used concat method and works well.

concat(//SomeElement/text(),'_',//OtherElement/text())

ActiveX component can't create object

If its a 32 bit COM/Active X, use version 32 bit of cscript.exe/wscript.exe located in C:\Windows\SysWOW64\

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

PowerShell: Format-Table without headers

Try -ExpandProperty. For example, I use this for sending the clean variable to Out-Gridview -PassThru , otherwise the variable has the header info stored. Note that these aren't great if you want to return more than one property.

An example:

Get-ADUser -filter * | select name -expandproperty name

Alternatively, you could do this:

(Get-ADUser -filter * ).name

Markdown and image alignment

Even cleaner would be to just put p#given img { float: right } in the style sheet, or in the <head> and wrapped in style tags. Then, just use the markdown ![Alt text](/path/to/img.jpg).

How to align absolutely positioned element to center?

All you have to do is,

make sure your parent DIV has position:relative

and the element you want center, set it a height and width. use the following CSS

.layer {
    width: 600px; height: 500px;
    display: block;
    position:absolute;
    top:0;
    left: 0;
    right:0;
    bottom: 0;
    margin:auto;
  }
http://jsbin.com/aXEZUgEJ/1/

Creating InetAddress object in Java

The api is fairly easy to use.

// Lookup the dns, if the ip exists.
 if (!ip.isEmpty()) {
     InetAddress inetAddress = InetAddress.getByName(ip);
     dns = inetAddress.getCanonicalHostName(); 
 }

Associating existing Eclipse project with existing SVN repository

Try this- Close the project then open it. It links with svn automatically,if project was checked out from valid svn path.

How to subtract 30 days from the current datetime in mysql?

another way

SELECT COUNT(*) FROM tbl_debug WHERE TO_DAYS(`when`) < TO_DAYS(NOW())-30 ;

How to Create a real one-to-one relationship in SQL Server

1 To 1 Relationships in SQL are made by merging the field of both table in one !

I know you can split a Table in two entity with a 1 to 1 relation. Most of time you use this because you want to use lazy loading on "heavy field of binary data in a table".

Exemple: You have a table containing pictures with a name column (string), maybe some metadata column, a thumbnail column and the picture itself varbinary(max). In your application, you will certainly display first only the name and the thumbnail in a collection control and then load the "full picture data" only if needed.

If it is what your are looking for. It is something called "table splitting" or "horizontal splitting".

https://visualstudiomagazine.com/articles/2014/09/01/splitting-tables.aspx

How to access component methods from “outside” in ReactJS?

You could also do it like this, not sure if it's a good plan :D

class Parent extends Component {
  handleClick() {
    if (this._getAlert !== null) {
      this._getAlert()
    }
  }

  render() {
    return (
      <div>
        <Child>
        {(getAlert, childScope) => (
          <span> {!this._getAlert ? this._getAlert = getAlert.bind(childScope) : null}</span>
        )}
        </Child>
        <button onClick={() => this.handleClick()}> Click me</button>
      </div>
      );
    }
  }

class Child extends Component {
  constructor() {
    super();
    this.state = { count: 0 }
  }

  getAlert() {
    alert(`Child function called state: ${this.state.count}`);
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return this.props.children(this.getAlert, this)
  }
}

Angular bootstrap datepicker date format does not format ng-model value

Although similar answers have been posted I'd like to contribute what seemed to be the easiest and cleanest fix to me. Assuming you are using the AngularUI datepicker and your initial value for the ng-Model does not get formatted simply adding the following directive to your project will fix the issue:

angular.module('yourAppName')
.directive('datepickerPopup', function (){
    return {
        restrict: 'EAC',
        require: 'ngModel',
        link: function(scope, element, attr, controller) {
      //remove the default formatter from the input directive to prevent conflict
      controller.$formatters.shift();
  }
}
});

I found this solution in the Github AngularUI issues and therefore all credit goes to the people over there.

How to upgrade glibc from version 2.13 to 2.15 on Debian?

I was able to install libc6 2.17 in Debian Wheezy by editing the recommendations in perror's answer:

IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1. Then you can stop x (slim) with sudo /etc/init.d/slim stop

(replace slim with mdm or lightdm or whatever)

Add the following line to the file /etc/apt/sources.list:

deb http://ftp.debian.org/debian experimental main

Should be changed to:

deb http://ftp.debian.org/debian sid main

Then follow the rest of perror's post:

Update your package database:

apt-get update

Install the eglibc package:

apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg

IMPORTANT
After done updating libc6, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main), or else you risk upgrading your whole distro to sid.

Hope this helps. It took me a while to figure out.

Is there a RegExp.escape function in JavaScript?

For anyone using Lodash, since v3.0.0 a _.escapeRegExp function is built-in:

_.escapeRegExp('[lodash](https://lodash.com/)');
// ? '\[lodash\]\(https:\/\/lodash\.com\/\)'

And, in the event that you don't want to require the full Lodash library, you may require just that function!

What do Push and Pop mean for Stacks?

Simply:

  • pop: returns the item at the top then remove it from the stack

  • push: add an item onto the top of the stack.

How do I create a link using javascript?

There are a couple of ways:

If you want to use raw Javascript (without a helper like JQuery), then you could do something like:

var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";

// and append it to where you'd like it to go:
document.body.appendChild(element);

The other method is to write the link directly into the document:

document.write("<a href='" + link + "'>" + text + "</a>");

JavaScript/jQuery - "$ is not defined- $function()" error

Try:

(function($) {
    $(function() {
        $('.update').live('change', function() {
            formObject.run($(this));
        });
    });
})(jQuery);

By using this way you ensure the global variable jQuery will be bound to the "$" inside the closure. Just make sure jQuery is properly loaded into the page by inserting:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

Replace "http://code.jquery.com/jquery-1.7.1.min.js" to the path where your jQuery source is located within the page context.

How to prove that a problem is NP complete?

To show a problem is NP complete, you need to:

Show it is in NP

In other words, given some information C, you can create a polynomial time algorithm V that will verify for every possible input X whether X is in your domain or not.

Example

Prove that the problem of vertex covers (that is, for some graph G, does it have a vertex cover set of size k such that every edge in G has at least one vertex in the cover set?) is in NP:

  • our input X is some graph G and some number k (this is from the problem definition)

  • Take our information C to be "any possible subset of vertices in graph G of size k"

  • Then we can write an algorithm V that, given G, k and C, will return whether that set of vertices is a vertex cover for G or not, in polynomial time.

Then for every graph G, if there exists some "possible subset of vertices in G of size k" which is a vertex cover, then G is in NP.

Note that we do not need to find C in polynomial time. If we could, the problem would be in `P.

Note that algorithm V should work for every G, for some C. For every input there should exist information that could help us verify whether the input is in the problem domain or not. That is, there should not be an input where the information doesn't exist.

Prove it is NP Hard

This involves getting a known NP-complete problem like SAT, the set of boolean expressions in the form:

(A or B or C) and (D or E or F) and ...

where the expression is satisfiable, that is there exists some setting for these booleans, which makes the expression true.

Then reduce the NP-complete problem to your problem in polynomial time.

That is, given some input X for SAT (or whatever NP-complete problem you are using), create some input Y for your problem, such that X is in SAT if and only if Y is in your problem. The function f : X -> Y must run in polynomial time.

In the example above, the input Y would be the graph G and the size of the vertex cover k.

For a full proof, you'd have to prove both:

  • that X is in SAT => Y in your problem

  • and Y in your problem => X in SAT.

marcog's answer has a link with several other NP-complete problems you could reduce to your problem.

Footnote: In step 2 (Prove it is NP-hard), reducing another NP-hard (not necessarily NP-complete) problem to the current problem will do, since NP-complete problems are a subset of NP-hard problems (that are also in NP).

Reverse a string without using reversed() or [::-1]?

This is a way to do it with a while loop:

def reverse(s):
    t = -1
    s2 = ''
    while abs(t) < len(s) + 1: 
        s2 = s2 + s[t]
        t  = t - 1
    return s2