Programs & Examples On #Atunit

Java unit tests with mocks (JMock or EasyMock) and dependency injection (Spring or Guice)

jQuery datepicker, onSelect won't work

No comma after the last property.

Semicolon after alert(date);

Case on datepicker (not datePicker)

Check your other uppercase / lowercase for the properties.

$(function() {
    $('.date-pick').datepicker( {
        onSelect: function(date) {
            alert(date);
        },
        selectWeek: true,
        inline: true,
        startDate: '01/01/2000',
        firstDay: 1
    });
});

C function that counts lines in file

I don't see anything immediately obvious as to what would cause a segmentation fault. My only suspicion is that your code expects to get a filename as a parameter when you run it, but if you don't pass it, it will attempt to reference one, anyway.

Accessing argv[1] when it doesn't exist would cause a segmentation fault. It's generally good practice to check the number of arguments before trying to reference them. You can do this by using the following function prototype for main(), and checking that argc is greater than 1 (simply, it will indicate the number entries in argv).

int main(int argc, char** argv)

The best way to figure out what causes a segfault in general is to use a debugger. If you're in Visual Studio, put a breakpoint at the top of your main function and then choose Run with debugging instead of "Run without debugging" when you start the program. It will stop execution at the top, and let you step line-by-line until you see a problem.

If you're in Linux, you can just grab the core file (it will have "core" in the name) and load that with gdb (GNU Debugger). It can give you a stack dump which will point you straight to the line that caused the segmentation fault to occur.

EDIT: I see you changed your question and code. So this answer probably isn't useful anymore, but I'll leave it as it's good advice anyway, and see if I can address the modified question, shortly).

IE 8: background-size fix

Also i have found another useful link. It is a background hack used like this

.selector { background-size: cover; -ms-behavior: url(/backgroundsize.min.htc); }

https://github.com/louisremi/background-size-polyfill

Collections.emptyList() returns a List<Object>?

The issue you're encountering is that even though the method emptyList() returns List<T>, you haven't provided it with the type, so it defaults to returning List<Object>. You can supply the type parameter, and have your code behave as expected, like this:

public Person(String name) {
  this(name,Collections.<String>emptyList());
}

Now when you're doing straight assignment, the compiler can figure out the generic type parameters for you. It's called type inference. For example, if you did this:

public Person(String name) {
  List<String> emptyList = Collections.emptyList();
  this(name, emptyList);
}

then the emptyList() call would correctly return a List<String>.

Access elements of parent window from iframe

I think you can just use window.parent from the iframe. window.parent returns the window object of the parent page, so you could do something like:

window.parent.document.getElementById('yourdiv');

Then do whatever you want with that div.

What are the advantages and disadvantages of recursion?

For the most part recursion is slower, and takes up more of the stack as well. The main advantage of recursion is that for problems like tree traversal it make the algorithm a little easier or more "elegant". Check out some of the comparisons:

link

Show spinner GIF during an $http request in AngularJS?

Here is my solution which i feel is alot easer that the other posted here. Not sure how "pretty" it is though, but it solved all my issues

I have a css style called "loading"

.loading { display: none; }

The html for the loading div can be whatever but I used some FontAwesome icons and the spin method there:

<div style="text-align:center" ng-class="{ 'loading': !loading }">
    <br />
    <h1><i class="fa fa-refresh fa-spin"></i> Loading data</h1>
</div>

On the elements that you want to hide you simply write this:

<something ng-class="{ 'loading': loading }" class="loading"></something>

and in the function i just set this on load.

(function (angular) {
    function MainController($scope) {
        $scope.loading = true

I am using SignalR so in the hubProxy.client.allLocks function (when its done going through the locks) I juts put

 $scope.loading = false
 $scope.$apply();

This also hides the {{someField}} when the page is loading since I am setting the loading class on load and AngularJS removes it afterwards.

What does localhost:8080 mean?

http uses port 80, and understandably, your internet browser will automatically use that port when you type in an address - unless you specify another port. Now, when running a web server on your computer, you need to access that server somehow - and since port 80 is already busy, you need to use a different port to successfully connect to it. Although any open port is fair game, usually such a server is configured to use port 8080, hence when accessing your server you type in:

http:// (protocol) localhost (your computer) :8080 (port 8080) / (path pointing to the root of the public folder of your server)

PHP Session Destroy on Log Out Button

The folder being password protected has nothing to do with PHP!

The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...

Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess or wherever it is first):

login.php:

<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
    $_SESSION['logged_in'] = true;
    header('Location: /index.php');
}
else
{
    ?>

    <form method="POST">
    Username: <input name="user" type="text"><br>
    Password: <input name="pass" type="text"><br><br>
    <input type="submit" value="submit">
    </form>

    <?php
}

index.php

<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
    ?>

    <p>here is my super-secret content</p>
    <a href='logout.php'>Click here to log out</a>

    <?php
}
else
{
    echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
}

logout.php:

<?php
session_start();
session_destroy();
echo 'You have been logged out. <a href="/">Go back</a>';

Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.

Hope this helps you understand what's going on.

Regex: Specify "space or start of string" and "space or end of string"

You can use any of the following:

\b      #A word break and will work for both spaces and end of lines.
(^|\s)  #the | means or. () is a capturing group. 


/\b(stackoverflow)\b/

Also, if you don't want to include the space in your match, you can use lookbehind/aheads.

(?<=\s|^)         #to look behind the match
(stackoverflow)   #the string you want. () optional
(?=\s|$)          #to look ahead.

What is the difference between DSA and RSA?

With reference to man ssh-keygen, the length of a DSA key is restricted to exactly 1024 bit to remain compliant with NIST's FIPS 186-2. Nonetheless, longer DSA keys are theoretically possible; FIPS 186-3 explicitly allows them. Furthermore, security is no longer guaranteed with 1024 bit long RSA or DSA keys.

In conclusion, a 2048 bit RSA key is currently the best choice.

MORE PRECAUTIONS TO TAKE

Establishing a secure SSH connection entails more than selecting safe encryption key pair technology. In view of Edward Snowden's NSA revelations, one has to be even more vigilant than what previously was deemed sufficient.

To name just one example, using a safe key exchange algorithm is equally important. Here is a nice overview of current best SSH hardening practices.

How to save a list to a file and read it as a list type?

I am using pandas.

import pandas as pd
x = pd.Series([1,2,3,4,5])
x.to_excel('temp.xlsx')
y = list(pd.read_excel('temp.xlsx')[0])
print(y)

Use this if you are anyway importing pandas for other computations.

How to find a hash key containing a matching value

try this:

clients.find{|key,value| value["client_id"] == "2178"}.first

ES6 Class Multiple inheritance

There is no easy way to do multiple class inheritance. I follow the combination of association and inheritance to achieve this kind of behavior.

    class Person {
        constructor(firstname, lastname, age){
            this.firstname = firstname,
            this.lastname = lastname
            this.Age = age
        }

        fullname(){
                return this.firstname +" " + this.lastname;
            } 
    }

    class Organization {
        constructor(orgname){
            this.orgname = orgname;
        }
    }

    class Employee extends Person{
        constructor(firstname, lastname, age,id) {
            super(firstname, lastname, age);
            this.id = id;
        }

    }
    var emp = new Employee("John", "Doe", 33,12345);
    Object.assign(emp, new Organization("Innovate"));
    console.log(emp.id);
    console.log(emp.orgname);
    console.log(emp.fullname());

Hope this is helpful.

Angular2 QuickStart npm start is not working correctly

If you use proxy it may cause this error:

  1. npm config set proxy http://username:pass@proxy:port

  2. npm config set https-proxy http://username:pass@proxy:port

  3. create a file named .typingsrc in your application folder that includes:

    • proxy = (value on step 1)
    • https-proxy = (value on step 1)
  4. run npm cache clean

  5. run npm install
  6. run npm typings install
  7. run npm start

it will work then

How do you install GLUT and OpenGL in Visual Studio 2012?

For an easy and appropriate way of doing this, first download a prepackaged release of freeglut from here. Then read its Readme.txt.

I copied some important parts of that package here:

... Create a folder on your PC which is readable by all users, for example “C:\Program Files\Common Files\MSVC\freeglut\” on a typical Windows system. Copy the “lib\” and “include\” folders from this zip archive to that location ... freeglut DLL can be placed in the same folder as your application...

... Open up the project properties, and select “All Configurations” (this is necessary to ensure our changes are applied for both debug and release builds). Open up the “general” section under “C/C++”, and configure the “include\” folder you created above as an “Additional Include Directory”. If you have more than one GLUT package which contains a “glut.h” file, it’s important to ensure that the freeglut include folder appears above all other GLUT include folders ... Open up the “general” section under “Linker”, and configure the “lib\” folder you created above as an “Additional Library Directory”...

Java - Convert integer to string

This is the method which i used to convert the integer to string.Correct me if i did wrong.

/**
 * @param a
 * @return
 */
private String convertToString(int a) {

    int c;
    char m;
    StringBuilder ans = new StringBuilder();
    // convert the String to int
    while (a > 0) {
        c = a % 10;
        a = a / 10;
        m = (char) ('0' + c);
        ans.append(m);
    }
    return ans.reverse().toString();
}

How do I install jmeter on a Mac?

Once you got the ZIP from the download, extract it locally, and with your finder, go in bin directory.

Then double-click on ApacheJMeter.jar to launch the User Interface of JMeter.

This and the next steps are described in a blog entry.

How to fix Python indentation

Use the reindent.py script that you find in the Tools/scripts/ directory of your Python installation:

Change Python (.py) files to use 4-space indents and no hard tab characters. Also trim excess spaces and tabs from ends of lines, and remove empty lines at the end of files. Also ensure the last line ends with a newline.

Have a look at that script for detailed usage instructions.

Are table names in MySQL case sensitive?

It depends upon lower_case_table_names system variable:

show variables where Variable_name='lower_case_table_names'

There are three possible values for this:

  • 0 - lettercase specified in the CREATE TABLE or CREATE DATABASE statement. Name comparisons are case sensitive.
  • 1 - Table names are stored in lowercase on disk and name comparisons are not case sensitive.
  • 2 - lettercase specified in the CREATE TABLE or CREATE DATABASE statement, but MySQL converts them to lowercase on lookup. Name comparisons are not case sensitive.

Documentation

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

Sometimes dict() is a good choice:

a=dict(zip(['Mon','Tue','Wed','Thu','Fri'], [x for x in range(1, 6)]))

mydict=dict(zip(['mon','tue','wed','thu','fri','sat','sun'],

[random.randint(0,100) for x in range(0,7)]))

center a row using Bootstrap 3

you can use grid system without adding empty columns

<div class="col-xs-2 center-block" style="float:none"> ... </div>

change col-xs-2 to suit your layout.

check preview: http://jsfiddle.net/rashivkp/h4869dja/

Difference between matches() and find() in Java Regex

matches() will only return true if the full string is matched. find() will try to find the next occurrence within the substring that matches the regex. Note the emphasis on "the next". That means, the result of calling find() multiple times might not be the same. In addition, by using find() you can call start() to return the position the substring was matched.

final Matcher subMatcher = Pattern.compile("\\d+").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + subMatcher.matches());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find());
System.out.println("Found: " + subMatcher.find());
System.out.println("Matched: " + subMatcher.matches());

System.out.println("-----------");
final Matcher fullMatcher = Pattern.compile("^\\w+$").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + fullMatcher.find() + " - position " + fullMatcher.start());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());

Will output:

Found: false
Found: true - position 4
Found: true - position 17
Found: true - position 20
Found: false
Found: false
Matched: false
-----------
Found: true - position 0
Found: false
Found: false
Matched: true
Matched: true
Matched: true
Matched: true

So, be careful when calling find() multiple times if the Matcher object was not reset, even when the regex is surrounded with ^ and $ to match the full string.

Twitter Bootstrap and ASP.NET GridView

You need to set useaccessibleheader attribute of the gridview to true and also then also specify a TableSection to be a header after calling the DataBind() method on you GridView object. So if your grid view is mygv

mygv.UseAccessibleHeader = True
mygv.HeaderRow.TableSection = TableRowSection.TableHeader

This should result in a proper formatted grid with thead and tbody tags

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

I ran into this problem as well. The underlying problem is that the ssl library in Python 2.7 versions < 2.7.9 is no longer compatible with the pip mechanism.

If you are running on Windows, and you (like us) can't easily upgrade from an incompatible version of 2.7, FWIW, I found that if you copy the following files from another install of the latest version of Python (e.g. Python 2.7.15) on another machine to your installation:

    Lib\ssl.py
    libs\_ssl.lib
    DLLs\_ssl.dll

it will effectively "upgrade" your SSL layer to one which is supported; we were then be able to use pip again, even to upgrade pip.

numpy matrix vector multiplication

Simplest solution

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

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

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


Other Solutions

Also know there are other options:

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

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

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

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

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

Rarer options for edge cases

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

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

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.

You can check this by running in Windows PowerShell:

> Get-Service ssh-agent

And then check the output of status is not running.

Status   Name               DisplayName
------   ----               -----------
Stopped  ssh-agent          OpenSSH Authentication Agent

Then check that the service has been disabled by running

> Get-Service ssh-agent | Select StartType

StartType
---------
Disabled

I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:

 > Get-Service -Name ssh-agent | Set-Service -StartupType Manual

Alternatively, you can set it through the GUI if you prefer.

services.msc showing the properties of the OpenSSH Agent

Return Bit Value as 1/0 and NOT True/False in SQL Server

