Programs & Examples On #Discrete space

Merge unequal dataframes and replace missing rows with 0

Another alternative with data.table.

EXAMPLE DATA

dt1 <- data.table(df1)
dt2 <- data.table(df2)
setkey(dt1,x)
setkey(dt2,x)

CODE

dt2[dt1,list(y=ifelse(is.na(y),0,y))]

SCCM 2012 application install "Failed" in client Software Center

The execmgr.log will show the commandline and ccmcache folder used for installation. Typically, required apps don't show on appenforce.log and some clients will have outdated appenforce or no ppenforce.log files. execmgr.log also shows required hidden uninstall actions as well.

You may want to save the blog link. I still reference it from time to time.

On npm install: Unhandled rejection Error: EACCES: permission denied

as per npm community

sudo npm cache clean --force --unsafe-perm

and then npm install goes normally.

source: npm community-unhandled-rejection-error-eacces-permission-denied

How to convert Django Model object to dict with its fields and values?

Update

The newer aggregated answer posted by @zags is more complete and elegant than my own. Please refer to that answer instead.

Original

If you are willing to define your own to_dict method like @karthiker suggested, then that just boils this problem down to a sets problem.

>>># Returns a set of all keys excluding editable = False keys
>>>dict = model_to_dict(instance)
>>>dict

{u'id': 1L, 'reference1': 1L, 'reference2': [1L], 'value': 1}


>>># Returns a set of editable = False keys, misnamed foreign keys, and normal keys
>>>otherDict = SomeModel.objects.filter(id=instance.id).values()[0]
>>>otherDict

{'created': datetime.datetime(2014, 2, 21, 4, 38, 51, tzinfo=<UTC>),
 u'id': 1L,
 'reference1_id': 1L,
 'value': 1L,
 'value2': 2L}

We need to remove the mislabeled foreign keys from otherDict.

To do this, we can use a loop that makes a new dictionary that has every item except those with underscores in them. Or, to save time, we can just add those to the original dict since dictionaries are just sets under the hood.

>>>for item in otherDict.items():
...    if "_" not in item[0]:
...            dict.update({item[0]:item[1]})
...
>>>

Thus we are left with the following dict:

>>>dict
{'created': datetime.datetime(2014, 2, 21, 4, 38, 51, tzinfo=<UTC>),
 u'id': 1L,
 'reference1': 1L,
 'reference2': [1L],
 'value': 1,
 'value2': 2L}

And you just return that.

On the downside, you can't use underscores in your editable=false field names. On the upside, this will work for any set of fields where the user-made fields do not contain underscores.

This is not the best way of doing this, but it could work as a temporary solution until a more direct method is found.

For the example below, dict would be formed based on model_to_dict and otherDict would be formed by filter's values method. I would have done this with the models themselves, but I can't get my machine to accept otherModel.

>>> import datetime
>>> dict = {u'id': 1, 'reference1': 1, 'reference2': [1], 'value': 1}
>>> otherDict = {'created': datetime.datetime(2014, 2, 21, 4, 38, 51), u'id': 1, 'reference1_id': 1, 'value': 1, 'value2': 2}
>>> for item in otherDict.items():
...     if "_" not in item[0]:
...             dict.update({item[0]:item[1]})
...
>>> dict
{'reference1': 1, 'created': datetime.datetime(2014, 2, 21, 4, 38, 51), 'value2': 2, 'value': 1, 'id': 1, 'reference2': [1]}
>>>

That should put you in a rough ballpark of the answer to your question, I hope.

How to set the maximum memory usage for JVM?

You shouldn't have to worry about the stack leaking memory (it is highly uncommon). The only time you can have the stack get out of control is with infinite (or really deep) recursion.

This is just the heap. Sorry, didn't read your question fully at first.

You need to run the JVM with the following command line argument.

-Xmx<ammount of memory>

Example:

-Xmx1024m

That will allow a max of 1GB of memory for the JVM.

How do you uninstall MySQL from Mac OS X?

I also had entries in:

/Library/Receipts/InstallHistory.plist

that i had to delete.

is there a require for json in node.js

As of node v0.5.x yes you can require your JSON just as you would require a js file.

var someObject = require('./somefile.json')

In ES6:

import someObject from ('./somefile.json')

How do I create a Python function with optional arguments?

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b

React - How to get parameter value from query string?

React Router v5.1 introduced hooks:

For

<Route path="/posts/:id">
  <BlogPost />
</Route>

You can access params / id with hook:

const { id } = useParams();

More here.

What is referencedColumnName used for in JPA?

"referencedColumnName" property is the name of the column in the table that you are making reference with the column you are anotating. Or in a short manner: it's the column referenced in the destination table. Imagine something like this: cars and persons. One person can have many cars but one car belongs only to one person (sorry, I don't like anyone else driving my car).

Table Person
name char(64) primary key
age int

Table Car
car_registration char(32) primary key
car_brand (char 64)
car_model (char64)
owner_name char(64) foreign key references Person(name)

When you implement classes you will have something like

class Person{
   ...
}

class Car{
    ...
    @ManyToOne
    @JoinColumn([column]name="owner_name", referencedColumnName="name")
    private Person owner;
}

EDIT: as @searchengine27 has commented, columnName does not exist as a field in persistence section of Java7 docs. I can't remember where I took this property from, but I remember using it, that's why I'm leaving it in my example.

Ways to implement data versioning in MongoDB

If you're looking for a ready-to-roll solution -

Mongoid has built in simple versioning

http://mongoid.org/en/mongoid/docs/extras.html#versioning

mongoid-history is a Ruby plugin that provides a significantly more complicated solution with auditing, undo and redo

https://github.com/aq1018/mongoid-history

How to display PDF file in HTML?

In html page for pc is easy to implement

<embed src="study/sample.pdf" type="application/pdf"   height="300px" width="100%">

but pdf show in mobile by this code is not possible you must need a plugin

if you have not responsive your site. Then above code pdf not show in mobile but you can put download option after the code

<embed src="study/sample.pdf" type="application/pdf"   height="300px" width="100%" class="responsive">
<a href="study/sample.pdf">download</a>

SaveFileDialog setting default path and file type?

Environment.GetSystemVariable("%SystemDrive%"); will provide the drive OS installed, and you can set filters to savedialog Obtain file path of C# save dialog box

How do I specify new lines on Python, when writing on files?

The same way with '\n', though you'd probably not need the '\r'. Is there a reason you have it in your Java version? If you do need/want it, you can use it in the same way in Python too.

Using C# regular expressions to remove HTML tags

The question is too broad to be answered definitively. Are you talking about removing all tags from a real-world HTML document, like a web page? If so, you would have to:

  • remove the <!DOCTYPE declaration or <?xml prolog if they exist
  • remove all SGML comments
  • remove the entire HEAD element
  • remove all SCRIPT and STYLE elements
  • do Grabthar-knows-what with FORM and TABLE elements
  • remove the remaining tags
  • remove the <![CDATA[ and ]]> sequences from CDATA sections but leave their contents alone

That's just off the top of my head--I'm sure there's more. Once you've done all that, you'll end up with words, sentences and paragraphs run together in some places, and big chunks of useless whitespace in others.

But, assuming you're working with just a fragment and you can get away with simply removing all tags, here's the regex I would use:

@"(?></?\w+)(?>(?:[^>'""]+|'[^']*'|""[^""]*"")*)>"

Matching single- and double-quoted strings in their own alternatives is sufficient to deal with the problem of angle brackets in attribute values. I don't see any need to explicitly match the attribute names and other stuff inside the tag, like the regex in Ryan's answer does; the first alternative handles all of that.

In case you're wondering about those (?>...) constructs, they're atomic groups. They make the regex a little more efficient, but more importantly, they prevent runaway backtracking, which is something you should always watch out for when you mix alternation and nested quantifiers as I've done. I don't really think that would be a problem here, but I know if I don't mention it, someone else will. ;-)

This regex isn't perfect, of course, but it's probably as good as you'll ever need.

How to round to 2 decimals with Python?

You can use round operator for up to 2 decimal

num = round(343.5544, 2)
print(num) // output is 343.55

Hide horizontal scrollbar on an iframe?

This answer is only applicable for websites which use Bootstrap. The responsive embed feature of the Bootstrap takes care of the scrollbars.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="http://www.youtube.com/embed/WsFWhL4Y84Y"></iframe>
</div> 

jsfiddle: http://jsfiddle.net/00qggsjj/2/

http://getbootstrap.com/components/#responsive-embed

How to Make Laravel Eloquent "IN" Query?

If you are using Query builder then you may use a blow

DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()

If you are working with Eloquent then you can use as below

$sendUsersList = Newsletter Subscription:: select ('*')
                ->whereIn('id', $send_users_list)
                ->get();

What is the mouse down selector in CSS?

I recently found out that :active:focus does the same thing in css as :active:hover if you need to override a custom css library, they might use both.

How to click a link whose href has a certain substring in Selenium?

You can do this:

//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));

//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
    if(linkList.get(i).getAttribute("href").contains("long"))
    {
        linkList.get(i).click();
        break;
    }
}

in this what we r doing is first we are finding all the <a> tags and storing them in a list.After that we are iterating the list one by one to find <a> tag whose href attribute contains long string. And then we click on that particular <a> tag and comes out of the loop.

HTML checkbox onclick called in Javascript

You can also extract the event code from the HTML, like this :

<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All" />
<label for="check_all_1">Select All</label>

<script>
function selectAll(frmElement, chkElement) {
    // ...
}
document.getElementById("check_all_1").onclick = function() {
    selectAll(document.wizard_form, this);
}
</script>

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Starting Webcam Video with different browsers

For Opera 12

window.navigator.getUserMedia(param, function(stream) {
                            video.src =window.URL.createObjectURL(stream);
                        }, videoError );

For Firefox Nightly 18.0

window.navigator.mozGetUserMedia(param, function(stream) {
                            video.mozSrcObject = stream;
                        }, videoError );

For Chrome 22

window.navigator.webkitGetUserMedia(param, function(stream) {
                            video.src =window.webkitURL.createObjectURL(stream);
                        },  videoError );

Stopping Webcam Video with different browsers

For Opera 12

video.pause();
video.src=null;

For Firefox Nightly 18.0

video.pause();
video.mozSrcObject=null;

For Chrome 22

video.pause();
video.src="";

With this the Webcam light go down everytime...

replace anchor text with jquery

function liReplace(replacement) {
    $(".dropit-submenu li").each(function() {
        var t = $(this);
        t.html(t.html().replace(replacement, "*" + replacement + "*"));
        t.children(":first").html(t.children(":first").html().replace(replacement, "*" +` `replacement + "*"));
        t.children(":first").html(t.children(":first").html().replace(replacement + " ", ""));
        alert(t.children(":first").text());
    });
}
  • First code find a title replace t.html(t.html()
  • Second code a text replace t.children(":first")

Sample <a title="alpc" href="#">alpc</a>

Pip install - Python 2.7 - Windows 7

I've seen this issue before with 2.7.14. Fixed it by :

  1. Re-install python 2.7.14
  2. During the installation, select default path and put a check mark in the installation options to add python to windows path i.e. environmental variables.
  3. After installation is complete, go to System from the Control Panel, select Advanced system settings, and clicking Environment Variables.
  4. Verify that the system variable "path" has "C:\Python\;C:\Python\Scripts;" added to the list.
  5. In cmd, run "where python" and then "where pip". Which will show for example:

    ? where python
    C:\Python\python.exe
    
    ? where pip
    C:\Python\Scripts\pip.exe
    
  6. Run pip, then it should show different pip run command options.

How to kill a nodejs process in Linux?

pkill is the easiest command line utility

pkill -f node

or

pkill -f nodejs

whatever name the process runs as for your os

Direct method from SQL command text to DataSet

Just finish it up.

string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";

DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
    DataSet ds = new DataSet();
    using (SqlCommand cmd = new SqlCommand(
        sqlCommand, new SqlConnection(connectionString)))
    {
        cmd.Connection.Open();
        DataTable table = new DataTable();
        table.Load(cmd.ExecuteReader());
        ds.Tables.Add(table);
    }
    return ds;
}

How to get the size of a range in Excel

The Range object has both width and height properties, which are measured in points.

SonarQube Exclude a directory

what version of sonar are you using? There is one option called "sonar.skippedModules=yourmodulename".

This will skip the whole module. So be aware of it.

Placeholder in UITextView

this is how I did it:

UITextView2.h

#import <UIKit/UIKit.h>

@interface UITextView2 : UITextView <UITextViewDelegate> {
 NSString *placeholder;
 UIColor *placeholderColor;
}

@property(nonatomic, retain) NSString *placeholder;
@property(nonatomic, retain) UIColor *placeholderColor;

-(void)textChanged:(NSNotification*)notif;

@end

UITextView2.m

@implementation UITextView2

@synthesize placeholder, placeholderColor;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setPlaceholder:@""];
        [self setPlaceholderColor:[UIColor lightGrayColor]];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

-(void)textChanged:(NSNotification*)notif {
    if ([[self placeholder] length]==0)
        return;
    if ([[self text] length]==0) {
        [[self viewWithTag:999] setAlpha:1];
    } else {
        [[self viewWithTag:999] setAlpha:0];
    }

}

- (void)drawRect:(CGRect)rect {
    if ([[self placeholder] length]>0) {
        UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(8, 8, 0, 0)];
        [l setFont:self.font];
        [l setTextColor:self.placeholderColor];
        [l setText:self.placeholder];
        [l setAlpha:0];
        [l setTag:999];
        [self addSubview:l];
        [l sizeToFit];
        [self sendSubviewToBack:l];
        [l release];
    }
    if ([[self text] length]==0 && [[self placeholder] length]>0) {
        [[self viewWithTag:999] setAlpha:1];
    }
    [super drawRect:rect];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}


@end

How to delete or add column in SQLITE?

I rewrote the @Udinic answer so that the code generates table creation query automatically. It also doesn't need ConnectionSource. It also has to do this inside a transaction.

