Programs & Examples On #Database deployment

Align div right in Bootstrap 3

Bootstrap 4+ has made changes to the utility classes for this. From the documentation:

Added .float-{sm,md,lg,xl}-{left,right,none} classes for responsive floats and removed .pull-left and .pull-right since they’re redundant to .float-left and .float-right.

So use the .float-right (or a size equivalent such as .float-lg-right) instead of .pull-right for your right alignment if you're using a newer Bootstrap version.

What's the syntax to import a class in a default package in Java?

That's not possible.

The alternative is using reflection:

 Class.forName("SomeClass").getMethod("someMethod").invoke(null);

Chrome not rendering SVG referenced via <img> tag

A simple and easy way; according to https://css-tricks.com/forums/topic/svg-css-background-image-not-showing-in-chrome/ You have to open the .SVG file with a text editor (like notepad) and change

xlink:href="data:img/png;base64,

to:

xlink:href="data:image/png;base64,

it worked for me!

EditText, clear focus on touch outside

The best way is use the default method clearFocus()

You know how to solve codes in onTouchListener right?

Just call EditText.clearFocus(). It will clear focus in last EditText.

Remove the last three characters from a string

The new C# 8.0 range operator can be a great shortcut to achieve this.

Example #1 (to answer the question):

string myString = "abcdxxx";
var shortenedString = myString[0..^3]
System.Console.WriteLine(shortenedString);
// Results: abcd

Example #2 (to show you how awesome range operators are):

string s = "FooBar99";
// If the last 2 characters of the string are 99 then change to 98
s = s[^2..] == "99" ? s[0..^2] + "98" : s;
System.Console.WriteLine(s);
// Results: FooBar98

Best way to define private methods for a class in Objective-C

There isn't really a "private method" in Objective-C, if the runtime can work out which implementation to use it will do it. But that's not to say that there aren't methods which aren't part of the documented interface. For those methods I think that a category is fine. Rather than putting the @interface at the top of the .m file like your point 2, I'd put it into its own .h file. A convention I follow (and have seen elsewhere, I think it's an Apple convention as Xcode now gives automatic support for it) is to name such a file after its class and category with a + separating them, so @interface GLObject (PrivateMethods) can be found in GLObject+PrivateMethods.h. The reason for providing the header file is so that you can import it in your unit test classes :-).

By the way, as far as implementing/defining methods near the end of the .m file is concerned, you can do that with a category by implementing the category at the bottom of the .m file:

@implementation GLObject(PrivateMethods)
- (void)secretFeature;
@end

or with a class extension (the thing you call an "empty category"), just define those methods last. Objective-C methods can be defined and used in any order in the implementation, so there's nothing to stop you putting the "private" methods at the end of the file.

Even with class extensions I will often create a separate header (GLObject+Extension.h) so that I can use those methods if required, mimicking "friend" or "protected" visibility.

Since this answer was originally written, the clang compiler has started doing two passes for Objective-C methods. This means you can avoid declaring your "private" methods completely, and whether they're above or below the calling site they'll be found by the compiler.

How do I compare two string variables in an 'if' statement in Bash?

$ if [ "$s1" == "$s2" ]; then echo match; fi
match
$ test "s1" = "s2" ;echo match
match
$

/bin/sh: pushd: not found

sudo dpkg-reconfigure dash 

Then select no.

Change image source with JavaScript

The Following Example Program used to change the image src attribute for every 100 milliseconds. you may call the given function as your wish.

<html>
<head>
</head>
<body>
<img src="bulboff.jpg" height=200 width=200 id="imm" align="right">

<script type="text/javascript">

function bulb() {

var b = document.getElementById("imm");

if(b.src.match("bulboff.jpg")) {
 b.src = "bulbon.jpg";
}
 else {

 b.src="bulboff.jpg";
}
}
 setInterval(bulb,100);
</script>
</body>
</html>

Bulk Record Update with SQL

Or you can simply update without using join like this:

Update t1 set  t1.Description = t2.Description from @tbl2 t2,tbl1 t1
where t1.ID= t2.ID

Inserting a PDF file in LaTeX

For putting a whole pdf in your file and not just 1 page, use:

\usepackage{pdfpages}

\includepdf[pages=-]{myfile.pdf}

What's the difference between RANK() and DENSE_RANK() functions in oracle?

RANK gives you the ranking within your ordered partition. Ties are assigned the same rank, with the next ranking(s) skipped. So, if you have 3 items at rank 2, the next rank listed would be ranked 5.

DENSE_RANK again gives you the ranking within your ordered partition, but the ranks are consecutive. No ranks are skipped if there are ranks with multiple items.

As for nulls, it depends on the ORDER BY clause. Here is a simple test script you can play with to see what happens:

with q as (
select 10 deptno, 'rrr' empname, 10000.00 sal from dual union all
select 11, 'nnn', 20000.00 from dual union all
select 11, 'mmm', 5000.00 from dual union all
select 12, 'kkk', 30000 from dual union all
select 10, 'fff', 40000 from dual union all
select 10, 'ddd', 40000 from dual union all
select 10, 'bbb', 50000 from dual union all
select 10, 'xxx', null from dual union all
select 10, 'ccc', 50000 from dual)
select empname, deptno, sal
     , rank() over (partition by deptno order by sal nulls first) r
     , dense_rank() over (partition by deptno order by sal nulls first) dr1
     , dense_rank() over (partition by deptno order by sal nulls last) dr2
 from q; 

EMP     DEPTNO        SAL          R        DR1        DR2
--- ---------- ---------- ---------- ---------- ----------
xxx         10                     1          1          4
rrr         10      10000          2          2          1
fff         10      40000          3          3          2
ddd         10      40000          3          3          2
ccc         10      50000          5          4          3
bbb         10      50000          5          4          3
mmm         11       5000          1          1          1
nnn         11      20000          2          2          2
kkk         12      30000          1          1          1

9 rows selected.

Here's a link to a good explanation and some examples.

Convert ndarray from float64 to integer

There's also a really useful discussion about converting the array in place, In-place type conversion of a NumPy array. If you're concerned about copying your array (which is whatastype() does) definitely check out the link.

How can I check if some text exist or not in the page using Selenium?

This will help you to check whether required text is there in webpage or not.

driver.getPageSource().contains("Text which you looking for");

Java FileReader encoding issue

Since Java 11 you may use that:

public FileReader(String fileName, Charset charset) throws IOException;

@angular/material/index.d.ts' is not a module

Just update @angular/material from 7 to 9,

npm uninstall @angular/material --save

npm install @angular/material@^7.1.0 --save

ng update @angular/material

Just wait and see Angular doing the Migration alone,

Hope it helps someone :)

How to use log levels in java

The java.util.logging.Level documentation does a good job of defining when to use a log level and the target audience of that log level.

Most of the confusion with java.util.logging is in the tracing methods. It should be in the class level documentation but instead the Level.FINE field provides a good overview:

FINE is a message level providing tracing information. All of FINE, FINER, and FINEST are intended for relatively detailed tracing. The exact meaning of the three levels will vary between subsystems, but in general, FINEST should be used for the most voluminous detailed output, FINER for somewhat less detailed output, and FINE for the lowest volume (and most important) messages. In general the FINE level should be used for information that will be broadly interesting to developers who do not have a specialized interest in the specific subsystem. FINE messages might include things like minor (recoverable) failures. Issues indicating potential performance problems are also worth logging as FINE.

One important thing to understand which is not mentioned in the level documentation is that call-site tracing information is logged at FINER.

  • Logger#entering A LogRecord with message "ENTRY", log level FINER, ...
  • Logger#throwing The logging is done using the FINER level...The LogRecord's message is set to "THROW"
  • Logger#exiting A LogRecord with message "RETURN", log level FINER...

If you log a message as FINE you will be able to configure logging system to see the log output with or without tracing log records surrounding the log message. So use FINE only when tracing log records are not required as context to understand the log message.

FINER indicates a fairly detailed tracing message. By default logging calls for entering, returning, or throwing an exception are traced at this level.

In general, most use of FINER should be left to call of entering, exiting, and throwing. That will for the most part reserve FINER for call-site tracing when verbose logging is turned on. When swallowing an expected exception it makes sense to use FINER in some cases as the alternative to calling trace throwing method since the exception is not actually thrown. This makes it look like a trace when it isn't a throw or an actual error that would be logged at a higher level.

FINEST indicates a highly detailed tracing message.

Use FINEST when the tracing log message you are about to write requires context information about program control flow. You should also use FINEST for tracing messages that produce large amounts of output data.

CONFIG messages are intended to provide a variety of static configuration information, to assist in debugging problems that may be associated with particular configurations. For example, CONFIG message might include the CPU type, the graphics depth, the GUI look-and-feel, etc.

The CONFIG works well for assisting system admins with the items listed above.

Typically INFO messages will be written to the console or its equivalent. So the INFO level should only be used for reasonably significant messages that will make sense to end users and system administrators.

Examples of this are tracing program startup and shutdown.

In general WARNING messages should describe events that will be of interest to end users or system managers, or which indicate potential problems.

An example use case could be exceptions thrown from AutoCloseable.close implementations.

In general SEVERE messages should describe events that are of considerable importance and which will prevent normal program execution. They should be reasonably intelligible to end users and to system administrators.

For example, if you have transaction in your program where if any one of the steps fail then all of the steps voided then SEVERE would be appropriate to use as the log level.

View content of H2 or HSQLDB in-memory database

For H2, you can start a web server within your code during a debugging session if you have a database connection object. You could add this line to your code, or as a 'watch expression' (dynamically):

org.h2.tools.Server.startWebServer(conn);

The server tool will start a web browser locally that allows you to access the database.

json and empty array

"location" : null // this is not really an array it's a null object
"location" : []   // this is an empty array

It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.

How do you programmatically update query params in react-router?

From DimitriDushkin on GitHub:

import { browserHistory } from 'react-router';

/**
 * @param {Object} query
 */
export const addQuery = (query) => {
  const location = Object.assign({}, browserHistory.getCurrentLocation());

  Object.assign(location.query, query);
  // or simple replace location.query if you want to completely change params

  browserHistory.push(location);
};

/**
 * @param {...String} queryNames
 */
export const removeQuery = (...queryNames) => {
  const location = Object.assign({}, browserHistory.getCurrentLocation());
  queryNames.forEach(q => delete location.query[q]);
  browserHistory.push(location);
};

or

import { withRouter } from 'react-router';
import { addQuery, removeQuery } from '../../utils/utils-router';

function SomeComponent({ location }) {
  return <div style={{ backgroundColor: location.query.paintRed ? '#f00' : '#fff' }}>
    <button onClick={ () => addQuery({ paintRed: 1 })}>Paint red</button>
    <button onClick={ () => removeQuery('paintRed')}>Paint white</button>
  </div>;
}

export default withRouter(SomeComponent);

How to drop a list of rows from Pandas dataframe?

You can also pass to DataFrame.drop the label itself (instead of Series of index labels):

In[17]: df
Out[17]: 
            a         b         c         d         e
one  0.456558 -2.536432  0.216279 -1.305855 -0.121635
two -1.015127 -0.445133  1.867681  2.179392  0.518801

In[18]: df.drop('one')
Out[18]: 
            a         b         c         d         e
two -1.015127 -0.445133  1.867681  2.179392  0.518801

Which is equivalent to:

In[19]: df.drop(df.index[[0]])
Out[19]: 
            a         b         c         d         e
two -1.015127 -0.445133  1.867681  2.179392  0.518801

Checking if a file is a directory or just a file

Yes, there is better. Check the stat or the fstat function

Call js-function using JQuery timer

setInterval is the function you want. That repeats every x miliseconds.

window.setInterval(function() {
    alert('test');
}, 10000);

The system cannot find the file specified. in Visual Studio