Modify your query to generate the output that you want.

Try casting them to int:

select cast(bitFlag as int)

Or, if you like, use case:

select (case when bitFlag = 0 then 0 else 1 end)

Best Free Text Editor Supporting *More Than* 4GB Files?

I found that FAR commander could open large files ( I tried 4.2 GB xml file) And it does not load the entire file in memory and works fast.

support FragmentPagerAdapter holds reference to old fragments

Just so you know...

Adding to the litany of woes with these classes, there is a rather interesting bug that's worth sharing.

I'm using a ViewPager to navigate a tree of items (select an item and the view pager animates scrolling to the right, and the next branch appears, navigate back, and the ViewPager scrolls in the opposite direction to return to the previous node).

The problem arises when I push and pop fragments off the end of the FragmentStatePagerAdapter. It's smart enough to notice that the items change, and smart enough to create and replace a fragment when the item has changed. But not smart enough to discard the fragment state, or smart enough to trim the internally saved fragment states when the adapter size changes. So when you pop an item, and push a new one onto the end, the fragment for the new item gets the saved state of the fragment for the old item, which caused absolute havoc in my code. My fragments carry data that may require a lot of work to refetch from the internet, so not saving state really wasn't an option.

I don't have a clean workaround. I used something like this:

  public void onSaveInstanceState(Bundle outState) {
    IFragmentListener listener = (IFragmentListener)getActivity();
    if (listener!= null)
    {
        if (!listener.isStillInTheAdapter(this.getAdapterItem()))
        {
            return; // return empty state.
        }

    }
    super.onSaveInstanceState(outState);

    // normal saving of state for flips and 
    // paging out of the activity follows
    ....
  }

An imperfect solution because the new fragment instance still gets a savedState Bundle, but at least it doesn't carry stale data.

log4net vs. Nlog

For us, the key difference is in overall perf...

Have a look at Logger.IsDebugEnabled in NLog versus Log4Net, from our tests, NLog has less overhead and that's what we are after (low-latency stuff).

Cheers, Florian

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

iPhone UITextField - Change placeholder text color

Swift 3.0 + Storyboard

In order to change placeholder color in storyboard, create an extension with next code. (feel free to update this code, if you think, it can be clearer and safer).

extension UITextField {
    @IBInspectable var placeholderColor: UIColor {
        get {
            guard let currentAttributedPlaceholderColor = attributedPlaceholder?.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: nil) as? UIColor else { return UIColor.clear }
            return currentAttributedPlaceholderColor
        }
        set {
            guard let currentAttributedString = attributedPlaceholder else { return }
            let attributes = [NSForegroundColorAttributeName : newValue]

            attributedPlaceholder = NSAttributedString(string: currentAttributedString.string, attributes: attributes)
        }
    }
}

enter image description here

Swift 4 version

extension UITextField {
    @IBInspectable var placeholderColor: UIColor {
        get {
            return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
        }
        set {
            guard let attributedPlaceholder = attributedPlaceholder else { return }
            let attributes: [NSAttributedStringKey: UIColor] = [.foregroundColor: newValue]
            self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
        }
    }
}

Swift 5 version

extension UITextField {
    @IBInspectable var placeholderColor: UIColor {
        get {
            return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
        }
        set {
            guard let attributedPlaceholder = attributedPlaceholder else { return }
            let attributes: [NSAttributedString.Key: UIColor] = [.foregroundColor: newValue]
            self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
        }
    }
}

Uncaught TypeError: Cannot read property 'appendChild' of null

For people who have the same issue of querySelector or getElementById that returns the following error:

Uncaught TypeError: Cannot read property 'appendChild' of null

but you have a class name or id in the HTML...

If your script tag is in the head, the JavaScript is loaded before your HTML. You will need to add defer to your script like so:

<script src="script.js" defer></script>

Create an ISO date object in javascript

In node, the Mongo driver will give you an ISO string, not the object. (ex: Mon Nov 24 2014 01:30:34 GMT-0800 (PST)) So, simply convert it to a js Date by: new Date(ISOString);

Insert Data Into Temp Table with Query

SQL Server R2 2008 needs the AS clause as follows:

SELECT * 
INTO #temp
FROM (
    SELECT col1, col2
    FROM table1
) AS x

The query failed without the AS x at the end.


EDIT

It's also needed when using SS2016, had to add as t to the end.

 Select * into #result from (SELECT * FROM  #temp where [id] = @id) as t //<-- as t

how to check which version of nltk, scikit learn installed?

Try this:

$ python -c "import nltk; print nltk.__version__"

preventDefault() on an <a> tag

Alternatively, you could just return false from the click event:

 $('div.toggle').hide();
 $('ul.product-info li a').click(function(event){
  $(this).next('div').slideToggle(200);
+ return false; 
 });

Which would stop the A-Href being triggered.

Note however, for usability reasons, in an ideal world that href should still go somewhere, for the people whom want to open link in new tab ;)

Can you split/explode a field in a MySQL query?

Until now, I wanted to keep those comma separated lists in my SQL db - well aware of all warnings!

I kept thinking that they have benefits over lookup tables (which provide a way to a normalized data base). After some days of refusing, I've seen the light:

  • Using lookup tables is NOT causing more code than those ugly string operations when using comma separated values in one field.
  • The lookup table allows for native number formats and is thus NOT bigger than those csv fields. It is SMALLER though.
  • The involved string operations are slim in high level language code (SQL and PHP), but expensive compared to using arrays of integers.
  • Databases are not meant to be human readable, and it is mostly stupid to try to stick to structures due to their readability / direct editability, as I did.

In short, there is a reason why there is no native SPLIT() function in MySQL.

Polygon Drawing and Getting Coordinates with Google Map API v3

Well, unfortunately it seems that one cannot place custom markers and draw (and obtain coordinates) directly from maps.google.com if one is anonymous/not logged in (as it was possible some years ago, if I recall correctly). Still, thanks to the answers here, I managed to make a combination of examples that has both the Google Places search, and allows drawing via the drawing library, and dumps coordinates upon making a selection of any type of shape (including coordinates for polygon) that can be copypasted; the code is here:

This is how it looks like:

test.png

(The Places markers are handled separately, and can be deleted via the DEL "button" by the search input form element; "curpos" shows the current center [position] and zoom level of the map viewport).

Iterate over object attributes in python

The correct answer to this is that you shouldn't. If you want this type of thing either just use a dict, or you'll need to explicitly add attributes to some container. You can automate that by learning about decorators.

In particular, by the way, method1 in your example is just as good of an attribute.

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

How to find the sum of an array of numbers

This is possible by looping over all items, and adding them on each iteration to a sum-variable.

var array = [1, 2, 3];

for (var i = 0, sum = 0; i < array.length; sum += array[i++]);

JavaScript doesn't know block scoping, so sum will be accesible:

console.log(sum); // => 6

The same as above, however annotated and prepared as a simple function:

function sumArray(array) {
  for (
    var
      index = 0,              // The iterator
      length = array.length,  // Cache the array length
      sum = 0;                // The total amount
      index < length;         // The "for"-loop condition
      sum += array[index++]   // Add number on each iteration
  );
  return sum;
}

Run JavaScript when an element loses focus

How about onblur event :

<input type="text" name="name" value="value" onblur="alert(1);"/>

Find the similarity metric between two strings

I think maybe you are looking for an algorithm describing the distance between strings. Here are some you may refer to:

  1. Hamming distance
  2. Levenshtein distance
  3. Damerau–Levenshtein distance
  4. Jaro–Winkler distance

Where are the Properties.Settings.Default stored?

User-specific settings are saved in the user's Application Data folder for that application. Look for a user.config file.

I don't know what you expected, since users often don't even have write access to the executable directory in the first place.

How to convert rdd object to dataframe in spark

This code works perfectly from Spark 2.x with Scala 2.11

Import necessary classes

import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{DoubleType, StringType, StructField, StructType}

Create SparkSession Object, and Here it's spark

val spark: SparkSession = SparkSession.builder.master("local").getOrCreate
val sc = spark.sparkContext // Just used to create test RDDs

Let's an RDD to make it DataFrame

val rdd = sc.parallelize(
  Seq(
    ("first", Array(2.0, 1.0, 2.1, 5.4)),
    ("test", Array(1.5, 0.5, 0.9, 3.7)),
    ("choose", Array(8.0, 2.9, 9.1, 2.5))
  )
)

Method 1

Using SparkSession.createDataFrame(RDD obj).

val dfWithoutSchema = spark.createDataFrame(rdd)

dfWithoutSchema.show()
+------+--------------------+
|    _1|                  _2|
+------+--------------------+
| first|[2.0, 1.0, 2.1, 5.4]|
|  test|[1.5, 0.5, 0.9, 3.7]|
|choose|[8.0, 2.9, 9.1, 2.5]|
+------+--------------------+

Method 2

Using SparkSession.createDataFrame(RDD obj) and specifying column names.

val dfWithSchema = spark.createDataFrame(rdd).toDF("id", "vals")

dfWithSchema.show()
+------+--------------------+
|    id|                vals|
+------+--------------------+
| first|[2.0, 1.0, 2.1, 5.4]|
|  test|[1.5, 0.5, 0.9, 3.7]|
|choose|[8.0, 2.9, 9.1, 2.5]|
+------+--------------------+

Method 3 (Actual answer to the question)

This way requires the input rdd should be of type RDD[Row].

val rowsRdd: RDD[Row] = sc.parallelize(
  Seq(
    Row("first", 2.0, 7.0),
    Row("second", 3.5, 2.5),
    Row("third", 7.0, 5.9)
  )
)

create the schema

val schema = new StructType()
  .add(StructField("id", StringType, true))
  .add(StructField("val1", DoubleType, true))
  .add(StructField("val2", DoubleType, true))

Now apply both rowsRdd and schema to createDataFrame()

val df = spark.createDataFrame(rowsRdd, schema)

df.show()
+------+----+----+
|    id|val1|val2|
+------+----+----+
| first| 2.0| 7.0|
|second| 3.5| 2.5|
| third| 7.0| 5.9|
+------+----+----+

Use of 'prototype' vs. 'this' in JavaScript?

In most cases they are essentially the same, but the second version saves memory because there is only one instance of the function instead of a separate function for each object.

A reason to use the first form is to access "private members". For example:

var A = function () {
    var private_var = ...;

    this.x = function () {
        return private_var;
    };

    this.setX = function (new_x) {
        private_var = new_x;
    };
};

Because of javascript's scoping rules, private_var is available to the function assigned to this.x, but not outside the object.

ReactJS - .JS vs .JSX

Besides the mentioned fact that JSX tags are not standard javascript, the reason I use .jsx extension is because with it Emmet still works in the editor - you know, that useful plugin that expands html code, for example ul>li into

<ul>
  <li></li>
</ul>

Simplest JQuery validation rules example

The examples contained in this blog post do the trick.

Reset auto increment counter in postgres

Here is the command that you are looking for, assuming your sequence for the product table is product_id_seq:

ALTER SEQUENCE product_id_seq RESTART WITH 1453;

How to convert a string to lower case in Bash?

The are various ways:

POSIX standard

tr

$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all

AWK

$ echo "$a" | awk '{print tolower($0)}'
hi all

Non-POSIX

You may run into portability issues with the following examples:

Bash 4.0

$ echo "${a,,}"
hi all

sed

$ echo "$a" | sed -e 's/\(.*\)/\L\1/'
hi all
# this also works:
$ sed -e 's/\(.*\)/\L\1/' <<< "$a"
hi all

Perl

$ echo "$a" | perl -ne 'print lc'
hi all

Bash