public static String getOneTableDbSchema(SQLiteDatabase db, String tableName) {
    Cursor c = db.rawQuery(
            "SELECT * FROM `sqlite_master` WHERE `type` = 'table' AND `name` = '" + tableName + "'", null);
    String result = null;
    if (c.moveToFirst()) {
        result = c.getString(c.getColumnIndex("sql"));
    }
    c.close();
    return result;
}

public List<String> getTableColumns(SQLiteDatabase db, String tableName) {
    ArrayList<String> columns = new ArrayList<>();
    String cmd = "pragma table_info(" + tableName + ");";
    Cursor cur = db.rawQuery(cmd, null);

    while (cur.moveToNext()) {
        columns.add(cur.getString(cur.getColumnIndex("name")));
    }
    cur.close();

    return columns;
}

private void dropColumn(SQLiteDatabase db, String tableName, String[] columnsToRemove) {
    db.beginTransaction();
    try {
        List<String> columnNamesWithoutRemovedOnes = getTableColumns(db, tableName);
        // Remove the columns we don't want anymore from the table's list of columns
        columnNamesWithoutRemovedOnes.removeAll(Arrays.asList(columnsToRemove));

        String newColumnNamesSeparated = TextUtils.join(" , ", columnNamesWithoutRemovedOnes);
        String sql = getOneTableDbSchema(db, tableName);
        // Extract the SQL query that contains only columns
        String oldColumnsSql = sql.substring(sql.indexOf("(")+1, sql.lastIndexOf(")"));

        db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tableName + "_old;");
        db.execSQL("CREATE TABLE `" + tableName + "` (" + getSqlWithoutRemovedColumns(oldColumnsSql, columnsToRemove)+ ");");
        db.execSQL("INSERT INTO " + tableName + "(" + newColumnNamesSeparated + ") SELECT " + newColumnNamesSeparated + " FROM " + tableName + "_old;");
        db.execSQL("DROP TABLE " + tableName + "_old;");
        db.setTransactionSuccessful();
    } catch {
        //Error in between database transaction 
    } finally {
        db.endTransaction();
    }


}

WebService Client Generation Error with JDK8

I have just tried that if you use SoapUI (5.4.x) and use Apache CXF tool to generate java code, put javax.xml.accessExternalSchema = all in YOUR_JDK/jre/lib/jaxp.properties file also works.

"No such file or directory" but it exists

Added here for future reference (for users who might fall into the same case): This error happens when working on Windows (which introduces extra characters because of different line separator than Linux system) and trying to run this script (with extra characters inserted) in Linux. The error message is misleading.

In Windows, the line separator is CRLF (\r\n) whereas in linux it is LF (\n). This can be usually be chosen in text editor.

In my case, this happened due to working on Windows and uploading to Unix server for execution.

HTML button opening link in new tab

Try using below code:

<button title="button title" class="action primary tocart" onclick=" window.open('http://www.google.com', '_blank'); return false;">Google</button>

Here, the window.open with _blank as second argument of window.open function will open the link in new tab.

And by the use of return false we can remove/cancel the default behavior of the button like submit.

For more detail and live example, click here

Cluster analysis in R: determine the optimal number of clusters

If your question is how can I determine how many clusters are appropriate for a kmeans analysis of my data?, then here are some options. The wikipedia article on determining numbers of clusters has a good review of some of these methods.

First, some reproducible data (the data in the Q are... unclear to me):

n = 100
g = 6 
set.seed(g)
d <- data.frame(x = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))), 
                y = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))))
plot(d)

enter image description here

One. Look for a bend or elbow in the sum of squared error (SSE) scree plot. See http://www.statmethods.net/advstats/cluster.html & http://www.mattpeeples.net/kmeans.html for more. The location of the elbow in the resulting plot suggests a suitable number of clusters for the kmeans:

mydata <- d
wss <- (nrow(mydata)-1)*sum(apply(mydata,2,var))
  for (i in 2:15) wss[i] <- sum(kmeans(mydata,
                                       centers=i)$withinss)
plot(1:15, wss, type="b", xlab="Number of Clusters",
     ylab="Within groups sum of squares")

We might conclude that 4 clusters would be indicated by this method: enter image description here

Two. You can do partitioning around medoids to estimate the number of clusters using the pamk function in the fpc package.

library(fpc)
pamk.best <- pamk(d)
cat("number of clusters estimated by optimum average silhouette width:", pamk.best$nc, "\n")
plot(pam(d, pamk.best$nc))

enter image description here enter image description here

# we could also do:
library(fpc)
asw <- numeric(20)
for (k in 2:20)
  asw[[k]] <- pam(d, k) $ silinfo $ avg.width
k.best <- which.max(asw)
cat("silhouette-optimal number of clusters:", k.best, "\n")
# still 4

Three. Calinsky criterion: Another approach to diagnosing how many clusters suit the data. In this case we try 1 to 10 groups.

require(vegan)
fit <- cascadeKM(scale(d, center = TRUE,  scale = TRUE), 1, 10, iter = 1000)
plot(fit, sortg = TRUE, grpmts.plot = TRUE)
calinski.best <- as.numeric(which.max(fit$results[2,]))
cat("Calinski criterion optimal number of clusters:", calinski.best, "\n")
# 5 clusters!

enter image description here

Four. Determine the optimal model and number of clusters according to the Bayesian Information Criterion for expectation-maximization, initialized by hierarchical clustering for parameterized Gaussian mixture models

# See http://www.jstatsoft.org/v18/i06/paper
# http://www.stat.washington.edu/research/reports/2006/tr504.pdf
#
library(mclust)
# Run the function to see how many clusters
# it finds to be optimal, set it to search for
# at least 1 model and up 20.
d_clust <- Mclust(as.matrix(d), G=1:20)
m.best <- dim(d_clust$z)[2]
cat("model-based optimal number of clusters:", m.best, "\n")
# 4 clusters
plot(d_clust)

enter image description here enter image description here enter image description here

Five. Affinity propagation (AP) clustering, see http://dx.doi.org/10.1126/science.1136800

library(apcluster)
d.apclus <- apcluster(negDistMat(r=2), d)
cat("affinity propogation optimal number of clusters:", length(d.apclus@clusters), "\n")
# 4
heatmap(d.apclus)
plot(d.apclus, d)

enter image description here enter image description here

Six. Gap Statistic for Estimating the Number of Clusters. See also some code for a nice graphical output. Trying 2-10 clusters here:

library(cluster)
clusGap(d, kmeans, 10, B = 100, verbose = interactive())

Clustering k = 1,2,..., K.max (= 10): .. done
Bootstrapping, b = 1,2,..., B (= 100)  [one "." per sample]:
.................................................. 50 
.................................................. 100 
Clustering Gap statistic ["clusGap"].
B=100 simulated reference sets, k = 1..10
 --> Number of clusters (method 'firstSEmax', SE.factor=1): 4
          logW   E.logW        gap     SE.sim
 [1,] 5.991701 5.970454 -0.0212471 0.04388506
 [2,] 5.152666 5.367256  0.2145907 0.04057451
 [3,] 4.557779 5.069601  0.5118225 0.03215540
 [4,] 3.928959 4.880453  0.9514943 0.04630399
 [5,] 3.789319 4.766903  0.9775842 0.04826191
 [6,] 3.747539 4.670100  0.9225607 0.03898850
 [7,] 3.582373 4.590136  1.0077628 0.04892236
 [8,] 3.528791 4.509247  0.9804556 0.04701930
 [9,] 3.442481 4.433200  0.9907197 0.04935647
[10,] 3.445291 4.369232  0.9239414 0.05055486

Here's the output from Edwin Chen's implementation of the gap statistic: enter image description here

Seven. You may also find it useful to explore your data with clustergrams to visualize cluster assignment, see http://www.r-statistics.com/2010/06/clustergram-visualization-and-diagnostics-for-cluster-analysis-r-code/ for more details.

Eight. The NbClust package provides 30 indices to determine the number of clusters in a dataset.

library(NbClust)
nb <- NbClust(d, diss=NULL, distance = "euclidean",
        method = "kmeans", min.nc=2, max.nc=15, 
        index = "alllong", alphaBeale = 0.1)
hist(nb$Best.nc[1,], breaks = max(na.omit(nb$Best.nc[1,])))
# Looks like 3 is the most frequently determined number of clusters
# and curiously, four clusters is not in the output at all!

enter image description here

If your question is how can I produce a dendrogram to visualize the results of my cluster analysis, then you should start with these: http://www.statmethods.net/advstats/cluster.html http://www.r-tutor.com/gpu-computing/clustering/hierarchical-cluster-analysis http://gastonsanchez.wordpress.com/2012/10/03/7-ways-to-plot-dendrograms-in-r/ And see here for more exotic methods: http://cran.r-project.org/web/views/Cluster.html

Here are a few examples:

d_dist <- dist(as.matrix(d))   # find distance matrix 
plot(hclust(d_dist))           # apply hirarchical clustering and plot

enter image description here

# a Bayesian clustering method, good for high-dimension data, more details:
# http://vahid.probstat.ca/paper/2012-bclust.pdf
install.packages("bclust")
library(bclust)
x <- as.matrix(d)
d.bclus <- bclust(x, transformed.par = c(0, -50, log(16), 0, 0, 0))
viplot(imp(d.bclus)$var); plot(d.bclus); ditplot(d.bclus)
dptplot(d.bclus, scale = 20, horizbar.plot = TRUE,varimp = imp(d.bclus)$var, horizbar.distance = 0, dendrogram.lwd = 2)
# I just include the dendrogram here

enter image description here

Also for high-dimension data is the pvclust library which calculates p-values for hierarchical clustering via multiscale bootstrap resampling. Here's the example from the documentation (wont work on such low dimensional data as in my example):

library(pvclust)
library(MASS)
data(Boston)
boston.pv <- pvclust(Boston)
plot(boston.pv)

enter image description here

Does any of that help?

How to detect if a browser is Chrome using jQuery?

When I test the answer @IE, I got always "true". The better way is this which works also @IE:

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

As described in this answer: https://stackoverflow.com/a/4565120/1201725

How to show alert message in mvc 4 controller?

Use this:

return JavaScript(alert("Hello this is an alert"));

or:

return Content("<script language='javascript' type='text/javascript'>alert('Thanks for Feedback!');</script>");

mysqldump with create database line

Here is how to do dump the database (with just the schema):

mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql

If you also want the data, remove the --no-data option.

How to get CRON to call in the correct PATHs

Set the required PATH in your cron

crontab -e

Edit: Press i

PATH=/usr/local/bin:/usr/local/:or_whatever

10 * * * * your_command

Save and exit :wq

Difference between VARCHAR and TEXT in MySQL

There is an important detail that has been omitted in the answer above.

MySQL imposes a limit of 65,535 bytes for the max size of each row. The size of a VARCHAR column is counted towards the maximum row size, while TEXT columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.

Also note that the actual number of bytes required by a VARCHAR field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4 (which you almost certainly should) it will use up even more of your maximum row size.

Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR/TEXT field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)

Reasons to use TEXT:

  • If you want to store a paragraph or more of text
  • If you don't need to index the column
  • If you have reached the row size limit for your table

Reasons to use VARCHAR:

  • If you want to store a few words or a sentence
  • If you want to index the (entire) column
  • If you want to use the column with foreign-key constraints

Is there a JavaScript function that can pad a string to get to a determined length?

1. function
var _padLeft = function(paddingString, width, replacementChar) {
    return paddingString.length >= width ? paddingString : _padLeft(replacementChar + paddingString, width, replacementChar || ' ');
};

2. String prototype
String.prototype.padLeft = function(width, replacementChar) {
        return this.length >= width ? this.toString() : (replacementChar + this).padLeft(width, replacementChar || ' ');
};

3. slice
('00000' + paddingString).slice(-5)

Enzyme - How to access and set <input> value?

Got it. (updated/improved version)

  it('cancels changes when user presses esc', done => {
    const wrapper = mount(<EditableText defaultValue="Hello" />);
    const input = wrapper.find('input');

    input.simulate('focus');
    input.simulate('change', { target: { value: 'Changed' } });
    input.simulate('keyDown', {
      which: 27,
      target: {
        blur() {
          // Needed since <EditableText /> calls target.blur()
          input.simulate('blur');
        },
      },
    });
    expect(input.get(0).value).to.equal('Hello');

    done();
  });

How do I find the authoritative name-server for a domain name?

You can use the whois service. On a UNIX like operating system you would execute the following command. Alternatively you can do it on the web at http://www.internic.net/whois.html.

whois stackoverflow.com

You would get the following response.

...text removed here...

Domain servers in listed order: NS51.DOMAINCONTROL.COM NS52.DOMAINCONTROL.COM

You can use nslookup or dig to find out more information about records for a given domain. This might help you resolve the conflicts you have described.

DBMS_OUTPUT.PUT_LINE not printing

What is "it" in the statement "it just says the procedure is completed"?

By default, most tools do not configure a buffer for dbms_output to write to and do not attempt to read from that buffer after code executes. Most tools, on the other hand, have the ability to do so. In SQL*Plus, you'd need to use the command set serveroutput on [size N|unlimited]. So you'd do something like

SQL> set serveroutput on size 30000;
SQL> exec print_actor_quotes( <<some value>> );

In SQL Developer, you'd go to View | DBMS Output to enable the DBMS Output window, then push the green plus icon to enable DBMS Output for a particular session.

Additionally, assuming that you don't want to print the literal "a.firstNamea.lastName" for every row, you probably want

FOR row IN quote_recs
LOOP
  DBMS_OUTPUT.PUT_LINE( row.firstName || ' ' || row.lastName );
END LOOP;

Google Colab: how to read data from my google drive?

What I have done is first:

from google.colab import drive
drive.mount('/content/drive/')

Then

%cd /content/drive/My Drive/Colab Notebooks/

After I can for example read csv files with

df = pd.read_csv("data_example.csv")

If you have different locations for the files just add the correct path after My Drive

How to upgrade Angular CLI project?