The system cannot find the file specified usually means the build failed (which it will for your code as you're missing a # infront of include, you have a stray >> at the end of your cout line and you need std:: infront of cout) but you have the 'run anyway' option checked which means it runs an executable that doesn't exist. Hit F7 to just do a build and make sure it says '0 errors' before you try running it.

Code which builds and runs:

#include <iostream>

int main()
{
   std::cout << "Hello World";
   system("pause");
   return 0;
}

How to read XML response from a URL in java?

I found that the above answer caused me an exception when I tried to instantiate the parser. I found the following code that resolved this at http://docstore.mik.ua/orelly/xml/sax2/ch03_02.htm.

import org.xml.sax.*;
import javax.xml.parsers.*;

XMLReader        parser;

try {
    SAXParserFactory factory;

    factory = SAXParserFactory.newInstance ();
    factory.setNamespaceAware (true);
    parser = factory.newSAXParser ().getXMLReader ();
    // success!

} catch (FactoryConfigurationError err) {
    System.err.println ("can't create JAXP SAXParserFactory, "
    + err.getMessage ());
} catch (ParserConfigurationException err) {
    System.err.println ("can't create XMLReader with namespaces, "
    + err.getMessage ());
} catch (SAXException err) {
    System.err.println ("Hmm, SAXException, " + err.getMessage ());
}

How to validate phone number in laravel 5.2?

You can use this :

        'mobile_number' => ['required', 'digits:10'],

Getting scroll bar width using JavaScript

// offsetWidth includes width of scroll bar and clientWidth doesn't. As rule, it equals 14-18px. so:

 var scrollBarWidth = element.offsetWidth - element.clientWidth;

Gradle: Execution failed for task ':processDebugManifest'

In a general way, to see what is the error, you can see the merged Manifest File in Android studio

Go on your manifest file

enter image description here

Click on the bottom tab "Merged Manifest"

enter image description here

On the right screen, in "Other Manifest Files", check for any error due to graddle :

enter image description here

Uint8Array to string in Javascript

If you can't use the TextDecoder API because it is not supported on IE:

  1. You can use the FastestSmallestTextEncoderDecoder polyfill recommended by the Mozilla Developer Network website;
  2. You can use this function also provided at the MDN website:

_x000D_
_x000D_
function utf8ArrayToString(aBytes) {_x000D_
    var sView = "";_x000D_
    _x000D_
    for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) {_x000D_
        nPart = aBytes[nIdx];_x000D_
        _x000D_
        sView += String.fromCharCode(_x000D_
            nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */_x000D_
                /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */_x000D_
                (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */_x000D_
                (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */_x000D_
                (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */_x000D_
                (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */_x000D_
                (nPart - 192 << 6) + aBytes[++nIdx] - 128_x000D_
            : /* nPart < 127 ? */ /* one byte */_x000D_
                nPart_x000D_
        );_x000D_
    }_x000D_
    _x000D_
    return sView;_x000D_
}_x000D_
_x000D_
let str = utf8ArrayToString([50,72,226,130,130,32,43,32,79,226,130,130,32,226,135,140,32,50,72,226,130,130,79]);_x000D_
_x000D_
// Must show 2H2 + O2 ? 2H2O_x000D_
console.log(str);
_x000D_
_x000D_
_x000D_

A simple explanation of Naive Bayes Classification

Your question as I understand it is divided in two parts, part one being you need a better understanding of the Naive Bayes classifier & part two being the confusion surrounding Training set.

In general all of Machine Learning Algorithms need to be trained for supervised learning tasks like classification, prediction etc. or for unsupervised learning tasks like clustering.

During the training step, the algorithms are taught with a particular input dataset (training set) so that later on we may test them for unknown inputs (which they have never seen before) for which they may classify or predict etc (in case of supervised learning) based on their learning. This is what most of the Machine Learning techniques like Neural Networks, SVM, Bayesian etc. are based upon.

So in a general Machine Learning project basically you have to divide your input set to a Development Set (Training Set + Dev-Test Set) & a Test Set (or Evaluation set). Remember your basic objective would be that your system learns and classifies new inputs which they have never seen before in either Dev set or test set.

The test set typically has the same format as the training set. However, it is very important that the test set be distinct from the training corpus: if we simply reused the training set as the test set, then a model that simply memorized its input, without learning how to generalize to new examples, would receive misleadingly high scores.

In general, for an example, 70% of our data can be used as training set cases. Also remember to partition the original set into the training and test sets randomly.

Now I come to your other question about Naive Bayes.

To demonstrate the concept of Naïve Bayes Classification, consider the example given below:

enter image description here

As indicated, the objects can be classified as either GREEN or RED. Our task is to classify new cases as they arrive, i.e., decide to which class label they belong, based on the currently existing objects.

Since there are twice as many GREEN objects as RED, it is reasonable to believe that a new case (which hasn't been observed yet) is twice as likely to have membership GREEN rather than RED. In the Bayesian analysis, this belief is known as the prior probability. Prior probabilities are based on previous experience, in this case the percentage of GREEN and RED objects, and often used to predict outcomes before they actually happen.

Thus, we can write:

Prior Probability of GREEN: number of GREEN objects / total number of objects

Prior Probability of RED: number of RED objects / total number of objects

Since there is a total of 60 objects, 40 of which are GREEN and 20 RED, our prior probabilities for class membership are:

Prior Probability for GREEN: 40 / 60

Prior Probability for RED: 20 / 60

Having formulated our prior probability, we are now ready to classify a new object (WHITE circle in the diagram below). Since the objects are well clustered, it is reasonable to assume that the more GREEN (or RED) objects in the vicinity of X, the more likely that the new cases belong to that particular color. To measure this likelihood, we draw a circle around X which encompasses a number (to be chosen a priori) of points irrespective of their class labels. Then we calculate the number of points in the circle belonging to each class label. From this we calculate the likelihood:

enter image description here

enter image description here

From the illustration above, it is clear that Likelihood of X given GREEN is smaller than Likelihood of X given RED, since the circle encompasses 1 GREEN object and 3 RED ones. Thus:

enter image description here

enter image description here

Although the prior probabilities indicate that X may belong to GREEN (given that there are twice as many GREEN compared to RED) the likelihood indicates otherwise; that the class membership of X is RED (given that there are more RED objects in the vicinity of X than GREEN). In the Bayesian analysis, the final classification is produced by combining both sources of information, i.e., the prior and the likelihood, to form a posterior probability using the so-called Bayes' rule (named after Rev. Thomas Bayes 1702-1761).

enter image description here

Finally, we classify X as RED since its class membership achieves the largest posterior probability.

Conditionally ignoring tests in JUnit 4

The JUnit way is to do this at run-time is org.junit.Assume.

 @Before
 public void beforeMethod() {
     org.junit.Assume.assumeTrue(someCondition());
     // rest of setup.
 }

You can do it in a @Before method or in the test itself, but not in an @After method. If you do it in the test itself, your @Before method will get run. You can also do it within @BeforeClass to prevent class initialization.

An assumption failure causes the test to be ignored.

Edit: To compare with the @RunIf annotation from junit-ext, their sample code would look like this:

@Test
public void calculateTotalSalary() {
    assumeThat(Database.connect(), is(notNull()));
    //test code below.
}

Not to mention that it is much easier to capture and use the connection from the Database.connect() method this way.

In a Git repository, how to properly rename a directory?

lots of correct answers, but as I landed here to copy & paste a folder rename with history, I found that this

git mv <old name> <new name>

will move the old folder (itself) to nest within the new folder

while

git mv <old name>/ <new name>

(note the '/') will move the nested content from the old folder to the new folder

both commands didn't copy along the history of nested files. I eventually renamed each nested folder individually ?

git mv <old name>/<nest-folder> <new name>/<nest-folder>

How can I make sticky headers in RecyclerView? (Without external lib)

Easiest way is to just create an Item Decoration for your RecyclerView.

import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class RecyclerSectionItemDecoration extends RecyclerView.ItemDecoration {

private final int             headerOffset;
private final boolean         sticky;
private final SectionCallback sectionCallback;

private View     headerView;
private TextView header;

public RecyclerSectionItemDecoration(int headerHeight, boolean sticky, @NonNull SectionCallback sectionCallback) {
    headerOffset = headerHeight;
    this.sticky = sticky;
    this.sectionCallback = sectionCallback;
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    super.getItemOffsets(outRect, view, parent, state);

    int pos = parent.getChildAdapterPosition(view);
    if (sectionCallback.isSection(pos)) {
        outRect.top = headerOffset;
    }
}

@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
    super.onDrawOver(c,
                     parent,
                     state);

    if (headerView == null) {
        headerView = inflateHeaderView(parent);
        header = (TextView) headerView.findViewById(R.id.list_item_section_text);
        fixLayoutSize(headerView,
                      parent);
    }

    CharSequence previousHeader = "";
    for (int i = 0; i < parent.getChildCount(); i++) {
        View child = parent.getChildAt(i);
        final int position = parent.getChildAdapterPosition(child);

        CharSequence title = sectionCallback.getSectionHeader(position);
        header.setText(title);
        if (!previousHeader.equals(title) || sectionCallback.isSection(position)) {
            drawHeader(c,
                       child,
                       headerView);
            previousHeader = title;
        }
    }
}

private void drawHeader(Canvas c, View child, View headerView) {
    c.save();
    if (sticky) {
        c.translate(0,
                    Math.max(0,
                             child.getTop() - headerView.getHeight()));
    } else {
        c.translate(0,
                    child.getTop() - headerView.getHeight());
    }
    headerView.draw(c);
    c.restore();
}

private View inflateHeaderView(RecyclerView parent) {
    return LayoutInflater.from(parent.getContext())
                         .inflate(R.layout.recycler_section_header,
                                  parent,
                                  false);
}

/**
 * Measures the header view to make sure its size is greater than 0 and will be drawn
 * https://yoda.entelect.co.za/view/9627/how-to-android-recyclerview-item-decorations
 */
private void fixLayoutSize(View view, ViewGroup parent) {
    int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(),
                                                     View.MeasureSpec.EXACTLY);
    int heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getHeight(),
                                                      View.MeasureSpec.UNSPECIFIED);

    int childWidth = ViewGroup.getChildMeasureSpec(widthSpec,
                                                   parent.getPaddingLeft() + parent.getPaddingRight(),
                                                   view.getLayoutParams().width);
    int childHeight = ViewGroup.getChildMeasureSpec(heightSpec,
                                                    parent.getPaddingTop() + parent.getPaddingBottom(),
                                                    view.getLayoutParams().height);

    view.measure(childWidth,
                 childHeight);

    view.layout(0,
                0,
                view.getMeasuredWidth(),
                view.getMeasuredHeight());
}

public interface SectionCallback {

    boolean isSection(int position);

    CharSequence getSectionHeader(int position);
}

}

XML for your header in recycler_section_header.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_item_section_text"
    android:layout_width="match_parent"
    android:layout_height="@dimen/recycler_section_header_height"
    android:background="@android:color/black"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:textColor="@android:color/white"
    android:textSize="14sp"
/>

And finally to add the Item Decoration to your RecyclerView:

RecyclerSectionItemDecoration sectionItemDecoration =
        new RecyclerSectionItemDecoration(getResources().getDimensionPixelSize(R.dimen.recycler_section_header_height),
                                          true, // true for sticky, false for not
                                          new RecyclerSectionItemDecoration.SectionCallback() {
                                              @Override
                                              public boolean isSection(int position) {
                                                  return position == 0
                                                      || people.get(position)
                                                               .getLastName()
                                                               .charAt(0) != people.get(position - 1)
                                                                                   .getLastName()
                                                                                   .charAt(0);
                                              }

                                              @Override
                                              public CharSequence getSectionHeader(int position) {
                                                  return people.get(position)
                                                               .getLastName()
                                                               .subSequence(0,
                                                                            1);
                                              }
                                          });
    recyclerView.addItemDecoration(sectionItemDecoration);

With this Item Decoration you can either make the header pinned/sticky or not with just a boolean when creating the Item Decoration.

You can find a complete working example on github: https://github.com/paetztm/recycler_view_headers

Is it possible to get a list of files under a directory of a website? How?

If a website's directory does NOT have an "index...." file, AND .htaccess has NOT been used to block access to the directory itself, then Apache will create an "index of" page for that directory. You can save that page, and its icons, using "Save page as..." along with the "Web page, complete" option (Firefox example). If you own the website, temporarily rename any "index...." file, and reference the directory locally. Then restore your "index...." file.

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

Data-frame Object has no Attribute

Quick fix: Change how excel converts imported files. Go to 'File', then 'Options', then 'Advanced'. Scroll down and uncheck 'Use system seperators'. Also change 'Decimal separator' to '.' and 'Thousands separator' to ',' . Then simply 're-save' your file in the CSV (Comma delimited) format. The root cause is usually associated with how the csv file is created. Trust that helps. Point is, why use extra code if not necessary? Cross-platform understanding and integration is key in engineering/development.

C++ display stack trace on exception

I would like to add a standard library option (i.e. cross-platform) how to generate exception backtraces, which has become available with C++11:

Use std::nested_exception and std::throw_with_nested

This won't give you a stack unwind, but in my opinion the next best thing. It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.

Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

How to get a jqGrid cell value when editing

Try this, it will give you particular column's value

onSelectRow: function(id) {
    var rowData = jQuery(this).getRowData(id); 
    var temp= rowData['name'];//replace name with you column
    alert(temp);
}

Open Redis port for remote connections

Another possibly helpful note.

Redis can be bound to multiple IPs - that's very helpful when you don't want to open it to entire world (0.0.0.0) but only make it accessible in local networks.

  1. sudo nano /etc/redis/redis.conf
  2. add your local network IP to the end of bind setting:

bind 127.0.0.1 10.0.0.1

  1. restart the service: sudo service redis-server restart

Now you can easily access redis from other computers in same network, e.g. redis-cli -h 10.0.0.1

How to go from one page to another page using javascript?

The correct solution that i get is

<html>
      <head>
        <script type="text/javascript" language="JavaScript">
                  function clickedButton()
            {

                window.location = 'new url'

            }
             </script>
      </head>

      <form name="login_form" method="post">
            ..................
            <input type="button" value="Login" onClick="clickedButton()"/>
      </form>
 </html>

Here the new url is given inside the single quote.

Bootstrap Carousel : Remove auto slide

Please try the following:

<script>
    $(document).ready(function() {      
        $('.carousel').carousel('pause');
    });
</script>

Common elements comparison between 2 lists

The solutions suggested by S.Mark and SilentGhost generally tell you how it should be done in a Pythonic way, but I thought you might also benefit from knowing why your solution doesn't work. The problem is that as soon as you find the first common element in the two lists, you return that single element only. Your solution could be fixed by creating a result list and collecting the common elements in that list:

def common_elements(list1, list2):
    result = []
    for element in list1:
        if element in list2:
            result.append(element)
    return result

An even shorter version using list comprehensions:

def common_elements(list1, list2):
    return [element for element in list1 if element in list2]

However, as I said, this is a very inefficient way of doing this -- Python's built-in set types are way more efficient as they are implemented in C internally.

Understanding unique keys for array children in React.js

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:

const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
   <li key={index}>
      {todo.text}
   </li>
);

Please refer to List and Keys - React

How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?

If you are using JNA, you can check whether com.sun.jna.Native.POINTER_SIZE == 4 (32 bit) or com.sun.jna.Native.POINTER_SIZE == 8 (64 bit).

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

This message can also occur when you specify the incorrect decryption password (yeah, lame, but not quite obvious to realize this from the error message, huh?).

I was using the command line to decrypt the recent DataBase backup for my auxiliary tool and suddenly faced this issue.

Finally, after 10 mins of grief and plus reading through this question/answers I have remembered that the password is different and everything worked just fine with the correct password.

How to select ALL children (in any level) from a parent in jQuery?

It seems that the original test case is wrong.

I can confirm that the selector #my_parent_element * works with unbind().

Let's take the following html as an example:

<div id="#my_parent_element">
  <div class="div1">
    <div class="div2">hello</div>
    <div class="div3">my</div>
  </div>
  <div class="div4">name</div>
  <div class="div5">
    <div class="div6">is</div>
    <div class="div7">
      <div class="div8">marco</div>
      <div class="div9">(try and click on any word)!</div>
    </div>
  </div>
</div>
<button class="unbind">Now, click me and try again</button>

And the jquery bit:

$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
  alert('hi!');
})
$('button.unbind').click(function() {
  $('#my_parent_element *').unbind('click');
})

You can try it here: http://jsfiddle.net/fLvwbazk/7/

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

As promised, I'm putting an example for how to use annotations to serialize/deserialize polymorphic objects, I based this example in the Animal class from the tutorial you were reading.