lc(){
    case "$1" in
        [A-Z])
        n=$(printf "%d" "'$1")
        n=$((n+32))
        printf \\$(printf "%o" "$n")
        ;;
        *)
        printf "%s" "$1"
        ;;
    esac
}
word="I Love Bash"
for((i=0;i<${#word};i++))
do
    ch="${word:$i:1}"
    lc "$ch"
done

Note: YMMV on this one. Doesn't work for me (GNU bash version 4.2.46 and 4.0.33 (and same behaviour 2.05b.0 but nocasematch is not implemented)) even with using shopt -u nocasematch;. Unsetting that nocasematch causes [[ "fooBaR" == "FOObar" ]] to match OK BUT inside case weirdly [b-z] are incorrectly matched by [A-Z]. Bash is confused by the double-negative ("unsetting nocasematch")! :-)

Parsing a comma-delimited std::string

Input one number at a time, and check whether the following character is ,. If so, discard it.

#include <vector>
#include <string>
#include <sstream>
#include <iostream>

int main()
{
    std::string str = "1,2,3,4,5,6";
    std::vector<int> vect;

    std::stringstream ss(str);

    for (int i; ss >> i;) {
        vect.push_back(i);    
        if (ss.peek() == ',')
            ss.ignore();
    }

    for (std::size_t i = 0; i < vect.size(); i++)
        std::cout << vect[i] << std::endl;
}

How to asynchronously call a method in Java

Java 8 introduced CompletableFuture available in package java.util.concurrent.CompletableFuture, can be used to make a asynch call :

CompletableFuture.runAsync(() -> {
    // method call or code to be asynch.
});

Find the version of an installed npm package

If you are brave enough (and have node installed), you can always do something like:

echo "console.log(require('./package.json').version);" | node

This will print the version of the current package. You can also modify it to go insane, like this:

echo "eval('var result='+require('child_process').execSync('npm version',{encoding:'utf8'})); console.log(result.WHATEVER_PACKAGE_NAME);" | node

That will print the version of WHATEVER_PACKAGE_NAME package, that is seen by npm version.

TypeScript Objects as Dictionary types as in C#

In addition to using an map-like object, there has been an actual Map object for some time now, which is available in TypeScript when compiling to ES6, or when using a polyfill with the ES6 type-definitions:

let people = new Map<string, Person>();

It supports the same functionality as Object, and more, with a slightly different syntax:

// Adding an item (a key-value pair):
people.set("John", { firstName: "John", lastName: "Doe" });

// Checking for the presence of a key:
people.has("John"); // true

// Retrieving a value by a key:
people.get("John").lastName; // "Doe"

// Deleting an item by a key:
people.delete("John");

This alone has several advantages over using a map-like object, such as:

  • Support for non-string based keys, e.g. numbers or objects, neither of which are supported by Object (no, Object does not support numbers, it converts them to strings)
  • Less room for errors when not using --noImplicitAny, as a Map always has a key type and a value type, whereas an object might not have an index-signature
  • The functionality of adding/removing items (key-value pairs) is optimized for the task, unlike creating properties on an Object

Additionally, a Map object provides a more powerful and elegant API for common tasks, most of which are not available through simple Objects without hacking together helper functions (although some of these require a full ES6 iterator/iterable polyfill for ES5 targets or below):

// Iterate over Map entries:
people.forEach((person, key) => ...);

// Clear the Map:
people.clear();

// Get Map size:
people.size;

// Extract keys into array (in insertion order):
let keys = Array.from(people.keys());

// Extract values into array (in insertion order):
let values = Array.from(people.values());

Convert JavaScript String to be all lower case?

toLocaleUpperCase() or lower case functions don't behave like they should do.

For example in my system, Safari 4, Chrome 4 Beta, Firefox 3.5.x it converts strings with Turkish characters incorrectly.

The browsers respond to navigator.language as "en-US", "tr", "en-US" respectively.

But there is no way to get user's Accept-Lang setting in the browser as far as I could find.

Only Chrome gives me trouble although I have configured every browser as tr-TR locale preferred.

I think these settings only affect HTTP header, but we can't access to these settings via JS.

In the Mozilla documentation it says "The characters within a string are converted to ... while respecting the current locale.

For most languages, this will return the same as ...".

I think it's valid for Turkish, it doesn't differ it's configured as en or tr.

In Turkish it should convert "DINÇ" to "dinç" and "DINÇ" to "dinç" or vice-versa.

How to repeat a char using printf?

There is no such thing. You'll have to either write a loop using printf or puts, or write a function that copies the string count times into a new string.

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

I was facing with the same issue and tried everything restarting, packages get, repair everything, But none of these solution worked. The only thing which worked was to set the encoding of the packages file giving error to UTF-8.

PS: I faced this on Android studio

Hope this would help someone.

How to convert a boolean array to an int array

I know you asked for non-looping solutions, but the only solutions I can come up with probably loop internally anyway:

map(int,y)

or:

[i*1 for i in y]

or:

import numpy
y=numpy.array(y)
y*1

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

The accepted answer is through but there is official explanation on this:

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Using themes), and that it knows which Servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.

Cited from Spring web framework reference

By the way servlet and root context are both webApplicationContext:

Typical context hierarchy in Spring Web MVC

Common MySQL fields and their appropriate data types

Someone's going to post a much better answer than this, but just wanted to make the point that personally I would never store a phone number in any kind of integer field, mainly because:

  1. You don't need to do any kind of arithmetic with it, and
  2. Sooner or later someone's going to try to (do something like) put brackets around their area code.

In general though, I seem to almost exclusively use:

  • INT(11) for anything that is either an ID or references another ID
  • DATETIME for time stamps
  • VARCHAR(255) for anything guaranteed to be under 255 characters (page titles, names, etc)
  • TEXT for pretty much everything else.

Of course there are exceptions, but I find that covers most eventualities.

Rails: How can I rename a database column in a Ruby on Rails migration?

Manually we can use the below method:

We can edit the migration manually like:

  • Open app/db/migrate/xxxxxxxxx_migration_file.rb

  • Update hased_password to hashed_password

  • Run the below command

    $> rake db:migrate:down VERSION=xxxxxxxxx
    

Then it will remove your migration:

$> rake db:migrate:up VERSION=xxxxxxxxx

It will add your migration with the updated change.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

I ran into the same error. My web app was pointed towards report viewer version 10.0 however if 11.0 is installed it adds a redirect in the 10.0 .dll to 11.0. This became an issue when 11.0 was uninstalled as this does not correct the redirect in the 10.0 .dll. The fix in my case was to simply uninstall and reinstall 10.0.

How to draw circle in html page?

  • No width and height requirement (specify just whichever you prefer)
  • No SVG, canvas or Unicode

_x000D_
_x000D_
.circle {
    background: green;
    border-radius: 50%;
    width: 1rem;
    aspect-ratio: 1/1;
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

Borwser support:

  • Chrome/Edge 88+
  • Firefox 83+ behind a flag

How to convert a std::string to const char* or char*?

Use the .c_str() method for const char *.

You can use &mystring[0] to get a char * pointer, but there are a couple of gotcha's: you won't necessarily get a zero terminated string, and you won't be able to change the string's size. You especially have to be careful not to add characters past the end of the string or you'll get a buffer overrun (and probable crash).

There was no guarantee that all of the characters would be part of the same contiguous buffer until C++11, but in practice all known implementations of std::string worked that way anyway; see Does “&s[0]” point to contiguous characters in a std::string?.

Note that many string member functions will reallocate the internal buffer and invalidate any pointers you might have saved. Best to use them immediately and then discard.

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt

OR

tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt

OR

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

Loading another html page from javascript

You can use the following code :

<!DOCTYPE html>
<html>
    <body onLoad="triggerJS();">

    <script>
        function triggerJS(){
        location.replace("http://www.google.com");
        /*
        location.assign("New_WebSite_Url");
        //Use assign() instead of replace if you want to have the first page in the history (i.e if you want the user to be able to navigate back when New_WebSite_Url is loaded)
        */
        }
    </script>

    </body>
</html>

Flutter - The method was called on null

As stated in the above answers, it's always a good practice to initialize the variables, but if you have something which you don't know what value should it takes, and you want to leave it uninitialized so you have to make sure that you are updating it before using it.

For example: Assume we have double _bmi; and you don't know what value should it takes, so you can leave it as it is, but before using it, you have to update its value first like calling a function that calculating BMI like follows:

String calculateBMI (){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);}

or whatever, what I mean is, you can leave the variable as it is, but before using it make sure you have initialized it using whatever the method you are using.

Cannot run Eclipse; JVM terminated. Exit code=13

Make sure the Eclipse and the Java that you are using are both either 32-bit or 64-bit.

You cannot run 64-bit eclipse with 32-bit JRE.

java -version

Java HotSpot(TM) 64-Bit Server VM

The 32 bit version JRE will not have 64-Bit in it.

Prevent row names to be written to file when using write.csv

write.csv(t, "t.csv", row.names=FALSE)

From ?write.csv:

row.names: either a logical value indicating whether the row names of
          ‘x’ are to be written along with ‘x’, or a character vector
          of row names to be written.

Checking for Undefined In React

In case you also need to check if nextProps.blog is not undefined ; you can do that in a single if statement, like this:

if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
    //
}

And, when an undefined , empty or null value is not expected; you can make it more concise:

if (nextProps.blog && nextProps.blog.content) {
    //
}

Disable webkit's spin buttons on input type="number"?

I discovered that there is a second portion of the answer to this.

The first portion helped me, but I still had a space to the right of my type=number input. I had zeroed out the margin on the input, but apparently I had to zero out the margin on the spinner as well.

This fixed it:

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

The problem is that the CASE statement won't work in the way you're trying to use it. You can only use it to switch the value of one field in a query. If I understand what you're trying to do, you might need this:

SELECT 
   ActivityID,
   FieldName = CASE 
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END,
   FieldName2 = CASE
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END

Change hover color on a button with Bootstrap customization

The color for your buttons comes from the btn-x classes (e.g., btn-primary, btn-success), so if you want to manually change the colors by writing your own custom css rules, you'll need to change:

/*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/
.btn-primary {
    color: #fff;
    background-color: #0495c9;
    border-color: #357ebd; /*set the color you want here*/
}
.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
    color: #fff;
    background-color: #00b3db;
    border-color: #285e8e; /*set the color you want here*/
}

Remove white space above and below large text in an inline-block element

The best way is to use display:

inline-block; 

and

overflow: hidden;

How do I redirect with JavaScript?

You may need to explain your question a little more.

When you say "redirect", to most people that suggest changing the location of the HTML page:

window.location = url;

When you say "redirect to function" - it doesn't really make sense. You can call a function or you can redirect to another page.
You can even redirect and have a function called when the new page loads.

Moment JS - check if a date is today or in the future

// Returns true if it is today or false if it's not
moment(SpecialToDate).isSame(moment(), 'day');

Parse JSON file using GSON

I'm using gson 2.2.3

public class Main {

/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

    JsonReader jsonReader = new JsonReader(new FileReader("jsonFile.json"));

    jsonReader.beginObject();

    while (jsonReader.hasNext()) {

    String name = jsonReader.nextName();
        if (name.equals("descriptor")) {
             readApp(jsonReader);

        }
    }

   jsonReader.endObject();
   jsonReader.close();

}

public static void readApp(JsonReader jsonReader) throws IOException{
    jsonReader.beginObject();
     while (jsonReader.hasNext()) {
         String name = jsonReader.nextName();
         System.out.println(name);
         if (name.contains("app")){
             jsonReader.beginObject();
             while (jsonReader.hasNext()) {
                 String n = jsonReader.nextName();
                 if (n.equals("name")){
                     System.out.println(jsonReader.nextString());
                 }
                 if (n.equals("age")){
                     System.out.println(jsonReader.nextInt());
                 }
                 if (n.equals("messages")){
                     jsonReader.beginArray();
                     while  (jsonReader.hasNext()) {
                          System.out.println(jsonReader.nextString());
                     }
                     jsonReader.endArray();
                 }
             }
             jsonReader.endObject();
         }

     }
     jsonReader.endObject();
}
}

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

This demo is returning correctly for me in Chrome 14, FF3 and FF5 (with Firebug):

var mytextvalue = document.getElementById("mytext").value;
console.log(mytextvalue == ''); // true
console.log(mytextvalue == null); // false

and changing the console.log to alert, I still get the desired output in IE6.

Message Queue vs. Web Services?

There's been a fair amount of recent research in considering how REST HTTP calls could replace the message queue concept.

If you introduce the concept of a process and a task as a resource, the need for middle messaging layer starts to evaporate.

Ex:

POST /task/name
    - Returns a 202 accepted status immediately
    - Returns a resource url for the created task: /task/name/X
    - Returns a resource url for the started process: /process/Y

GET /process/Y
    - Returns status of ongoing process

A task can have multiple steps for initialization, and a process can return status when polled or POST to a callback URL when complete.

This is dead simple, and becomes quite powerful when you realize that you can now subscribe to an rss/atom feed of all running processes and tasks without any middle layer. Any queuing system is going to require some sort of web front end anyway, and this concept has it built in without another layer of custom code.

Your resources exist until you delete them, which means you can view historical information long after the process and task complete.

You have built in service discovery, even for a task that has multiple steps, without any extra complicated protocols.

GET /task/name
    - returns form with required fields