JJB's answer got me on the right track, but the upgrade didn't go very smoothly. My process is detailed below. Hopefully the process becomes easier in the future and JJB's answer can be used or something even more straightforward.

Solution Details

I have followed the steps captured in JJB's answer to update the angular-cli precisely. However, after running npm install angular-cli was broken. Even trying to do ng version would produce an error. So I couldn't do the ng init command. See error below:

$ ng init
core_1.Version is not a constructor
TypeError: core_1.Version is not a constructor
    at Object.<anonymous> (C:\_git\my-project\code\src\main\frontend\node_modules\@angular\compiler-cli\src\version.js:18:19)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    ...

To be able to use any angular-cli commands, I had to update my package.json file by hand and bump the @angular dependencies to 2.4.1, then do another npm install.

After this I was able to do ng init. I updated my configuration files, but none of my app/* files. When this was done, I was still getting errors. The first one is detailed below, the second was the same type of error but in a different file.

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 62:9 in the original .ts file), resolving symbol AppModule in C:/_git/my-project/code/src/main/frontend/src/app/app.module.ts

This error is tied to the following factory provider in my AppModule

{ provide: Http, useFactory: 
    (backend: XHRBackend, options: RequestOptions, router: Router, navigationService: NavigationService, errorService: ErrorService) => {
    return new HttpRerouteProvider(backend, options, router, navigationService, errorService);  
  }, deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
}

To address this error, I had use an exported function and made the following change to the provider.

    { 
      provide: Http, 
      useFactory: httpFactory, 
      deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
    }

... // elsewhere in AppModule

export function httpFactory(backend: XHRBackend, 
                            options: RequestOptions, 
                            router: Router, 
                            navigationService: NavigationService, 
                            errorService: ErrorService) {
  return new HttpRerouteProvider(backend, options, router, navigationService, errorService);
}

Summary

To summarize what I understand to be the most important details, the following changes were required:

  1. Update angular-cli version using the steps detailed in JJB's answer (and on their github page).

  2. Updating @angular version by hand, 2.0.0 did not seem to be supported by angular-cli version 1.0.0-beta.24

  3. With the assistance of angular-cli and the ng init command, I updated my configuration files. I think the critical changes were to angular-cli.json and package.json. See configuration file changes at the bottom.

  4. Make code changes to export functions before I reference them, as captured in the solution details.

Key Configuration Changes

angular-cli.json changes

{
  "project": {
    "version": "1.0.0-beta.16",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": "assets",
...

changed to...

{
  "project": {
    "version": "1.0.0-beta.24",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
...

My package.json looks like this after a manual merge that considers the versions used by ng-init. Note my angular version is not 2.4.1, but the change I was after was component inheritance which was introduced in 2.3, so I was fine with these versions. The original package.json is in the question.

{
  "name": "frontend",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor",
    "build": "ng build",
    "buildProd": "ng build --env=prod"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.3.1",
    "@angular/compiler": "^2.3.1",
    "@angular/core": "^2.3.1",
    "@angular/forms": "^2.3.1",
    "@angular/http": "^2.3.1",
    "@angular/platform-browser": "^2.3.1",
    "@angular/platform-browser-dynamic": "^2.3.1",
    "@angular/router": "^3.3.1",
    "@angular/material": "^2.0.0-beta.1",
    "@types/google-libphonenumber": "^7.4.8",
    "angular2-datatable": "^0.4.2",
    "apollo-client": "^0.4.22",
    "core-js": "^2.4.1",
    "rxjs": "^5.0.1",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.7.2",
    "google-libphonenumber": "^2.0.4",
    "graphql-tag": "^0.1.15",
    "hammerjs": "^2.0.8",
    "ng2-bootstrap": "^1.1.16"
  },
  "devDependencies": {
    "@types/hammerjs": "^2.0.33",
    "@angular/compiler-cli": "^2.3.1",
    "@types/jasmine": "2.5.38",
    "@types/lodash": "^4.14.39",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.24",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.0.2",
    "typescript": "~2.0.3",
    "typings": "1.4.0"
  }
}

1064 error in CREATE TABLE ... TYPE=MYISAM

A complementary note about CREATE TABLE .. TYPE="" syntax in SQL dump files

TLDR: If you still get CREATE TABLE ... TYPE="..." statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode of MYSQL40 or MYSQL323.

Long story

As it was said by others, the TYPE argument to CREATE TABLE has been deprecated for a long time in MySQL. mysqldump correctly uses the ENGINE argument, unless you specifically ask it to generate a backward compatible dump (for example using --compatible=mysql40 in versions of mysqldump up to 5.7).

However, many external SQL dump tools (for example, those integrated in MySQL clients such as phpmyadmin, Navicat and DBVisualizer, as well as those used by external automated backup services such as iControlWP) are not specifically aware of this change, and instead rely on the SHOW CREATE TABLE ... command to provide table creation statements for each tables (and just to it make it clear: this is actually a good thing). However, the SHOW CREATE TABLE will actually produce outdated syntax, including the TYPE argument, if the sqlmode variable is set to MYSQL40 or MYSQL323.

Therefore, if you still get CREATE TABLE ... TYPE="..." statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode of MYSQL40 or MYSQL323.

These sqlmodes basically configure MySQL to retain some backward compatible behaviours, and using them by default was largely recommended a few years ago. It is however highly improbable that you still have any code that wouldn't work correctly without these modes. Anyway, MYSQL40, MYSQL323 and several other similar sqlmodes have themselves been deprecated and are not supported in MySQL 8.0 and higher.

If your server is still configured with these sqlmodes and you are worried that some legacy program might fail if you change these, then one possibility is to set the sqlmode locally for that program, by executing SET SESSION sql_mode = 'MYSQL40'; immediately after connection. Note that this should only be considered as a temporary patch, and will not work in MySQL 8.0 and higher.

A more future-proof solution that do not involve rewriting your SQL queries would be to determine exactly which compatibility features need to be enable, and to enable only those, on a per-program basis (as described previously). The default sqlmode (that is, in server's configuration) should ideally be left unset (which will use official MySQL defaults for your current version). The full list of sqlmode (as of MySQL 5.7) is described here: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html.

Start/Stop and Restart Jenkins service on Windows

Open Console/Command line --> Go to your Jenkins installation directory. Execute the following commands respectively:

to stop:
jenkins.exe stop

to start:
jenkins.exe start

to restart:
jenkins.exe restart

Current user in Magento?

$customer = Mage::getSingleton('customer/session')->getCustomer();
    $customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
    $address = Mage::getModel('customer/address')->load($customerAddressId);
    $fullname = $customer->getName();
    $firstname = $customer->getFirstname();
    $lastname = $customer->getLastname();
    $email = $customer->getEmail();
    $taxvat = $customer->getTaxvat();
    $tele = $customer->getTelephone();
    $telephone = $address->getTelephone();
    $street = $address->getStreet();
    $City = $address->getCity();
    $region = $address->getRegion();
    $postcode = $address->getPostcode();

Get customer Default Billing address

OS specific instructions in CMAKE: How to?

I want to leave this here because I struggled with this when compiling for Android in Windows with the Android SDK.

CMake distinguishes between TARGET and HOST platform.

My TARGET was Android so the variables like CMAKE_SYSTEM_NAME had the value "Android" and the variable WIN32 from the other answer here was not defined. But I wanted to know if my HOST system was Windows because I needed to do a few things differently when compiling on either Windows or Linux or IOs. To do that I used CMAKE_HOST_SYSTEM_NAME which I found is barely known or mentioned anywhere because for most people TARGEt and HOST are the same or they don't care.

Hope this helps someone somewhere...

How to load a UIView using a nib file created with Interface Builder

This is a great question (+1) and the answers were almost helpful ;) Sorry guys, but I had a heck of a time slogging through this, though both Gonso & AVeryDev gave good hints. Hopefully, this answer will help others.

MyVC is the view controller holding all this stuff.

MySubview is the view that we want to load from a xib

  • In MyVC.xib, create a view of type MySubView that is the right size & shape & positioned where you want it.
  • In MyVC.h, have

    IBOutlet MySubview *mySubView
    // ...
    @property (nonatomic, retain) MySubview *mySubview;
    
  • In MyVC.m, @synthesize mySubView; and don't forget to release it in dealloc.

  • In MySubview.h, have an outlet/property for UIView *view (may be unnecessary, but worked for me.) Synthesize & release it in .m
  • In MySubview.xib
    • set file owner type to MySubview, and link the view property to your view.
    • Lay out all the bits & connect to the IBOutlet's as desired
  • Back in MyVC.m, have

    NSArray *xibviews = [[NSBundle mainBundle] loadNibNamed: @"MySubview" owner: mySubview options: NULL];
    MySubview *msView = [xibviews objectAtIndex: 0];
    msView.frame = mySubview.frame;
    UIView *oldView = mySubview;
    // Too simple: [self.view insertSubview: msView aboveSubview: mySubview];
    [[mySubview superview] insertSubview: msView aboveSubview: mySubview]; // allows nesting
    self.mySubview = msView;
    [oldCBView removeFromSuperview];
    

The tricky bit for me was: the hints in the other answers loaded my view from the xib, but did NOT replace the view in MyVC (duh!) -- I had to swap that out on my own.

Also, to get access to mySubview's methods, the view property in the .xib file must be set to MySubview. Otherwise, it comes back as a plain-old UIView.

If there's a way to load mySubview directly from its own xib, that'd rock, but this got me where I needed to be.

How do you dismiss the keyboard when editing a UITextField

I set the delegate of the UITextField to my ViewController class.

In that class I implemented this method as following:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}

Using Node.js require vs. ES6 import/export

The main advantages are syntactic:

  • More declarative/compact syntax
  • ES6 modules will basically make UMD (Universal Module Definition) obsolete - essentially removes the schism between CommonJS and AMD (server vs browser).

You are unlikely to see any performance benefits with ES6 modules. You will still need an extra library to bundle the modules, even when there is full support for ES6 features in the browser.

Using Mockito to test abstract classes

Mocking frameworks are designed to make it easier to mock out dependencies of the class you are testing. When you use a mocking framework to mock a class, most frameworks dynamically create a subclass, and replace the method implementation with code for detecting when a method is called and returning a fake value.

When testing an abstract class, you want to execute the non-abstract methods of the Subject Under Test (SUT), so a mocking framework isn't what you want.

Part of the confusion is that the answer to the question you linked to said to hand-craft a mock that extends from your abstract class. I wouldn't call such a class a mock. A mock is a class that is used as a replacement for a dependency, is programmed with expectations, and can be queried to see if those expectations are met.

Instead, I suggest defining a non-abstract subclass of your abstract class in your test. If that results in too much code, than that may be a sign that your class is difficult to extend.

An alternative solution would be to make your test case itself abstract, with an abstract method for creating the SUT (in other words, the test case would use the Template Method design pattern).

What is the difference between T(n) and O(n)?

one is Big "O"

one is Big Theta

http://en.wikipedia.org/wiki/Big_O_notation

Big O means your algorithm will execute in no more steps than in given expression(n^2)

Big Omega means your algorithm will execute in no fewer steps than in the given expression(n^2)

When both condition are true for the same expression, you can use the big theta notation....

how to set JAVA_OPTS for Tomcat in Windows?

Apparently the correct form is without the ""

As in

set JAVA_OPTS=-Xms512M -Xmx1024M

how to set textbox value in jquery

Note that the .value attribute is a JavaScript feature. If you want to use jQuery, use:

$('#pid').val()

to get the value, and:

$('#pid').val('value')

to set it.

http://api.jquery.com/val/

Regarding your second issue, I have never tried automatically setting the HTML value using the load method. For sure, you can do something like this:

$('#subtotal').load( 'compz.php?prodid=' + x + '&qbuys=' + y, function(response){ $('#subtotal').val(response);
});

Note that the code above is untested.

http://api.jquery.com/load/

CSS disable text selection

::selection,::moz-selection {color:currentColor;background:transparent}

Inline style to act as :hover in CSS

I put together a quick solution for anyone wanting to create hover popups without CSS using the onmouseover and onmouseout behaviors.

http://jsfiddle.net/Lk9w1mkv/

<div style="position:relative;width:100px;background:#ddffdd;overflow:hidden;" onmouseover="this.style.overflow='';" onmouseout="this.style.overflow='hidden';">first hover<div style="width:100px;position:absolute;top:5px;left:110px;background:white;border:1px solid gray;">stuff inside</div></div>

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Important Note: As of mid-2018, the process to get twitter API tokens became a lot more bureaucratic. It has taken me over one working week to be provided a set of API tokens, and this is for an open source project for you guys and girls with over 1.2 million installations on Packagist and 1.6k stars on Github, which theoretically should be higher priority.

If you are tasked with working with the twitter API for your work, you must take this potentially extremely long wait-time into account. Also consider other social media avenues like Facebook or Instagram and provide these options, as the process for retrieving their tokens is instant.


So you want to use the Twitter v1.1 API?

Note: the files for these are on GitHub.

Version 1.0 will soon be deprecated and unauthorised requests won't be allowed. So, here's a post to help you do just that, along with a PHP class to make your life easier.

1. Create a developer account: Set yourself up a developer account on Twitter

You need to visit the official Twitter developer site and register for a developer account. This is a free and necessary step to make requests for the v1.1 API.

2. Create an application: Create an application on the Twitter developer site

What? You thought you could make unauthenticated requests? Not with Twitter's v1.1 API. You need to visit http://dev.twitter.com/apps and click the "Create Application" button.

Enter image description here

On this page, fill in whatever details you want. For me, it didn't matter, because I just wanted to make a load of block requests to get rid of spam followers. The point is you are going to get yourself a set of unique keys to use for your application.

So, the point of creating an application is to give yourself (and Twitter) a set of keys. These are:

  • The consumer key
  • The consumer secret
  • The access token
  • The access token secret

There's a little bit of information here on what these tokens for.

3. Create access tokens: You'll need these to make successful requests

OAuth requests a few tokens. So you need to have them generated for you.

Enter image description here

Click "create my access token" at the bottom. Then once you scroll to the bottom again, you'll have some newly generated keys. You need to grab the four previously labelled keys from this page for your API calls, so make a note of them somewhere.

4. Change access level: You don't want read-only, do you?

If you want to make any decent use of this API, you'll need to change your settings to Read & Write if you're doing anything other than standard data retrieval using GET requests.

Enter image description here

Choose the "Settings" tab near the top of the page.

Enter image description here

Give your application read / write access, and hit "Update" at the bottom.

You can read more about the applications permission model that Twitter uses here.


5. Write code to access the API: I've done most of it for you

I combined the code above, with some modifications and changes, into a PHP class so it's really simple to make the requests you require.

This uses OAuth and the Twitter v1.1 API, and the class I've created which you can find below.

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",
    'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",
    'consumer_key' => "YOUR_CONSUMER_KEY",
    'consumer_secret' => "YOUR_CONSUMER_SECRET"
);

Make sure you put the keys you got from your application above in their respective spaces.

Next you need to choose a URL you want to make a request to. Twitter has their API documentation to help you choose which URL and also the request type (POST or GET).

/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
$url = 'https://api.twitter.com/1.1/blocks/create.json';
$requestMethod = 'POST';

In the documentation, each URL states what you can pass to it. If we're using the "blocks" URL like the one above, I can pass the following POST parameters:

/** POST fields required by the URL above. See relevant docs as above **/
$postfields = array(
    'screen_name' => 'usernameToBlock', 
    'skip_status' => '1'
);