First of all your Animal class with the Json Annotations for the subclasses.

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
    @JsonSubTypes.Type(value = Dog.class, name = "Dog"),

    @JsonSubTypes.Type(value = Cat.class, name = "Cat") }
)
public abstract class Animal {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Then your subclasses, Dog and Cat.

public class Dog extends Animal {

    private String breed;

    public Dog() {

    }

    public Dog(String name, String breed) {
        setName(name);
        setBreed(breed);
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }
}

public class Cat extends Animal {

    public String getFavoriteToy() {
        return favoriteToy;
    }

    public Cat() {}

    public Cat(String name, String favoriteToy) {
        setName(name);
        setFavoriteToy(favoriteToy);
    }

    public void setFavoriteToy(String favoriteToy) {
        this.favoriteToy = favoriteToy;
    }

    private String favoriteToy;

}

As you can see, there is nothing special for Cat and Dog, the only one that know about them is the abstract class Animal, so when deserializing, you'll target to Animal and the ObjectMapper will return the actual instance as you can see in the following test:

public class Test {

    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();

        Animal myDog = new Dog("ruffus","english shepherd");

        Animal myCat = new Cat("goya", "mice");

        try {
            String dogJson = objectMapper.writeValueAsString(myDog);

            System.out.println(dogJson);

            Animal deserializedDog = objectMapper.readValue(dogJson, Animal.class);

            System.out.println("Deserialized dogJson Class: " + deserializedDog.getClass().getSimpleName());

            String catJson = objectMapper.writeValueAsString(myCat);

            Animal deseriliazedCat = objectMapper.readValue(catJson, Animal.class);

            System.out.println("Deserialized catJson Class: " + deseriliazedCat.getClass().getSimpleName());



        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Output after running the Test class:

{"@type":"Dog","name":"ruffus","breed":"english shepherd"}

Deserialized dogJson Class: Dog

{"@type":"Cat","name":"goya","favoriteToy":"mice"}

Deserialized catJson Class: Cat

Hope this helps,

Jose Luis

load Js file in HTML

If this is your detail.html I don't see where do you load detail.js? Maybe this

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

should be this

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

?

No log4j2 configuration file found. Using default configuration: logging only errors to the console

If you don't have the fortune of the log4j-1.2.jar on your classpath as Renko points out in his comment, you will only see the message no log4j2 configuration file found.

This is a problem if there is an error in your configuration file, as you will not be told where the problem lies upon start-up.

For instance if you have a log4j2.yaml file which log4j2 fails to process, because for example, you have not configured a YAML parser for your project, or your config is simply incorrect. You will encounter the no log4j2 configuration file found message, with no further information. This is the case even if you have a valid log4j2.xml file, as log4j2 will only attempt to process the first configuration file it finds.

I've found the best way to debug the problem is to explicitly state the configuration file you wish to use as per the command line argument mentioned above.

-Dlog4j.configurationFile=

Hopefully this will help you pinpoint if the issue is actually caused by your classloader not finding the log4j2 configuration file or something else in your configuration.

Update

You can also use the below property to change the default level of the status logger to get further information:

-Dorg.apache.logging.log4j.simplelog.StatusLogger.level=<level>

Render a string in HTML and preserve spaces and linebreaks

Just style the content with white-space: pre-wrap;.

_x000D_
_x000D_
div {_x000D_
    white-space: pre-wrap;_x000D_
}
_x000D_
<div>_x000D_
This is some text   with some extra spacing    and a_x000D_
few newlines along with some trailing spaces        _x000D_
     and five leading spaces thrown in_x000D_
for                                              good_x000D_
measure                                              _x000D_
</div>
_x000D_
_x000D_
_x000D_

How to pass datetime from c# to sql correctly?

You've already done it correctly by using a DateTime parameter with the value from the DateTime, so it should already work. Forget about ToString() - since that isn't used here.

If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).

I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357

Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.

Resolve absolute path from relative path and/or file name

stijn's solution works with subfolders under C:\Program Files (86)\,

@echo off
set projectDirMc=test.txt

for /f "delims=" %%a in ('powershell -Command "[System.IO.Path]::GetFullPath( '%projectDirMc%' )"') do @set resolvedPath=%%a

echo full path:    %resolvedPath%

Modulo operation with negative numbers

It seems the problem is that / is not floor operation.

int mod(int m, float n)
{  
  return m - floor(m/n)*n;
}

How to find longest string in the table column data

With two queries you can achieve this. This is for mysql

//will select shortest length coulmn and display its length.
// only 1 row will be selected, because we limit it by 1

SELECT column, length(column) FROM table order by length(column) asc limit 1;

//will select shortest length coulmn and display its length.

SELECT CITY, length(city) FROM STATION order by length(city) desc limit 1;

Django - Static file not found

STATICFILES_DIRS is used in development and STATIC_ROOT in production,

STATICFILES_DIRS and STATIC_ROOT should not have same folder name,

If you need to use the exact same static folder in development and production, try this method

include this in settings.py

import socket

HOSTNAME = socket.gethostname()

# if hostname same as production url name use STATIC_ROOT 
if HOSTNAME == 'www.example.com':
    STATIC_ROOT = os.path.join(BASE_DIR, "static/")

else:
    STATICFILES_DIRS = [
            os.path.join(BASE_DIR, 'static/'),
        ]

RESTful Authentication

That's the way to do that: Using OAuth 2.0 for Login.

You may use other authentication methods other then Google's as long as it supports OAuth.

LocalDate to java.util.Date and vice versa simplest conversion?

I solved this question with solution below

  import org.joda.time.LocalDate;
  Date myDate = new Date();
  LocalDate localDate = LocalDate.fromDateFields(myDate);
  System.out.println("My date using Date" Nov 18 11:23:33 BRST 2016);
  System.out.println("My date using joda.time LocalTime" 2016-11-18);

In this case localDate print your date in this format "yyyy-MM-dd"

onclick="location.href='link.html'" does not load page in Safari

You can try this:

 <a href="link.html">
       <input type="button" value="Visit Page" />
    </a>

This will create button inside a link and it works on any browser

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

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

FWIW, it smells like an error (or at least a potential source of future pain) to be using files from /usr/include when cross-compiling.

If Else If In a Sql Server Function

You'll need to create local variables for those columns, assign them during the select and use them for your conditional tests.

declare @yes_ans int,
        @no_ans int,
        @na_ans int

SELECT @yes_ans = yes_ans, @no_ans = no_ans, @na_ans = na_ans 
    from dbo.qrc_maintally 
    where school_id = @SchoolId

If @yes_ans > @no_ans and @yes_ans > @na_ans 
begin
Set @Final = 'Yes'
end
-- etc.

How to modify existing, unpushed commit messages?

I use the Git GUI as much as I can, and that gives you the option to amend the last commit:

Tick that box

Also, git rebase -i origin/masteris a nice mantra that will always present you with the commits you have done on top of master, and give you the option to amend, delete, reorder or squash. No need to get hold of that hash first.

What's a "static method" in C#?

Static variable doesn't link with object of the class. It can be accessed using classname. All object of the class will share static variable.

By making function as static, It will restrict the access of that function within that file.

PowerShell: Run command from script's directory

I often used the following code to import a module which sit under the same directory as the running script. It will first get the directory from which powershell is running

$currentPath=Split-Path ((Get-Variable MyInvocation -Scope 0).Value).MyCommand.Path

import-module "$currentPath\sqlps.ps1"

JSP : JSTL's <c:out> tag

c:out escapes HTML characters so that you can avoid cross-site scripting.

if person.name = <script>alert("Yo")</script>

the script will be executed in the second case, but not when using c:out

How to change package name of Android Project in Eclipse?

Renaming an Application- The Complete Guide

**A) for changing Just the application name
   (App name which is displayed below icon)
    in the Manifest.xml file, in <application tag, 
    android:label="YourAppName"
    then do the same in All the <activity Tags        

  B) For changing EVERYTHING 
   (folder names, Package names, Refrences,app name, etc.)
  *1) Renaming package names in gen folder and manifest.xml
      Right Click on Your project
      Android tools- Rename Application Package

  *2) Renaming package names in src folder 
      Expand src folder, Click on package (Single click) 
      Press Alt+Shift+R
      Check Update references and Rename subpackages      
   3) Renaming the app's main Folder (Optional)
      click on the application's folder (Single click)
      then Press Alt+Shift+R 

   4) Renaming application name- Refer "A)"**

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

Use :

$(PROJECT_DIR)/Project name/PrefixHeader.pch

How do you check in python whether a string contains only numbers?

Use string isdigit function:

>>> s = '12345'
>>> s.isdigit()
True
>>> s = '1abc'
>>> s.isdigit()
False

Replace a value if null or undefined in JavaScript

Logical nullish assignment, 2020+ solution

A new operator has been added, ??=. This is equivalent to value = value ?? defaultValue.

||= and &&= are similar, links below.

This checks if left side is undefined or null, short-circuiting if already defined. If not, the left side is assigned the right-side value.

Basic Examples

let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

// Equivalent to
a = a ?? true

Object/Array Examples

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

Functional Example

function config(options) {
    options.duration ??= 100
    options.speed ??= 25
    return options
}

config({ duration: 555 })   // { duration: 555, speed: 25 }
config({})                  // { duration: 100, speed: 25 }
config({ duration: null })  // { duration: 100, speed: 25 }

??= Browser Support Nov 2020 - 77%

??= Mozilla Documentation

||= Mozilla Documentation

&&= Mozilla Documentation

How to solve "Fatal error: Class 'MySQLi' not found"?

Some distributions (such as Gentoo) support multiple installations of PHP, and you have to make sure you're using one with mysqli installed and enabled.

On Gentoo, I had installed a new PHP (with the mysqli USE flag enabled), but I needed to activate the new version of PHP (since the old one must have been missing mysqli):

# eselect php list apache2
  [1]   php5.3 *
  [2]   php5.5