POST (URL provided form's "action" attribute)

Your service discovery is an HTML form - a universal and human readable format.

The entire flow can be used programmatically or by a human, using universally accepted tools. It's a client driven, and therefore RESTful. Every tool created for the web can drive your business processes. You still have alternate message channels by POSTing asynchronously to a separate array of log servers.

After you consider it for a while, you sit back and start to realize that REST may just eliminate the need for a messaging queue and an ESB altogether.

http://www.infoq.com/presentations/BPM-with-REST

Delegation: EventEmitter or Observable in Angular

Breaking news: I've added another answer that uses an Observable rather than an EventEmitter. I recommend that answer over this one. And actually, using an EventEmitter in a service is bad practice.


Original answer: (don't do this)

Put the EventEmitter into a service, which allows the ObservingComponent to directly subscribe (and unsubscribe) to the event:

import {EventEmitter} from 'angular2/core';

export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emit(number) {
    this.navchange.emit(number);
  }
  subscribe(component, callback) {
    // set 'this' to component when callback is called
    return this.navchange.subscribe(data => call.callback(component, data));
  }
}

@Component({
  selector: 'obs-comp',
  template: 'obs component, index: {{index}}'
})
export class ObservingComponent {
  item: number;
  subscription: any;
  constructor(private navService:NavService) {
   this.subscription = this.navService.subscribe(this, this.selectedNavItem);
  }
  selectedNavItem(item: number) {
    console.log('item index changed!', item);
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">item 1 (click me)</div>
  `,
})
export class Navigation {
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emit(item);
  }
}

If you try the Plunker, there are a few things I don't like about this approach:

  • ObservingComponent needs to unsubscribe when it is destroyed
  • we have to pass the component to subscribe() so that the proper this is set when the callback is called

Update: An alternative that solves the 2nd bullet is to have the ObservingComponent directly subscribe to the navchange EventEmitter property:

constructor(private navService:NavService) {
   this.subscription = this.navService.navchange.subscribe(data =>
     this.selectedNavItem(data));
}

If we subscribe directly, then we wouldn't need the subscribe() method on the NavService.

To make the NavService slightly more encapsulated, you could add a getNavChangeEmitter() method and use that:

getNavChangeEmitter() { return this.navchange; }  // in NavService

constructor(private navService:NavService) {  // in ObservingComponent
   this.subscription = this.navService.getNavChangeEmitter().subscribe(data =>
     this.selectedNavItem(data));
}

Can't accept license agreement Android SDK Platform 24

If you want to avoid creating the licence folder manually, and in case your sdk is not in the "Users/User" you can go to android studio => Configure => SDK Manager and install any component, i installed the google usb driver from the sdk tools, it automatically generated the license in the correct location.

replacing text in a file with Python

I might consider using a dict and re.sub for something like this:

import re
repldict = {'zero':'0', 'one':'1' ,'temp':'bob','garage':'nothing'}
def replfunc(match):
    return repldict[match.group(0)]

regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open('file.txt') as fin, open('fout.txt','w') as fout:
    for line in fin:
        fout.write(regex.sub(replfunc,line))

This has a slight advantage to replace in that it is a bit more robust to overlapping matches.

Get user input from textarea

Here is full component example

import { Component } from '@angular/core';

@Component({
  selector: 'app-text-box',
  template: `
        <h1>Text ({{textValue}})</h1>
        <input #textbox type="text" [(ngModel)]="textValue" required>
        <button (click)="logText(textbox.value)">Update Log</button>
        <button (click)="textValue=''">Clear</button>

        <h2>Template Reference Variable</h2>
        Type: '{{textbox.type}}', required: '{{textbox.hasAttribute('required')}}',
        upper: '{{textbox.value.toUpperCase()}}'

        <h2>Log <button (click)="log=''">Clear</button></h2>
        <pre>{{log}}</pre>`
})
export class TextComponent {

  textValue = 'initial value';
  log = '';

  logText(value: string): void {
    this.log += `Text changed to '${value}'\n`;
  }
}

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

Android Error - Open Failed ENOENT

Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt"); to open a stream to this file.

What is this: [Ljava.lang.Object;?

[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

The naming scheme is documented in Class.getName():

If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).

If this class object represents a primitive type or void, then the name returned is the Java language keyword corresponding to the primitive type or void.

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

Element Type        Encoding
boolean             Z
byte                B
char                C
double              D
float               F
int                 I
long                J
short               S 
class or interface  Lclassname;

Yours is the last on that list. Here are some examples:

// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx

The reason why the toString() method on arrays returns String in this format is because arrays do not @Override the method inherited from Object, which is specified as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Note: you can not rely on the toString() of any arbitrary object to follow the above specification, since they can (and usually do) @Override it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass() on it (a final method inherited from Object) and then reflecting on the returned Class object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).


On a more "useful" toString for arrays

java.util.Arrays provides toString overloads for primitive arrays and Object[]. There is also deepToString that you may want to use for nested arrays.

Here are some examples:

int[] nums = { 1, 2, 3 };

System.out.println(nums);
// [I@xxxxx

System.out.println(Arrays.toString(nums));
// [1, 2, 3]

int[][] table = {
        { 1, },
        { 2, 3, },
        { 4, 5, 6, },
};

System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]

System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]

There are also Arrays.equals and Arrays.deepEquals that perform array equality comparison by their elements, among many other array-related utility methods.

Related questions

Replace only some groups with Regex

go through the below coding to get the separate group replacement.

new_bib = Regex.Replace(new_bib, @"(?s)(\\bibitem\[[^\]]+\]\{" + pat4 + @"\})[\s\n\v]*([\\\{\}a-zA-Z\.\s\,\;\\\#\\\$\\\%\\\&\*\@\\\!\\\^+\-\\\=\\\~\\\:\\\" + dblqt + @"\\\;\\\`\\\']{20,70})", delegate(Match mts)
                    {
                           var fg = mts.Groups[0].Value.ToString(); 
                           var fs = mts.Groups[1].Value.ToString();
                           var fss = mts.Groups[2].Value.ToString();
                               fss = Regex.Replace(fss, @"[\\\{\}\\\#\\\$\\\%\\\&\*\@\\\!\\\^+\-\\\=\\\~\\\:\\\" + dblqt + @"\\\;\\\`\\\']+", "");
                           return "<augroup>" + fss + "</augroup>" + fs;
                    }, RegexOptions.IgnoreCase);

Can you force Visual Studio to always run as an Administrator in Windows 8?

  1. On Windows 8 Start Menu select All Apps
  2. Right click on Visual Studio 2010 Icon
  3. Select Open File Location
  4. Right click on Visual Studio 2010 shortcut icon
  5. Click Advanced button
  6. Check the Run as Administrator checkbox
  7. Click OK

How to find and replace all occurrences of a string recursively in a directory tree?

For me works the next command:

find /path/to/dir -name "file.txt" | xargs sed -i 's/string_to_replace/new_string/g'

if string contains slash 'path/to/dir' it can be replace with another character to separate, like '@' instead '/'.

For example: 's@string/to/replace@new/string@g'

Hide/Show Column in an HTML Table

Here's a little more fully featured answer that provides some user interaction on a per column basis. If this is going to be a dynamic experience, there needs to be a clickable toggle on each column that indicates the ability to hide the column, and then a way to restore previously hidden columns.

That would look something like this in JavaScript:

$('.hide-column').click(function(e){
  var $btn = $(this);
  var $cell = $btn.closest('th,td')
  var $table = $btn.closest('table')

  // get cell location - https://stackoverflow.com/a/4999018/1366033
  var cellIndex = $cell[0].cellIndex + 1;

  $table.find(".show-column-footer").show()
  $table.find("tbody tr, thead tr")
        .children(":nth-child("+cellIndex+")")
        .hide()
})

$(".show-column-footer").click(function(e) {
    var $table = $(this).closest('table')
    $table.find(".show-column-footer").hide()
    $table.find("th, td").show()

})

To support this, we'll add some markup to the table. In each column header, we can add something like this to provide a visual indicator of something clickable

<button class="pull-right btn btn-default btn-condensed hide-column" 
            data-toggle="tooltip" data-placement="bottom" title="Hide Column">
    <i class="fa fa-eye-slash"></i>  
</button>

We'll allow the user to restore columns via a link in the table footer. If it's not persistent by default, then toggling it on dynamically in the header could jostle around the table, but you can really put it anywhere you'd like:

<tfoot class="show-column-footer">
   <tr>
    <th colspan="4"><a class="show-column" href="#">Some columns hidden - click to show all</a></th>
  </tr>
</tfoot>

That's the basic functionality. Here's a demo below with a couple more things fleshed out. You can also add a tooltip to the button to help clarify its purpose, style the button a little more organically to a table header, and collapse the column width in order to add some (somewhat wonky) css animations to make the transition a little less jumpy.

Demo Screengrab

Working Demo in jsFiddle & Stack Snippets:

_x000D_
_x000D_
$(function() {_x000D_
  // on init_x000D_
  $(".table-hideable .hide-col").each(HideColumnIndex);_x000D_
_x000D_
  // on click_x000D_
  $('.hide-column').click(HideColumnIndex)_x000D_
_x000D_
  function HideColumnIndex() {_x000D_
    var $el = $(this);_x000D_
    var $cell = $el.closest('th,td')_x000D_
    var $table = $cell.closest('table')_x000D_
_x000D_
    // get cell location - https://stackoverflow.com/a/4999018/1366033_x000D_
    var colIndex = $cell[0].cellIndex + 1;_x000D_
_x000D_
    // find and hide col index_x000D_
    $table.find("tbody tr, thead tr")_x000D_
      .children(":nth-child(" + colIndex + ")")_x000D_
      .addClass('hide-col');_x000D_
      _x000D_
    // show restore footer_x000D_
    $table.find(".footer-restore-columns").show()_x000D_
  }_x000D_
_x000D_
  // restore columns footer_x000D_
  $(".restore-columns").click(function(e) {_x000D_
    var $table = $(this).closest('table')_x000D_
    $table.find(".footer-restore-columns").hide()_x000D_
    $table.find("th, td")_x000D_
      .removeClass('hide-col');_x000D_
_x000D_
  })_x000D_
_x000D_
  $('[data-toggle="tooltip"]').tooltip({_x000D_
    trigger: 'hover'_x000D_
  })_x000D_
_x000D_
})
_x000D_
body {_x000D_
  padding: 15px;_x000D_
}_x000D_
_x000D_
.table-hideable td,_x000D_
.table-hideable th {_x000D_
  width: auto;_x000D_
  transition: width .5s, margin .5s;_x000D_
}_x000D_
_x000D_
.btn-condensed.btn-condensed {_x000D_
  padding: 0 5px;_x000D_
  box-shadow: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* use class to have a little animation */_x000D_
.hide-col {_x000D_
  width: 0px !important;_x000D_
  height: 0px !important;_x000D_
  display: block !important;_x000D_
  overflow: hidden !important;_x000D_
  margin: 0 !important;_x000D_
  padding: 0 !important;_x000D_
  border: none !important;_x000D_
}
_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css">_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/paper/bootstrap.min.css">_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<table class="table table-condensed table-hover table-bordered table-striped table-hideable">_x000D_
_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>_x000D_
        Controller_x000D_
        <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column">_x000D_
          <i class="fa fa-eye-slash"></i>  _x000D_
        </button>_x000D_
      </th>_x000D_
      <th class="hide-col">_x000D_
        Action_x000D_
        <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column">_x000D_
          <i class="fa fa-eye-slash"></i>  _x000D_
        </button>_x000D_
      </th>_x000D_
      <th>_x000D_
        Type_x000D_
        <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column">_x000D_
          <i class="fa fa-eye-slash"></i>  _x000D_
        </button>_x000D_
      </th>_x000D_
      <th>_x000D_
        Attributes_x000D_
        <button class="pull-right btn btn-default btn-condensed hide-column" data-toggle="tooltip" data-placement="bottom" title="Hide Column">_x000D_
          <i class="fa fa-eye-slash"></i>  _x000D_
        </button>_x000D_
      </th>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
_x000D_
    <tr>_x000D_
      <td>Home</td>_x000D_
      <td>Index</td>_x000D_
      <td>ActionResult</td>_x000D_
      <td>Authorize</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
      <td>Client</td>_x000D_
      <td>Index</td>_x000D_
      <td>ActionResult</td>_x000D_
      <td>Authorize</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
      <td>Client</td>_x000D_
      <td>Edit</td>_x000D_
      <td>ActionResult</td>_x000D_
      <td>Authorize</td>_x000D_
    </tr>_x000D_
_x000D_
  </tbody>_x000D_
  <tfoot class="footer-restore-columns">_x000D_
    <tr>_x000D_
      <th colspan="4"><a class="restore-columns" href="#">Some columns hidden - click to show all</a></th>_x000D_
    </tr>_x000D_
  </tfoot>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Pass multiple optional parameters to a C# function

1.You can make overload functions.

SomeF(strin s){}   
SomeF(string s, string s2){}    
SomeF(string s1, string s2, string s3){}   

More info: http://csharpindepth.com/Articles/General/Overloading.aspx

2.or you may create one function with params

SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like

More info: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

3.or you can use simple array

Main(string[] args){}

What does the NS prefix mean?

From Apple's developer docs:

Historical Note: If you’re wondering why so many of the classes you encounter have an NS prefix, it’s because of the past history of Cocoa and Cocoa Touch. Cocoa began life as the collected frameworks used to build apps for the NeXTStep operating system. When Apple purchased NeXT back in 1996, much of NeXTStep was incorporated into OS X, including the existing class names. Cocoa Touch was introduced as the iOS equivalent of Cocoa; some classes are available in both Cocoa and Cocoa Touch, though there are also a large number of classes unique to each platform. Two-letter prefixes like NS and UI (for User Interface elements on iOS) are reserved for use by Apple.

Source: Programming with Objective-C

Flutter : Vertically center column

Try this one. It centers vertically and horizontally.

Center(
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: children,
  ),
)

Round a floating-point number down to the nearest integer?

a lot of people say to use int(x), and this works ok for most cases, but there is a little problem. If OP's result is:

x = 1.9999999999999999

it will round to

x = 2

after the 16th 9 it will round. This is not a big deal if you are sure you will never come across such thing. But it's something to keep in mind.

shorthand If Statements: C#

Use the ternary operator

direction == 1 ? dosomething () : dosomethingelse ();

How can I install a local gem?

Yup, when you do gem install, it will search the current directory first, so if your .gem file is there, it will pick it up. I found it on the gem reference, which you may find handy as well:

gem install will install the named gem. It will attempt a local installation (i.e. a .gem file in the current directory), and if that fails, it will attempt to download and install the most recent version of the gem you want.

How to define a List bean in Spring?

And this is how to inject set in some property in Spring:

<bean id="process"
      class="biz.bsoft.processing">
    <property name="stages">
        <set value-type="biz.bsoft.AbstractStage">
            <ref bean="stageReady"/>
            <ref bean="stageSteady"/>
            <ref bean="stageGo"/>
        </set>
    </property>
</bean>

Check if string begins with something?

Use stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}

Does MySQL ignore null values on unique constraints?

I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL values while using UNIQUE?" Or "How to only allow one UNIQUE NULL value?"

The question has already been answered, yes you can have duplicate NULL values while using the UNIQUE index.

Since I stumbled upon this answer while searching for "how to allow one UNIQUE NULL value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...

In MySQL you can not have one UNIQUE NULL value, however you can have one UNIQUE empty value by inserting with the value of an empty string.

Warning: Numeric and types other than string may default to 0 or another default value.

How do I set up Android Studio to work completely offline?

OK guys I finally overcame this problem. Here is the solution:

  1. Download gradle-1.6-bin.zip for offline use.

  2. Paste it in the C:\Users\username\.gradle directory.

  3. Open Android Studio and click on the "Create New Project" option and you will not get this error any more while offline.

    You might get some other errors like this:

    Don't worry, just ignore it. Your project has been created.

  4. So now click on "Import Project" and go to the path C:\Users\username\AndroidStudioProjects and open your project and you are done.

Angular-Material DateTime Picker Component?

Angular Material 10 now includes a new date range picker.

To use the new date range picker, you can use the mat-date-range-input and mat-date-range-picker components.

Example

HTML

<mat-form-field>
  <mat-label>Enter a date range</mat-label>
  <mat-date-range-input [rangePicker]="picker">
    <input matStartDate matInput placeholder="Start date">
    <input matEndDate matInput placeholder="End date">
  </mat-date-range-input>
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>

You can read and learn more about this in their official documentation.

Unfortunately, they still haven't build a timepicker on this release.

NSAttributedString add text alignment

In swift 4:

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

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

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


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

Mod of negative number is melting my brain

Adding some understanding.

By Euclidean definition the mod result must be always positive.

Ex:

 int n = 5;
 int x = -3;

 int mod(int n, int x)
 {
     return ((n%x)+x)%x;
 }

Output:

 -1

Add event handler for body.onload by javascript within <body> part

body.addEventListener("load", init(), false);

That init() is saying run this function now and assign whatever it returns to the load event.

What you want is to assign the reference to the function, not the result. So you need to drop the ().

body.addEventListener("load", init, false);

Also you should be using window.onload and not body.onload

addEventListener is supported in most browsers except IE 8.

Java, List only subdirectories from a directory, not files

ArrayList<File> directories = new ArrayList<File>(
    Arrays.asList(
        new File("your/path/").listFiles(File::isDirectory)
    )
);

jQuery duplicate DIV into another DIV

You'll want to use the clone() method in order to get a deep copy of the element:

$(function(){
  var $button = $('.button').clone();
  $('.package').html($button);
});

Full demo: http://jsfiddle.net/3rXjx/

From the jQuery docs:

The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes. When used in conjunction with one of the insertion methods, .clone() is a convenient way to duplicate elements on a page.

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

Also ensure that your controllers are defined within script tags toward the bottom of your index.html just before the closing tag for body.

 <!-- build:js({.tmp,app}) scripts/scripts.js -->
    <script src="scripts/app.js"></script>
    <script src="scripts/controllers/main.js"></script>
    <script src="scripts/controllers/Administration.js"></script>
    <script src="scripts/controllers/Leaderboard.js"></script>
    <script src="scripts/controllers/Login.js"></script>
    <script src="scripts/controllers/registration.js"></script>

provided everything is spelled "correctly" (the same) on your specific.html, specific.js and app.js pages this should resolve your issue.

Fastest way to convert JavaScript NodeList to Array?

Check out this blog post here that talks about the same thing. From what I gather, the extra time might have to do with walking up the scope chain.

Create instance of generic type in Java?

package org.foo.com;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Basically the same answer as noah's.
 */
public class Home<E>
{

    @SuppressWarnings ("unchecked")
    public Class<E> getTypeParameterClass()
    {
        Type type = getClass().getGenericSuperclass();
        ParameterizedType paramType = (ParameterizedType) type;
        return (Class<E>) paramType.getActualTypeArguments()[0];
    }

    private static class StringHome extends Home<String>
    {
    }

    private static class StringBuilderHome extends Home<StringBuilder>
    {
    }

    private static class StringBufferHome extends Home<StringBuffer>
    {
    }   

    /**
     * This prints "String", "StringBuilder" and "StringBuffer"
     */
    public static void main(String[] args) throws InstantiationException, IllegalAccessException
    {
        Object object0 = new StringHome().getTypeParameterClass().newInstance();
        Object object1 = new StringBuilderHome().getTypeParameterClass().newInstance();
        Object object2 = new StringBufferHome().getTypeParameterClass().newInstance();
        System.out.println(object0.getClass().getSimpleName());
        System.out.println(object1.getClass().getSimpleName());
        System.out.println(object2.getClass().getSimpleName());
    }

}

How to run Spring Boot web application in Eclipse itself?

First Method:(if STS is available in eclipse)
1.right click on project->run as ->Spring Boot app.

Second Method:
1.right click on project->run as ->run configuration
2. set base directory of you project ie.${workspace_loc:/first}
3. set goal spring-boot:run
4. Run

Third Method:
1.Right click on @SpringBootApplication annotation class ->Run as ->Java Application

Laravel 5.5 ajax call 419 (unknown status)

2019 Laravel Update, Never thought i will post this but for those developers like me using the browser fetch api on Laravel 5.8 and above. You have to pass your token via the headers parameter.

var _token = "{{ csrf_token }}";
fetch("{{url('add/new/comment')}}", {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': _token,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(name, email, message, article_id)
            }).then(r => {
                return r.json();
            }).then(results => {}).catch(err => console.log(err));

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

Serializing class instance to JSON

An approach which I have been using in my Flask app to serialize Class instance to JSON response.

Github project for reference

from json import JSONEncoder
import json
from typing import List

class ResponseEncoder(JSONEncoder):
    def default(self, o):
        return o.__dict__

class ListResponse:
    def __init__(self, data: List):
        self.data = data
        self.count = len(data)

class A:
    def __init__(self, message: str):
        self.message = message

class B:
    def __init__(self, record: A):
        self.record = record

class C:
    def __init__(self, data: B):
        self.data = data

Now create an instance of A, B, C then encode.

data_a = A('Test Data')
data_b = B(data_a)
data_c = C(data_b)

response = ResponseEncoder().encode(data_c)
json_response = json.loads(response)

Output

{
    "data": {
        "record": {
            "message": "Test Data"
        }
    }
}

For list type response

records = ['One', 'Two', 'Three']
list_response = ListResponse(records)
response = ResponseEncoder().encode(list_response)
json_response = json.loads(response)

Output

{
    "data": [
        "One",
        "Two",
        "Three"
    ],
    "count": 3
}

Dismissing a Presented View Controller

I think Apple are covering their backs a little here for a potentially kludgy piece of API.

  [self dismissViewControllerAnimated:NO completion:nil]

Is actually a bit of a fiddle. Although you can - legitimately - call this on the presented view controller, all it does is forward the message on to the presenting view controller. If you want to do anything over and above just dismissing the VC, you will need to know this, and you need to treat it much the same way as a delegate method - as that's pretty much what it is, a baked-in somewhat inflexible delegate method.

Perhaps they've come across loads of bad code by people not really understanding how this is put together, hence their caution.

But of course, if all you need to do is dismiss the thing, go ahead.

My own approach is a compromise, at least it reminds me what is going on:

  [[self presentingViewController] dismissViewControllerAnimated:NO completion:nil]

[Swift]

  self.presentingViewController?.dismiss(animated: false, completion:nil)

Where is Ubuntu storing installed programs?

for some applications, for example google chrome, they store it under /opt. you can follow the above instruction using dpkg -l to get the correct naming then dpkg -L to get the detail.

hope it helps

How To Change DataType of a DataColumn in a DataTable?

Consider also altering the return type:

select cast(columnName as int) columnName from table

"Undefined reference to" template class constructor

This link explains where you're going wrong:

[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?

Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.

This offers another solution:

How can I avoid linker errors with my template functions?

However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.

HTML input fields does not get focus when clicked

I had this issue using Bootstrap + contact form 7. I for some reason I put the label as the container of the form and that was the issue for not being selectable on mobile.

<label>
    <contact form>...</contact form>
</label>

Seemed to break all inputs except the first input and the submit.

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

I had the same issue on Windows 7. The cause was, that I had been connected to VPN using Cisco AnyConnect Secure Mobility Client.

Call a function with argument list in python

You need to use arguments unpacking..

def wrapper(func, *args):
    func(*args)

def func1(x):
    print(x)

def func2(x, y, z):
    print x+y+z

wrapper(func1, 1)
wrapper(func2, 1, 2, 3)

PL/SQL, how to escape single quote in a string?

Here's a blog post that should help with escaping ticks in strings.

Here's the simplest method from said post:

The most simple and most used way is to use a single quotation mark with two single >quotation marks in both sides.

SELECT 'test single quote''' from dual;

The output of the above statement would be:

test single quote'

Simply stating you require an additional single quote character to print a single quote >character. That is if you put two single quote characters Oracle will print one. The first >one acts like an escape character.

This is the simplest way to print single quotation marks in Oracle. But it will get >complex when you have to print a set of quotation marks instead of just one. In this >situation the following method works fine. But it requires some more typing labour.

How to express a One-To-Many relationship in Django

To be more clear - there's no OneToMany in Django, only ManyToOne - which is Foreignkey described above. You can describe OneToMany relation using Foreignkey but that is very inexpressively.

A good article about it: https://amir.rachum.com/blog/2013/06/15/a-case-for-a-onetomany-relationship-in-django/

Setting selected values for ng-options bound select elements

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

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

anaconda/conda - install a specific package version

If any of these characters, '>', '<', '|' or '*', are used, a single or double quotes must be used

conda install [-y] package">=version"
conda install [-y] package'>=low_version, <=high_version'
conda install [-y] "package>=low_version, <high_version"

conda install -y torchvision">=0.3.0"
conda install  openpyxl'>=2.4.10,<=2.6.0'
conda install "openpyxl>=2.4.10,<3.0.0"

where option -y, --yes Do not ask for confirmation.

Here is a summary:

Format         Sample Specification     Results
Exact          qtconsole==4.5.1         4.5.1
Fuzzy          qtconsole=4.5            4.5.0, 4.5.1, ..., etc.
>=, >, <, <=  "qtconsole>=4.5"          4.5.0 or higher
               qtconsole"<4.6"          less than 4.6.0

OR            "qtconsole=4.5.1|4.5.2"   4.5.1, 4.5.2
AND           "qtconsole>=4.3.1,<4.6"   4.3.1 or higher but less than 4.6.0

Potion of the above information credit to Conda Cheat Sheet

Tested on conda 4.7.12

Pandas - Plotting a stacked Bar Chart

Maybe you can use pandas crosstab function

test5 = pd.crosstab(index=faultdf['Site Name'], columns=faultdf[''Abuse/NFF''])

test5.plot(kind='bar', stacked=True)

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

I created a working demo of a landscape/portrait layout but the zoom must be disabled for it to work without JavaScript:

http://matthewjamestaylor.com/blog/ipad-layout-with-landscape-portrait-modes

Angular File Upload

Here is how I did it to upload the excel files:
Directory structure:

app
|-----uploadcomponent
           |-----uploadcomponent.module.ts
           |-----uploadcomponent.html
|-----app.module.ts
|-----app.component.ts
|-----app.service.ts

uploadcomponent.html

<div>
   <form [formGroup]="form" (ngSubmit)="onSubmit()">
     <input type="file" name="profile"  enctype="multipart/form-data" accept=".xlsm,application/msexcel" (change)="onChange($event)" />
     <button type="submit">Upload Template</button>
     <button id="delete_button" class="delete_button" type="reset"><i class="fa fa-trash"></i></button> 
   </form>           
</div>

uploadcomponent.ts

    import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
    import { Component, OnInit } from '@angular/core';
    ....
    export class UploadComponent implements OnInit {
        form: FormGroup;
        constructor(private formBuilder: FormBuilder, private uploadService: AppService) {}
        ngOnInit() {  
            this.form = this.formBuilder.group({
               profile: ['']
            });
        }

        onChange(event) {
            if (event.target.files.length > 0) {
              const file = event.target.files[0];

              this.form.get('profile').setValue(file);
              console.log(this.form.get('profile').value)
            }
        }

        onSubmit() {
           const formData = new FormData();
           formData.append('file', this.form.get('profile').value);

           this.uploadService.upload(formData).subscribe(
             (res) => {
               this.response = res;

               console.log(res);

             },
             (err) => {  
               console.log(err);
             });
         }
    }

app.service.ts

    upload(formData) {
        const endpoint = this.service_url+'upload/';
        const httpOptions = headers: new HttpHeaders({    <<<< Changes are here
            'Authorization': 'token xxxxxxx'})
        };
        return this.http.post(endpoint, formData, httpOptions);
    }

In Backend I use DJango REST Framework.
models.py

from __future__ import unicode_literals
from django.db import models
from django.db import connection
from django_mysql.models import JSONField, Model
import uuid
import os


def change_filename(instance, filename):
    extension = filename.split('.')[-1]
    file_name = os.path.splitext(filename)[0]
    uuid_name = uuid.uuid4()
    return file_name+"_"+str(uuid_name)+"."+extension

class UploadTemplate (Model):
    id = models.AutoField(primary_key=True)
    file = models.FileField(blank=False, null=False, upload_to=change_filename)

    def __str__(self):
        return str(self.file.name)

views.py.

class UploadView(APIView):
    serializer_class = UploadSerializer
    parser_classes = [MultiPartParser]       

    def get_queryset(self):
        queryset = UploadTemplate.objects.all()
        return queryset

    def post(self, request, *args, **kwargs):
        file_serializer = UploadSerializer(data=request.data)
        status = None
        message = None
        if file_serializer.is_valid():
            file_serializer.save()
            status = "Success"
            message = "Success"
        else:
            status = "Failure"
            message = "Failure!"
        content = {'status': status, 'message': message}
        return Response(content)

serializers.py.

from uploadtemplate.models import UploadTemplate
from rest_framework import serializers

class UploadSerializer(serializers.ModelSerializer):
    class Meta:
        model = UploadTemplate
        fields = '__all__'   

urls.py.

router.register(r'uploadtemplate', uploadtemplateviews.UploadTemplateView, 
    base_name='UploadTemplate')
urlpatterns = [
    ....
    url(r'upload/', uploadtemplateviews.UploadTemplateView.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

MEDIA_URL and MEDIA_ROOT is defined in settings.py of the project.

Thanks!

How to convert Blob to File in JavaScript

Joshua P Nixon's answer is correct but I had to set last modified date also. so here is the code.

var file = new File([blob], "file_name", {lastModified: 1534584790000});

1534584790000 is an unix timestamp for "GMT: Saturday, August 18, 2018 9:33:10 AM"

How to use double or single brackets, parentheses, curly braces

Truncate the contents of a variable

$ var="abcde"; echo ${var%d*}
abc

Make substitutions similar to sed

$ var="abcde"; echo ${var/de/12}
abc12

Use a default value

$ default="hello"; unset var; echo ${var:-$default}
hello

Linux command-line call not returning what it should from os.system?

What gets returned is the return value of executing this command. What you see in while executing it directly is the output of the command in stdout. That 0 is returned means, there was no error in execution.

Use popen etc for capturing the output .

Some thing along this line:

import subprocess as sub
p = sub.Popen(['your command', 'arg1', 'arg2', ...],stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
print output

or

import os
p = os.popen('command',"r")
while 1:
    line = p.readline()
    if not line: break
    print line

ON SO : Popen and python

How to center an element horizontally and vertically

to center the Div in a page check the fiddle link

_x000D_
_x000D_
#vh {_x000D_
    border-radius: 15px;_x000D_
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.4);_x000D_
    padding: 25px;_x000D_
    width: 200px;_x000D_
    height: 200px;_x000D_
    background: white;_x000D_
    text-align: center;_x000D_
    margin: auto;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    bottom: 0;_x000D_
    right: 0;_x000D_
}
_x000D_
<div id="vh">Div to be aligned vertically</div>
_x000D_
_x000D_
_x000D_

Update Another option is to use flex box check the fiddle link

_x000D_
_x000D_
.vh {_x000D_
    background-color: #ddd;_x000D_
    height: 200px;_x000D_
    align-items: center;_x000D_
    display: flex;_x000D_
}_x000D_
.vh > div {_x000D_
    width: 100%;_x000D_
    text-align: center;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<div class="vh">_x000D_
    <div>Div to be aligned vertically</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

how to attach url link to an image?

Alternatively,

<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;
}
</style>

<a href="http://www.example.com" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

Change background image opacity

You can also simply use this:

_x000D_
_x000D_
.bg_rgba {
  background: linear-gradient(0deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.9)), url('https://picsum.photos/200');
  width: 200px;
  height: 200px;
  border: 1px solid black;
}
_x000D_
<div class='bg_rgba'></div>
_x000D_
_x000D_
_x000D_

You can change the opacity of the color to your preference.

Remove First and Last Character C++

std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; } 
else {
    while(str.at(0) == ' ') { str.erase(0, 1);}
    while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
    return str ;
    } 
}

Importing two classes with same name. How to handle?

You can import one of them using import. For all other similar class , you need to specify Fully qualified class names. Otherwise you will get compilation error.

Eg:

import java.util.Date;

class Test{

  public static void main(String [] args){

    // your own date
    my.own.Date myOwndate ;

    // util.Date
    Date utilDate;
  }
}

jQuery checkbox checked state changed event

Try this jQuery validation

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#myform').validate({ // initialize the plugin_x000D_
    rules: {_x000D_
      agree: {_x000D_
        required: true_x000D_
      }_x000D_
_x000D_
    },_x000D_
    submitHandler: function(form) {_x000D_
      alert('valid form submitted');_x000D_
      return false;_x000D_
    }_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>_x000D_
_x000D_
<form id="myform" action="" method="post">_x000D_
  <div class="buttons">_x000D_
    <div class="pull-right">_x000D_
      <input type="checkbox" name="agree" /><br/>_x000D_
      <label>I have read and agree to the <a href="https://stackexchange.com/legal/terms-of-service">Terms of services</a> </label>_x000D_
    </div>_x000D_
  </div>_x000D_
  <button type="submit">Agree</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Let JSON object accept bytes or let urlopen output strings

I used below program to use of json.loads()

import urllib.request
import json
endpoint = 'https://maps.googleapis.com/maps/api/directions/json?'
api_key = 'AIzaSyABbKiwfzv9vLBR_kCuhO7w13Kseu68lr0'
origin = input('where are you ?').replace(' ','+')
destination = input('where do u want to go').replace(' ','+')
nav_request = 'origin={}&destination={}&key={}'.format(origin,destination,api_key)
request = endpoint + nav_request
response = urllib.request.urlopen(request).read().decode('utf-8')
directions = json.loads(response)
print(directions)

Playing .mp3 and .wav in Java?

To add MP3 reading support to Java Sound, add the mp3plugin.jar of the JMF to the run-time class path of the application.

Note that the Clip class has memory limitations that make it unsuitable for more than a few seconds of high quality sound.

How to pass a variable to the SelectCommand of a SqlDataSource?

SqlDataSource1.SelectCommand = "select * from ta where name like '%'+@p+'%'";
if (SqlDataSource1.SelectParameters.Count == 0)
{
   SqlDataSource1.SelectParameters.Add("p", DbType.String, TextBox1.Text);
}
SqlDataSource1.SelectParameters["p"].DefaultValue = TextBox1.Text;

What is the correct way to declare a boolean variable in Java?

First of all, you should use none of them. You are using wrapper type, which should rarely be used in case you have a primitive type. So, you should use boolean rather.

Further, we initialize the boolean variable to false to hold an initial default value which is false. In case you have declared it as instance variable, it will automatically be initialized to false.

But, its completely upto you, whether you assign a default value or not. I rather prefer to initialize them at the time of declaration.

But if you are immediately assigning to your variable, then you can directly assign a value to it, without having to define a default value.

So, in your case I would use it like this: -

boolean isMatch = email1.equals (email2);

Fragments within Fragments

If you find your nested fragment not being removed or being duplicated (eg. on Activity restart, on screen rotate) try changing:

transaction.add(R.id.placeholder, newFragment);

to

transaction.replace(R.id.placeholder, newFragment);

If above doesn't help, try:

Fragment f = getChildFragmentManager().findFragmentById(R.id.placeholder);

FragmentTransaction transaction = getChildFragmentManager().beginTransaction();

if (f == null) {
    Log.d(TAG, "onCreateView: fragment doesn't exist");
    newFragment= new MyFragmentType();
    transaction.add(R.id.placeholder, newFragment);
} else {
    Log.d(TAG, "onCreateView: fragment already exists");
    transaction.replace(R.id.placeholder, f);
}
transaction.commit();

Learnt here

Why use multiple columns as primary keys (composite primary key)

Multiple columns in a key are going to, in general, perform more poorly than a surrogate key. I prefer to have a surrogate key and then a unique index on a multicolumn key. That way you can have better performance and the uniqueness needed is maintained. And even better, when one of the values in that key changes, you don't also have to update a million child entries in 215 child tables.

How can I detect when an Android application is running in the emulator?

Based on hints from other answers, this is probably the most robust way:

isEmulator = "goldfish".equals(Build.HARDWARE)

How to implement a binary search tree in Python?

The following code is basic on @DTing‘s answer and what I learn from class, which uses a while loop to insert (indicated in the code).

class Node:
    def __init__(self, val):
        self.l_child = None
        self.r_child = None
        self.data = val


def binary_insert(root, node):
    y = None
    x = root
    z = node
    #while loop here
    while x is not None:
        y = x
        if z.data < x.data:
            x = x.l_child
        else:
            x = x.r_child
    z.parent = y
    if y == None:
        root = z
    elif z.data < y.data:
        y.l_child = z
    else:
        y.r_child = z


def in_order_print(root):
    if not root:
        return
    in_order_print(root.l_child)
    print(root.data)
    in_order_print(root.r_child)


r = Node(3)
binary_insert(r, Node(7))
binary_insert(r, Node(1))
binary_insert(r, Node(5))

in_order_print(r)

No mapping found for HTTP request with URI Spring MVC

With the web.xml configured they way you have in the question, in particular:

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

ALL requests being made to your web app will be directed to the DispatcherServlet. This includes requests like /tasklist/, /tasklist/some-thing.html, /tasklist/WEB-INF/views/index.jsp.

Because of this, when your controller returns a view that points to a .jsp, instead of allowing your server container to service the request, the DispatcherServlet jumps in and starts looking for a controller that can service this request, it doesn't find any and hence the 404.

The simplest way to solve is to have your servlet url mapping as follows:

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Notice the missing *. This tells the container that any request that does not have a path info in it (urls without a .xxx at the end), should be sent to the DispatcherServlet. With this configuration, when a xxx.jsp request is received, the DispatcherServlet is not consulted, and your servlet container's default servlet will service the request and present the jsp as expected.

Hope this helps, I realize your earlier comments state that the problem has been resolved, but the solution CAN NOT be just adding method=RequestMethod.GET to the RequestMethod.

Cannot declare instance members in a static class in C#

public static class Employee
{
    public static string SomeSetting
    {
        get 
        {
            return ConfigurationManager.AppSettings["SomeSetting"];    
        }
    }
}

Declare the property as static, as well. Also, Don't bother storing a private reference to ConfigurationManager.AppSettings. ConfigurationManager is already a static class.

If you feel that you must store a reference to appsettings, try

public static class Employee
{
    private static NameValueCollection _appSettings=ConfigurationManager.AppSettings;

    public static NameValueCollection AppSettings { get { return _appSettings; } }

}

It's good form to always give an explicit access specifier (private, public, etc) even though the default is private.

Get model's fields in Django

The model fields contained by _meta are listed in multiple locations as lists of the respective field objects. It may be easier to work with them as a dictionary where the keys are the field names.

In my opinion, this is most irredundant and expressive way to collect and organize the model field objects:

def get_model_fields(model):
  fields = {}
  options = model._meta
  for field in sorted(options.concrete_fields + options.many_to_many + options.virtual_fields):
    fields[field.name] = field
  return fields

(See This example usage in django.forms.models.fields_for_model.)

send/post xml file using curl command line

From the manpage, I believe these are the droids you are looking for:

-F/--form <name=content>

(HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content-Type multipart/form-data according to RFC2388. This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign.

Example, to send your password file to the server, where 'password' is the name of the form-field to which /etc/passwd will be the input:

curl -F password=@/etc/passwd www.mypasswords.com

So in your case, this would be something like
curl -F file=@/some/file/on/your/local/disk http://localhost:8080

Generate PDF from HTML using pdfMake in Angularjs

I know its not relevant to this post but might help others converting HTML to PDF on client side. This is a simple solution if you use kendo. It also preserves the css (most of the cases).

_x000D_
_x000D_
var generatePDF = function() {_x000D_
  kendo.drawing.drawDOM($("#formConfirmation")).then(function(group) {_x000D_
    kendo.drawing.pdf.saveAs(group, "Converted PDF.pdf");_x000D_
  });_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <!-- Latest compiled and minified CSS -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <!-- Optional theme -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <!-- Latest compiled and minified JavaScript -->_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <script src="//kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <br/>_x000D_
  <button class="btn btn-primary" onclick="generatePDF()"><i class="fa fa-save"></i> Save as PDF</button>_x000D_
  <br/>_x000D_
  <br/>_x000D_
  <div id="formConfirmation">_x000D_
_x000D_
    <div class="container theme-showcase" role="main">_x000D_
      <!-- Main jumbotron for a primary marketing message or call to action -->_x000D_
      <div class="jumbotron">_x000D_
        <h1>Theme example</h1>_x000D_
        <p>This is a template showcasing the optional theme stylesheet included in Bootstrap. Use it as a starting point to create something more unique by building on or modifying it.</p>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Buttons</h1>_x000D_
      </div>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-lg btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-lg btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-lg btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-lg btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-lg btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-lg btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-lg btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-sm btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-sm btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-sm btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-sm btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-sm btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-sm btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-sm btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-xs btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-xs btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-xs btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-xs btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-xs btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-xs btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-xs btn-link">Link</button>_x000D_
      </p>_x000D_
      <div class="page-header">_x000D_
        <h1>Tables</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-md-6">_x000D_
          <table class="table">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-striped">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-bordered">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td rowspan="2">1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@TwBootstrap</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td colspan="2">Larry the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-condensed">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td colspan="2">Larry the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Thumbnails</h1>_x000D_
      </div>_x000D_
      <img data-src="holder.js/200x200" class="img-thumbnail" alt="A generic square placeholder image with a white border around it, making it resemble a photograph taken with an old instant camera">_x000D_
      <div class="page-header">_x000D_
        <h1>Labels</h1>_x000D_
      </div>_x000D_
      <h1>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h1>_x000D_
      <h2>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h2>_x000D_
      <h3>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h3>_x000D_
      <h4>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h4>_x000D_
      <h5>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h5>_x000D_
      <h6>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h6>_x000D_
      <p>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </p>_x000D_
      <div class="page-header">_x000D_
        <h1>Badges</h1>_x000D_
      </div>_x000D_
      <p>_x000D_
        <a href="#">Inbox <span class="badge">42</span></a>_x000D_
      </p>_x000D_
      <ul class="nav nav-pills" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages <span class="badge">3</span></a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <div class="page-header">_x000D_
        <h1>Dropdown menus</h1>_x000D_
      </div>_x000D_
      <div class="dropdown theme-dropdown clearfix">_x000D_
        <a id="dropdownMenu1" href="#" class="sr-only dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">_x000D_
          <li class="active"><a href="#">Action</a>_x000D_
          </li>_x000D_
          <li><a href="#">Another action</a>_x000D_
          </li>_x000D_
          <li><a href="#">Something else here</a>_x000D_
          </li>_x000D_
          <li role="separator" class="divider"></li>_x000D_
          <li><a href="#">Separated link</a>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Navs</h1>_x000D_
      </div>_x000D_
      <ul class="nav nav-tabs" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <ul class="nav nav-pills" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <div class="page-header">_x000D_
        <h1>Navbars</h1>_x000D_
      </div>_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">Project name</a>_x000D_
          </div>_x000D_
          <div class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="#">Home</a>_x000D_
              </li>_x000D_
              <li><a href="#about">About</a>_x000D_
              </li>_x000D_
              <li><a href="#contact">Contact</a>_x000D_
              </li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="#">Action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Another action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Something else here</a>_x000D_
                  </li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li class="dropdown-header">Nav header</li>_x000D_
                  <li><a href="#">Separated link</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">One more separated link</a>_x000D_
                  </li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
          </div>_x000D_
          <!--/.nav-collapse -->_x000D_
        </div>_x000D_
      </nav>_x000D_
      <nav class="navbar navbar-inverse">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">Project name</a>_x000D_
          </div>_x000D_
          <div class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="#">Home</a>_x000D_
              </li>_x000D_
              <li><a href="#about">About</a>_x000D_
              </li>_x000D_
              <li><a href="#contact">Contact</a>_x000D_
              </li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="#">Action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Another action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Something else here</a>_x000D_
                  </li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li class="dropdown-header">Nav header</li>_x000D_
                  <li><a href="#">Separated link</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">One more separated link</a>_x000D_
                  </li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
          </div>_x000D_
          <!--/.nav-collapse -->_x000D_
        </div>_x000D_
      </nav>_x000D_
      <div class="page-header">_x000D_
        <h1>Alerts</h1>_x000D_
      </div>_x000D_
      <div class="alert alert-success" role="alert">_x000D_
        <strong>Well done!</strong> You successfully read this important alert message._x000D_
      </div>_x000D_
      <div class="alert alert-info" role="alert">_x000D_
        <strong>Heads up!</strong> This alert needs your attention, but it's not super important._x000D_
      </div>_x000D_
      <div class="alert alert-warning" role="alert">_x000D_
        <strong>Warning!</strong> Best check yo self, you're not looking too good._x000D_
      </div>_x000D_
      <div class="alert alert-danger" role="alert">_x000D_
        <strong>Oh snap!</strong> Change a few things up and try submitting again._x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Progress bars</h1>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"><span class="sr-only">60% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"><span class="sr-only">40% Complete (success)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"><span class="sr-only">20% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete (warning)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"><span class="sr-only">80% Complete (danger)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-success" style="width: 35%"><span class="sr-only">35% Complete (success)</span>_x000D_
        </div>_x000D_
        <div class="progress-bar progress-bar-warning" style="width: 20%"><span class="sr-only">20% Complete (warning)</span>_x000D_
        </div>_x000D_
        <div class="progress-bar progress-bar-danger" style="width: 10%"><span class="sr-only">10% Complete (danger)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>List groups</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-sm-4">_x000D_
          <ul class="list-group">_x000D_
            <li class="list-group-item">Cras justo odio</li>_x000D_
            <li class="list-group-item">Dapibus ac facilisis in</li>_x000D_
            <li class="list-group-item">Morbi leo risus</li>_x000D_
            <li class="list-group-item">Porta ac consectetur ac</li>_x000D_
            <li class="list-group-item">Vestibulum at eros</li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="list-group">_x000D_
            <a href="#" class="list-group-item active">_x000D_
              Cras justo odio_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">Dapibus ac facilisis in</a>_x000D_
            <a href="#" class="list-group-item">Morbi leo risus</a>_x000D_
            <a href="#" class="list-group-item">Porta ac consectetur ac</a>_x000D_
            <a href="#" class="list-group-item">Vestibulum at eros</a>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="list-group">_x000D_
            <a href="#" class="list-group-item active">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Panels</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-default">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-primary">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-success">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-info">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-warning">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-danger">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
      </div>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Embedding SVG into ReactJS

Update 2016-05-27

As of React v15, support for SVG in React is (close to?) 100% parity with current browser support for SVG (source). You just need to apply some syntax transformations to make it JSX compatible, like you already have to do for HTML (class ? className, style="color: purple" ? style={{color: 'purple'}}). For any namespaced (colon-separated) attribute, e.g. xlink:href, remove the : and capitalize the second part of the attribute, e.g. xlinkHref. Here’s an example of an svg with <defs>, <use>, and inline styles:

function SvgWithXlink (props) {
    return (
        <svg
            width="100%"
            height="100%"
            xmlns="http://www.w3.org/2000/svg"
            xmlnsXlink="http://www.w3.org/1999/xlink"
        >
            <style>
                { `.classA { fill:${props.fill} }` }
            </style>
            <defs>
                <g id="Port">
                    <circle style={{fill:'inherit'}} r="10"/>
                </g>
            </defs>

            <text y="15">black</text>
            <use x="70" y="10" xlinkHref="#Port" />
            <text y="35">{ props.fill }</text>
            <use x="70" y="30" xlinkHref="#Port" className="classA"/>
            <text y="55">blue</text>
            <use x="0" y="50" xlinkHref="#Port" style={{fill:'blue'}}/>
        </svg>
    );
}

Working codepen demo

For more details on specific support, check the docs’ list of supported SVG attributes. And here’s the (now closed) GitHub issue that tracked support for namespaced SVG attributes.


Previous answer

You can do a simple SVG embed without having to use dangerouslySetInnerHTML by just stripping the namespace attributes. For example, this works:

        render: function() {
            return (
                <svg viewBox="0 0 120 120">
                    <circle cx="60" cy="60" r="50"/>
                </svg>
            );
        }

At which point you can think about adding props like fill, or whatever else might be useful to configure.

how to draw directed graphs using networkx in python?

Fully fleshed out example with arrows for only the red edges:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_edges_from(
    [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
     ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
           'D': 0.5714285714285714,
           'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
                for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]

# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), 
                       node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()

Red edges

How to add "class" to host element?

You can simply add @HostBinding('class') class = 'someClass'; inside your @Component class.

Example:

@Component({
   selector: 'body',
   template: 'app-element'       
})
export class App implements OnInit {

  @HostBinding('class') class = 'someClass';

  constructor() {}      

  ngOnInit() {}
}

How to view query error in PDO PHP

a quick way to see your errors whilst testing:

$error= $st->errorInfo();
echo $error[2];

Calling stored procedure with return value

I know this is old, but i stumbled on it with Google.

If you have a return value in your stored procedure say "Return 1" - not using output parameters.

You can do the following - "@RETURN_VALUE" is silently added to every command object. NO NEED TO EXPLICITLY ADD

    cmd.ExecuteNonQuery();
    rtn = (int)cmd.Parameters["@RETURN_VALUE"].Value;

How to force div to appear below not next to another?

use clear:left; or clear:both in your css.

#map { float:left; width:700px; height:500px; }
 #list { float:left; width:200px; background:#eee; list-style:none; padding:0; }
 #similar { float:left; width:200px; background:#000; clear:both; } 


<div id="map"></div>        
<ul id="list"></ul>
<div id ="similar">
 this text should be below, not next to ul.
</div>

Split string with string as delimiter

@ECHO OFF
SETLOCAL
SET "string=string1 by string2.txt"
SET "string=%string:* by =%"
ECHO +%string%+

GOTO :EOF

The above SET command will remove the unwanted data. Result shown between + to demonstrate absence of spaces.

Formula: set var=%somevar:*string1=string2%

will assign to var the value of somevar with all characters up to string1 replaced by string2. The enclosing quotes in a set command ensure that any stray trailing spaces on the line are not included in the value assigned.

performSelector may cause a leak because its selector is unknown

To make Scott Thompson's macro more generic:

// String expander
#define MY_STRX(X) #X
#define MY_STR(X) MY_STRX(X)

#define MYSilenceWarning(FLAG, MACRO) \
_Pragma("clang diagnostic push") \
_Pragma(MY_STR(clang diagnostic ignored MY_STR(FLAG))) \
MACRO \
_Pragma("clang diagnostic pop")

Then use it like this:

MYSilenceWarning(-Warc-performSelector-leaks,
[_target performSelector:_action withObject:self];
                )

How to convert An NSInteger to an int?

Commonly used in UIsegmentedControl, "error" appear when compiling in 64bits instead of 32bits, easy way for not pass it to a new variable is to use this tips, add (int):

[_monChiffre setUnite:(int)[_valUnites selectedSegmentIndex]];

instead of :

[_monChiffre setUnite:[_valUnites selectedSegmentIndex]];

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

C#: Converting byte array to string and printing out to console

For some fun with linq and string interpolation:

public string ByteArrayToString(byte[] bytes)
{
    if ( bytes == null ) return "null";
    string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
    return $"new byte[] {{ {joinedBytes} }}";
}

Test cases:

byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();

Output:

new byte[] { 1, 2, 3, 4 }
null
new byte[] {  }

How to set up fixed width for <td>?

in Bootstrap Table 4.x

If you are creating the table in the init parameters instead of using HTML.

You can specify the width parameters in the columns attribute:

$("table").bootstrapTable({
    columns: [
        { field: "title", title: "title", width: "100px" }
    ]
});

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

you make the use of the HTML Helper and have

    @using(Html.BeginForm())
    {
        Username: <input type="text" name="username" /> <br />
        Password: <input type="text" name="password" /> <br />
        <input type="submit" value="Login">
        <input type="submit" value="Create Account"/>
    }

or use the Url helper

<form method="post" action="@Url.Action("MyAction", "MyController")" >

Html.BeginForm has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:

@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    < ... >
}

If you don't specify any arguments, the Html.BeginForm() will create a POST form that points to your current controller and current action. As an example, let's say you have a controller called Posts and an action called Delete

public ActionResult Delete(int id)
{
   var model = db.GetPostById(id);
   return View(model);
}

[HttpPost]
public ActionResult Delete(int id)
{
    var model = db.GetPostById(id);
    if(model != null) 
        db.DeletePost(id);

    return RedirectToView("Index");
}

and your html page would be something like:

<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>

@using(Html.BeginForm())
{
    <input type="submit" class="btn btn-danger" value="Delete Post"/>
    <text>or</text>
    @Url.ActionLink("go to list", "Index")
}

Create a sample login page using servlet and JSP?

You're comparing the message with the empty string using ==.

First, your comparison is wrong because the message will be null (and not the empty string).

Second, it's wrong because Objects must be compared with equals() and not with ==.

Third, it's wrong because you should avoid scriptlets in JSP, and use the JSP EL, the JSTL, and other custom tags instead:

<c:id test="${!empty message}">
    <c:out value="${message}"/>
</c:if>

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

How to change package name in flutter?

For Android App Name

Change the label name in your AndroidManifest.xml file:

 <application
    android:name="io.flutter.app.FlutterApplication"
    android:label="TheNameOfYourApp"   

For Package Name

Change the package name in your AndroidManifest.xml (in 3 of them, folders: main, debug and profile, according what environment you want to deploy) file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package.name">

Also in your build.gradle file inside app folder

defaultConfig {
    applicationId "your.package.name"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

Finally, change the package in your MainActivity.java class (if the MainActivity.java is not available, check the MainActivity.kt)

    package your.package.name;

    import android.os.Bundle;
    import io.flutter.app.FlutterActivity;
    import io.flutter.plugins.GeneratedPluginRegistrant;
    public class MainActivity extends FlutterActivity {

Change the directory name:

From:

  android\app\src\main\java\com\example\name

To:

  android\app\src\main\java\your\package\name
  

EDITED : 27-Dec-18

for package name just change in build build.gradle only

defaultConfig {
    applicationId "your.package.name"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

For iOS

Change the bundle identifier from your Info.plist file inside your ios/Runner directory.

<key>CFBundleIdentifier</key>
<string>com.your.packagename</string>

UPDATE

To avoid renaming the package and bundle identifier, you can start your project using this command in your terminal:

flutter create --org com.yourdomain appname

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21

webViewClient = object : WebViewClient() {
.
.
        @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            parseUri(request?.url)
            return true
        }

        @SuppressWarnings("deprecation")
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            parseUri(Uri.parse(url))
            return true
        }
}

How to update data in one table from corresponding data in another table in SQL Server 2005

Try a query like

INSERT INTO NEW_TABLENAME SELECT * FROM OLD_TABLENAME;

How add "or" in switch statements?

You may do this as of C# 9.0:

switch(myvar)
{
    case 2 or 5:
        // ...
        break;

    case 7 or 12:
        // ...
        break;
    // ...
}

Background images: how to fill whole div if image is small and vice versa

To automatically enlarge the image and cover the entire div section without leaving any part of it unfilled, use:

background-size: cover;

What is the difference between a generative and a discriminative algorithm?

My two cents: Discriminative approaches highlight differences Generative approaches do not focus on differences; they try to build a model that is representative of the class. There is an overlap between the two. Ideally both approaches should be used: one will be useful to find similarities and the other will be useful to find dis-similarities.

VB.NET - Remove a characters from a String

The String class has a Replace method that will do that.

Dim clean as String
clean = myString.Replace(",", "")

Node.js Generate html

Although @yanick-rochon answer is correct, the simplest way to achieve your goal (if it's to serve a dynamically generated html) is:

var http = require('http');
http.createServer(function (req, res) {
  res.write('<html><head></head><body>');
  res.write('<p>Write your HTML content here</p>');
  res.end('</body></html>');
}).listen(1337);

This way when you browse at http://localhost:1337 you'll get your html page.

Sending JSON object to Web API

Try this:

jquery

    $('#save-source').click(function (e) {
        e.preventDefault();
        var source = {
            'ID': 0,
            //'ProductID': $('#ID').val(),
            'PartNumber': $('#part-number').val(),
            //'VendorID': $('#Vendors').val()
        }
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "/api/PartSourceAPI",
            data: source,
            success: function (data) {
                alert(data);
            },
            error: function (error) {
                jsonValue = jQuery.parseJSON(error.responseText);
                //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
            }
        });
    });

Controller

    public string Post(PartSourceModel model)
    {
        return model.PartNumber;
    }

View

<label>Part Number</label>
<input type="text" id="part-number" name="part-number" />

<input type="submit" id="save-source" name="save-source" value="Add" />

Now when you click 'Add' after you fill out the text box, the controller will spit back out what you wrote in the PartNumber box in an alert.

Mockito - difference between doReturn() and when()

Continuing this answer, There is another difference that if you want your method to return different values for example when it is first time called, second time called etc then you can pass values so for example...

PowerMockito.doReturn(false, false, true).when(SomeClass.class, "SomeMethod", Matchers.any(SomeClass.class));

So it will return false when the method is called in same test case and then it will return false again and lastly true.

Which SchemaType in Mongoose is Best for Timestamp?

new mongoose.Schema({ description: { type: String, required: true, trim: true }, completed: { type: Boolean, default: false }, owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' } }, { timestamps: true });

Fling gesture detection on grid layout

Also as a minor enhancement.

The main reason for the try/catch block is that e1 could be null for the initial movement. in addition to the try/catch, include a test for null and return. similar to the following

if (e1 == null || e2 == null) return false;
try {
...
} catch (Exception e) {}
return false;

Numbering rows within groups in a data frame

Another dplyr possibility could be:

df %>%
 group_by(cat) %>%
 mutate(num = 1:n())

   cat      val   num
   <fct>  <dbl> <int>
 1 aaa   0.0564     1
 2 aaa   0.258      2
 3 aaa   0.308      3
 4 aaa   0.469      4
 5 aaa   0.552      5
 6 bbb   0.170      1
 7 bbb   0.370      2
 8 bbb   0.484      3
 9 bbb   0.547      4
10 bbb   0.812      5
11 ccc   0.280      1
12 ccc   0.398      2
13 ccc   0.625      3
14 ccc   0.763      4
15 ccc   0.882      5

Bad Request, Your browser sent a request that this server could not understand

in my magento2 website ,show exactly the same error when click a product,

my solution is to go to edit the value of Search Engine Optimization - URL Key of this product,

make sure that there are only alphabet,number and - in URL Key, such as 100-washed-cotton-duvet-cover-set, deleting all other special characters ,such as % .

.autocomplete is not a function Error

Found the problem, I was including another jquery file for my google translator, they were conflicting with each other and resulting in not loading the autocomplete function.

How to define Gradle's home in IDEA?

Installed on a Mac via Homebrew, the path

/usr/local/opt/gradle/libexec

is preferable to

/usr/local/Cellar/gradle/X.X/libexec

since the former will survive version upgrades.

Erase whole array Python

Well yes arrays do exist, and no they're not different to lists when it comes to things like del and append:

>>> from array import array
>>> foo = array('i', range(5))
>>> foo
array('i', [0, 1, 2, 3, 4])
>>> del foo[:]
>>> foo
array('i')
>>> foo.append(42)
>>> foo
array('i', [42])
>>>

Differences worth noting: you need to specify the type when creating the array, and you save storage at the expense of extra time converting between the C type and the Python type when you do arr[i] = expression or arr.append(expression), and lvalue = arr[i]

Shortcut to exit scale mode in VirtualBox

I was having the similar issue when using VirtualBox on Ubuntu 12.04LTS. Now if anyone is using or has ever used Ubuntu, you might be aware that how things are hard sometimes when using shortcut keys in Ubuntu. For me, when i was trying to revert back the Host key, it was just not happening and the shortcut keys won't just work. I even tried the command line option to revert back the scale mode and it won't work either. Finally i found the following when all the other options fails:

Fix the Scale Mode Issue in Oracle VirtualBox in Ubuntu using the following steps:

  1. Close all virtual machines and VirtualBox windows.
  2. Find your machine config files (i.e. /home/<username>/VirtualBox VMs/ANKSVM) where ANKSVM is your VM Name and edit and change the following in ANKSVM.vbox and ANKSVM.vbox-prev files:

  3. Edit the line: <ExtraDataItem name="GUI/Scale" value="on"/> to <ExtraDataItem name="GUI/Scale" value="off"/>

  4. Restart VirtualBox

You are done.

This works every time specially when all other options fails like how it happened for me.

Requested bean is currently in creation: Is there an unresolvable circular reference?

In my case, I was defining a bean and autowiring it in the constructor of the same class file.

@SpringBootApplication
public class MyApplication {
    private MyBean myBean;

    public MyApplication(MyBean myBean) {
        this.myBean = myBean;
    }

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

My solution was to move the bean definition to another class file.

@Configuration
public CustomConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

OWIN Security - How to Implement OAuth2 Refresh Tokens

You need to implement RefreshTokenProvider. First create class for RefreshTokenProvider ie.

public class ApplicationRefreshTokenProvider : AuthenticationTokenProvider
{
    public override void Create(AuthenticationTokenCreateContext context)
    {
        // Expiration time in seconds
        int expire = 5*60;
        context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
        context.SetToken(context.SerializeTicket());
    }

    public override void Receive(AuthenticationTokenReceiveContext context)
    {
        context.DeserializeTicket(context.Token);
    }
}

Then add instance to OAuthOptions.

OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/authenticate"),
    Provider = new ApplicationOAuthProvider(),
    AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(expire),
    RefreshTokenProvider = new ApplicationRefreshTokenProvider()
};

Change app language programmatically in Android

I finally figured out how to setup it to work on both =N android versions.

Extend AppCompatActivity with your own abstract class, like:

abstract class MLAppCompatActivity : AppCompatActivity() {
  override fun attachBaseContext(newBase: Context?) {
    super.attachBaseContext(LocaleHelper.wrap(newBase))
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        LocaleHelper.wrap(this)
    }
  }
}

attachBaseContext is called on Android >=N versions and on this way activity will use the correct context. On Android <N, we have to call this function on one other way, before setting content view. Therefore we override onCreate function to set correct context. Means, whenever you create a new Activity you have to extend your abstract class. Like this one:

class TermsActivity : MLAppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_terms)
  }
}

And finally the LocaleHelper is like this:

import android.annotation.TargetApi;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.util.DisplayMetrics;

import com.at_zone.constants.SharedPreferencesKeys;

import java.util.Locale;

public class LocaleHelper extends ContextWrapper {

    public LocaleHelper(Context base) {
        super(base);
    }

    public static Context wrap(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                SharedPreferencesKeys.SHARED_PREFERENCES, Context.MODE_PRIVATE
        );
        String language = sharedPreferences.getString(SharedPreferencesKeys.CURRENT_LANGUAGE, "default");
        if (!language.equals("default")) {
            Configuration config = context.getResources().getConfiguration();
            if (!language.equals("")) {
                Locale locale = new Locale(language);
                Locale.setDefault(locale);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    setSystemLocale(config, locale);
                } else {
                    setSystemLocaleLegacy(context, config, locale);
                }
                config.setLayoutDirection(locale);
                context = context.createConfigurationContext(config);
            }
            return new LocaleHelper(context);
        }
        return context;
    }

    public static String getSystemLanguage(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return getSystemLocale(context).getLanguage().toLowerCase();
        } else {
            return getSystemLocaleLegacy(context).getLanguage().toLowerCase();
        }
    }

    public static Locale getSystemLocaleLegacy(Context context) {
        Configuration config = context.getResources().getConfiguration();
        return config.locale;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static Locale getSystemLocale(Context context) {
        return context.getResources().getConfiguration().getLocales().get(0);
    }

    public static void setSystemLocaleLegacy(Context context, Configuration config, Locale locale) {
        config.locale = locale;
        Resources res = context.getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        res.updateConfiguration(config, dm);
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static void setSystemLocale(Configuration config, Locale locale) {
        config.setLocale(locale);
    }

}

Confirm password validation in Angular 6

My answer is very simple>i have created password and confirm password validation using template driiven in angular 6

My html file

<div class="form-group">
  <label class="label-sm">Confirm Password</label>
  <input class="form-control" placeholder="Enter Password" type="password" #confirm_password="ngModel" [(ngModel)]="userModel.confirm_password" name="confirm_password" required (keyup)="checkPassword($event)" />
  <div *ngIf="confirm_password.errors && (confirm_password.dirty||confirm_password.touched||signup.submitted)">
  <div class="error" *ngIf="confirm_password.errors.required">Please confirm your password</div>
  </div>
  <div *ngIf="i" class='error'>Password does not match</div>
</div>

My typescript file

      public i: boolean;

      checkPassword(event) {
        const password = this.userModel.password;
        const confirm_new_password = event.target.value;

        if (password !== undefined) {
          if (confirm_new_password !== password) {
            this.i = true;
          } else {
            this.i = false;
          }
        }
      }

when clicking on submit button i check whether value of i is true or false

if true

if (this.i) {
      return false;
    }

else{
**form submitted code comes here**
}

PHP Date Format to Month Name and Year

You could use:

echo date('F Y', strtotime('20130814'));

which should do the trick.

Edit: You have a date which is in a string format. To be able to format it nicelt, you first need to change it into a date itself - which is where strtotime comes in. It is a fantastic feature that converts almost any plausible expression of a date into a date itself. Then we can actually use the date() function to format the output into what you want.

Angular @ViewChild() error: Expected 2 arguments, but got 1

In Angular 8, ViewChild has another param

@ViewChild('nameInput', {static: false}) component

I resolved my issue like below

@ViewChild(MatSort, {static: false}) sort: MatSort;

Package signatures do not match the previously installed version

I had this issue on a Samsung device, Uninstalling the app gave the same message. The problem was that the app was also installed in the phone's "Secure Folder" area. Worth checking if this is your scenario.

FirstOrDefault: Default value other than null

Copied over from comment by @sloth

Instead of YourCollection.FirstOrDefault(), you could use YourCollection.DefaultIfEmpty(YourDefault).First() for example.

Example:

var viewModel = new CustomerDetailsViewModel
    {
            MainResidenceAddressSection = (MainResidenceAddressSection)addresses.DefaultIfEmpty(new MainResidenceAddressSection()).FirstOrDefault( o => o is MainResidenceAddressSection),
            RiskAddressSection = addresses.DefaultIfEmpty(new RiskAddressSection()).FirstOrDefault(o => !(o is MainResidenceAddressSection)),
    };

What are the JavaScript KeyCodes?

Here are some useful links:

The 2nd column is the keyCode and the html column shows how it will displayed. You can test it here.

Pass object to javascript function

when you pass an object within curly braces as an argument to a function with one parameter , you're assigning this object to a variable which is the parameter in this case

Load local JSON file into variable

The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.

You can load it using var fs = require('fs');

Asynchronous

fs.readFile('./content.json', (err, data) => {
    if (err)
      console.log(err);
    else {
      var json = JSON.parse(data);
    //your code using json object
    }
})

Synchronous

var json = JSON.parse(fs.readFileSync('./content.json').toString());

Best approach to real time http streaming to HTML5 video client

How about use jpeg solution, just let server distribute jpeg one by one to browser, then use canvas element to draw these jpegs? http://thejackalofjavascript.com/rpi-live-streaming/

How to print star pattern in JavaScript in a very simple manner?

Try this. Maybe it will work for you:

<html>
<head>
<script type="text/javascript">
    var i, j;
    //outer loop
    for(i = 0;i < 5; i++){
      //inner loop
      for(j = 0;j <= i; j++){
        document.write('*');
      }
      document.write('<br/>');
   }
</script>
</head>
<body>
</body>
</html>

Install opencv for Python 3.3

I know this is an old thread, but just in case anyone is looking, here is how I got it working on El Capitan:

brew install opencv3 --with-python3

and wait a while for it to finish.

Then run the following as necessary:

brew unlink opencv

Then run the following as the final step:

brew ln opencv3 --force

Now you should be able to run import cv2 no problem in a python 3.x script.

IFrame: This content cannot be displayed in a frame

The X-Frame-Options is defined in the Http Header and not in the <head> section of the page you want to use in the iframe.

Accepted values are: DENY, SAMEORIGIN and ALLOW-FROM "url"