Now that you've set up what you want to do with the API, it's time to make the actual request.

/** Perform the request and echo the response **/
$twitter = new TwitterAPIExchange($settings);
echo $twitter->buildOauth($url, $requestMethod)
             ->setPostfields($postfields)
             ->performRequest();

And for a POST request, that's it!

For a GET request, it's a little different. Here's an example:

/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?username=J7mbo';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();     

Final code example: For a simple GET request for a list of my followers.

$url = 'https://api.twitter.com/1.1/followers/list.json';
$getfield = '?username=J7mbo&skip_status=1';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();  

I've put these files on GitHub with credit to @lackovic10 and @rivers! I hope someone finds it useful; I know I did (I used it for bulk blocking in a loop).

Also, for those on Windows who are having problems with SSL certificates, look at this post. This library uses cURL under the hood so you need to make sure you have your cURL certs set up probably. Google is also your friend.

How do you use colspan and rowspan in HTML tables?

It is similar to your table

  <table border=1 width=50%>
<tr>
    <td rowspan="2">x</td> 
    <td colspan="4">y</td>
</tr>
<tr>
    <td bgcolor=#FFFF00 >I</td>
    <td>II</td>
    <td bgcolor=#FFFF00>III</td>
    <td>IV</td>
</tr>
<tr>
    <td>empty</td>
    <td bgcolor=#FFFF00>1</td>
    <td>2</td>
    <td bgcolor=#FFFF00>3</td>
    <td>4</td>
</tr>

How do you use global variables or constant values in Ruby?

One thing you need to realize is in Ruby everything is an object. Given that, if you don't define your methods within Module or Class, Ruby will put it within the Object class. So, your code will be local to the Object scope.

A typical approach on Object Oriented Programming is encapsulate all logic within a class:

class Point
  attr_accessor :x, :y

  # If we don't specify coordinates, we start at 0.
  def initialize(x = 0, y = 0)
    # Notice that `@` indicates instance variables.
    @x = x
    @y = y
  end

  # Here we override the `+' operator.
  def +(point)
    Point.new(self.x + point.x, self.y + point.y)
  end

  # Here we draw the point.
  def draw(offset = nil)
    if offset.nil?
      new_point = self
    else
      new_point = self + offset 
    end
    new_point.draw_absolute
  end

  def draw_absolute
    puts "x: #{self.x}, y: #{self.y}"
  end
end

first_point = Point.new(100, 200)
second_point = Point.new(3, 4)

second_point.draw(first_point)

Hope this clarifies a bit.

Combine two or more columns in a dataframe into a new column with a new name

There are other great answers, but in the case where you don't know the column names or the number of columns you want to concatenate beforehand, the following is useful.

df = data.frame(x = letters[1:5], y = letters[6:10], z = letters[11:15])
colNames = colnames(df) # could be any number of column names here
df$newColumn = apply(df[, colNames, drop = F], MARGIN = 1, FUN = function(i) paste(i, collapse = ""))

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

Go to resources folder where the application.properties is present, update the below code in that.

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

the MySQL service on local computer started and then stopped

Delete or rename the 2 following files from "C:\ProgramData\MySQL\MySQL Server 5.7\Data": ib_logfile0 ib_logfile1

Best way to Bulk Insert from a C# DataTable

If using SQL Server, SqlBulkCopy.WriteToServer(DataTable)

Or also with SQL Server, you can write it to a .csv and use BULK INSERT

If using MySQL, you could write it to a .csv and use LOAD DATA INFILE

If using Oracle, you can use the array binding feature of ODP.NET

If SQLite:

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:

$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});

If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:

$.post('/url/to/page', {'someKeyName': ['value','value']});

If you want to pass a JavaScript array then you can do:

$.post('/url/to/page', {'someKeyName': variableName});

MySQL Fire Trigger for both Insert and Update

You have to create two triggers, but you can move the common code into a procedure and have them both call the procedure.

Laravel 5 Application Key

You can generate a key by the following command:

php artisan key:generate 

The key will be written automatically in your .env file.

APP_KEY=YOUR_GENERATED_KEY

If you want to see your key after generation use --show option

php artisan key:generate --show

Note: The .env is a hidden file in your project folder.

enter image description here

Best way to check for nullable bool in a condition expression (if ...)

I think a lot of people concentrate on the fact that this value is nullable, and don't think about what they actually want :)

bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else { ... } // false or null

Or if you want more options...

bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else if (nullableBool == false) { ... } // false
else { ... } // null

(nullableBool == true) will never return true if the bool? is null :P

MySQL combine two columns and add into a new column

SELECT CONCAT (zipcode, ' - ', city, ', ', state) AS COMBINED FROM TABLE

Why my regexp for hyphenated words doesn't work?

This regex should do it.

\b[a-z]+-[a-z]+\b 

\b indicates a word-boundary.

What are all codecs and formats supported by FFmpeg?

ffmpeg -codecs

should give you all the info about the codecs available.

You will see some letters next to the codecs:

Codecs:
 D..... = Decoding supported
 .E.... = Encoding supported
 ..V... = Video codec
 ..A... = Audio codec
 ..S... = Subtitle codec
 ...I.. = Intra frame-only codec
 ....L. = Lossy compression
 .....S = Lossless compression

How to display multiple images in one figure correctly?

You could try the following:

import matplotlib.pyplot as plt
import numpy as np

def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in zip(range(len(figures)), figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional



# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}

# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)

plt.show()

However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.

I hope this helps.

Example use of "continue" statement in Python?

I like to use continue in loops where there are a lot of contitions to be fulfilled before you get "down to business". So instead of code like this:

for x, y in zip(a, b):
    if x > y:
        z = calculate_z(x, y)
        if y - z < x:
            y = min(y, z)
            if x ** 2 - y ** 2 > 0:
                lots()
                of()
                code()
                here()

I get code like this:

for x, y in zip(a, b):
    if x <= y:
        continue
    z = calculate_z(x, y)
    if y - z >= x:
        continue
    y = min(y, z)
    if x ** 2 - y ** 2 <= 0:
        continue
    lots()
    of()
    code()
    here()

By doing it this way I avoid very deeply nested code. Also, it is easy to optimize the loop by eliminating the most frequently occurring cases first, so that I only have to deal with the infrequent but important cases (e.g. divisor is 0) when there is no other showstopper.

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

This is a good example to demonstrate that BFS is better than DFS in certain case. https://leetcode.com/problems/01-matrix/

When correctly implemented, both solutions should visit cells that have farther distance than the current cell +1. But DFS is inefficient and repeatedly visited the same cell resulting O(n*n) complexity.

For example,

1,1,1,1,1,1,1,1, 
1,1,1,1,1,1,1,1, 
1,1,1,1,1,1,1,1, 
0,0,0,0,0,0,0,0,

Oracle: how to set user password unexpire?

The following statement causes a user's password to expire:

ALTER USER user PASSWORD EXPIRE;

If you cause a database user's password to expire with PASSWORD EXPIRE, then the user (or the DBA) must change the password before attempting to log in to the database following the expiration. Tools such as SQL*Plus allow the user to change the password on the first attempted login following the expiration.

ALTER USER scott IDENTIFIED BY password;

Will set/reset the users password.

See the alter user doc for more info

How to get MAC address of your machine using a C program?

A very portable way is to parse the output of this command.

ifconfig | awk '$0 ~ /HWaddr/ { print $5 }'

Provided ifconfig can be run as the current user (usually can) and awk is installed (it often is). This will give you the mac address of the machine.

Beginner Python: AttributeError: 'list' object has no attribute

They are lists because you type them as lists in the dictionary:

bikes = {
    # Bike designed for children"
    "Trike": ["Trike", 20, 100],
    # Bike designed for everyone"
    "Kruzer": ["Kruzer", 50, 165]
    }

You should use the bike-class instead:

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165)
    }

This will allow you to get the cost of the bikes with bike.cost as you were trying to.

for bike in bikes.values():
    profit = bike.cost * margin
    print(bike.name + " : " + str(profit))

This will now print:

Kruzer : 33.0
Trike : 20.0

How to send UTF-8 email?

You can add header "Content-Type: text/html; charset=UTF-8" to your message body.

$headers = "Content-Type: text/html; charset=UTF-8";

If you use native mail() function $headers array will be the 4th parameter mail($to, $subject, $message, $headers)

If you user PEAR Mail::factory() code will be:

$smtp = Mail::factory('smtp', $params);

$mail = $smtp->send($to, $headers, $body);

Android: Internet connectivity change listener

Here's the Java code using registerDefaultNetworkCallback (and registerNetworkCallback for API < 24):

ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        // network available
    }

    @Override
    public void onLost(Network network) {
        // network unavailable
    }
};

ConnectivityManager connectivityManager =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
    NetworkRequest request = new NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
    connectivityManager.registerNetworkCallback(request, networkCallback);
}

Background service with location listener in android

Very easy no need create class extends LocationListener 1- Variable

private LocationManager mLocationManager;
private LocationListener mLocationListener;
private static double currentLat =0;
private static double currentLon =0;

2- onStartService()

@Override public void onStartService() {
    addListenerLocation();
}

3- Method addListenerLocation()

 private void addListenerLocation() {
    mLocationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            currentLat = location.getLatitude();
            currentLon = location.getLongitude();

            Toast.makeText(getBaseContext(),currentLat+"-"+currentLon, Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
            Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if(lastKnownLocation!=null){
                currentLat = lastKnownLocation.getLatitude();
                currentLon = lastKnownLocation.getLongitude();
            }

        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };
    mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 500, 10, mLocationListener);
}

4- onDestroy()

@Override
public void onDestroy() {
    super.onDestroy();
    mLocationManager.removeUpdates(mLocationListener);
}

Argument Exception "Item with Same Key has already been added"

That Exception is thrown if there is already a key in the dictionary when you try to add the new one.

There must be more than one line in rct3Lines with the same first word. You can't have 2 entries in the same dictionary with the same key.

You need to decide what you want to happen if the key already exists - if you want to just update the value where the key exists you can simply

rct3Features[items[0]]=items[1]

but, if not you may want to test if the key already exists with:

if(rect3Features.ContainsKey(items[0]))
{
    //Do something
} 
else 
{
    //Do something else
}

Generic Interface

If I understand correctly, you want to have one class implement multiple of those interfaces with different input/output parameters? This will not work in Java, because the generics are implemented via erasure.

The problem with the Java generics is that the generics are in fact nothing but compiler magic. At runtime, the classes do not keep any information about the types used for generic stuff (class type parameters, method type parameters, interface type parameters). Therefore, even though you could have overloads of specific methods, you cannot bind those to multiple interface implementations which differ in their generic type parameters only.

In general, I can see why you think that this code has a smell. However, in order to provide you with a better solution, it would be necessary to know a little more about your requirements. Why do you want to use a generic interface in the first place?

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.

SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;

Find out the history of SQL queries

    select v.SQL_TEXT,
           v.PARSING_SCHEMA_NAME,
           v.FIRST_LOAD_TIME,
           v.DISK_READS,
           v.ROWS_PROCESSED,
           v.ELAPSED_TIME,
           v.service
      from v$sql v
where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss')>ADD_MONTHS(trunc(sysdate,'MM'),-2)

where clause is optional. You can sort the results according to FIRST_LOAD_TIME and find the records up to 2 months ago.

How can I pass POST parameters in a URL?

I would like to share my implementation as well. It does require some JavaScript code though.

<form action="./index.php" id="homePage" method="post" style="display: none;">
    <input type="hidden" name="action" value="homePage" />
</form>

<a href="javascript:;" onclick="javascript:
document.getElementById('homePage').submit()">Home</a>

The nice thing about this is that, contrary to GET requests, it doesn't show the parameters in the URL, which is safer.

Variable might not have been initialized error

You haven't initialised a and b, only declared them. There is a subtle difference.

int a = 0;
int b = 0;

At least this is for C++, I presume Java is the same concept.

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

My Problem has also been solved by changing in styles.xml

<!-- Base application theme. -->
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

How to scroll to bottom in a ScrollView on activity startup

After initializing your UI component and fill it with data. add those line to your on create method

Runnable runnable=new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    };
    scrollView.post(runnable);

JavaScript closures vs. anonymous functions

In a nutshell Javascript Closures allow a function to access a variable that is declared in a lexical-parent function.

Let's see a more detailed explanation. To understand closures it is important to understand how JavaScript scopes variables.

Scopes

In JavaScript scopes are defined with functions. Every function defines a new scope.

Consider the following example;