# eselect php set apache2 2
You have to run `/etc/init.d/apache2 restart' for the changes to take effect
# /etc/init.d/apache2 restart

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

How to turn off magic quotes on shared hosting?

If you can't turn it off, here is what I usually do:

get_magic_quotes_gpc() ? $_POST['username'] : mysql_real_escape_string($_POST['username']);

It will be placed in the database in its proper format.

JavaScript editor within Eclipse

Eclipse HTML Editor Plugin

I too have struggled with this totally obvious question. It seemed crazy that this wasn't an extremely easy-to-find feature with all the web development happening in Eclipse these days.

I was very turned off by Aptana because of how bloated it is, and the fact that it starts up a local web server (by default on port 8000) everytime you start Eclipse and you can't disable this functionality. Adobe's port of JSEclipse is now a 400Mb plugin, which is equally insane.

However, I just found a super-lightweight JavaScript editor called Eclipse HTML Editor Plugin, made by Amateras, which was exactly what I was looking for.

How do I fit an image (img) inside a div and keep the aspect ratio?

What worked for me was:

<div style='display: inline-flex; width: 80px; height: 80px;'>
<img style='max-width: 100%; max-height: 100%' src='image file'>
</div>

inline-flex was required to keep the images from going outside of the div.

Get value from SimpleXMLElement Object

If you know that the value of the XML element is a float number (latitude, longitude, distance), you can use (float)

$value = (float) $xml->code[0]->lat;

Also, (int) for integer number:

$value = (int) $xml->code[0]->distance;

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

The <Comment> tag contains two text nodes and two <br> nodes as children.

Your xpath expression was

//*[contains(text(),'ABC')]

To break this down,

  1. * is a selector that matches any element (i.e. tag) -- it returns a node-set.
  2. The [] are a conditional that operates on each individual node in that node set. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  3. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  4. contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order. Hence, it can match only the first text node in your <Comment> element -- namely BLAH BLAH BLAH. Since that doesn't match, you don't get a <Comment> in your results.

You need to change this to

//*[text()[contains(.,'ABC')]]
  1. * is a selector that matches any element (i.e. tag) -- it returns a node-set.
  2. The outer [] are a conditional that operates on each individual node in that node set -- here it operates on each element in the document.
  3. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  4. The inner [] are a conditional that operates on each node in that node set -- here each individual text node. Each individual text node is the starting point for any path in the brackets, and can also be referred to explicitly as . within the brackets. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  5. contains is a function that operates on a string. Here it is passed an individual text node (.). Since it is passed the second text node in the <Comment> tag individually, it will see the 'ABC' string and be able to match it.

Convert a string to int using sql query

Also be aware that when converting from numeric string ie '56.72' to INT you may come up against a SQL error.

Conversion failed when converting the varchar value '56.72' to data type int.

To get around this just do two converts as follows:

STRING -> NUMERIC -> INT

or

SELECT CAST(CAST (MyVarcharCol AS NUMERIC(19,4)) AS INT)

When copying data from TableA to TableB, the conversion is implicit, so you dont need the second convert (if you are happy rounding down to nearest INT):

INSERT INTO TableB (MyIntCol)
SELECT CAST(MyVarcharCol AS NUMERIC(19,4)) as [MyIntCol]
FROM TableA

Can typescript export a function?

To answer the title of your question directly because this comes up in Google first:

YES, TypeScript can export a function!

Here is a direct quote from the TS Documentation:

"Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword."

Reference Link

Editing in the Chrome debugger

This is what you are looking for:

1.- Navigate to the Source tab and open the javascript file

2.- Edit the file, right-click it and a menu will appear: click Save and save it locally.

In order to view the diff or revert your changes, right-click and select the option Local Modifications... from the menu. You will see your changes diff with respect to the original file if you expand the timestamp shown.

More detailed info here: http://www.sitepoint.com/edit-source-files-in-chrome/

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

What does the question mark and the colon (?: ternary operator) mean in objective-c?

I just learned something new about the ternary operator. The short form that omits the middle operand is truly elegant, and is one of the many reasons that C remains relevant. FYI, I first really got my head around this in the context of a routine implemented in C#, which also supports the ternary operator. Since the ternary operator is in C, it stands to reason that it would be in other languages that are essentially extensions thereof (e. g., Objective-C, C#).

Print the stack trace of an exception

Throwable.printStackTrace(..) can take a PrintWriter or PrintStream argument:

} catch (Exception ex) {
    ex.printStackTrace(new java.io.PrintStream(yourOutputStream));
}

That said, consider using a logger interface like SLF4J with an logging implementation like LOGBack or log4j.

How to find substring inside a string (or how to grep a variable)?

expr is used instead of [ rather than inside it, and variables are only expanded inside double quotes, so try this:

if expr match "$LIST" "$SOURCE"; then

But I'm not really clear what SOURCE is supposed to represent.

It looks like your code will read in a pattern from standard input, and exit if it matches a database alias, otherwise it will echo "ok". Is that what you want?

How to get the currently logged in user's user id in Django?

You can access Current logged in user by using the following code:

request.user.id

How do I verify/check/test/validate my SSH passphrase?

You can verify your SSH key passphrase by attempting to load it into your SSH agent. With OpenSSH this is done via ssh-add.

Once you're done, remember to unload your SSH passphrase from the terminal by running ssh-add -d.

What determines the monitor my app runs on?

I'm fairly sure the primary monitor is the default. If the app was coded decently, when it's closed, it'll remember where it was last at and will reopen there, but -- as you've noticed -- it isn't a default behavior.

EDIT: The way I usually do it is to have the location stored in the app's settings. On load, if there is no value for them, it defaults to the center of the screen. On closing of the form, it records its position. That way, whenever it opens, it's where it was last. I don't know of a simple way to tell it to launch onto the second monitor the first time automatically, however.

-- Kevin Fairchild

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

You can declare the books (on line 2) as an array:

title: any = 'List of books are represted in the bookstore';
books: any = []; 
constructor(private service:  AppService){
}

ngOnInit(){
  this.getBookDetails();
}

getBookDetails() {
    this.service.getBooks().subscribe(books => {
        this.books = books.json();
        console.log(this.books);
    });
}

Location of the android sdk has not been setup in the preferences in mac os?

Simply create this folder:

C:\Users\xxxxx\android-sdk\tools

and then from Window -> Preferences -> Android, put this path:

 C:\Users\xxxxx\android-sdk

.NET / C# - Convert char[] to string

Use the constructor of string which accepts a char[]

char[] c = ...;
string s = new string(c);

How can I use an array of function pointers?

The simplest solution is to give the address of the final vector you want , and modify it inside the function.

void calculation(double result[] ){  //do the calculation on result

   result[0] = 10+5;
   result[1] = 10 +6;
   .....
}

int main(){

    double result[10] = {0}; //this is the vector of the results

    calculation(result);  //this will modify result
}

how to change any data type into a string in python

Be careful if you really want to "change" the data type. Like in other cases (e.g. changing the iterator in a for loop) this might bring up unexpected behaviour:

>> dct = {1:3, 2:1}
>> len(str(dct))
12
>> print(str(dct))
{1: 31, 2: 0}
>> l = ["all","colours"]
>> len(str(l))
18

How to change root logging level programmatically for logback

using logback 1.1.3 I had to do the following (Scala code):

import ch.qos.logback.classic.Logger
import org.slf4j.LoggerFactory    
...
val root: Logger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).asInstanceOf[Logger]

How to center an element in the middle of the browser window?

I surprised that nobody said about position=fixed. It makes exactly what I asked and works in all "human" browsers and IE since 7.

How to "grep" for a filename instead of the contents of a file?

find . | grep KeywordToSearch

Here . means current directory which is value for path parameter for find command. It is piped to grep to search keyword which should return all matching result.

Note: This is case sensitive. So for example fileName and FileName are not same.

Mockito - NullpointerException when stubbing Method

In my case it was due to wrong import of the @Test annotation

Make sure you are using the following import

import org.junit.jupiter.api.Test;

Usage of __slots__?

The original question was about general use cases not only about memory. So it should be mentioned here that you also get better performance when instantiating large amounts of objects - interesting e.g. when parsing large documents into objects or from a database.

Here is a comparison of creating object trees with a million entries, using slots and without slots. As a reference also the performance when using plain dicts for the trees (Py2.7.10 on OSX):

********** RUN 1 **********
1.96036410332 <class 'css_tree_select.element.Element'>
3.02922606468 <class 'css_tree_select.element.ElementNoSlots'>
2.90828204155 dict
********** RUN 2 **********
1.77050495148 <class 'css_tree_select.element.Element'>
3.10655999184 <class 'css_tree_select.element.ElementNoSlots'>
2.84120798111 dict
********** RUN 3 **********
1.84069895744 <class 'css_tree_select.element.Element'>
3.21540498734 <class 'css_tree_select.element.ElementNoSlots'>
2.59615707397 dict
********** RUN 4 **********
1.75041103363 <class 'css_tree_select.element.Element'>
3.17366290092 <class 'css_tree_select.element.ElementNoSlots'>
2.70941114426 dict

Test classes (ident, appart from slots):

class Element(object):
    __slots__ = ['_typ', 'id', 'parent', 'childs']
    def __init__(self, typ, id, parent=None):
        self._typ = typ
        self.id = id
        self.childs = []
        if parent:
            self.parent = parent
            parent.childs.append(self)

class ElementNoSlots(object): (same, w/o slots)

testcode, verbose mode:

na, nb, nc = 100, 100, 100
for i in (1, 2, 3, 4):
    print '*' * 10, 'RUN', i, '*' * 10
    # tree with slot and no slot:
    for cls in Element, ElementNoSlots:
        t1 = time.time()
        root = cls('root', 'root')
        for i in xrange(na):
            ela = cls(typ='a', id=i, parent=root)
            for j in xrange(nb):
                elb = cls(typ='b', id=(i, j), parent=ela)
                for k in xrange(nc):
                    elc = cls(typ='c', id=(i, j, k), parent=elb)
        to =  time.time() - t1
        print to, cls
        del root

    # ref: tree with dicts only:
    t1 = time.time()
    droot = {'childs': []}
    for i in xrange(na):
        ela =  {'typ': 'a', id: i, 'childs': []}
        droot['childs'].append(ela)
        for j in xrange(nb):
            elb =  {'typ': 'b', id: (i, j), 'childs': []}
            ela['childs'].append(elb)
            for k in xrange(nc):
                elc =  {'typ': 'c', id: (i, j, k), 'childs': []}
                elb['childs'].append(elc)
    td = time.time() - t1
    print td, 'dict'
    del droot

Is there a PowerShell "string does not contain" cmdlet or syntax?

You can use the -notmatch operator to get the lines that don't have the characters you are interested in.

     Get-Content $FileName | foreach-object { 
     if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }

Reload content in modal (twitter bootstrap)

I was also stuck on this problem then I saw that the ids of the modal are the same. You need different ids of modals if you want multiple modals. I used dynamic id. Here is my code in haml:

.modal.hide.fade{"id"=> discount.id,"aria-hidden" => "true", "aria-labelledby" => "myModalLabel", :role => "dialog", :tabindex => "-1"}

you can do this

<div id="<%= some.id %>" class="modal hide fade in">
  <div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>Header</h3>
  </div>
  <div class="modal-body"></div>
  <div class="modal-footer">
    <input type="submit" class="btn btn-success" value="Save" />
  </div>
</div>

and your links to modal will be

<a data-toggle="modal" data-target="#" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>

I hope this will work for you.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

Try the following

  1. download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.

  2. Unzip the file and Run intelhaxm-android.exe.

  3. Run silent_install.bat.

In my computer Win10 x64 - VS2015 it worked

How do I manage conflicts with git submodules?

I have not seen that exact error before. But I have a guess about the trouble you are encountering. It looks like because the master and one.one branches of supery contain different refs for the subby submodule, when you merge changes from master git does not know which ref - v1.0 or v1.1 - should be kept and tracked by the one.one branch of supery.

If that is the case, then you need to select the ref that you want and commit that change to resolve the conflict. Which is exactly what you are doing with the reset command.

This is a tricky aspect of tracking different versions of a submodule in different branches of your project. But the submodule ref is just like any other component of your project. If the two different branches continue to track the same respective submodule refs after successive merges, then git should be able to work out the pattern without raising merge conflicts in future merges. On the other hand you if switch submodule refs frequently you may have to put up with a lot of conflict resolving.

HTTP Error 500.30 - ANCM In-Process Start Failure

I had an issue in my Program.cs file. I was trying to connect with AddAzureKeyVault that had been deleted long time ago.

Conclusion:

This error could come to due to any silly error in the application. Debug step by step your application startup process.

Switching users inside Docker image to a non-root user

There's no real way to do this. As a result, things like mysqld_safe fail, and you can't install mysql-server in a Debian docker container without jumping through 40 hoops because.. well... it aborts if it's not root.

You can use USER, but you won't be able to apt-get install if you're not root.

Send JSON data from Javascript to PHP?

using JSON.stringify(yourObj) or Object.toJSON(yourObj) last one is for using prototype.js, then send it using whatever you want, ajax or submit, and you use, as suggested, json_decode ( http://www.php.net/manual/en/function.json-decode.php ) to parse it in php. And then you can use it as an array.

Reference to a non-shared member requires an object reference occurs when calling public sub

Go to the Declaration of the desired object and mark it Shared.

Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX

How can I execute Shell script in Jenkinsfile?

There's the Managed Script Plugin which provides an easy way of managing user scripts. It also adds a build step action which allows you to select which user script to execute.

SQL Call Stored Procedure for each Row without using a cursor

I like to do something similar to this (though it is still very similar to using a cursor)

[code]

-- Table variable to hold list of things that need looping
DECLARE @holdStuff TABLE ( 
    id INT IDENTITY(1,1) , 
    isIterated BIT DEFAULT 0 , 
    someInt INT ,
    someBool BIT ,
    otherStuff VARCHAR(200)
)

-- Populate your @holdStuff with... stuff
INSERT INTO @holdStuff ( 
    someInt ,
    someBool ,
    otherStuff
)
SELECT  
    1 , -- someInt - int
    1 , -- someBool - bit
    'I like turtles'  -- otherStuff - varchar(200)
UNION ALL
SELECT  
    42 , -- someInt - int
    0 , -- someBool - bit
    'something profound'  -- otherStuff - varchar(200)

-- Loop tracking variables
DECLARE @tableCount INT
SET     @tableCount = (SELECT COUNT(1) FROM [@holdStuff])

DECLARE @loopCount INT
SET     @loopCount = 1

-- While loop variables
DECLARE @id INT
DECLARE @someInt INT
DECLARE @someBool BIT
DECLARE @otherStuff VARCHAR(200)

-- Loop through item in @holdStuff
WHILE (@loopCount <= @tableCount)
    BEGIN

        -- Increment the loopCount variable
        SET @loopCount = @loopCount + 1

        -- Grab the top unprocessed record
        SELECT  TOP 1 
            @id = id ,
            @someInt = someInt ,
            @someBool = someBool ,
            @otherStuff = otherStuff
        FROM    @holdStuff
        WHERE   isIterated = 0

        -- Update the grabbed record to be iterated
        UPDATE  @holdAccounts
        SET     isIterated = 1
        WHERE   id = @id

        -- Execute your stored procedure
        EXEC someRandomSp @someInt, @someBool, @otherStuff

    END

[/code]

Note that you don't need the identity or the isIterated column on your temp/variable table, i just prefer to do it this way so i don't have to delete the top record from the collection as i iterate through the loop.

How to load/edit/run/save text files (.py) into an IPython notebook cell?

I have not found a satisfying answer for this question, i.e how to load edit, run and save. Overwriting either using %%writefile or %save -f doesn't work well if you want to show incremental changes in git. It would look like you delete all the lines in filename.py and add all new lines, even though you just edit 1 line.

Conditional statement in a one line lambda function in python?

I found I COULD use "if-then" statements in a lambda. For instance:

eval_op = {
    '|'  : lambda x,y: eval(y) if (eval(x)==0) else eval(x),
    '&'  : lambda x,y: 0 if (eval(x)==0) else eval(y),
    '<'  : lambda x,y: 1 if (eval(x)<eval(y)) else 0,
    '>'  : lambda x,y: 1 if (eval(x)>eval(y)) else 0,
}

Messages Using Command prompt in Windows 7

Type "msg /?" in the command prompt to get various ways of sending meessages to a user.

Type "net send /?" in the command prompt to get another variation of sending messages across.

How can I escape latex code received through user input?

If you want to convert an existing string to raw string, then we can reassign that like below

s1 = "welcome\tto\tPython"
raw_s1 = "%r"%s1
print(raw_s1)

Will print

welcome\tto\tPython

AssertionError: View function mapping is overwriting an existing endpoint function: main

There is a fix for Flask issue #570 introduced recenty (flask 0.10) that causes this exception to be raised.

See https://github.com/mitsuhiko/flask/issues/796

So if you go to flask/app.py and comment out the 4 lines 948..951, this may help until the issue is resovled fully in a new version.

The diff of that change is here: http://github.com/mitsuhiko/flask/commit/661ee54bc2bc1ea0763ac9c226f8e14bb0beb5b1

Binding a WPF ComboBox to a custom list

I had what at first seemed to be an identical problem, but it turned out to be due to an NHibernate/WPF compatibility issue. The problem was caused by the way WPF checks for object equality. I was able to get my stuff to work by using the object ID property in the SelectedValue and SelectedValuePath properties.

<ComboBox Name="CategoryList"
          DisplayMemberPath="CategoryName"
          SelectedItem="{Binding Path=CategoryParent}"
          SelectedValue="{Binding Path=CategoryParent.ID}"
          SelectedValuePath="ID">

See the blog post from Chester, The WPF ComboBox - SelectedItem, SelectedValue, and SelectedValuePath with NHibernate, for details.

Find and replace entire mysql database

I just wanted to share how I did this find/replace thing with sql database, because I needed to replace links from Chrome's sessionbuddy db file.

  • So I exported sql database file as .txt file by using SQLite Database Browser 2.0 b1
  • Find/replace in notepad++
  • Imported the .txt file back on SQLite Database Browser 2.0 b1

Ruby on Rails: Where to define global constants?

Some options:

Using a constant:

class Card
  COLOURS = ['white', 'blue', 'black', 'red', 'green', 'yellow'].freeze
end

Lazy loaded using class instance variable:

class Card
  def self.colours
    @colours ||= ['white', 'blue', 'black', 'red', 'green', 'yellow'].freeze
  end
end

If it is a truly global constant (avoid global constants of this nature, though), you could also consider putting a top-level constant in config/initializers/my_constants.rb for example.

How to use a ViewBag to create a dropdownlist?

Use Viewbag is wrong for sending list to view.You should using Viewmodel in this case. like this:

Send Country list and City list and Other list you need to show in View:

HomeController Code:

[HttpGet]
        public ActionResult NewAgahi() // New Advertising
        {
            //--------------------------------------------------------
            // ??????? ?? ?????? ???? ????? ??? ??? ?? ???
            Country_Repository blCountry = new Country_Repository();
            Ostan_Repository blOstan = new Ostan_Repository();
            City_Repository blCity = new City_Repository();
            Mahale_Repository blMahale = new Mahale_Repository();
            Agahi_Repository blAgahi = new Agahi_Repository();

            var vm = new NewAgahi_ViewModel();
            vm.Country = blCountry.Select();
            vm.Ostan = blOstan.Select();
            vm.City = blCity.Select();
            vm.Mahale = blMahale.Select();
            //vm.Agahi = blAgahi.Select();

            return View(vm);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult NewAgahi(Agahi agahi)
        {

            if (ModelState.IsValid == true)
            {
                Agahi_Repository blAgahi = new Agahi_Repository();

                agahi.Date = DateTime.Now.Date;
                agahi.UserId = 1048;
                agahi.GroupId = 1;


                if (blAgahi.Add(agahi) == true)
                {
                    //Success
                    return JavaScript("alert('??? ??')");

                }
                else
                {
                    //Fail
                    return JavaScript("alert('????? ?? ???')");

            }

Viewmodel Code:

using ProjectName.Models.DomainModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProjectName.ViewModels
{
    public class NewAgahi_ViewModel // ???? ??????? ???? ?? ??? ??? ?? ?? ???
    { 

        public IEnumerable<Country> Country { get; set; }

        public IEnumerable<Ostan> Ostan { get; set; }

        public IEnumerable<City> City { get; set; }

        public IQueryable<Mahale> Mahale { get; set; }

        public ProjectName.Models.DomainModels.Agahi Agahi { get; set; }

    }
}

View Code:

@model ProjectName.ViewModels.NewAgahi_ViewModel

..... .....

@Html.DropDownList("CountryList", new SelectList(Model.Country, "id", "Name"))

 @Html.DropDownList("CityList", new SelectList(Model.City, "id", "Name"))

Country_Repository Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectName.Models.DomainModels;

namespace ProjectName.Models.Repositories
{
    public class Country_Repository : IDisposable
    {
        private MyWebSiteDBEntities db = null;


        public Country_Repository()
        {
            db = new DomainModels.MyWebSiteDBEntities();
        }

        public Boolean Add(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Add(entity);
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges()); 
                                                                //return "True";
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message;
                //return e.Message;
                return false;
            }
        }


        public bool Update(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Attach(entity);
                db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message; // ?? ?????????? ??? ???? ?????? ?????? ??? ?? ?????

                return false;
            }
        }

        public bool Delete(Country entity, bool autoSave = true)
        {
            try
            {
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public bool Delete(int id, bool autoSave = true)
        {
            try
            {
                var entity = db.Country.Find(id);
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public Country Find(int id)
        {
            try
            {
                return db.Country.Find(id);
            }
            catch
            {
                return null;
            }
        }


        public IQueryable<Country> Where(System.Linq.Expressions.Expression<Func<Country, bool>> predicate)
        {
            try
            {
                return db.Country.Where(predicate);
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<Country> Select()
        {
            try
            {
                return db.Country.AsQueryable();
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<TResult> Select<TResult>(System.Linq.Expressions.Expression<Func<Country, TResult>> selector)
        {
            try
            {
                return db.Country.Select(selector);
            }
            catch
            {
                return null;
            }
        }

        public int GetLastIdentity()
        {
            try
            {
                if (db.Country.Any())
                    return db.Country.OrderByDescending(p => p.id).First().id;
                else
                    return 0;
            }
            catch
            {
                return -1;
            }
        }

        public int Save()
        {
            try
            {
                return db.SaveChanges();
            }
            catch
            {
                return -1;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.db != null)
                {
                    this.db.Dispose();
                    this.db = null;
                }
            }
        }

        ~Country_Repository()
        {
            Dispose(false);
        }
    }
}

C# convert int to string with padding zeros?

You can use:

int x = 1;
x.ToString("0000");

CSS selector for first element with class

you could use first-of-type or nth-of-type(1)

_x000D_
_x000D_
.red {_x000D_
  color: green;  _x000D_
}_x000D_
_x000D_
/* .red:nth-of-type(1) */_x000D_
.red:first-of-type {_x000D_
  color: red;  _x000D_
}
_x000D_
<div class="home">_x000D_
  <span>blah</span>_x000D_
  <p class="red">first</p>_x000D_
  <p class="red">second</p>_x000D_
  <p class="red">third</p>_x000D_
  <p class="red">fourth</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Strangest language feature

In JavaScript:

2 == [2]

// Even stranger 2 == [[[2]]]

// And down-right nutty var a = { "abc" : 1 }; a[[[["abc"]]]] === a["abc"]; // this is also true

Luckily the kind folks at stackoverflow.com explained the whole thing to me: http:/stackoverflow.com/questions/1724255/why-does-2-2-in-javascript

python: changing row index of pandas data frame

When you are not sure of the number of rows, then you can do it this way:

followers_df.index = range(len(followers_df))

How do I move an existing Git submodule within a Git repository?

Note: As mentioned in the comments this answer refers to the steps needed with older versions of git. Git now has native support for moving submodules:

Since git 1.8.5, git mv old/submod new/submod works as expected and does all the plumbing for you. You might want to use git 1.9.3 or newer, because it includes fixes for submodule moving.


The process is similar to how you'd remove a submodule (see How do I remove a submodule?):

  1. Edit .gitmodules and change the path of the submodule appropriately, and put it in the index with git add .gitmodules.
  2. If needed, create the parent directory of the new location of the submodule (mkdir -p new/parent).
  3. Move all content from the old to the new directory (mv -vi old/parent/submodule new/parent/submodule).
  4. Make sure Git tracks this directory (git add new/parent).
  5. Remove the old directory with git rm --cached old/parent/submodule.
  6. Move the directory .git/modules/old/parent/submodule with all its content to .git/modules/new/parent/submodule.
  7. Edit the .git/modules/new/parent/config file, make sure that worktree item points to the new locations, so in this example it should be worktree = ../../../../../new/parent/module. Typically there should be two more .. than directories in the direct path in that place.
  8. Edit the file new/parent/module/.git, make sure that the path in it points to the correct new location inside the main project .git folder, so in this example gitdir: ../../../.git/modules/new/parent/submodule.

    git status output looks like this for me afterwards:

    # On branch master
    # Changes to be committed:
    #   (use "git reset HEAD <file>..." to unstage)
    #
    #       modified:   .gitmodules
    #       renamed:    old/parent/submodule -> new/parent/submodule
    #
    
  9. Finally, commit the changes.

Get DOS path instead of Windows path

In windows batch scripts, %~s1 expands path parameters to short names. Create this batch file:

@ECHO OFF
echo %~s1

I called mine shortNamePath.cmd and call it like this:

c:\>shortNamePath "c:\Program Files (x86)\Android\android-sdk"
c:\PROGRA~2\Android\ANDROI~1

Edit: here's a version that uses the current directory if no parameter was supplied:

@ECHO OFF
if '%1'=='' (%0 .) else echo %~s1

Called without parameters:

C:\Program Files (x86)\Android\android-sdk>shortNamePath
C:\PROGRA~2\Android\ANDROI~1

How can I access a hover state in reactjs?

For having hover effect you can simply try this code

import React from "react";
  import "./styles.css";

    export default function App() {

      function MouseOver(event) {
        event.target.style.background = 'red';
      }
      function MouseOut(event){
        event.target.style.background="";
      }
      return (
        <div className="App">
          <button onMouseOver={MouseOver} onMouseOut={MouseOut}>Hover over me!</button>
        </div>
      );
    }

Or if you want to handle this situation using useState() hook then you can try this piece of code

import React from "react";
import "./styles.css";


export default function App() {
   let [over,setOver]=React.useState(false);

   let buttonstyle={
    backgroundColor:''
  }

  if(over){
    buttonstyle.backgroundColor="green";
  }
  else{
    buttonstyle.backgroundColor='';
  }

  return (
    <div className="App">
      <button style={buttonstyle}
      onMouseOver={()=>setOver(true)} 
      onMouseOut={()=>setOver(false)}
      >Hover over me!</button>
    </div>
  );
}

Both of the above code will work for hover effect but first procedure is easier to write and understand

Correct way to initialize empty slice

As an addition to @ANisus' answer...

below is some information from the "Go in action" book, which I think is worth mentioning:

Difference between nil & empty slices

If we think of a slice like this:

[pointer] [length] [capacity]

then:

nil slice:   [nil][0][0]
empty slice: [addr][0][0] // points to an address

nil slice

They’re useful when you want to represent a slice that doesn’t exist, such as when an exception occurs in a function that returns a slice.

// Create a nil slice of integers.
var slice []int

empty slice

Empty slices are useful when you want to represent an empty collection, such as when a database query returns zero results.

// Use make to create an empty slice of integers.
slice := make([]int, 0)

// Use a slice literal to create an empty slice of integers.
slice := []int{}

Regardless of whether you’re using a nil slice or an empty slice, the built-in functions append, len, and cap work the same.


Go playground example:

package main

import (
    "fmt"
)

func main() {

    var nil_slice []int
    var empty_slice = []int{}

    fmt.Println(nil_slice == nil, len(nil_slice), cap(nil_slice))
    fmt.Println(empty_slice == nil, len(empty_slice), cap(empty_slice))

}

prints:

true 0 0
false 0 0

Adding custom radio buttons in android

In order to hide the default radio button, I'd suggest to remove the button instead of making it transparent as all visual feedback is handled by the drawable background :

android:button="@null"

Also it would be better to use styles as there are several radio buttons :

<RadioButton style="@style/RadioButtonStyle" ... />

<style name="RadioButtonStyle" parent="@android:style/Widget.CompoundButton">
    <item name="android:background">@drawable/customButtonBackground</item>
    <item name="android:button">@null</item>
</style>

You'll need the Seslyn customButtonBackground drawable too.

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

In your cshtml,

<tr ng-repeat="value in Results">                
 <td>{{value.FileReceivedOn | mydate | date : 'dd-MM-yyyy'}} </td>
</tr>

In Your JS File, maybe app.js,

Outside of app.controller, add the below filter.

Here the "mydate" is the function which you are calling for parsing the date. Here the "app" is the variable which contains the angular.module

app.filter("mydate", function () {
    var re = /\/Date\(([0-9]*)\)\//;
    return function (x) {
        var m = x.match(re);
        if (m) return new Date(parseInt(m[1]));
        else return null;
    };
});

How does autowiring work in Spring?

First, and most important - all Spring beans are managed - they "live" inside a container, called "application context".

Second, each application has an entry point to that context. Web applications have a Servlet, JSF uses a el-resolver, etc. Also, there is a place where the application context is bootstrapped and all beans - autowired. In web applications this can be a startup listener.

Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.

What is "living" in the application context? This means that the context instantiates the objects, not you. I.e. - you never make new UserServiceImpl() - the container finds each injection point and sets an instance there.

In your controllers, you just have the following:

@Controller // Defines that this class is a spring bean
@RequestMapping("/users")
public class SomeController {

    // Tells the application context to inject an instance of UserService here
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public void login(@RequestParam("username") String username,
           @RequestParam("password") String password) {

        // The UserServiceImpl is already injected and you can use it
        userService.login(username, password);

    }
}

A few notes:

  • In your applicationContext.xml you should enable the <context:component-scan> so that classes are scanned for the @Controller, @Service, etc. annotations.
  • The entry point for a Spring-MVC application is the DispatcherServlet, but it is hidden from you, and hence the direct interaction and bootstrapping of the application context happens behind the scene.
  • UserServiceImpl should also be defined as bean - either using <bean id=".." class=".."> or using the @Service annotation. Since it will be the only implementor of UserService, it will be injected.
  • Apart from the @Autowired annotation, Spring can use XML-configurable autowiring. In that case all fields that have a name or type that matches with an existing bean automatically get a bean injected. In fact, that was the initial idea of autowiring - to have fields injected with dependencies without any configuration. Other annotations like @Inject, @Resource can also be used.

Maven2 property that indicates the parent directory

Did you try ../../env_${env}.properties ?

Normally we do the following when module2 is on the same level as the sub-modules

<modules>
    <module>../sub-module1</module>
    <module>../sub-module2</module>
    <module>../sub-module3</module>
</modules>

I would think the ../.. would let you jump up two levels. If not, you might want to contact the plug in authors and see if this is a known issue.

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

In my own case I have the following error

Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '='

$this->db->select("users.username as matric_no, CONCAT(users.surname, ' ', users.first_name, ' ', users.last_name) as fullname") ->join('users', 'users.username=classroom_students.matric_no', 'left') ->where('classroom_students.session_id', $session) ->where('classroom_students.level_id', $level) ->where('classroom_students.dept_id', $dept);

After weeks of google searching I noticed that the two fields I am comparing consists of different collation name. The first one i.e username is of utf8_general_ci while the second one is of utf8_unicode_ci so I went back to the structure of the second table and changed the second field (matric_no) to utf8_general_ci and it worked like a charm.

Getting cursor position in Python

Using the standard ctypes library, this should yield the current on screen mouse coordinates without any third party modules:

from ctypes import windll, Structure, c_long, byref


class POINT(Structure):
    _fields_ = [("x", c_long), ("y", c_long)]



def queryMousePosition():
    pt = POINT()
    windll.user32.GetCursorPos(byref(pt))
    return { "x": pt.x, "y": pt.y}


pos = queryMousePosition()
print(pos)

I should mention that this code was taken from an example found here So credit goes to Nullege.com for this solution.

How to control the width of select tag?

You've simply got it backwards. Specifying a minimum width would make the select menu always be at least that width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.

You need to use max-width instead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.

Has Windows 7 Fixed the 255 Character File Path Limit?

Workarounds are not solutions, therefore the answer is "No".

Still looking for workarounds, here are possible solutions: http://support.code42.com/CrashPlan/Latest/Troubleshooting/Windows_File_Paths_Longer_Than_255_Characters

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

user authentication libraries for node.js?

A few years have passed and I'd like to introduce my authentication solution for Express. It's called Lockit. You can find the project on GitHub and a short intro at my blog.

So what are the differences to the existing solutions?

  • easy to use: set up your DB, npm install, require('lockit'), lockit(app), done
  • routes already built-in (/signup, /login, /forgot-password, etc.)
  • views already built-in (based on Bootstrap but you can easily use your own views)
  • it supports JSON communication for your AngularJS / Ember.js single page apps
  • it does NOT support OAuth and OpenID. Only username and password.
  • it works with several databases (CouchDB, MongoDB, SQL) out of the box
  • it has tests (I couldn't find any tests for Drywall)
  • it is actively maintained (compared to everyauth)
  • email verification and forgot password process (send email with token, not supported by Passport)
  • modularity: use only what you need
  • flexibility: customize all the things

Take a look at the examples.

Pandas: Appending a row to a dataframe and specify its index label

There is another solution. The next code is bad (although I think pandas needs this feature):

import pandas as pd

# empty dataframe
a = pd.DataFrame()
a.loc[0] = {'first': 111, 'second': 222}

But the next code runs fine:

import pandas as pd

# empty dataframe
a = pd.DataFrame()
a = a.append(pd.Series({'first': 111, 'second': 222}, name=0))

Getting RAW Soap Data from a Web Reference Client running in ASP.net

It looks like Tim Carter's solution doesn't work if the call to the web reference throws an exception. I've been trying to get at the raw web resonse so I can examine it (in code) in the error handler once the exception is thrown. However, I'm finding that the response log written by Tim's method is blank when the call throws an exception. I don't completely understand the code, but it appears that Tim's method cuts into the process after the point where .Net has already invalidated and discarded the web response.

I'm working with a client that's developing a web service manually with low level coding. At this point, they are adding their own internal process error messages as HTML formatted messages into the response BEFORE the SOAP formatted response. Of course, the automagic .Net web reference blows up on this. If I could get at the raw HTTP response after an exception is thrown, I could look for and parse any SOAP response within the mixed returning HTTP response and know that they received my data OK or not.

Later ...

Here's a solution that does work, even after an execption (note that I'm only after the response - could get the request too):

namespace ChuckBevitt
{
    class GetRawResponseSoapExtension : SoapExtension
    {
        //must override these three methods
        public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
        {
            return null;
        }
        public override object GetInitializer(Type serviceType)
        {
            return null;
        }
        public override void Initialize(object initializer)
        {
        }

        private bool IsResponse = false;

        public override void ProcessMessage(SoapMessage message)
        {
            //Note that ProcessMessage gets called AFTER ChainStream.
            //That's why I'm looking for AfterSerialize, rather than BeforeDeserialize
            if (message.Stage == SoapMessageStage.AfterSerialize)
                IsResponse = true;
            else
                IsResponse = false;
        }

        public override Stream ChainStream(Stream stream)
        {
            if (IsResponse)
            {
                StreamReader sr = new StreamReader(stream);
                string response = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();

                File.WriteAllText(@"C:\test.txt", response);

                byte[] ResponseBytes = Encoding.ASCII.GetBytes(response);
                MemoryStream ms = new MemoryStream(ResponseBytes);
                return ms;

            }
            else
                return stream;
        }
    }
}

Here's how you configure it in the config file:

<configuration>
     ...
  <system.web>
    <webServices>
      <soapExtensionTypes>
        <add type="ChuckBevitt.GetRawResponseSoapExtension, TestCallWebService"
           priority="1" group="0" />
      </soapExtensionTypes>
    </webServices>
  </system.web>
</configuration>

"TestCallWebService" shoud be replaced with the name of the library (that happened to be the name of the test console app I was working in).

You really shouldn't have to go to ChainStream; you should be able to do it more simply from ProcessMessage as:

public override void ProcessMessage(SoapMessage message)
{
    if (message.Stage == SoapMessageStage.BeforeDeserialize)
    {
        StreamReader sr = new StreamReader(message.Stream);
        File.WriteAllText(@"C:\test.txt", sr.ReadToEnd());
        message.Stream.Position = 0; //Will blow up 'cause type of stream ("ConnectStream") doesn't alow seek so can't reset position
    }
}

If you look up SoapMessage.Stream, it's supposed to be a read-only stream that you can use to inspect the data at this point. This is a screw-up 'cause if you do read the stream, subsequent processing bombs with no data found errors (stream was at end) and you can't reset the position to the beginning.

Interestingly, if you do both methods, the ChainStream and the ProcessMessage ways, the ProcessMessage method will work because you changed the stream type from ConnectStream to MemoryStream in ChainStream, and MemoryStream does allow seek operations. (I tried casting the ConnectStream to MemoryStream - wasn't allow.)

So ..... Microsoft should either allow seek operations on the ChainStream type or make the SoapMessage.Stream truly a read-only copy as it's supposed to be. (Write your congressman, etc...)

One further point. After creating a way to retreive the raw HTTP response after an exception, I still didn't get the full response (as determined by a HTTP sniffer). This was because when the development web service added the HTML error messages to the beginning of the response, it didn't adjust the Content-Length header, so the Content-Length value was less than the size of the actual response body. All I got was the Content-Length value number of characters - the rest were missing. Obviously, when .Net reads the response stream, it just reads the Content-Length number of characters and doesn't allow for the Content-Length value possibily being wrong. This is as it should be; but if the Content-Length header value is wrong, the only way you'll ever get the entire response body is with a HTTP sniffer (I user HTTP Analyzer from http://www.ieinspector.com).

Creating SVG elements dynamically with javascript inside HTML

Add this to html:

<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>

Try this function and adapt for you program:

var svgNS = "http://www.w3.org/2000/svg";  

function createCircle()
{
    var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
    myCircle.setAttributeNS(null,"id","mycircle");
    myCircle.setAttributeNS(null,"cx",100);
    myCircle.setAttributeNS(null,"cy",100);
    myCircle.setAttributeNS(null,"r",50);
    myCircle.setAttributeNS(null,"fill","black");
    myCircle.setAttributeNS(null,"stroke","none");

    document.getElementById("mySVG").appendChild(myCircle);
}     

File Not Found when running PHP with Nginx

When getting "File not found", my problem was that there was no symlink in the folder where was pointing this line in ngix config:

root /var/www/claims/web;

Cannot run the macro... the macro may not be available in this workbook

If you have a space in the name of the workbook you must use single quotes (') around the file name. I have also removed the full stop.

Application.Run "'Python solution macro.xlsm'!PreparetheTables"

How can I run a PHP script inside a HTML file?

<?php 
     echo '<p>Hello World</p>' 
?>

As simple as placing something along those lines within your HTML assuming your server is set-up to execute PHP in files with the HTML extension.

Context.startForegroundService() did not then call Service.startForeground()

I have a widget which does relatively frequent updates when the device is awake and I was seeing thousands of crashes in just a few days.

The issue trigger

I even noticed the issue even on my Pixel 3 XL when I wouldn't have thought the device to have much load at all. And any and all code paths were covered with startForeground(). But then I realized that in many cases my service gets the job done really quickly. I believe the trigger for my app was that the service was finishing before the system actually got around to showing a notification.

The workaround/solution

I was able to get rid of all crashes. What I did was to remove the call to stopSelf(). (I was thinking about delaying the stop until I was pretty sure the notification was shown, but I don't want the user to see the notification if it isn't necessary.) When the service has been idle for a minute or the system destroys it normally without throwing any exceptions.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    stopForeground(true);
} else {
    stopSelf();
}

Load dimension value from res/values/dimension.xml from source code

The Resource class also has a method getDimensionPixelSize() which I think will fit your needs.

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

In my case, it happenned for the master branch. Later found that my access to the project was accidentally revoked by the project manager. To cross-check, I visited the review site and couldn't see any commits of the said branch and others for that project.

Open local folder from link

Solution: Launching a Downloadable Link

The following works in all browsers, but as always there are caveats.

Background:

"URL Shortcuts" are OS dependent. The following solution is for MS Windows due to a lack of standards between environments.

If you require linux support for the solution below, please see this article.
* I have no connection to the article, YMMV.

URL shortcuts come in two forms:

  1. Files with .URL extensions are text based. Can be dynamically generated.

    [InternetShortcut]
    URL=file:///D:/

  2. Files with .LNK extension are binary. They can be generated dynamically, but require iShelLinkInterface implementer. This is complicated by default OS restrictions, which rightfully prevent an IIS process from reaching Shell.

.URL is the recommended solution, as dynamic generation is viable across Web Languages/Frameworks and allows for a KISS implementation.


Overview/Recap:

  1. Security restrictions will not allow you to open a path/launch explorer directly from the page (as stated by @Pekka).
  2. Sites hosted externally (not on your local computer) will not allow file:///... uri's under default security permissions.

Solution:

Provide a downloadable link (.URL or .LNK) to the resource. Browser behavior will be explained at end of post.

Option 1: Produce a .lnk file and save it to the server. Due to the binary nature of the .LNK file, this is not the recommended solution, but a pre-generated file should be viable.

Option 2: Produce a .url file and either save it to the server or dynamically generate it. In my situation, I am dynamically creating the .URL file.


Solution Details (.URL):

  1. Add .url to the available MIME types in your web server.

    For IIS open the site, choose MIME Types, and add the following:

    File name Extension= .url
    MIME type: application/internet-shortcut

    Per @cremax ... For Webkit Browsers like Chrome on Apache Servers add this code to .htaccess or http.config:

    SetEnvIf Request_URI ".url$" requested_url=url Header add Content-Disposition "attachment" env=requested_url

  2. The .url file is a text file formatted as follows (again, this can be dynamically generated).

    File Contents:

    [InternetShortcut]
    URL=file:///D:

  3. Provide a link to the script that generates the .url file, or to the file itself.

    If you've simply uploaded a .url file to your server, add the following to your HTML:

    <a href="URIShortcut.url">Round-About Linking</a>


Browser Dependent Behavior

Chrome: Download/Save file.url then open
In Chrome, this behavior can be augmented by choosing the "Always open files of this type" option.

FireFox: Download/Save file.url then open

Internet Explorer: Click “Open” and go straight to directory (no need to save shortcut)

Internet Explorer has the preferred behavior, but Chrome and Firefox are at least serviceable.

How to access the local Django webserver from outside world

just do this:

python manage.py runserver 0:8000

by the above command you are actually binding it to the external IP address. so now when you access your IP address with the port number, you will be able to access it in the browser without any problem.

just type in the following in the browser address bar:

<your ip address>:8000

eg:

192.168.1.130:8000

you may have to edit the settings.py add the following in the settings.py in the last line:

ALLOWED_HOSTS = ['*']

hope this will help...

Disable button after click in JQuery

*Updated

jQuery version would be something like below:

function load(recieving_id){
    $('#roommate_but').prop('disabled', true);
    $.get('include.inc.php?i=' + recieving_id, function(data) {
        $("#roommate_but").html(data);
    });
}

How to disable clicking inside div

How to disable clicking another div click until first one popup div close

Image of the example

 <p class="btn1">One</p>
 <div id="box1" class="popup">
 Test Popup Box One
 <span class="close">X</span>
 </div>

 <!-- Two -->
 <p class="btn2">Two</p>
 <div id="box2" class="popup">
 Test Popup Box Two
 <span class="close">X</span>
  </div>

<style>
.disabledbutton {
 pointer-events: none;
 }

.close {
cursor: pointer;
}

</style>
<script>
$(document).ready(function(){
//One
$(".btn1").click(function(){
  $("#box1").css('display','block');
  $(".btn2,.btn3").addClass("disabledbutton");

});
$(".close").click(function(){
  $("#box1").css('display','none');
  $(".btn2,.btn3").removeClass("disabledbutton");
});
</script>

Unable to connect to any of the specified mysql hosts. C# MySQL

In my case by removing portion "port=3306;" from the connection string solved the problem.

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

What I was trying to achieve was using already provided private key and certificate to sign message that was going someplace that needed to make sure that the message was coming from me (private keys sign while public keys encrypt).

So if you already have a .key file and a .crt file?

Try this:

Step1: Convert the key and cert to .p12 file

openssl pkcs12 -export -in certificate.crt -inkey privateKey.key -name alias -out yourconvertedfile.p12

Step 2: Import the key and create a .jsk file with a single command

keytool -importkeystore -deststorepass changeit -destkeystore keystore.jks -srckeystore umeme.p12 -srcstoretype PKCS12

Step 3: In your java:

char[] keyPassword = "changeit".toCharArray();

KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream keyStoreData = new FileInputStream("keystore.jks");

keyStore.load(keyStoreData, keyPassword);
KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(keyPassword);
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry("alias", entryPassword);

System.out.println(privateKeyEntry.toString());

If you need to sign some string using this key do the following:

Step 1: Convert the text you want to encrypt

byte[] data = "test".getBytes("UTF8");

Step 2: Get base64 encoded private key

keyStore.load(keyStoreData, keyPassword);

//get cert, pubkey and private key from the store by alias
Certificate cert = keyStore.getCertificate("localhost");
PublicKey publicKey = cert.getPublicKey();
KeyPair keyPair = new KeyPair(publicKey, (PrivateKey) key);

//sign with this alg
Signature sig = Signature.getInstance("SHA1WithRSA");
sig.initSign(keyPair.getPrivate());
sig.update(data);
byte[] signatureBytes = sig.sign();
System.out.println("Signature:" + Base64.getEncoder().encodeToString(signatureBytes));

sig.initVerify(keyPair.getPublic());
sig.update(data);

System.out.println(sig.verify(signatureBytes));

References:

  1. How to import an existing x509 certificate and private key in Java keystore to use in SSL?
  2. http://tutorials.jenkov.com/java-cryptography/keystore.html
  3. http://www.java2s.com/Code/Java/Security/RetrievingaKeyPairfromaKeyStore.htm
  4. How to sign string with private key

Final program

public static void main(String[] args) throws Exception {

    byte[] data = "test".getBytes("UTF8");

    // load keystore
    char[] keyPassword = "changeit".toCharArray();

    KeyStore keyStore = KeyStore.getInstance("JKS");
    //System.getProperty("user.dir") + "" < for a file in particular path 
    InputStream keyStoreData = new FileInputStream("keystore.jks");
    keyStore.load(keyStoreData, keyPassword);

    Key key = keyStore.getKey("localhost", keyPassword);

    Certificate cert = keyStore.getCertificate("localhost");

    PublicKey publicKey = cert.getPublicKey();

    KeyPair keyPair = new KeyPair(publicKey, (PrivateKey) key);

    Signature sig = Signature.getInstance("SHA1WithRSA");

    sig.initSign(keyPair.getPrivate());
    sig.update(data);
    byte[] signatureBytes = sig.sign();
    System.out.println("Signature:" + Base64.getEncoder().encodeToString(signatureBytes));

    sig.initVerify(keyPair.getPublic());
    sig.update(data);

    System.out.println(sig.verify(signatureBytes));
}

How to convert datetime format to date format in crystal report using C#?

In case the formatting needs to be done on Crystal Report side.

Simple way.

Crystal Report Design Window->Right click on the date field->format Field->Customize the date format per your need.

Works effectively.

How do I plot only a table in Matplotlib?

If you just wanted to change the example and put the table at the top, then loc='top' in the table declaration is what you need,

the_table = ax.table(cellText=cell_text,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='top')

Then adjusting the plot with,

plt.subplots_adjust(left=0.2, top=0.8)

A more flexible option is to put the table in its own axis using subplots,

import numpy as np
import matplotlib.pyplot as plt


fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')

axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()

which looks like this,

enter image description here

You are then free to adjust the locations of the axis as required.

What is difference between @RequestBody and @RequestParam?

@RequestParam annotation tells Spring that it should map a request parameter from the GET/POST request to your method argument. For example:

request:

GET: http://someserver.org/path?name=John&surname=Smith

endpoint code:

public User getUser(@RequestParam(value = "name") String name, 
                    @RequestParam(value = "surname") String surname){ 
    ...  
    }

So basically, while @RequestBody maps entire user request (even for POST) to a String variable, @RequestParam does so with one (or more - but it is more complicated) request param to your method argument.

Chrome DevTools Devices does not detect device when plugged in

Chrome appears to have bug renegotiating the device authentication. You can try disabling USB Debugging and enabling it again. Sometimes you'll get a pop-up asking you to trust your computer key again.

Or you can go to your Android SDK and run adb devices which will force a renegotiation.

After either (or both), Chrome should start working.

Select unique or distinct values from a list in UNIX shell script

For larger data sets where sorting may not be desirable, you can also use the following perl script:

./yourscript.ksh | perl -ne 'if (!defined $x{$_}) { print $_; $x{$_} = 1; }'

This basically just remembers every line output so that it doesn't output it again.

It has the advantage over the "sort | uniq" solution in that there's no sorting required up front.

Find text string using jQuery?

This will select just the leaf elements that contain "I am a simple string".

$('*:contains("I am a simple string")').each(function(){
     if($(this).children().length < 1) 
          $(this).css("border","solid 2px red") });

Paste the following into the address bar to test it.

javascript: $('*:contains("I am a simple string")').each(function(){ if($(this).children().length < 1) $(this).css("border","solid 2px red") }); return false;

If you want to grab just "I am a simple string". First wrap the text in an element like so.

$('*:contains("I am a simple string")').each(function(){
     if($(this).children().length < 1) 
          $(this).html( 
               $(this).text().replace(
                    /"I am a simple string"/
                    ,'<span containsStringImLookingFor="true">"I am a simple string"</span>' 
               )  
           ) 
});

and then do this.

$('*[containsStringImLookingFor]').css("border","solid 2px red");

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

Just 2 things I think make it ALWAYS preferable to use a # Temp Table rather then a CTE are:

  1. You can not put a primary key on a CTE so the data being accessed by the CTE will have to traverse each one of the indexes in the CTE's tables rather then just accessing the PK or Index on the temp table.

  2. Because you can not add constraints, indexes and primary keys to a CTE they are more prone to bugs creeping in and bad data.


-onedaywhen yesterday

Here is an example where #table constraints can prevent bad data which is not the case in CTE's

DECLARE @BadData TABLE ( 
                       ThisID int
                     , ThatID int );
INSERT INTO @BadData
       ( ThisID
       , ThatID
       ) 
VALUES
       ( 1, 1 ),
       ( 1, 2 ),
       ( 2, 2 ),
       ( 1, 1 );

IF OBJECT_ID('tempdb..#This') IS NOT NULL
    DROP TABLE #This;
CREATE TABLE #This ( 
             ThisID int NOT NULL
           , ThatID int NOT NULL
                        UNIQUE(ThisID, ThatID) );
INSERT INTO #This
SELECT * FROM @BadData;
WITH This_CTE
     AS (SELECT *
           FROM @BadData)
     SELECT *
       FROM This_CTE;

Convert tabs to spaces in Notepad++

Obsolete: This answer is correct only for an older version of Notepad++. Converting between tabs/spaces is now built into Notepad++ and the TextFX plugin is no longer available in the Plugin Manager dialog.

  • First set the "replace by spaces" setting in Preferences -> Language Menu/Tab Settings.
  • Next, open the document you wish to replace tabs with.
  • Highlight all the text (CTRL+A).
  • Then select TextFX -> TextFX Edit -> Leading spaces to tabs or tabs to spaces.

Note: Make sure TextFX Characters plugin is installed (Plugins -> Plugin manager -> Show plugin manager, Installed tab). Otherwise, there will be no TextFX menu.

How to install both Python 2.x and Python 3.x in Windows

I have installed both python 2.7.13 and python 3.6.1 on windows 10pro and I was getting the same "Fatal error" when I tried pip2 or pip3.

What I did to correct this was to go to the location of python.exe for python 2 and python 3 files and create a copy of each, I then renamed each copy to python2.exe and python3.exe depending on the python version in the installation folder. I therefore had in each python installation folder both a python.exe file and a python2.exe or python3.exe depending on the python version.

This resolved my problem when I typed either pip2 or pip3.

Git refusing to merge unrelated histories on rebase

Since all the other answers are not actually answering the question, here is a solution inspired by this answer on a related question.

So you get your error doing git rebase:

$ git rebase origin/development
fatal: refusing to merge unrelated histories
Error redoing merge 1234deadbeef1234deadbeef

This error doesn't actually cancel the rebase, but you are now in the middle of it:

$ git status
interactive rebase in progress; onto 4321beefdead
Last command done (1 command done):
   pick 1234deadbeef1234deadbeef test merge commit

So you can now do the merge by hand. Find out the parent commits of the original merge commit:

$ git log -1 1234deadbeef1234deadbeef
commit 1234deadbeef1234deadbeef
Merge: 111111111 222222222
Author: Hans Dampf
Date:   Wed Jun 6 18:04:35 2018 +0200

    test merge commit

Find out which of the two merge parents is the one that was merged into the current one (probably the second one, verify with git log 222222222), and then do the merge by hand, copying the commit message of the original merge commit:

$ git merge --allow-unrelated 222222222 --no-commit
Automatic merge went well; stopped before committing as requested
$ git commit -C 1234deadbeef1234deadbeef
[detached HEAD 909af09ec] test merge commit
 Date: Wed Jun 6 18:04:35 2018 +0200
$ git rebase --continue
Successfully rebased and updated refs/heads/test-branch.

Using Excel OleDb to get sheet names IN SHEET ORDER

I don't see any documentation that says the order in app.xml is guaranteed to be the order of the sheets. It PROBABLY is, but not according to the OOXML specification.

The workbook.xml file, on the other hand, includes the sheetId attribute, which does determine the sequence - from 1 to the number of sheets. This is according to the OOXML specification. workbook.xml is described as the place where the sequence of the sheets is kept.

So reading workbook.xml after it is extracted form the XLSX would be my recommendation. NOT app.xml. Instead of docProps/app.xml, use xl/workbook.xml and look at the element, as shown here -

`