function f()
{//begin of scope f
  var foo='hello'; //foo is declared in scope f
  for(var i=0;i<2;i++){//i is declared in scope f
     //the for loop is not a function, therefore we are still in scope f
     var bar = 'Am I accessible?';//bar is declared in scope f
     console.log(foo);
  }
  console.log(i);
  console.log(bar);
}//end of scope f

calling f prints

hello
hello
2
Am I Accessible?

Let's now consider the case we have a function g defined within another function f.

function f()
{//begin of scope f
  function g()
  {//being of scope g
    /*...*/
  }//end of scope g
  /*...*/
}//end of scope f

We will call f the lexical parent of g. As explained before we now have 2 scopes; the scope f and the scope g.

But one scope is "within" the other scope, so is the scope of the child function part of the scope of the parent function? What happens with the variables declared in the scope of the parent function; will I be able to access them from the scope of the child function? That's exactly where closures step in.

Closures

In JavaScript the function g can not only access any variables declared in scope g but also access any variables declared in the scope of the parent function f.

Consider following;

function f()//lexical parent function
{//begin of scope f
  var foo='hello'; //foo declared in scope f
  function g()
  {//being of scope g
    var bar='bla'; //bar declared in scope g
    console.log(foo);
  }//end of scope g
  g();
  console.log(bar);
}//end of scope f

calling f prints

hello
undefined

Let's look at the line console.log(foo);. At this point we are in scope g and we try to access the variable foo that is declared in scope f. But as stated before we can access any variable declared in a lexical parent function which is the case here; g is the lexical parent of f. Therefore hello is printed.
Let's now look at the line console.log(bar);. At this point we are in scope f and we try to access the variable bar that is declared in scope g. bar is not declared in the current scope and the function g is not the parent of f, therefore bar is undefined

Actually we can also access the variables declared in the scope of a lexical "grand parent" function. Therefore if there would be a function h defined within the function g

function f()
{//begin of scope f
  function g()
  {//being of scope g
    function h()
    {//being of scope h
      /*...*/
    }//end of scope h
    /*...*/
  }//end of scope g
  /*...*/
}//end of scope f

then h would be able to access all the variables declared in the scope of function h, g, and f. This is done with closures. In JavaScript closures allows us to access any variable declared in the lexical parent function, in the lexical grand parent function, in the lexical grand-grand parent function, etc. This can be seen as a scope chain; scope of current function -> scope of lexical parent function -> scope of lexical grand parent function -> ... until the last parent function that has no lexical parent.

The window object

Actually the chain doesn't stop at the last parent function. There is one more special scope; the global scope. Every variable not declared in a function is considered to be declared in the global scope. The global scope has two specialities;

  • every variable declared in the global scope is accessible everywhere
  • the variables declared in the global scope correspond to the properties of the window object.

Therefore there are exactly two ways of declaring a variable foo in the global scope; either by not declaring it in a function or by setting the property foo of the window object.

Both attempts uses closures

Now that you have read a more detailed explanation it may now be apparent that both solutions uses closures. But to be sure, let's make a proof.

Let's create a new Programming Language; JavaScript-No-Closure. As the name suggests, JavaScript-No-Closure is identical to JavaScript except it doesn't support Closures.

In other words;

var foo = 'hello';
function f(){console.log(foo)};
f();
//JavaScript-No-Closure prints undefined
//JavaSript prints hello

Alright, let's see what happens with the first solution with JavaScript-No-Closure;

for(var i = 0; i < 10; i++) {
  (function(){
    var i2 = i;
    setTimeout(function(){
        console.log(i2); //i2 is undefined in JavaScript-No-Closure 
    }, 1000)
  })();
}

therefore this will print undefined 10 times in JavaScript-No-Closure.

Hence the first solution uses closure.

Let's look at the second solution;

for(var i = 0; i < 10; i++) {
  setTimeout((function(i2){
    return function() {
        console.log(i2); //i2 is undefined in JavaScript-No-Closure
    }
  })(i), 1000);
}

therefore this will print undefined 10 times in JavaScript-No-Closure.

Both solutions uses closures.

Edit: It is assumed that these 3 code snippets are not defined in the global scope. Otherwise the variables foo and i would be bind to the window object and therefore accessible through the window object in both JavaScript and JavaScript-No-Closure.

CentOS 64 bit bad ELF interpreter

In general, when you get an error like this, just do

yum provides ld-linux.so.2

then you'll see something like:

glibc-2.20-5.fc21.i686 : The GNU libc libraries
Repo        : fedora
Matched from:
Provides    : ld-linux.so.2

and then you just run the following like BRPocock wrote (in case you were wondering what the logic was...):

yum install glibc.i686

What is the purpose of the return statement?

return means, "output this value from this function".

print means, "send this value to (generally) stdout"

In the Python REPL, a function return will be output to the screen by default (this isn't quite the same as print).

This is an example of print:

>>> n = "foo\nbar" #just assigning a variable. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>

This is an example of return:

>>> def getN():
...    return "foo\nbar"
...
>>> getN() #When this isn't assigned to something, it is just output
'foo\nbar'
>>> n = getN() # assigning a variable to the return value. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>

Create an array of integers property in Objective-C

You can put this in your .h file for your class and define it as property, in XCode 7:

@property int  (*stuffILike) [10];

Split an integer into digits to compute an ISBN checksum

How about a one-liner list of digits...

ldigits = lambda n, l=[]: not n and l or l.insert(0,n%10) or ldigits(n/10,l)

Detect WebBrowser complete page loading

I think the DocumentCompleted event will get fired for all child documents that are loaded as well (like JS and CSS, for example). You could look at the WebBrowserDocumentCompletedEventArgs in DocumentCompleted and check the Url property and compare that to the Url of the main page.

Encrypt and decrypt a password in Java

Jasypt can do it for you easy and simple

Writing a string to a cell in excel

replace Range("A1") = "Asdf" with Range("A1").value = "Asdf"

Load vs. Stress testing

-> Testing the app with maximum number of user and input is defined as load testing. While testing the app with more than maximum number of user and input is defined as stress testing.

->In Load testing we measure the system performance based on a volume of users. While in Stress testing we measure the breakpoint of a system.

->Load Testing is testing the application for a given load requirements which may include any of the following criteria:

 .Total number of users.

 .Response Time

 .Through Put

Some parameters to check State of servers/application.

-> While stress testing is testing the application for unexpected load. It includes

 .Vusers

 .Think-Time

Example:

If an app is build for 500 users, then for load testing we check up to 500 users and for stress testing we check greater than 500.

What is the best way to filter a Java Collection?

With the ForEach DSL you may write

import static ch.akuhn.util.query.Query.select;
import static ch.akuhn.util.query.Query.$result;
import ch.akuhn.util.query.Select;

Collection<String> collection = ...

for (Select<String> each : select(collection)) {
    each.yield = each.value.length() > 3;
}

Collection<String> result = $result();

Given a collection of [The, quick, brown, fox, jumps, over, the, lazy, dog] this results in [quick, brown, jumps, over, lazy], ie all strings longer than three characters.

All iteration styles supported by the ForEach DSL are

  • AllSatisfy
  • AnySatisfy
  • Collect
  • Counnt
  • CutPieces
  • Detect
  • GroupedBy
  • IndexOf
  • InjectInto
  • Reject
  • Select

For more details, please refer to https://www.iam.unibe.ch/scg/svn_repos/Sources/ForEach

If statement with String comparison fails

You shouldn't do string comparisons with ==. That operator will only check to see if it is the same instance, not the same value. Use the .equals method to check for the same value.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

Warning: Do not use this in production code!

As a workaround, you can switch off certificate validation. Only ever do this to obtain confirmation that the error is being throw because of a bad certificate.

Call this method before you call smtpclient.Send():

    [Obsolete("Do not use this in Production code!!!",true)]
    static void NEVER_EAT_POISON_Disable_CertificateValidation()
    {
        // Disabling certificate validation can expose you to a man-in-the-middle attack
        // which may allow your encrypted message to be read by an attacker
        // https://stackoverflow.com/a/14907718/740639
        ServicePointManager.ServerCertificateValidationCallback =
            delegate (
                object s,
                X509Certificate certificate,
                X509Chain chain,
                SslPolicyErrors sslPolicyErrors
            ) {
                return true;
            };
    }

How do I see the commit differences between branches in git?

You can get a really nice, visual output of how your branches differ with this

git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative master..branch-X

Listen to changes within a DIV and act accordingly

http://api.jquery.com/change/

change does only work on input form elements.

you could just trigger a function after your XML / XSL transformation or make a listener:

var html = $('#laneconfigdisplay').html()
setInterval(function(){ if($('#laneconfigdisplay').html() != html){ alert('woo'); html = $('#laneconfigdisplay').html() } }, 10000) //checks your content box all 10 seconds and triggers alert when content has changed...

Twitter bootstrap scrollable modal

Your modal is being hidden in firefox, and that is because of the negative margin declaration you have inside your general stylesheet:

.modal {
    margin-top: -45%; /* remove this */
    max-height: 90%;
    overflow-y: auto;
}

Remove the negative margin and everything works just fine.

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

Multiple GitHub Accounts & SSH Config

I posted the technique I use to deal with these here

How to get the current TimeStamp?

Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch() to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.

Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.

How to tell if JRE or JDK is installed

Normally a jdk installation has javac in the environment path variables ... so if you check for javac in the path, that's pretty much a good indicator that you have a jdk installed.

Localhost : 404 not found

you need to stop that service running on this port .check service running on specific port by "netstat -ano".then in window search type services.exe and search that process and stop that process .to change port of that process check this http://seankilleen.com/2012/11/how-to-stop-sql-server-reporting-services-from-using-port-80-on-your-server-field-notes/

c# Best Method to create a log file

I would recommend log4net.

You would need multiple log files. So multiple file appenders. Plus you can create the file appenders dynamically.

Sample Code:

using log4net;
using log4net.Appender;
using log4net.Layout;
using log4net.Repository.Hierarchy;

// Set the level for a named logger
public static void SetLevel(string loggerName, string levelName)
{
    ILog log = LogManager.GetLogger(loggerName);
    Logger l = (Logger)log.Logger;

    l.Level = l.Hierarchy.LevelMap[levelName];
    }

// Add an appender to a logger
public static void AddAppender(string loggerName, IAppender appender)
{
    ILog log = LogManager.GetLogger(loggerName);
    Logger l = (Logger)log.Logger;

    l.AddAppender(appender);
}

// Create a new file appender
public static IAppender CreateFileAppender(string name, string fileName)
{
    FileAppender appender = new
        FileAppender();
    appender.Name = name;
    appender.File = fileName;
    appender.AppendToFile = true;

    PatternLayout layout = new PatternLayout();
    layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n";
    layout.ActivateOptions();

    appender.Layout = layout;
    appender.ActivateOptions();

    return appender;
}

// In order to set the level for a logger and add an appender reference you
// can then use the following calls:
SetLevel("Log4net.MainForm", "ALL");
AddAppender("Log4net.MainForm", CreateFileAppender("appenderName", "fileName.log"));

// repeat as desired

Sources/Good links:

Log4Net: Programmatically specify multiple loggers (with multiple file appenders)

Adding appenders programmatically

How to configure log4net programmatically from scratch (no config)

Plus the log4net also allows to write into event log as well. Everything is configuration based, and the configuration can be loaded dynamically from xml at runtime as well.

Edit 2:

One way to switch log files on the fly: Log4Net configuration file supports environment variables:

Environment.SetEnvironmentVariable("log4netFileName", "MyApp.log");

and in the log4net config:

<param name="File" value="${log4netFileName}".log/>

Align div right in Bootstrap 3

Do you mean something like this:

HTML

<div class="row">
  <div class="container">

    <div class="col-md-4">
      left content
    </div>

    <div class="col-md-4 col-md-offset-4">

      <div class="yellow-background">
        text
        <div class="pull-right">right content</div>  
      </div>

    </div>
  </div>
</div>

CSS

.yellow-background {
  background: blue;
}

.pull-right {
  background: yellow;
}

A full example can be found on Codepen.

Using malloc for allocation of multi-dimensional arrays with different row lengths

First, you need to allocate array of pointers like char **c = malloc( N * sizeof( char* )), then allocate each row with a separate call to malloc, probably in the loop:


/* N is the number of rows  */
/* note: c is char** */
if (( c = malloc( N*sizeof( char* ))) == NULL )
{ /* error */ }

for ( i = 0; i < N; i++ )
{
  /* x_i here is the size of given row, no need to
   * multiply by sizeof( char ), it's always 1
   */
  if (( c[i] = malloc( x_i )) == NULL )
  { /* error */ }

  /* probably init the row here */
}

/* access matrix elements: c[i] give you a pointer
 * to the row array, c[i][j] indexes an element
 */
c[i][j] = 'a';

If you know the total number of elements (e.g. N*M) you can do this in a single allocation.

Convert char * to LPWSTR

The clean way to use mbstowcs is to call it twice to find the length of the result:

  const char * cs = <your input char*>
  size_t wn = mbsrtowcs(NULL, &cs, 0, NULL);

  // error if wn == size_t(-1)

  wchar_t * buf = new wchar_t[wn + 1]();  // value-initialize to 0 (see below)

  wn = mbsrtowcs(buf, &cs, wn + 1, NULL);

  // error if wn == size_t(-1)

  assert(cs == NULL); // successful conversion

  // result now in buf, return e.g. as std::wstring

  delete[] buf;

Don't forget to call setlocale(LC_CTYPE, ""); at the beginning of your program!

The advantage over the Windows MultiByteToWideChar is that this is entirely standard C, although on Windows you might prefer the Windows API function anyway.

I usually wrap this method, along with the opposite one, in two conversion functions string->wstring and wstring->string. If you also add trivial overloads string->string and wstring->wstring, you can easily write code that compiles with the Winapi TCHAR typedef in any setting.

[Edit:] I added zero-initialization to buf, in case you plan to use the C array directly. I would usually return the result as std::wstring(buf, wn), though, but do beware if you plan on using C-style null-terminated arrays.[/]

In a multithreaded environment you should pass a thread-local conversion state to the function as its final (currently invisible) parameter.

Here is a small rant of mine on this topic.

Reliable way to convert a file to a byte[]

byte[] bytes = File.ReadAllBytes(filename) 

or ...

var bytes = File.ReadAllBytes(filename) 

How to add double quotes to a string that is inside a variable?

In C# you can use:

 string1 = @"Your ""Text"" Here";
 string2 = "Your \"Text\" Here";

How to check programmatically if an application is installed or not in Android?

You can do it using Kotlin extensions :

fun Context.getInstalledPackages(): List<String> {
    val packagesList = mutableListOf<String>()
    packageManager.getInstalledPackages(0).forEach {
        if ( it.applicationInfo.sourceDir.startsWith("/data/app/") && it.versionName != null)
            packagesList.add(it.packageName)
    }
    return packagesList
}

fun Context.isInDevice(packageName: String): Boolean {
    return getInstalledPackages().contains(packageName)
}

Can't get value of input type="file"?

It's old question but just in case someone bump on this tread...

var input = document.getElementById("your_input");
var file = input.value.split("\\");
var fileName = file[file.length-1];

No need for regex, jQuery....

how to get list of port which are in use on the server

There are a lot of options and tools. If you just want a list of listening ports and their owner processes try.

netstat -bano

How to call a C# function from JavaScript?

You can use a Web Method and Ajax:

<script type="text/javascript">             //Default.aspx
   function DeleteKartItems() {     
         $.ajax({
         type: "POST",
         url: 'Default.aspx/DeleteItem',
         data: "",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (msg) {
             $("#divResult").html("success");
         },
         error: function (e) {
             $("#divResult").html("Something Wrong.");
         }
     });
   }
</script>

[WebMethod]                                 //Default.aspx.cs
public static void DeleteItem()
{
    //Your Logic
}

Pycharm/Python OpenCV and CV2 install error

When I was facing this issue I used to install OpenCV in pycharm installed package panel where we can find under the settings tab. Search "OpenCV-python" and install it in the installed package panel of right interpreter.

Extract string between two strings in java

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

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

Window vs Page vs UserControl for WPF navigation?

  • Window is like Windows.Forms.Form, so just a new window
  • Page is, according to online documentation:

    Encapsulates a page of content that can be navigated to and hosted by Windows Internet Explorer, NavigationWindow, and Frame.

    So you basically use this if going you visualize some HTML content

  • UserControl is for cases when you want to create some reusable component (but not standalone one) to use it in multiple different Windows

PHP refresh window? equivalent to F5 page reload?

guess you could echo the meta tag to do the refresh in regular intervals ... like

<meta http-equiv="refresh" content="600" url="your-url-here"> 

How to start a background process in Python?

Use subprocess.Popen() with the close_fds=True parameter, which will allow the spawned subprocess to be detached from the Python process itself and continue running even after Python exits.

https://gist.github.com/yinjimmy/d6ad0742d03d54518e9f

import os, time, sys, subprocess

if len(sys.argv) == 2:
    time.sleep(5)
    print 'track end'
    if sys.platform == 'darwin':
        subprocess.Popen(['say', 'hello'])
else:
    print 'main begin'
    subprocess.Popen(['python', os.path.realpath(__file__), '0'], close_fds=True)
    print 'main end'

Selecting/excluding sets of columns in pandas

In a similar vein, when reading a file, one may wish to exclude columns upfront, rather than wastefully reading unwanted data into memory and later discarding them.

As of pandas 0.20.0, usecols now accepts callables.1 This update allows more flexible options for reading columns:

skipcols = [...]
read_csv(..., usecols=lambda x: x not in skipcols)

The latter pattern is essentially the inverse of the traditional usecols method - only specified columns are skipped.


Given

Data in a file

import numpy as np
import pandas as pd


df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))

filename = "foo.csv"
df.to_csv(filename)

Code

skipcols = ["B", "D"]
df1 = pd.read_csv(filename, usecols=lambda x: x not in skipcols, index_col=0)
df1

Output

          A         C
0  0.062350  0.076924
1 -0.016872  1.091446
2  0.213050  1.646109
3 -1.196928  1.153497
4 -0.628839 -0.856529
...

Details

A DataFrame was written to a file. It was then read back as a separate DataFrame, now skipping unwanted columns (B and D).

Note that for the OP's situation, since data is already created, the better approach is the accepted answer, which drops unwanted columns from an extant object. However, the technique presented here is most useful when directly reading data from files into a DataFrame.

A request was raised for a "skipcols" option in this issue and was addressed in a later issue.

maximum value of int

#include <iostrema>

int main(){
    int32_t maxSigned = -1U >> 1;
    cout << maxSigned << '\n';
    return 0;
}

It might be architecture dependent but it does work at least in my setup.

Where is the IIS Express configuration / metabase file found?

Since the introduction of Visual Studio 2015, this location has changed and is added into your solution root under the following location:

C:\<Path\To\Solution>\.vs\config\applicationhost.config

I hope this saves you some time!

How can I pass a reference to a function, with parameters?

The following is equivalent to your second code block:

var f = function () {
        //Some logic here...
    };

var fr = f;

fr(pars);

If you want to actually pass a reference to a function to some other function, you can do something like this:

function fiz(x, y, z) {
    return x + y + z;
}

// elsewhere...

function foo(fn, p, q, r) {
    return function () {
        return fn(p, q, r);
    }
}

// finally...

f = foo(fiz, 1, 2, 3);
f(); // returns 6

You're almost certainly better off using a framework for this sort of thing, though.

Mercurial stuck "waiting for lock"

I am very familiar with Mercurial's locking code (as of 1.9.1). The above advice is good, but I'd add that:

  1. I've seen this in the wild, but rarely, and only on Windows machines.
  2. Deleting lock files is the easiest fix, BUT you have to make sure nothing else is accessing the repository. (If the lock is a string of zeros, this is almost certainly true).

(For the curious: I haven't yet been able to catch the cause of this problem, but suspect it's either an older version of Mercurial accessing the repository or a problem in Python's socket.gethostname() call on certain versions of Windows.)

How to extract hours and minutes from a datetime.datetime object?

It's easier to use the timestamp for this things since Tweepy gets both

import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))

Uncaught TypeError: data.push is not a function

Also make sure that the name of the variable is not some kind of a language keyword. For instance, the following produces the same type of error:

var history = [];
history.push("what a mess");

replacing it for:

var history123 = [];
history123.push("pray for a better language");

works as expected.

Current date and time - Default in MVC razor

Isn't this what default constructors are for?

class MyModel
{

    public MyModel()
    {
        this.ReturnDate = DateTime.Now;
    }

    public date ReturnDate {get; set;};

}

How to create a unique index on a NULL column?

Strictly speaking, a unique nullable column (or set of columns) can be NULL (or a record of NULLs) only once, since having the same value (and this includes NULL) more than once obviously violates the unique constraint.

However, that doesn't mean the concept of "unique nullable columns" is valid; to actually implement it in any relational database we just have to bear in mind that this kind of databases are meant to be normalized to properly work, and normalization usually involves the addition of several (non-entity) extra tables to establish relationships between the entities.

Let's work a basic example considering only one "unique nullable column", it's easy to expand it to more such columns.

Suppose we the information represented by a table like this:

create table the_entity_incorrect
(
  id integer,
  uniqnull integer null, /* we want this to be "unique and nullable" */
  primary key (id)
);

We can do it by putting uniqnull apart and adding a second table to establish a relationship between uniqnull values and the_entity (rather than having uniqnull "inside" the_entity):

create table the_entity
(
  id integer,
  primary key(id)
);

create table the_relation
(
  the_entity_id integer not null,
  uniqnull integer not null,

  unique(the_entity_id),
  unique(uniqnull),
  /* primary key can be both or either of the_entity_id or uniqnull */
  primary key (the_entity_id, uniqnull), 
  foreign key (the_entity_id) references the_entity(id)
);

To associate a value of uniqnull to a row in the_entity we need to also add a row in the_relation.

For rows in the_entity were no uniqnull values are associated (i.e. for the ones we would put NULL in the_entity_incorrect) we simply do not add a row in the_relation.

Note that values for uniqnull will be unique for all the_relation, and also notice that for each value in the_entity there can be at most one value in the_relation, since the primary and foreign keys on it enforce this.

Then, if a value of 5 for uniqnull is to be associated with an the_entity id of 3, we need to:

start transaction;
insert into the_entity (id) values (3); 
insert into the_relation (the_entity_id, uniqnull) values (3, 5);
commit;

And, if an id value of 10 for the_entity has no uniqnull counterpart, we only do:

start transaction;
insert into the_entity (id) values (10); 
commit;

To denormalize this information and obtain the data a table like the_entity_incorrect would hold, we need to:

select
  id, uniqnull
from
  the_entity left outer join the_relation
on
  the_entity.id = the_relation.the_entity_id
;

The "left outer join" operator ensures all rows from the_entity will appear in the result, putting NULL in the uniqnull column when no matching columns are present in the_relation.

Remember, any effort spent for some days (or weeks or months) in designing a well normalized database (and the corresponding denormalizing views and procedures) will save you years (or decades) of pain and wasted resources.

Bootstrap 3 offset on right not left

I modified Bootstrap SASS (v3.3.5) based on Rukshan's answer

Add this in the end of the calc-grid-column mixin in mixins/_grid-framework.scss, right below the $type == offset if condition.

@if ($type == offset-right) {
      .col-#{$class}-offset-right-#{$index} {
          margin-right: percentage(($index / $grid-columns));
      }
  }

Modify the make-grid mixin in mixins/_grid-framework.scss to generate the offset-right classes.

// Create grid for specific class
@mixin make-grid($class) {
  @include float-grid-columns($class);
  @include loop-grid-columns($grid-columns, $class, width);
  @include loop-grid-columns($grid-columns, $class, pull);
  @include loop-grid-columns($grid-columns, $class, push);
  @include loop-grid-columns($grid-columns, $class, offset);
  @include loop-grid-columns($grid-columns, $class, offset-right);
}

You can then use the classes like col-sm-offset-right-2 and col-md-offset-right-1

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

I'd consider the patterns you are using for your system, the naming conventions / cataloguing / grouping of classes of tends to be defined by the pattern used. Personally, I stick to these naming conventions as they are the most likely way for another person to be able to pick up my code and run with it.

For example UserRecordsClerk might be better explained as extending a generic RecordsClerk interface that both UserRecordsClerk and CompanyRecordsClerk implement and then specialise on, meaning one can look at the methods in the interface to see what the its subclasses do / are generally for.

See a book such as Design Patterns for info, it's an excellent book and might help you clear up where you're aiming to be with your code - if you aren't already using it! ;o)

I reckon so long as your pattern is well chosen and used as far as is appropriate, then pretty uninventive straightforward class names should suffice!

Maven package/install without test (skip tests)

You can add either -DskipTests or -Dmaven.test.skip=true to any mvn command for skipping tests. In your case it would be like below:

mvn package -DskipTests

OR

mvn package -Dmaven.test.skip=true

Get Image Height and Width as integer values?

PHP's getimagesize() returns an array of data. The first two items in the array are the two items you're interested in: the width and height. To get these, you would simply request the first two indexes in the returned array:

var $imagedata = getimagesize("someimage.jpg");

print "Image width  is: " . $imagedata[0];
print "Image height is: " . $imagedata[1];

For further information, see the documentation.

SQL Insert into table only if record doesn't exist

This might be a simple solution to achieve this:

INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
  FROM dual
 WHERE NOT EXISTS (SELECT 1 
                     FROM funds 
                    WHERE ID = 23
                      AND date = DATE('2013-02-12'));

p.s. alternatively (if ID a primary key):

 INSERT INTO funds (ID, date, price)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need

see this Fiddle.

Parameter "stratify" from method "train_test_split" (scikit Learn)

Scikit-Learn is just telling you it doesn't recognise the argument "stratify", not that you're using it incorrectly. This is because the parameter was added in version 0.17 as indicated in the documentation you quoted.

So you just need to update Scikit-Learn.

How to set root password to null

Worked for me and "5.7.11 MySQL Community Server":

use mysql;
update user set authentication_string=password(''), plugin='mysql_native_password' where user='root';

I had to change the 'plugin' field as well because it was set to 'auth_socket'.

After that I could connect as mysql -u root without a password.

How to completely DISABLE any MOUSE CLICK

something like:

    $('#doc').click(function(e){
       e.preventDefault()
       e.stopImmediatePropagation() //charles ma is right about that, but stopPropagation isn't also needed
});

should do the job you could also bind more mouse events with replacing for: edit: add this in the feezing part

    $('#doc').bind('click mousedown dblclick',function(e){
       e.preventDefault()
       e.stopImmediatePropagation()
});

and this in the unfreezing:

  $('#doc').unbind();

Getting number of elements in an iterator in Python

No, any method will require you to resolve every result. You can do

iter_length = len(list(iterable))

but running that on an infinite iterator will of course never return. It also will consume the iterator and it will need to be reset if you want to use the contents.

Telling us what real problem you're trying to solve might help us find you a better way to accomplish your actual goal.

Edit: Using list() will read the whole iterable into memory at once, which may be undesirable. Another way is to do

sum(1 for _ in iterable)

as another person posted. That will avoid keeping it in memory.

Pass variables to Ruby script via command line

Something like this:

ARGV.each do|a|
  puts "Argument: #{a}"
end

then

$ ./test.rb "test1 test2"

or

v1 = ARGV[0]
v2 = ARGV[1]
puts v1       #prints test1
puts v2       #prints test2

Convert generic List/Enumerable to DataTable?

I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable which returned an IEnumerable and the properties couldn't be enumerated. This did the trick:

// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
    List<IDataRecord> list = data.Cast<IDataRecord>().ToList();

    PropertyDescriptorCollection props = null;
    DataTable table = new DataTable();
    if (list != null && list.Count > 0)
    {
        props = TypeDescriptor.GetProperties(list[0]);
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }
    }
    if (props != null)
    {
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item) ?? DBNull.Value;
            }
            table.Rows.Add(values);
        }
    }
    return table;
}