<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
  <fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="9303" /> 
  <workbookPr defaultThemeVersion="124226" /> 
- <bookViews>
  <workbookView xWindow="120" yWindow="135" windowWidth="19035" windowHeight="8445" /> 
  </bookViews>
- <sheets>
  <sheet name="By song" sheetId="1" r:id="rId1" /> 
  <sheet name="By actors" sheetId="2" r:id="rId2" /> 
  <sheet name="By pit" sheetId="3" r:id="rId3" /> 
  </sheets>
- <definedNames>
  <definedName name="_xlnm._FilterDatabase" localSheetId="0" hidden="1">'By song'!$A$1:$O$59</definedName> 
  </definedNames>
  <calcPr calcId="145621" /> 
  </workbook>

`

Python and pip, list all versions of a package that's available?

Works with recent pip versions, no extra tools necessary:

pip install pylibmc== -v 2>/dev/null | awk '/Found link/ {print $NF}' | uniq

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

I've run into this with a couple virtual environments.

pip uninstall MySQL-python
pip install -U MySQL-python

Worked both times.

Date in to UTC format Java

What Time Zones?

No where in your question do you mention time zone. What time zone is implied that input string? What time zone do you want for your output? And, UTC is a time zone (or lack thereof depending on your mindset) not a string format.

ISO 8601

Your input string is in ISO 8601 format, except that it lacks an offset from UTC.

Joda-Time

Here is some example code in Joda-Time 2.3 to show you how to handle time zones. Joda-Time has built-in default formatters for parsing and generating String representations of date-time values.

String input = "2013-10-22T01:37:56";
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
DateTime dateTimeMontréal = dateTimeUtc.withZone( DateTimeZone.forID( "America/Montreal" );
String output = dateTimeMontréal.toString();

As for generating string representations in other formats, search StackOverflow for "Joda format".

How can I reverse a NSArray in Objective-C?

Or the Scala-way:

-(NSArray *)reverse
{
    if ( self.count < 2 )
        return self;
    else
        return [[self.tail reverse] concat:[NSArray arrayWithObject:self.head]];
}

-(id)head
{
    return self.firstObject;
}

-(NSArray *)tail
{
    if ( self.count > 1 )
        return [self subarrayWithRange:NSMakeRange(1, self.count - 1)];
    else
        return @[];
}

Changing datagridview cell color dynamically

Considere use DataBindingComplete event for update the style. The next code change the style of the cell:

    private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
    }

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

Define an <img>'s src attribute in CSS

They are right. IMG is a content element and CSS is about design. But, how about when you use some content elements or properties for design purposes? I have IMG across my web pages that must change if i change the style (the CSS).

Well this is a solution for defining IMG presentation (no really the image) in CSS style.
1: create a 1x1 transparent gif or png.
2: Assign propery "src" of IMG to that image.
3: Define final presentation with "background-image" in the CSS style.

It works like a charm :)

How to install PyQt5 on Windows?

If you have python installed completely, it can save you the hassle. All you need to do is enter the following command in your respective shell:

pip install pyqt5

And contrary to popular belief, AS LONG AS YOU HAVE PIP INSTALLED, you can do this on virtually any OS... Hope this helped!

Max length UITextField

you can extend UITextField and add an @IBInspectable object for handle it:

SWIFT 5

import UIKit
private var __maxLengths = [UITextField: Int]()
extension UITextField {
    @IBInspectable var maxLength: Int {
        get {
            guard let l = __maxLengths[self] else {
                return 150 // (global default-limit. or just, Int.max)
            }
            return l
        }
        set {
            __maxLengths[self] = newValue
            addTarget(self, action: #selector(fix), for: .editingChanged)
        }
    }
    @objc func fix(textField: UITextField) {
        if let t = textField.text {
            textField.text = String(t.prefix(maxLength))
        }
    }
}

and after that define it on attribute inspector

enter image description here

See Swift 4 original Answer

Checking if a number is an Integer in Java

/**
 * Check if the passed argument is an integer value.
 *
 * @param number double
 * @return true if the passed argument is an integer value.
 */
boolean isInteger(double number) {
    return number % 1 == 0;// if the modulus(remainder of the division) of the argument(number) with 1 is 0 then return true otherwise false.
}

Putting an if-elif-else statement on one line?

It also depends on the nature of your expressions. The general advice on the other answers of "not doing it" is quite valid for generic statements and generic expressions.

But if all you need is a "dispatch" table, like, calling a different function depending on the value of a given option, you can put the functions to call inside a dictionary.

Something like:

def save(): 
   ...
def edit():
   ...
options = {"save": save, "edit": edit, "remove": lambda : "Not Implemented"}

option = get_input()
result = options[option]()

Instead of an if-else:

if option=="save":
    save()
...

Load a Bootstrap popover content with AJAX. Is this possible?

<button type="button" id="popover2" title="" data-content="<div id='my_popover' style='height:250px;width:300px;overflow:auto;'>Loading...Please Wait</div>" data-html="true" data-toggle="popover2" class="btn btn-primary" data-original-title="A Title">Tags</button>

$('#popover2').popover({ 
    html : true,
    title: null,
    trigger: "click",
    placement:"right"
});

$("#popover2").on('shown.bs.popover', function(){
    $('#my_popover').html("dynamic content loaded");

});

check output from CalledProcessError

If you want to get stdout and stderr back (including extracting it from the CalledProcessError in the event that one occurs), use the following:

import subprocess

command = ["ls", "-l"]
try:
    output = subprocess.check_output(command, stderr=subprocess.STDOUT).decode()
    success = True 
except subprocess.CalledProcessError as e:
    output = e.output.decode()
    success = False

print(output)

This is Python 2 and 3 compatible.

If your command is a string rather than an array, prefix this with:

import shlex
command = shlex.split(command)

Maven fails to find local artifact

Even I faced this issue and solved it with 2 ways:

1) In your IDE select project and clean all projects then install all the maven dependencies by right clicking on project -> go to maven and Update project dependencies select all projects at once to install the same. Once this is done run the particular project

2) Else What you can do is check in the pom.xml for the dependencies for which you are getting error and "mvn clean install" those dependent project first and the install maven dependencies of the current project in which you facing issue. By this the dependencies of the local project will be build and jars will be created.

Where's the DateTime 'Z' format specifier?

When you use DateTime you are able to store a date and a time inside a variable.

The date can be a local time or a UTC time, it depend on you.

For example, I'm in Italy (+2 UTC)

var dt1 = new DateTime(2011, 6, 27, 12, 0, 0); // store 2011-06-27 12:00:00
var dt2 = dt1.ToUniversalTime()  // store 2011-06-27 10:00:00

So, what happen when I print dt1 and dt2 including the timezone?

dt1.ToString("MM/dd/yyyy hh:mm:ss z") 
// Compiler alert...
// Output: 06/27/2011 12:00:00 +2

dt2.ToString("MM/dd/yyyy hh:mm:ss z") 
// Compiler alert...
// Output: 06/27/2011 10:00:00 +2

dt1 and dt2 contain only a date and a time information. dt1 and dt2 don't contain the timezone offset.

So where the "+2" come from if it's not contained in the dt1 and dt2 variable?

It come from your machine clock setting.

The compiler is telling you that when you use the 'zzz' format you are writing a string that combine "DATE + TIME" (that are store in dt1 and dt2) + "TIMEZONE OFFSET" (that is not contained in dt1 and dt2 because they are DateTyme type) and it will use the offset of the server machine that it's executing the code.

The compiler tell you "Warning: the output of your code is dependent on the machine clock offset"

If i run this code on a server that is positioned in London (+1 UTC) the result will be completly different: instead of "+2" it will write "+1"

...
dt1.ToString("MM/dd/yyyy hh:mm:ss z") 
// Output: 06/27/2011 12:00:00 +1

dt2.ToString("MM/dd/yyyy hh:mm:ss z") 
// Output: 06/27/2011 10:00:00 +1

The right solution is to use DateTimeOffset data type in place of DateTime. It's available in sql Server starting from the 2008 version and in the .Net framework starting from the 3.5 version

How to write new line character to a file in Java

The BufferedWriter class offers a newLine() method. Using this will ensure platform independence.

Get input value from TextField in iOS alert in Swift

In Swift5 ans Xcode 10

Add two textfields with Save and Cancel actions and read TextFields text data

func alertWithTF() {
    //Step : 1
    let alert = UIAlertController(title: "Great Title", message: "Please input something", preferredStyle: UIAlertController.Style.alert )
    //Step : 2
    let save = UIAlertAction(title: "Save", style: .default) { (alertAction) in
        let textField = alert.textFields![0] as UITextField
        let textField2 = alert.textFields![1] as UITextField
        if textField.text != "" {
            //Read TextFields text data
            print(textField.text!)
            print("TF 1 : \(textField.text!)")
        } else {
            print("TF 1 is Empty...")
        }

        if textField2.text != "" {
            print(textField2.text!)
            print("TF 2 : \(textField2.text!)")
        } else {
            print("TF 2 is Empty...")
        }
    }

    //Step : 3
    //For first TF
    alert.addTextField { (textField) in
        textField.placeholder = "Enter your first name"
        textField.textColor = .red
    }
    //For second TF
    alert.addTextField { (textField) in
        textField.placeholder = "Enter your last name"
        textField.textColor = .blue
    }

    //Step : 4
    alert.addAction(save)
    //Cancel action
    let cancel = UIAlertAction(title: "Cancel", style: .default) { (alertAction) in }
    alert.addAction(cancel)
    //OR single line action
    //alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })

    self.present(alert, animated:true, completion: nil)

}

For more explanation https://medium.com/@chan.henryk/alert-controller-with-text-field-in-swift-3-bda7ac06026c

Binding select element to object in Angular

Create another getter for selected item

<form [formGroup]="countryForm">
  <select formControlName="country">
    <option *ngFor="let c of countries" [value]="c.id">{{c.name}}</option>
  </select>

  <p>Selected Country: {{selectedCountry?.name}}</p>
</form>

In ts :

get selectedCountry(){
  let countryId = this.countryForm.controls.country.value;
  let selected = this.countries.find(c=> c.id == countryId);
  return selected;
}

Passing structs to functions

It is possible to construct a struct inside the function arguments:

function({ .variable = PUT_DATA_HERE });

Undo git stash pop that results in merge conflict

Luckily git stash pop does not change the stash in the case of a conflict!

So nothing, to worry about, just clean up your code and try it again.

Say your codebase was clean before, you could go back to that state with: git checkout -f
Then do the stuff you forgot, e.g. git merge missing-branch
After that just fire git stash pop again and you get the same stash, that conflicted before.

Keep in mind: The stash is safe, however, uncommitted changes in the working directory are of course not. They can get messed up.

Sending cookies with postman

Enable intercepter in this way

Basically it is a chrome plug in. After installing the extention, you also need to make sure the extention is enabled from chrome side.

enter image description here

How do I send an HTML email?

You can use setText(java.lang.String text, boolean html) from MimeMessageHelper:

MimeMessage mimeMsg = javaMailSender.createMimeMessage();
MimeMessageHelper msgHelper = new MimeMessageHelper(mimeMsg, false, "utf-8");
boolean isHTML = true;
msgHelper.setText("<h1>some html</h1>", isHTML);

But you need to:

mimeMsg.saveChanges();

Before:

javaMailSender.send(mimeMsg);

XMLHttpRequest (Ajax) Error

I see 2 possible problems:

Problem 1

  • the XMLHTTPRequest object has not finished loading the data at the time you are trying to use it

Solution: assign a callback function to the objects "onreadystatechange" -event and handle the data in that function

xmlhttp.onreadystatechange = callbackFunctionName;

Once the state has reached DONE (4), the response content is ready to be read.

Problem 2

  • the XMLHTTPRequest object does not exist in all browsers (by that name)

Solution: Either use a try-catch for creating the correct object for correct browser ( ActiveXObject in IE) or use a framework, for example jQuery ajax-method

Note: if you decide to use jQuery ajax-method, you assign the callback-function with jqXHR.done()

Writing to a file in a for loop

It's preferable to use context managers to close the files automatically

with open("new.txt", "r"), open('xyz.txt', 'w') as textfile, myfile:
    for line in textfile:
        var1, var2 = line.split(",");
        myfile.writelines(var1)

How to check if character is a letter in Javascript?

So we got a first character using charArt() function then try to match ir using regular expression to check if there is an letter lowercased starting from a to z and return it results as a boolean

Boolean('#Foo'.charAt(0).match(/[a-zA-Z]/)) // false
Boolean('Foo'.charAt(0).match(/[a-zA-Z]/)) // true

How to format date and time in Android?

This will do it:

Date date = new Date();
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));

git error: failed to push some refs to remote

Best use rm -rf .git/hooks and then try git push

How does one remove a Docker image?

Update, as commented by VonC in How to remove old Docker containers.

With Docker 1.13 (Q4 2016), you now have:

docker system prune will delete ALL unused data (i.e., in order: containers stopped, volumes without containers and images with no containers).

See PR 26108 and commit 86de7c0, which are introducing a few new commands to help facilitate visualizing how much space the Docker daemon data is taking on disk and allowing for easily cleaning up "unneeded" excess.

docker system prune

WARNING! This will remove:
    - all stopped containers
    - all volumes not used by at least one container
    - all images without at least one container associated to them
Are you sure you want to continue? [y/N] y

How to change sender name (not email address) when using the linux mail command for autosending mail?

If no From: header is specified in the e-mail headers, the MTA uses the full name of the current user, in this case "Apache". You can edit full user names in /etc/passwd

How to identify platform/compiler from preprocessor macros?

Here's what I use:

#ifdef _WIN32 // note the underscore: without it, it's not msdn official!
    // Windows (x64 and x86)
#elif __unix__ // all unices, not all compilers
    // Unix
#elif __linux__
    // linux
#elif __APPLE__
    // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
#endif

EDIT: Although the above might work for the basics, remember to verify what macro you want to check for by looking at the Boost.Predef reference pages. Or just use Boost.Predef directly.

$('body').on('click', '.anything', function(){})

If you want to capture click on everything then do

$("*").click(function(){
//code here
}

I use this for selector: http://api.jquery.com/all-selector/

This is used for handling clicks: http://api.jquery.com/click/

And then use http://api.jquery.com/event.preventDefault/

To stop normal clicking actions.

Is there a unique Android device ID?

Using the code below, you can get the unique device ID of an Android OS device as a string.

deviceId = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID); 

Jenkins Slave port number for firewall

A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.

You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.

If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.

PHP check whether property exists in object or class

Just putting my 2 cents here.

Given the following class:

class Foo
{
  private $data;

  public function __construct(array $data)
  {
    $this->data = $data;
  }

  public function __get($name)
  {
    return $data[$name];
  }

  public function __isset($name)
  {
    return array_key_exists($name, $this->data);
  }
}

the following will happen:

$foo = new Foo(['key' => 'value', 'bar' => null]);

var_dump(property_exists($foo, 'key'));  // false
var_dump(isset($foo->key));  // true
var_dump(property_exists($foo, 'bar'));  // false
var_dump(isset($foo->bar));  // true, although $data['bar'] == null

Hope this will help anyone

How to copy an object in Objective-C

This is probably unpopular way. But here how I do it:

object1 = // object to copy

YourClass *object2 = [[YourClass alloc] init];
object2.property1 = object1.property1;
object2.property2 = object1.property2;
..
etc.

Quite simple and straight forward. :P

Reading an Excel file in python using pandas

Close: first you call ExcelFile, but then you call the .parse method and pass it the sheet name.

>>> xl = pd.ExcelFile("dummydata.xlsx")
>>> xl.sheet_names
[u'Sheet1', u'Sheet2', u'Sheet3']
>>> df = xl.parse("Sheet1")
>>> df.head()
                  Tid  dummy1    dummy2    dummy3    dummy4    dummy5  \
0 2006-09-01 00:00:00       0  5.894611  0.605211  3.842871  8.265307   
1 2006-09-01 01:00:00       0  5.712107  0.605211  3.416617  8.301360   
2 2006-09-01 02:00:00       0  5.105300  0.605211  3.090865  8.335395   
3 2006-09-01 03:00:00       0  4.098209  0.605211  3.198452  8.170187   
4 2006-09-01 04:00:00       0  3.338196  0.605211  2.970015  7.765058   

     dummy6  dummy7    dummy8    dummy9  
0  0.623354       0  2.579108  2.681728  
1  0.554211       0  7.210000  3.028614  
2  0.567841       0  6.940000  3.644147  
3  0.581470       0  6.630000  4.016155  
4  0.595100       0  6.350000  3.974442  

What you're doing is calling the method which lives on the class itself, rather than the instance, which is okay (although not very idiomatic), but if you're doing that you would also need to pass the sheet name:

>>> parsed = pd.io.parsers.ExcelFile.parse(xl, "Sheet1")
>>> parsed.columns
Index([u'Tid', u'dummy1', u'dummy2', u'dummy3', u'dummy4', u'dummy5', u'dummy6', u'dummy7', u'dummy8', u'dummy9'], dtype=object)

.setAttribute("disabled", false); changes editable attribute to false

Using method set and remove attribute

_x000D_
_x000D_
function radioButton(o) {_x000D_
_x000D_
  var text = document.querySelector("textarea");_x000D_
_x000D_
  if (o.value == "on") {_x000D_
    text.removeAttribute("disabled", "");_x000D_
    text.setAttribute("enabled", "");_x000D_
  } else {_x000D_
    text.removeAttribute("enabled", "");_x000D_
    text.setAttribute("disabled", "");_x000D_
  }_x000D_
  _x000D_
}
_x000D_
<input type="radio" name="radioButton" value="on" onclick = "radioButton(this)" />Enable_x000D_
<input type="radio" name="radioButton" value="off" onclick = "radioButton(this)" />Disabled<hr/>_x000D_
_x000D_
<textarea disabled ></textarea>
_x000D_
_x000D_
_x000D_

Setting different color for each series in scatter plot on matplotlib

The normal way to plot plots with points in different colors in matplotlib is to pass a list of colors as a parameter.

E.g.:

import matplotlib.pyplot
matplotlib.pyplot.scatter([1,2,3],[4,5,6],color=['red','green','blue'])

3 colors

When you have a list of lists and you want them colored per list. I think the most elegant way is that suggesyted by @DSM, just do a loop making multiple calls to scatter.

But if for some reason you wanted to do it with just one call, you can make a big list of colors, with a list comprehension and a bit of flooring division:

import matplotlib
import numpy as np

X = [1,2,3,4]
Ys = np.array([[4,8,12,16],
      [1,4,9,16],
      [17, 10, 13, 18],
      [9, 10, 18, 11],
      [4, 15, 17, 6],
      [7, 10, 8, 7],
      [9, 0, 10, 11],
      [14, 1, 15, 5],
      [8, 15, 9, 14],
       [20, 7, 1, 5]])
nCols = len(X)  
nRows = Ys.shape[0]

colors = matplotlib.cm.rainbow(np.linspace(0, 1, len(Ys)))

cs = [colors[i//len(X)] for i in range(len(Ys)*len(X))] #could be done with numpy's repmat
Xs=X*nRows #use list multiplication for repetition
matplotlib.pyplot.scatter(Xs,Ys.flatten(),color=cs)

All plotted

cs = [array([ 0.5,  0. ,  1. ,  1. ]),
 array([ 0.5,  0. ,  1. ,  1. ]),
 array([ 0.5,  0. ,  1. ,  1. ]),
 array([ 0.5,  0. ,  1. ,  1. ]),
 array([ 0.28039216,  0.33815827,  0.98516223,  1.        ]),
 array([ 0.28039216,  0.33815827,  0.98516223,  1.        ]),
 array([ 0.28039216,  0.33815827,  0.98516223,  1.        ]),
 array([ 0.28039216,  0.33815827,  0.98516223,  1.        ]),
 ...
 array([  1.00000000e+00,   1.22464680e-16,   6.12323400e-17,
          1.00000000e+00]),
 array([  1.00000000e+00,   1.22464680e-16,   6.12323400e-17,
          1.00000000e+00]),
 array([  1.00000000e+00,   1.22464680e-16,   6.12323400e-17,
          1.00000000e+00]),
 array([  1.00000000e+00,   1.22464680e-16,   6.12323400e-17,
          1.00000000e+00])]

Can you install and run apps built on the .NET framework on a Mac?

Yes you can!

As of November 2016, Microsoft now has integrated .NET Core in it's official .NET Site

They even have a new Visual Studio app that runs on MacOS