What's the effect of adding 'return false' to a click event listener?

I have this link on my HTML-page:

<a href = "" 
onclick = "setBodyHtml ('new content'); return false; "
> click here </a>

The function setBodyHtml() is defined as:

function setBodyHtml (s)
{ document.body.innerHTML = s;
}

When I click the link the link disappears and the text shown in the browser changes to "new content".

But if I remove the "false" from my link, clicking the link does (seemingly) nothing. Why is that?

It is because if I don't return false the default behavior of clicking the link and displaying its target-page happens, is not canceled. BUT, here the href of the hyperlink is "" so it links back to the SAME current page. So the page is effectively just refreshed and seemingly nothing happens.

In the background the function setBodyHtml() still does get executed. It assigns its argument to body.innerHTML. But because the page is immediately refreshed/reloaded the modified body-content does not stay visible for more than a few milliseconds perhaps, so I will not see it.

This example shows why it is sometimes USEFUL to use "return false".

I do want to assign SOME href to the link, so that it shows as a link, as underlined text. But I don't want the click to the link to effectively just reload the page. I want that default navigation=behavior to be canceled and whatever side-effects are caused by calling my function to take and stay in effect. Therefore I must "return false".

The example above is something you would quickly try out during development. For production you would more likely assign a click-handler in JavaScript and call preventDefault() instead. But for a quick try-it-out the "return false" above does the trick.

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

Using variables inside a bash heredoc

In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]

If you change your first example to use <<EOF instead of << "EOF" you'll find that it works.

In your second example, the shell invokes sudo only with the parameter cat, and the redirection applies to the output of sudo cat as the original user. It'll work if you try:

sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT

Way to get all alphabetic chars in an array in PHP?

Another way:

$c = 'A';
$chars = array($c);
while ($c < 'Z') $chars[] = ++$c;

How to create a .gitignore file

Here a nice tip under Windows:

  • Right click in Windows Explorer, New > Text Document
  • Name it .gitignore. (with a trailing dot - that is the tip)
  • You end up with a .gitignore file :)

Tested under Windows 7 and 8.

This tip assumes that your Windows Explorer displays the file extensions.

Windows Explorer .gitignore

What's the difference between a 302 and a 307 redirect?

Flowchart

  • 301: permanent redirect: the URL is old and should be replaced. Browsers will cache this.
    Example usage: URL moved from /register-form.html to signup-form.html.
    The method will change to GET, as per RFC 7231: "For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request."
  • 302: temporary redirect. Only use for HTTP/1.0 clients. This status code should not change the method, but browsers did it anyway. The RFC says: "Many pre-HTTP/1.1 user agents do not understand [303]. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303." Of course, some clients may implement it according to the spec, so if interoperability with such ancient clients is not a real concern, 303 is better for consistent results.
  • 303: temporary redirect, changing the method to GET.
    Example usage: if the browser sent POST to /register.php, then now load (GET) /success.html.
  • 307: temporary redirect, repeating the request identically.
    Example usage: if the browser sent a POST to /register.php, then this tells it to redo the POST at /signup.php.
  • 308: permanent redirect, repeating the request identically. Where 307 is the "no method change" counterpart of 303, this 308 status is the "no method change" counterpart of 301.

RFC 7231 (from 2014) is very readable and not overly verbose. If you want to know the exact answer, it's a recommended read. Some other answers use RFC 2616 from 1999, but nothing changed.

RFC 7238 specifies the 308 status. It is considered experimental, but it was already supported by all major browsers in 2016.

Enable 'xp_cmdshell' SQL Server

While the accepted answer will work most of the times, I have encountered (still do not know why) some cases that is does not. A slight modification of the query by using the WITH OVERRIDE in RECONFIGURE gives the solution

Use Master
GO

EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO

EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE
GO

The expected output is

Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.

What is Android's file system?

When analysing a Galaxy Ace 2.2 in a hex editor. The hex seemed to point to the device using FAT16 as its file system. I thought this unusual. However Fat 16 is compatible with the Linux kernel.

Simulate a specific CURL in PostMan

As per the above answers, it works well.

If we paste curl requests with Authorization data in import, Postman will set all headers automatically. We only just pass row JSON data in the request body if needed or Upload images through form-data in the body.

This is just an example. Your API should be a different one (if your API allows)

curl -X POST 'https://verifyUser.abc.com/api/v1/verification' \
    -H 'secret: secret' \
    -H 'email: [email protected]' \
    -H 'accept: application/json, text/plain, */*' \
    -H 'authorizationtoken: bearer' \
    -F 'referenceFilePath= Add file path' \
    --compressed

jQuery click / toggle between two functions

DEMO

.one() documentation.

I am very late to answer but i think it's shortest code and might help.

function handler1() {
    alert('First handler: ' + $(this).text());
    $(this).one("click", handler2);
}
function handler2() {
    alert('Second handler: ' + $(this).text());
    $(this).one("click", handler1);
}
$("div").one("click", handler1);

DEMO With Op's Code

function handler1() {
    $(this).animate({
        width: "260px"
    }, 1500);
    $(this).one("click", handler2);
}

function handler2() {
    $(this).animate({
        width: "30px"
    }, 1500);
    $(this).one("click", handler1);
}
$("#time").one("click", handler1);

Rails: How does the respond_to block work?

The meta-programming behind responder registration (see Parched Squid's answer) also allows you to do nifty stuff like this:

def index
  @posts = Post.all

  respond_to do |format|
    format.html  # index.html.erb
    format.json  { render :json => @posts }
    format.csv   { render :csv => @posts }
    format.js
  end
end

The csv line will cause to_csv to be called on each post when you visit /posts.csv. This makes it easy to export data as CSV (or any other format) from your rails site.

The js line will cause a javascript file /posts.js (or /posts.js.coffee) to be rendered/executed. I've found that to be a light-weight way to create an Ajax enabled site using jQuery UI pop-ups.

I'm trying to use python in powershell

Try setting the path this way:

 $env:path="$env:Path;C:\Python27"

How to set text color in submit button?

<input type = "button" style ="background-color:green"/>

How to detect when a youtube video finishes playing?

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>

    <script>

        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              width: '640',
              height: '390',
              videoId: '0Bmhjf0rKe8',
              events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange
              }
            });
        }

        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }

    </script>

Annotations from javax.validation.constraints not working

for method parameters you can use Objects.requireNonNull() like this: test(String str) { Objects.requireNonNull(str); } But this is only checked at runtime and throws an NPE if null. It is like a preconditions check. But that might be what you are looking for.

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

As has been discussed elsewhere, the .length property reference is failing because theHref is undefined. However, be aware of any solution which involves comparing theHref to undefined, which is not a keyword in JavaScript and can be redefined.

For a full discussion of checking for undefined variables, see Detecting an undefined object property and the first answer in particular.

How to install Boost on Ubuntu

Actually you don't need "install" or "compile" anything before using Boost in your project. You can just download and extract the Boost library to any location on your machine, which is usually like /usr/local/.

When you compile your code, you can just indicate the compiler where to find the libraries by -I. For example, g++ -I /usr/local/boost_1_59_0 xxx.hpp.

SQL Server - How to lock a table until a stored procedure finishes

Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.

How to set initial value and auto increment in MySQL?

MySQL - Setup an auto-incrementing primary key that starts at 1001:

Step 1, create your table:

create table penguins(
  my_id       int(16) auto_increment, 
  skipper     varchar(4000),
  PRIMARY KEY (my_id)
)

Step 2, set the start number for auto increment primary key:

ALTER TABLE penguins AUTO_INCREMENT=1001;

Step 3, insert some rows:

insert into penguins (skipper) values("We need more power!");
insert into penguins (skipper) values("Time to fire up");
insert into penguins (skipper) values("kowalski's nuclear reactor.");

Step 4, interpret the output:

select * from penguins

prints:

'1001', 'We need more power!'
'1002', 'Time to fire up'
'1003', 'kowalski\'s nuclear reactor'

Converting datetime.date to UTC timestamp in Python

For unix systems only:

>>> import datetime
>>> d = datetime.date(2011,01,01)
>>> d.strftime("%s")  # <-- THIS IS THE CODE YOU WANT
'1293832800'

Note 1: dizzyf observed that this applies localized timezones. Don't use in production.

Note 2: Jakub Narebski noted that this ignores timezone information even for offset-aware datetime (tested for Python 2.7).

how to get html content from a webview?

Why not get the html first then pass it to the web view?

private String getHtml(String url){
    HttpGet pageGet = new HttpGet(url);

    ResponseHandler<String> handler = new ResponseHandler<String>() {
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            HttpEntity entity = response.getEntity();
            String html; 

            if (entity != null) {
                html = EntityUtils.toString(entity);
                return html;
            } else {
                return null;
            }
        }
    };

    pageHTML = null;
    try {
        while (pageHTML==null){
            pageHTML = client.execute(pageGet, handler);
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return pageHTML;
}

@Override
public void customizeWebView(final ServiceCommunicableActivity activity, final WebView webview, final SearchResult mRom) {
    mRom.setFileSize(getFileSize(mRom.getURLSuffix()));
    webview.getSettings().setJavaScriptEnabled(true);
    WebViewClient anchorWebViewClient = new WebViewClient()
    {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

            //Do what you want to with the html
            String html = getHTML(url);

            if( html!=null && !url.equals(lastLoadedURL)){
                lastLoadedURL = url;
                webview.loadDataWithBaseURL(url, html, null, "utf-8", url);
            }
}

This should roughly do what you want to do. It is adapted from Is it possible to get the HTML code from WebView and shout out to https://stackoverflow.com/users/325081/aymon-fournier for his answer.

Scanf/Printf double variable C

When a float is passed to printf, it is automatically converted to a double. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...), largely for historical reasons. Therefore, the “natural” specifier for a float, %f, must work with a double argument. So the %f and %lf specifiers for printf are the same; they both take a double value.

When scanf is called, pointers are passed, not direct values. A pointer to float is not converted to a pointer to double (this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf, the argument for %f must be a pointer to float, and the argument for %lf must be a pointer to double.

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I had "C:\Users\User Name\OneDrive\Fonts", which was mklink'ed ( /D ) to "C:\Windows\Fonts", and I got the same problem. In my case

cd "C:\Users\User Name\OneDrive"

rd /s Fonts

Y (to confirm the action)

helped me. I hope, that it helps you too ;D

What are these ^M's that keep showing up in my files in emacs?

In git-config, set core.autocrlf to true to make git automatically convert line endings correctly for your platform, e.g. run this command for a global setting:

git config --global core.autocrlf true

How do I properly clean up Excel interop objects?

This sure seems like it has been over-complicated. From my experience, there are just three key things to get Excel to close properly:

1: make sure there are no remaining references to the excel application you created (you should only have one anyway; set it to null)

2: call GC.Collect()

3: Excel has to be closed, either by the user manually closing the program, or by you calling Quit on the Excel object. (Note that Quit will function just as if the user tried to close the program, and will present a confirmation dialog if there are unsaved changes, even if Excel is not visible. The user could press cancel, and then Excel will not have been closed.)

1 needs to happen before 2, but 3 can happen anytime.

One way to implement this is to wrap the interop Excel object with your own class, create the interop instance in the constructor, and implement IDisposable with Dispose looking something like

if (!mDisposed) {
   mExcel = null;
   GC.Collect();
   mDisposed = true;
}

That will clean up excel from your program's side of things. Once Excel is closed (manually by the user or by you calling Quit) the process will go away. If the program has already been closed, then the process will disappear on the GC.Collect() call.

(I'm not sure how important it is, but you may want a GC.WaitForPendingFinalizers() call after the GC.Collect() call but it is not strictly necessary to get rid of the Excel process.)

This has worked for me without issue for years. Keep in mind though that while this works, you actually have to close gracefully for it to work. You will still get accumulating excel.exe processes if you interrupt your program before Excel is cleaned up (usually by hitting "stop" while your program is being debugged).

Making TextView scrollable on Android

The code below creates an automatic horizontal scrolling textview:

While adding TextView to xml use

<TextView android:maxLines="1" 
          android:ellipsize="marquee"
          android:scrollHorizontally="true"/>

Set the following properties of TextView in onCreate()

tv.setSelected(true);
tv.setHorizontallyScrolling(true); 

SQL Server - In clause with a declared variable

I have another solution to do it without dynamic query. We can do it with the help of xquery as well.

    SET @Xml = cast(('<A>'+replace('3,4,22,6014',',' ,'</A><A>')+'</A>') AS XML)
    Select @Xml

    SELECT A.value('.', 'varchar(max)') as [Column] FROM @Xml.nodes('A') AS FN(A)

Here is the complete solution : http://raresql.com/2011/12/21/how-to-use-multiple-values-for-in-clause-using-same-parameter-sql-server/

HTML Table cell background image alignment

use like this your inline css

<td width="178" rowspan="3" valign="top" 
align="right" background="images/left.jpg" 
style="background-repeat:background-position: right top;">
</td>

Apache is downloading php files instead of displaying them

I got this kind of problem. This is how I solve it. After installed Apache then I installed PHP using this command.

sudo apt-get install php libapache2-mod-php

it executes correctly but I request .php file from Apache, it gives without executing the PHP script.

Then I check PHP is enabled.

$ cd /etc/apache2
$ ls -l mods-*/*php*

but it didn't show any results. I check installed PHP packages.

$ dpkg -l | grep php| awk '{print $2}' |tr "\n" " "

Different type of PHP versions installed to my computer. Then I remove some PHP packages from my previous list, using apt-get purge.

sudo apt-get purge libapache2-mod-php7.0 php7.0 php7.0-cli php7.0-common php7.0-json

I reinstall PHP

sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql

Verify that the PHP module is loaded

$ a2query -m php7.0

if not enabled with:

$ sudo a2enmod php7.0

Restart Apache server

$ sudo systemctl restart apache2

Finally, I check PHP process on Apache

create an empty file

sudo vim /var/www/html/info.php

Add this content to info.php & save.

<?php
  phpinfo();
?>

Check on browser:

http://localhost/info.php

it shows correctly.I think this will help anyone.

Why does my 'git branch' have no master?

It seems there must be at least one local commit on the master branch to do:

git push -u origin master

So if you did git init . and then git remote add origin ..., you still need to do:

git add ...
git commit -m "..."

Cannot connect to Database server (mysql workbench)

I also struggled with this problem for quite a while.

I came accross this interesting thread from MySQL forum: http://forums.mysql.com/read.php?11,11388,11388#msg-11388

I also came accross (obviously) some good SO Q/A.

It seems that the message mentioned in "user948950" 's question can be coming from a wide range of reasons: log file too big, incorrect mysql.ini file values, spaces in the file path, security/acl issue, old entries in the registry, and so on.

So, after trying for 3h to fix this... I abandonned and decided to do a good old re-install.

This is where this post from (again) this MySQL thread came in useful, I quote:

Gary Williams wrote: Hi Guys,

I've had exactly the same problem and this is how I got it working for me, starting with a non working installation.

  1. Stop the windows service for any existing mysql installation.

  2. Uninstall Mysql.

As with most uninstalls, old files are left behind. If your directory is C:\mysql\ etc then delete the innob, etc, files but leave the directories themselves as well as any existing databases in 'data'. If your directory is C:\Program Files\ etc, delete all the mysql directories.

  1. It's now worth running regedit to make sure the old registry entries are deleted as well by the uninstall. If not, delete them.

  2. It's ok to use the new .msi installer (essential files only), however ....

  3. Do not use their default install path! Some genius set a path with spaces in it! Choose the custom install and select a sensible path, ie, C:\mysql (note from Adrien: C:\mysqldata for ... the data)

  4. Do not choose to alter the security settings. Uncheck the relevant box and the install will complete without having to set a root password.

I think I have remembered everything.

Good luck

Gary

I did get into troubles when simply copy/pasting the databases I had in my previous "data" directory to the new one. So the work around I found was to export each database (I know... a lot of fun) and then re-import them one by one.

FYI: I used the following command to import C:/<MySQLInstallDir>/My SQL Server x.x/bin/mysql -u root -p <dbName> < "<dirPathOfDump>\<dumpName>.sql", that is for instance C:/mysql/MySQL Server 5.6/bin/mysql -u root -p mySupaCoolDb < "C:\mySupaCoolDbDump20130901.sql"

Show message box in case of exception

There are many ways, for example:

Method one:

public string test()
{
string ErrMsg = string.Empty;
 try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception ex)
    {
        ErrMsg = ex.Message;
    }
return ErrMsg
}

Method two:

public void test(ref string ErrMsg )
{

    ErrMsg = string.Empty;
     try
        {
            int num = int.Parse("gagw");
        }
        catch (Exception ex)
        {
            ErrMsg = ex.Message;
        }
}

Docker remove <none> TAG images

100% works: docker images | grep none | awk '{print $3}' | xargs docker rmi -f

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

add onclick function to a submit button

I need to see your submit button html tag for better help. I am not familiar with php and how it handles the postback, but I guess depending on what you want to do, you have three options:

  1. Getting the handling onclick button on the client-side: In this case you only need to call a javascript function.

_x000D_
_x000D_
function foo() {_x000D_
   alert("Submit button clicked!");_x000D_
   return true;_x000D_
}
_x000D_
<input type="submit" value="submit" onclick="return foo();" />
_x000D_
_x000D_
_x000D_

  1. If you want to handle the click on the server-side, you should first make sure that the form tag method attribute is set to post:

    <form method="post">
    
  2. You can use onsubmit event from form itself to bind your function to it.

_x000D_
_x000D_
<form name="frm1" method="post" onsubmit="return greeting()">_x000D_
    <input type="text" name="fname">_x000D_
    <input type="submit" value="Submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How do you store Java objects in HttpSession?

Here you can do it by using HttpRequest or HttpSession. And think your problem is within the JSP.

If you are going to use the inside servlet do following,

Object obj = new Object();
session.setAttribute("object", obj);

or

HttpSession session = request.getSession();
Object obj = new Object();
session.setAttribute("object", obj);

and after setting your attribute by using request or session, use following to access it in the JSP,

<%= request.getAttribute("object")%>

or

<%= session.getAttribute("object")%>

So seems your problem is in the JSP.

If you want use scriptlets it should be as follows,

<%
Object obj = request.getSession().getAttribute("object");
out.print(obj);
%>

Or can use expressions as follows,

<%= session.getAttribute("object")%>

or can use EL as follows, ${object} or ${sessionScope.object}

React onClick and preventDefault() link refresh/redirect?

If you use checkbox

<input 
    type='checkbox'
    onChange={this.checkboxHandler}
/>

stopPropagation and stopImmediatePropagation won't be working.

Because you must using onClick={this.checkboxHandler}

How to make HTTP Post request with JSON body in Swift

import UIKit

class ViewController: UIViewController {

    var getdata = NSMutableData()
    @IBOutlet weak var password_txt: UITextField!
    @IBOutlet weak var mobile_txt: UITextField!
    @IBOutlet weak var email_txt: UITextField!
    @IBOutlet weak var name_txt: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.

    }
    @IBAction func RegAction(_ sender: UIButton) {
        let url = URL(string: "https//.....")
        var requrl = URLRequest(url: url!)
        requrl.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content_type")
        requrl.httpMethod = "post"
        let postString = "name=\(name_txt.text!)&email=\(email_txt.text!)&mobile=\(mobile_txt.text!)&password=\(password_txt.text!)"
        print("poststring-->>",postString)
        requrl.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: requrl){(data,response,error) in
            let mydata = data
            do{
                print("mydata",mydata!)
                do{
                    self.getdata.append(mydata!)
                    let jsondata = try JSONSerialization.jsonObject(with: self.getdata as Data, options: [])
                    print("jsondata-->",jsondata)
                }
            }
            catch
            {
                print("error-->",error.localizedDescription)
            }
        };
        task.resume()

    }
}
`GET METHOD`
import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    var dataarray = [[String: Any]]()
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataarray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 450.0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        let  item = dataarray[indexPath.row]

        cell.name_txt.text = item["name"]as? String ?? ""
        cell.pname_txt.text = item["realname"]as? String ?? ""
        cell.team_txt.text = item["team"]as? String ?? ""
        cell.firstapp_txt.text = item["firstappearance"]as? String ?? ""
        cell.Createdby_txt.text = item["createdby"]as? String ?? ""
        cell.Publisher_txt.text = item["publisher"]as? String ?? ""

        if item["imageurl"]as? String ?? "" != ""{
            let url = URL(string: item["imageurl"]as? String ?? "")
            if url != nil{
                let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
                cell.imgvw.image = UIImage(data: data!)
            }
        }
        return cell
     }


    @IBOutlet weak var apiTable: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func viewWillAppear(_ animated: Bool) {
        guard let url = URL(string: "https://www.simplifiedcoding.net/demos/marvel/")
            else {return}
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let dataResponse = data,
                error == nil else {
                    print(error?.localizedDescription ?? "Response Error")
                    return }
            do{
                //here dataResponse received from a network request
                let jsonResponse = try JSONSerialization.jsonObject(with:
                    dataResponse, options: []) as? [[String:Any]] ?? [[:]]
                print("jsonResponse---->",jsonResponse) //Response result

                self.dataarray = jsonResponse
                DispatchQueue.main.async {



                    self.apiTable.reloadData()
                }
            } catch let parsingError {
                print("Error", parsingError)
            }
        }
        task.resume()
    }

}

Create numpy matrix filled with NaNs

As said, numpy.empty() is the way to go. However, for objects, fill() might not do exactly what you think it does:

In[36]: a = numpy.empty(5,dtype=object)
In[37]: a.fill([])
In[38]: a
Out[38]: array([[], [], [], [], []], dtype=object)
In[39]: a[0].append(4)
In[40]: a
Out[40]: array([[4], [4], [4], [4], [4]], dtype=object)

One way around can be e.g.:

In[41]: a = numpy.empty(5,dtype=object)
In[42]: a[:]= [ [] for x in range(5)]
In[43]: a[0].append(4)
In[44]: a
Out[44]: array([[4], [], [], [], []], dtype=object)

Uncaught Typeerror: cannot read property 'innerHTML' of null

If the script is in the head of your HTML document, the body of your HTML document has not yet been created by the browser, regardless of what will eventually be there (the same result occurs if your script is in the HTML file but above the element). When your variable tries to find document.getElementById("status") it does not yet exist, and so it returns a value of null. When you then use the variable later in your code, the initial value (null) is used and not the current one, because nothing has updated the variable.

I didn't want to move my script link out of the HTML head, so instead I did this in my JS file:

var idPost //define a global variable
function updateVariables(){
    idPost = document.getElementById("status").innerHTML; //update the global variable
}

And this in the HTML file:

<body onload="updateVariables()">

If you already have an onload function in place, you can just add the additional line to it or call the function.

If you don't want the variable to be global, define it locally in the function that you are trying to run and make sure the function is not called before the page has fully loaded.

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

New .NET 5 Solution:

In .NET 5, a new class has been introduced called JsonContent, which derives from HttpContent. See in Microsoft docs

This class has a static method called Create(), which takes an object as a parameter.

Usage:

var myObject = new
{
    foo = "Hello",
    bar = "World",
};

JsonContent content = JsonContent.Create(myObject);

HttpResponseMessage response = await _httpClient.PostAsync("https://...", content);

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

What is the attribute property="og:title" inside meta tag?

The property in meta tags allows you to specify values to property fields which come from a property library. The property library (RDFa format) is specified in the head tag.

For example, to use that code you would have to have something like this in your <head tag. <head xmlns:og="http://example.org/"> and inside the http://example.org/ there would be a specification for title (og:title).

The tag from your example was almost definitely from the Open Graph Protocol, the purpose is to specify structured information about your website for the use of Facebook (and possibly other search engines).

C# DropDownList with a Dictionary as DataSource

When a dictionary is enumerated, it will yield KeyValuePair<TKey,TValue> objects... so you just need to specify "Value" and "Key" for DataTextField and DataValueField respectively, to select the Value/Key properties.

Thanks to Joe's comment, I reread the question to get these the right way round. Normally I'd expect the "key" in the dictionary to be the text that's displayed, and the "value" to be the value fetched. Your sample code uses them the other way round though. Unless you really need them to be this way, you might want to consider writing your code as:

list.Add(cul.DisplayName, cod);

(And then changing the binding to use "Key" for DataTextField and "Value" for DataValueField, of course.)

In fact, I'd suggest that as it seems you really do want a list rather than a dictionary, you might want to reconsider using a dictionary in the first place. You could just use a List<KeyValuePair<string, string>>:

string[] languageCodsList = service.LanguagesAvailable();
var list = new List<KeyValuePair<string, string>>();

foreach (string cod in languageCodsList)
{
    CultureInfo cul = new CultureInfo(cod);
    list.Add(new KeyValuePair<string, string>(cul.DisplayName, cod));
}

Alternatively, use a list of plain CultureInfo values. LINQ makes this really easy:

var cultures = service.LanguagesAvailable()
                      .Select(language => new CultureInfo(language));
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

If you're not using LINQ, you can still use a normal foreach loop:

List<CultureInfo> cultures = new List<CultureInfo>();
foreach (string cod in service.LanguagesAvailable())
{
    cultures.Add(new CultureInfo(cod));
}
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();

JOptionPane Yes or No window

For better understand how it works!

int n = JOptionPane.showConfirmDialog(null, "Yes No Cancel", "YesNoCancel", JOptionPane.YES_NO_CANCEL_OPTION);
    if(n == 0)
        {
        JOptionPane.showConfirmDialog(null, "You pressed YES\n"+"Pressed value is = "+n);
        }
    else if(n == 1)
        {
        JOptionPane.showConfirmDialog(null, "You pressed NO\n"+"Pressed value is = "+n);
        }
    else if (n == 2)
        {
        JOptionPane.showConfirmDialog(null, "You pressed CANCEL\n"+"Pressed value is = "+n);
        }
    else if (n == -1)
        {
        JOptionPane.showConfirmDialog(null, "You pressed X\n"+"Pressed value is = "+n);
        }

OR

int n = JOptionPane.showConfirmDialog(null, "Yes No Cancel", "YesNoCancel", JOptionPane.YES_NO_CANCEL_OPTION);
    switch (n) {
        case 0:
            JOptionPane.showConfirmDialog(null, "You pressed YES\n"+"Pressed value is = "+n);
            break;
        case 1:
            JOptionPane.showConfirmDialog(null, "You pressed NO\n"+"Pressed value is = "+n);
            break;
        case 2:
            JOptionPane.showConfirmDialog(null, "You pressed CANCEL\n"+"Pressed value is = "+n);
            break;
        case -1:
            JOptionPane.showConfirmDialog(null, "You pressed X\n"+"Pressed value is = "+n);
            break;
        default:
            break;
    }

add maven repository to build.gradle

Android Studio Users:

If you want to use grade, go to http://search.maven.org/ and search for your maven repo. Then, click on the "latest version" and in the details page on the bottom left you will see "Gradle" where you can then copy/paste that link into your app's build.gradle.

enter image description here

How to set initial size of std::vector?

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

Bootstrap 3 .col-xs-offset-* doesn't work?

Just in case someone makes the same error I did before stumbling on this page, that is, adding CSS reset rules (like the very popular reset by Eric Meyer used on millions of websites) after including bootstrap.

Also, perhaps I should point out that such reset won't be necessary with bootstrap given bootsrap actually implements the normalize.css v3.0.2 reset.

DateTime and CultureInfo

Use CultureInfo class to change your culture info.

var dutchCultureInfo = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCultureInfo);

How to delete last character in a string in C#?

Personally I would go with Rob's suggestion, but if you want to remove one (or more) specific trailing character(s) you can use TrimEnd. E.g.

paramstr = paramstr.TrimEnd('&');