Programs & Examples On #Page loading message

Updating a java map entry

You just use the method

public Object put(Object key, Object value)

if the key was already present in the Map then the previous value is returned.

MVC Razor Hidden input and passing values

A move from WebForms to MVC requires a complete sea-change in logic and brain processes. You're no longer interacting with the 'form' both server-side and client-side (and in fact even with WebForms you weren't interacting client-side). You've probably just mixed up a bit of thinking there, in that with WebForms and RUNAT="SERVER" you were merely interacting with the building of the Web page.

MVC is somewhat similar in that you have server-side code in constructing the model (the data you need to build what your user will see), but once you have built the HTML you need to appreciate that the link between the server and the user no longer exists. They have a page of HTML, that's it.

So the HTML you are building is read-only. You pass the model through to the Razor page, which will build HTML appropriate to that model.

If you want to have a hidden element which sets true or false depending on whether this is the first view or not you need a bool in your model, and set it to True in the Action if it's in response to a follow up. This could be done by having different actions depending on whether the request is [HttpGet] or [HttpPost] (if that's appropriate for how you set up your form: a GET request for the first visit and a POST request if submitting a form).

Alternatively the model could be set to True when it's created (which will be the first time you visit the page), but after you check the value as being True or False (since a bool defaults to False when it's instantiated). Then using:

@Html.HiddenFor(x => x.HiddenPostBack)

in your form, which will put a hidden True. When the form is posted back to your server the model will now have that value set to True.

It's hard to give much more advice than that as your question isn't specific as to why you want to do this. It's perhaps vital that you read a good book on moving to MVC from WebForms, such as Steve Sanderson's Pro ASP.NET MVC.

How to make a JTable non-editable

table.setDefaultEditor(Object.class, null);

File URL "Not allowed to load local resource" in the Internet Browser

For people do not like to modify chrome's security options, we can simply start a python http server from directory which contains your local file:

python -m SimpleHTTPServer

and for python 3:

python3 -m http.server

Now you can reach any local file directly from your js code or externally with http://127.0.0.1:8000/some_file.txt

Strip first and last character from C string

Further to @pmg's answer, note that you can do both operations in one statement:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++[strlen(p)-1] = 0;

This will likely work as expected but behavior is undefined in C standard.

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

What is the size of ActionBar in pixels?

From the de-compiled sources of Android 3.2's framework-res.apk, res/values/styles.xml contains:

<style name="Theme.Holo">
    <!-- ... -->
    <item name="actionBarSize">56.0dip</item>
    <!-- ... -->
</style>

3.0 and 3.1 seem to be the same (at least from AOSP)...

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

I think there is a lot of confusion about which weights are used for what. I am not sure I know precisely what bothers you so I am going to cover different topics, bear with me ;).

Class weights

The weights from the class_weight parameter are used to train the classifier. They are not used in the calculation of any of the metrics you are using: with different class weights, the numbers will be different simply because the classifier is different.

Basically in every scikit-learn classifier, the class weights are used to tell your model how important a class is. That means that during the training, the classifier will make extra efforts to classify properly the classes with high weights.
How they do that is algorithm-specific. If you want details about how it works for SVC and the doc does not make sense to you, feel free to mention it.

The metrics

Once you have a classifier, you want to know how well it is performing. Here you can use the metrics you mentioned: accuracy, recall_score, f1_score...

Usually when the class distribution is unbalanced, accuracy is considered a poor choice as it gives high scores to models which just predict the most frequent class.

I will not detail all these metrics but note that, with the exception of accuracy, they are naturally applied at the class level: as you can see in this print of a classification report they are defined for each class. They rely on concepts such as true positives or false negative that require defining which class is the positive one.

             precision    recall  f1-score   support

          0       0.65      1.00      0.79        17
          1       0.57      0.75      0.65        16
          2       0.33      0.06      0.10        17
avg / total       0.52      0.60      0.51        50

The warning

F1 score:/usr/local/lib/python2.7/site-packages/sklearn/metrics/classification.py:676: DeprecationWarning: The 
default `weighted` averaging is deprecated, and from version 0.18, 
use of precision, recall or F-score with multiclass or multilabel data  
or pos_label=None will result in an exception. Please set an explicit 
value for `average`, one of (None, 'micro', 'macro', 'weighted', 
'samples'). In cross validation use, for instance, 
scoring="f1_weighted" instead of scoring="f1".

You get this warning because you are using the f1-score, recall and precision without defining how they should be computed! The question could be rephrased: from the above classification report, how do you output one global number for the f1-score? You could:

  1. Take the average of the f1-score for each class: that's the avg / total result above. It's also called macro averaging.
  2. Compute the f1-score using the global count of true positives / false negatives, etc. (you sum the number of true positives / false negatives for each class). Aka micro averaging.
  3. Compute a weighted average of the f1-score. Using 'weighted' in scikit-learn will weigh the f1-score by the support of the class: the more elements a class has, the more important the f1-score for this class in the computation.

These are 3 of the options in scikit-learn, the warning is there to say you have to pick one. So you have to specify an average argument for the score method.

Which one you choose is up to how you want to measure the performance of the classifier: for instance macro-averaging does not take class imbalance into account and the f1-score of class 1 will be just as important as the f1-score of class 5. If you use weighted averaging however you'll get more importance for the class 5.

The whole argument specification in these metrics is not super-clear in scikit-learn right now, it will get better in version 0.18 according to the docs. They are removing some non-obvious standard behavior and they are issuing warnings so that developers notice it.

Computing scores

Last thing I want to mention (feel free to skip it if you're aware of it) is that scores are only meaningful if they are computed on data that the classifier has never seen. This is extremely important as any score you get on data that was used in fitting the classifier is completely irrelevant.

Here's a way to do it using StratifiedShuffleSplit, which gives you a random splits of your data (after shuffling) that preserve the label distribution.

from sklearn.datasets import make_classification
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix

# We use a utility to generate artificial classification data.
X, y = make_classification(n_samples=100, n_informative=10, n_classes=3)
sss = StratifiedShuffleSplit(y, n_iter=1, test_size=0.5, random_state=0)
for train_idx, test_idx in sss:
    X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
    svc.fit(X_train, y_train)
    y_pred = svc.predict(X_test)
    print(f1_score(y_test, y_pred, average="macro"))
    print(precision_score(y_test, y_pred, average="macro"))
    print(recall_score(y_test, y_pred, average="macro"))    

Hope this helps.

Invalid default value for 'dateAdded'

I have mysql version 5.6.27 on my LEMP and CURRENT_TIMESTAMP as default value works fine.

Android Facebook integration with invalid key hash

I experienced the same problem. I made a short research on the possible reasons for this strange behavior and I found the following:

  • During the first execution of a new Facebook app, it will allow connection/login even if you don't specify any key hashes.

  • For me, the tutorial which Facebook provided didn't generate the correct key hash, because it was giving the wrong configuration. When executing:

    keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl
    base64
    

make sure you check all properties - the HOMEPATH, the existence of the keystore, etc. Maybe you also have to provide password.

  • What generated the proper configuration was the solution suggested by @Mahendran.

  • Also, if you see the error originally posted (http://i.stack.imgur.com/58q3v.png), most probably the key hash you see on the screen is your real one. If nothing else works, try inputting it in Facebook.

I got all those results with: Windows 7 64-bit edition, Android Studio 1.2.2, JDK 7.

Calculating text width

var calc = '<span style="display:none; margin:0 0 0 -999px">' + $('.move').text() + '</span>';

How to get the nth occurrence in a string?

I was playing around with the following code for another question on StackOverflow and thought that it might be appropriate for here. The function printList2 allows the use of a regex and lists all the occurrences in order. (printList was an attempt at an earlier solution, but it failed in a number of cases.)

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<title>Checking regex</title>_x000D_
<script>_x000D_
var string1 = "123xxx5yyy1234ABCxxxabc";_x000D_
var search1 = /\d+/;_x000D_
var search2 = /\d/;_x000D_
var search3 = /abc/;_x000D_
function printList(search) {_x000D_
   document.writeln("<p>Searching using regex: " + search + " (printList)</p>");_x000D_
   var list = string1.match(search);_x000D_
   if (list == null) {_x000D_
      document.writeln("<p>No matches</p>");_x000D_
      return;_x000D_
   }_x000D_
   // document.writeln("<p>" + list.toString() + "</p>");_x000D_
   // document.writeln("<p>" + typeof(list1) + "</p>");_x000D_
   // document.writeln("<p>" + Array.isArray(list1) + "</p>");_x000D_
   // document.writeln("<p>" + list1 + "</p>");_x000D_
   var count = list.length;_x000D_
   document.writeln("<ul>");_x000D_
   for (i = 0; i < count; i++) {_x000D_
      document.writeln("<li>" +  "  " + list[i] + "   length=" + list[i].length + _x000D_
          " first position=" + string1.indexOf(list[i]) + "</li>");_x000D_
   }_x000D_
   document.writeln("</ul>");_x000D_
}_x000D_
function printList2(search) {_x000D_
   document.writeln("<p>Searching using regex: " + search + " (printList2)</p>");_x000D_
   var index = 0;_x000D_
   var partial = string1;_x000D_
   document.writeln("<ol>");_x000D_
   for (j = 0; j < 100; j++) {_x000D_
       var found = partial.match(search);_x000D_
       if (found == null) {_x000D_
          // document.writeln("<p>not found</p>");_x000D_
          break;_x000D_
       }_x000D_
       var size = found[0].length;_x000D_
       var loc = partial.search(search);_x000D_
       var actloc = loc + index;_x000D_
       document.writeln("<li>" + found[0] + "  length=" + size + "  first position=" + actloc);_x000D_
       // document.writeln("  " + partial + "  " + loc);_x000D_
       partial = partial.substring(loc + size);_x000D_
       index = index + loc + size;_x000D_
       document.writeln("</li>");_x000D_
   }_x000D_
   document.writeln("</ol>");_x000D_
_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<p>Original string is <script>document.writeln(string1);</script></p>_x000D_
<script>_x000D_
   printList(/\d+/g);_x000D_
   printList2(/\d+/);_x000D_
   printList(/\d/g);_x000D_
   printList2(/\d/);_x000D_
   printList(/abc/g);_x000D_
   printList2(/abc/);_x000D_
   printList(/ABC/gi);_x000D_
   printList2(/ABC/i);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Jenkins: Cannot define variable in pipeline stage

I think error is not coming from the specified line but from the first 3 lines. Try this instead :

node {
   stage("first") {
     def foo = "foo"
     sh "echo ${foo}"
   }
}

I think you had some extra lines that are not valid...

From declaractive pipeline model documentation, it seems that you have to use an environment declaration block to declare your variables, e.g.:

pipeline {
   environment {
     FOO = "foo"
   }

   agent none
   stages {
       stage("first") {
           sh "echo ${FOO}"
       }
   }
}

How do I access refs of a child component in the parent component

Recommended for React versions prior to 16.3

If it cannot be avoided the suggested pattern extracted from the React docs would be:

import React, { Component } from 'react';

const Child = ({ setRef }) => <input type="text" ref={setRef} />;

class Parent extends Component {
    constructor(props) {
        super(props);
        this.setRef = this.setRef.bind(this);
    }

    componentDidMount() {
        // Calling a function on the Child DOM element
        this.childRef.focus();
    }

    setRef(input) {
        this.childRef = input;
    }

    render() {
        return <Child setRef={this.setRef} />
    }
}

The Parent forwards a function as prop bound to Parent's this. When React calls the Child's ref prop setRef it will assign the Child's ref to the Parent's childRef property.

Recommended for React >= 16.3

Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.

We create Components that forward their ref with React.forwardRef. The returned Component ref prop must be of the same type as the return type of React.createRef. Whenever React mounts the DOM node then property current of the ref created with React.createRef will point to the underlying DOM node.

import React from "react";

const LibraryButton = React.forwardRef((props, ref) => (
  <button ref={ref} {...props}>
    FancyButton
  </button>
));

class AutoFocus extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
    this.onClick = this.onClick.bind(this);
  }

  componentDidMount() {
    this.childRef.current.focus();
  }

  onClick() {
    console.log("fancy!");
  }

  render() {
    return <LibraryButton onClick={this.onClick} ref={this.childRef} />;
  }
}

Forwarding refs HOC example

Created Components are forwarding their ref to a child node.

function logProps(Component) {
  class LogProps extends React.Component {
    componentDidUpdate(prevProps) {
      console.log('old props:', prevProps);
      console.log('new props:', this.props);
    }

    render() {
      const {forwardedRef, ...rest} = this.props;

      // Assign the custom prop "forwardedRef" as a ref
      return <Component ref={forwardedRef} {...rest} />;
    }
  }

  // Note the second param "ref" provided by React.forwardRef.
  // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
  // And it can then be attached to the Component.
  return React.forwardRef((props, ref) => {
    return <LogProps {...props} forwardedRef={ref} />;
  });
}

See Forwarding Refs in React docs.

Close a div by clicking outside

Add a transparent background taking up the whole window size, just before your popup div

.transparent-back{
    position: fixed;
    top: 0px;
    left:0px;
    width: 100%;
    height: 100%;
    background-color: rgba(255,255,255,0.5);
}

Then on its click, dismiss the popup.

$(".transparent-back").on('click',function(){
    $('popup').fadeOut(300);
});

What is the use of a cursor in SQL Server?

Cursor itself is an iterator (like WHILE). By saying iterator I mean a way to traverse the record set (aka a set of selected data rows) and do operations on it while traversing. Operations could be INSERT or DELETE for example. Hence you can use it for data retrieval for example. Cursor works with the rows of the result set sequentially - row by row. A cursor can be viewed as a pointer to one row in a set of rows and can only reference one row at a time, but can move to other rows of the result set as needed.

This link can has a clear explanation of its syntax and contains additional information plus examples.

Cursors can be used in Sprocs too. They are a shortcut that allow you to use one query to do a task instead of several queries. However, cursors recognize scope and are considered undefined out of the scope of the sproc and their operations execute within a single procedure. A stored procedure cannot open, fetch, or close a cursor that was not declared in the procedure.

What does the term "Tuple" Mean in Relational Databases?

Tuples are known values which is used to relate the table in relational DB.

How to list files inside a folder with SQL Server

I hunted around for ages to find a decent easy solution to this and in the end found some ridiculously complicated CLR solutions so decided to write my own simple VB one. Simply create a new VB CLR project from the Database tab under Installed Templates, and then add a new SQL CLR VB User Defined Function. I renamed it to CLRGetFilesInDir.vb. Here's the code inside it...

Imports System
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.IO
-----------------------------------------------------------------------------
Public Class CLRFilesInDir
-----------------------------------------------------------------------------
<SqlFunction(FillRowMethodName:="FillRowFiles", IsDeterministic:=True, IsPrecise:=True, TableDefinition:="FilePath nvarchar(4000)")> _
Public Shared Function GetFiles(PathName As SqlString, Pattern As SqlString) As IEnumerable
    Dim FileNames As String()

    Try
    FileNames = Directory.GetFiles(PathName, Pattern, SearchOption.TopDirectoryOnly)
    Catch
        FileNames = Nothing
    End Try

    Return FileNames

End Function
-----------------------------------------------------------------------------
Public Shared Sub FillRowFiles(ByVal obj As Object, ByRef Val As SqlString)
    Val = CType(obj, String).ToString
End Sub

End Class

I also changed the Assembly Name in the Project Properties window to CLRExcelFiles, and the Default Namespace to CLRGetExcelFiles.

NOTE: Set the target framework to 3.5 if you are using anything less that SQL Server 2012.

Compile the project and then copy the CLRExcelFiles.dll from \bin\release to somewhere like C:\temp on the SQL Server machine, not your own.

In SSMS:-

CREATE ASSEMBLY <your assembly name in here - anything you like>
FROM 'C:\temp\CLRExcelFiles.dll';

CREATE FUNCTION dbo.fnGetFiles
(
@PathName NVARCHAR(MAX),
@Pattern NVARCHAR(MAX)
)
RETURNS TABLE (Val NVARCHAR(100))
AS
EXTERNAL NAME <your assembly name>."CLRGetExcelFiles.CLRFilesInDir".GetFiles;
GO

then call it

SELECT * FROM dbo.fnGetFiles('\\<SERVERNAME>\<$SHARE>\<folder>\' , '*.xls')

NOTE: Even though I changed the Permission Level to EXTERNAL_ACCESS on the SQLCLR tab under Project Properties, I still needed to run this every time I (re)created it.

ALTER ASSEMBLY [CLRFilesInDirAssembly] 
WITH PERMISSION_SET = EXTERNAL_ACCESS 
GO

and wullah! that should work.

Volatile Vs Atomic

The volatile keyword is used:

  • to make non atomic 64-bit operations atomic: long and double. (all other, primitive accesses are already guaranteed to be atomic!)
  • to make variable updates guaranteed to be seen by other threads + visibility effects: after writing to a volatile variable, all the variables that where visible before writing that variable become visible to another thread after reading the same volatile variable (happen-before ordering).

The java.util.concurrent.atomic.* classes are, according to the java docs:

A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:

boolean compareAndSet(expectedValue, updateValue);

The atomic classes are built around the atomic compareAndSet(...) function that maps to an atomic CPU instruction. The atomic classes introduce the happen-before ordering as the volatile variables do. (with one exception: weakCompareAndSet(...)).

From the java docs:

When a thread sees an update to an atomic variable caused by a weakCompareAndSet, it does not necessarily see updates to any other variables that occurred before the weakCompareAndSet.

To your question:

Does this mean that whosoever takes lock on it, that will be setting its value first. And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?

You don't lock anything, what you are describing is a typical race condition that will happen eventually if threads access shared data without proper synchronization. As already mentioned declaring a variable volatile in this case will only ensure that other threads will see the change of the variable (the value will not be cached in a register of some cache that is only seen by one thread).

What is the difference between AtomicInteger and volatile int?

AtomicInteger provides atomic operations on an int with proper synchronization (eg. incrementAndGet(), getAndAdd(...), ...), volatile int will just ensure the visibility of the int to other threads.

How can I use numpy.correlate to do autocorrelation?

I think the real answer to the OP's question is succinctly contained in this excerpt from the Numpy.correlate documentation:

mode : {'valid', 'same', 'full'}, optional
    Refer to the `convolve` docstring.  Note that the default
    is `valid`, unlike `convolve`, which uses `full`.

This implies that, when used with no 'mode' definition, the Numpy.correlate function will return a scalar, when given the same vector for its two input arguments (i.e. - when used to perform autocorrelation).

console.log timestamps in Chrome?

Try this:

console.logCopy = console.log.bind(console);

console.log = function(data)
{
    var currentDate = '[' + new Date().toUTCString() + '] ';
    this.logCopy(currentDate, data);
};



Or this, in case you want a timestamp:

console.logCopy = console.log.bind(console);

console.log = function(data)
{
    var timestamp = '[' + Date.now() + '] ';
    this.logCopy(timestamp, data);
};



To log more than one thing and in a nice way (like object tree representation):

console.logCopy = console.log.bind(console);

console.log = function()
{
    if (arguments.length)
    {
        var timestamp = '[' + Date.now() + '] ';
        this.logCopy(timestamp, arguments);
    }
};



With format string (JSFiddle)

console.logCopy = console.log.bind(console);

console.log = function()
{
    // Timestamp to prepend
    var timestamp = new Date().toJSON();

    if (arguments.length)
    {
        // True array copy so we can call .splice()
        var args = Array.prototype.slice.call(arguments, 0);

        // If there is a format string then... it must
        // be a string
        if (typeof arguments[0] === "string")
        {
            // Prepend timestamp to the (possibly format) string
            args[0] = "%o: " + arguments[0];

            // Insert the timestamp where it has to be
            args.splice(1, 0, timestamp);

            // Log the whole array
            this.logCopy.apply(this, args);
        }
        else
        { 
            // "Normal" log
            this.logCopy(timestamp, args);
        }
    }
};


Outputs with that:

Sample output

P.S.: Tested in Chrome only.

P.P.S.: Array.prototype.slice is not perfect here for it would be logged as an array of objects rather than a series those of.

SQL Server : trigger how to read value for Insert, Update, Delete

Here is the syntax to create a trigger:

CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
    { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
        [ WITH APPEND ]
        [ NOT FOR REPLICATION ]
        AS
        [ { IF UPDATE ( column )
            [ { AND | OR } UPDATE ( column ) ]
                [ ...n ]
        | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
                { comparison_operator } column_bitmask [ ...n ]
        } ]
        sql_statement [ ...n ]
    }
} 

If you want to use On Update you only can do it with the IF UPDATE ( column ) section. That's not possible to do what you are asking.

Dealing with multiple Python versions and PIP?

It worked for me in windows this way:

  1. I changed the name of python files python.py and pythonw.exe to python3.py pythonw3.py

  2. Then I just ran this command in the prompt:

    python3 -m pip install package

assign headers based on existing row in dataframe in R

Try this:

colnames(DF) = DF[1, ] # the first row will be the header
DF = DF[-1, ]          # removing the first row.

However, get a look if the data has been properly read. If you data.frame has numeric variables but the first row were characters, all the data has been read as character. To avoid this problem, it's better to save the data and read again with header=TRUE as you suggest. You can also get a look to this question: Reading a CSV file organized horizontally.

SQL Combine Two Columns in Select Statement

In MySQL you can use:

SELECT CONCAT(Address1, " ", Address2)
WHERE SOUNDEX(CONCAT(Address1, " ", Address2)) = SOUNDEX("Center St 3B")

The SOUNDEX function works similarly in most database systems, I can't think of the syntax for MSSQL at the minute, but it wouldn't be too far away from the above.

What is the use of printStackTrace() method in Java?

printStackTrace() helps the programmer to understand where the actual problem occurred. It helps to trace the exception. it is printStackTrace() method of Throwable class inherited by every exception class. This method prints the same message of e object and also the line number where the exception occurred.

The following is an another example of print stack of the Exception in Java.

public class Demo {
   public static void main(String[] args) {
      try {
         ExceptionFunc();
      } catch(Throwable e) {
         e.printStackTrace();
      }
   }
   public static void ExceptionFunc() throws Throwable {
      Throwable t = new Throwable("This is new Exception in Java...");

      StackTraceElement[] trace = new StackTraceElement[] {
         new StackTraceElement("ClassName","methodName","fileName",5)
      };
      t.setStackTrace(trace);
      throw t;
   }
}

java.lang.Throwable: This is new Exception in Java... at ClassName.methodName(fileName:5)

PersistenceContext EntityManager injection NullPointerException

If the component is an EJB, then, there shouldn't be a problem injecting an EM.

But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

This is probably the problem.

one line if statement in php

You can use Ternary operator logic Ternary operator logic is the process of using "(condition)? (true return value) : (false return value)" statements to shorten your if/else structures. i.e

/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

API vs. Webservice

Check this http://en.wikipedia.org/wiki/Web_service

As the link mentioned then Web API is a development in Web services that most likely relates to Web 2.0, whereas SOAP based services are replaced by REST based communications. Note that REST services do not require XML, SOAP, or WSDL service-API definitions so this is major different to traditional web service.

How to copy a collection from one database to another in MongoDB

I would abuse the connect function in mongo cli mongo doc. so that means you can start one or more connection. if you want to copy customer collection from test to test2 in same server. first you start mongo shell

use test
var db2 = connect('localhost:27017/test2')

do a normal find and copy the first 20 record to test2.

db.customer.find().limit(20).forEach(function(p) { db2.customer.insert(p); });

or filter by some criteria

db.customer.find({"active": 1}).forEach(function(p) { db2.customer.insert(p); });

just change the localhost to IP or hostname to connect to remote server. I use this to copy test data to a test database for testing.

What is the optimal way to compare dates in Microsoft SQL server?

Converting to a DATE or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand

From that article:

DECLARE @dateVar datetime = '19700204';

-- Quickest when there is an index on t.[DateColumn], 
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);

-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn] 
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND 
      t.[DateColumn] < @dateEnd;

Also from that article: using BETWEEN, DATEDIFF or CONVERT(CHAR(8)... are all slower.

How do multiple clients connect simultaneously to one port, say 80, on a server?

Multiple clients can connect to the same port (say 80) on the server because on the server side, after creating a socket and binding (setting local IP and port) listen is called on the socket which tells the OS to accept incoming connections.

When a client tries to connect to server on port 80, the accept call is invoked on the server socket. This creates a new socket for the client trying to connect and similarly new sockets will be created for subsequent clients using same port 80.

Words in italics are system calls.

Ref

http://www.scs.stanford.edu/07wi-cs244b/refs/net2.pdf

Programmatic equivalent of default(Type)

The Expressions can help here:

    private static Dictionary<Type, Delegate> lambdasMap = new Dictionary<Type, Delegate>();

    private object GetTypedNull(Type type)
    {
        Delegate func;
        if (!lambdasMap.TryGetValue(type, out func))
        {
            var body = Expression.Default(type);
            var lambda = Expression.Lambda(body);
            func = lambda.Compile();
            lambdasMap[type] = func;
        }
        return func.DynamicInvoke();
    }

I did not test this snippet, but i think it should produce "typed" nulls for reference types..

Set selected item in Android BottomNavigationView

bottomNavigationView.setSelectedItemId(R.id.action_item1);

where action_item1 is menu item ID.

Fastest Way to Find Distance Between Two Lat/Long Points

SELECT * FROM (SELECT *,(((acos(sin((43.6980168*pi()/180)) * 
sin((latitude*pi()/180))+cos((43.6980168*pi()/180)) * 
cos((latitude*pi()/180)) * cos(((7.266903899999988- longitude)* 
pi()/180))))*180/pi())*60*1.1515 ) as distance 
FROM wp_users WHERE 1 GROUP BY ID limit 0,10) as X 
ORDER BY ID DESC

This is the distance calculation query between to points in MySQL, I have used it in a long database, it it working perfect! Note: do the changes (database name, table name, column etc) as per your requirements.

Sending POST data without form

If you don't want your data to be seen by the user, use a PHP session.

Data in a post request is still accessible (and manipulable) by the user.

Checkout this tutorial on PHP Sessions.

How to make Bootstrap Panel body with fixed height

HTML :

<div class="span4">
  <div class="panel panel-primary">
    <div class="panel-heading">jhdsahfjhdfhs</div>
    <div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
  </div>
</div>

CSS :

.panel-height {
  height: 100px; / change according to your requirement/
}

How to embed a Google Drive folder in a website

At the time of writing this answer, there was no method to embed which let the user navigate inside folders and view the files without her leaving the website (the method in other answers, makes everything open in a new tab on google drive website), so I made my own tool for it. To embed a drive, paste the iframe code below in your HTML:

<iframe src="https://googledriveembedder.collegefam.com/?key=YOUR_API_KEY&folderid=FOLDER_ID_WHIHCH_IS_PUBLICLY_VIEWABLE" style="border:none;" width="100%"></iframe>

In the above code, you need to have your own API key and the folder ID. You can set the height as per your wish.

To get the API key:

1.) Go to https://console.developers.google.com/ Create a new project.

2.) From the menu button, go to 'APIs and Services' --> 'Dashboard' --> Click on 'Enable APIs and Services'.

3.) Search for 'Google Drive API', enable it. Then go to "credentials' tab, and create credentials. Keep your API key unrestricted.

4.) Copy the newly generated API key.

To get the folder ID:

1.)Go to the google drive folder you want to embed (for example, drive.google.com/drive/u/0/folders/1v7cGug_e3lNT0YjhvtYrwKV7dGY-Nyh5u [this is not a real folder]) Ensure that the folder is publicly shared and visible to anyone.

2.) Copy the part after 'folders/', this is your folder ID.

Now put both the API key and folder id in the above code and embed.

Note: To hide the download button for files, add '&allowdl=no' at the end of the iframe's src URL.

I made the widget keeping mobile users in mind, however it suits both mobile and desktop. If you run into issues, leave a comment here. I have attached some screenshots of the content of the iframe here.

The file preview looks like this The content of the iframe looks like this

Getting coordinates of marker in Google Maps API

Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:

            function map_init() {
            var lt=48.451778;
            var lg=31.646305;

            var myLatlng = new google.maps.LatLng(lt,lg);
            var mapOptions = {
                center: new google.maps.LatLng(lt,lg),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('map'),mapOptions);   
            var marker = new google.maps.Marker({
                position:myLatlng,
                map:map,
                draggable:true
            });

            google.maps.event.addListener(
                marker,
                'drag',
                function() {
                    document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
                    document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
                    document.getElementById('zoom').innerHTML = mapObject.getZoom();

                    // Dynamically show it somewhere if needed
                    $(".x").text(marker.position.lat().toFixed(6));
                    $(".y").text(marker.position.lng().toFixed(6));
                    $(".z").text(map.getZoom());

                }
            );                  
            }

How can I convert a stack trace to a string?

Without java.io.* it can be done like this.

String trace = e.toString() + "\n";                     

for (StackTraceElement e1 : e.getStackTrace()) {
    trace += "\t at " + e1.toString() + "\n";
}   

And then the trace variable holds your stack trace. Output also holds the initial cause, the output is identical to printStackTrace()

Example, printStackTrace() yields:

java.io.FileNotFoundException: / (Is a directory)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
    at Test.main(Test.java:9)

The trace String holds, when printed to stdout

java.io.FileNotFoundException: / (Is a directory)
     at java.io.FileOutputStream.open0(Native Method)
     at java.io.FileOutputStream.open(FileOutputStream.java:270)
     at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
     at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
     at Test.main(Test.java:9)

auto run a bat script in windows 7 at login

To run the batch file when the VM user logs in:

Drag the shortcut--the one that's currently on your desktop--(or the batch file itself) to Start - All Programs - Startup. Now when you login as that user, it will launch the batch file.

Another way to do the same thing is to save the shortcut or the batch file in %AppData%\Microsoft\Windows\Start Menu\Programs\Startup\.

As far as getting it to run full screen, it depends a bit what you mean. You can have it launch maximized by editing your batch file like this:

start "" /max "C:\Program Files\Oracle\VirtualBox\VirtualBox.exe" --comment "VM" --startvm "12dada4d-9cfd-4aa7-8353-20b4e455b3fa"

But if VirtualBox has a truly full-screen mode (where it hides even the taskbar), you'll have to look for a command-line parameter on VirtualBox.exe. I'm not familiar with that product.

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

It seems easy for me that use plt.savefig() function after plot() function:

import matplotlib.pyplot as plt
dtf = pd.DataFrame.from_records(d,columns=h)
dtf.plot()
plt.savefig('~/Documents/output.png')

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

This is a great sample:

String base64String = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAA...";
String base64Image = base64String.split(",")[1];
byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte);

Sample found at: https://freakycoder.com/android-notes-44-how-to-convert-base64-string-to-bitmap-53f98d5e57af

This is the only code that worked for me in the past.

Is it possible to send a variable number of arguments to a JavaScript function?

This is a sample program for calculating sum of integers for variable arguments and array on integers. Hope this helps.

var CalculateSum = function(){
    calculateSumService.apply( null, arguments );
}

var calculateSumService = function(){
    var sum = 0;

    if( arguments.length === 1){
        var args = arguments[0];

        for(var i = 0;i<args.length; i++){
           sum += args[i]; 
        }
    }else{
        for(var i = 0;i<arguments.length; i++){
           sum += arguments[i]; 
        }        
    }

     alert(sum);

}


//Sample method call

// CalculateSum(10,20,30);         

// CalculateSum([10,20,30,40,50]);

// CalculateSum(10,20);

How to get data from observable in angular2

Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http it returns observable instead of promise, like you did

 return this.http
      .get(this.configEndPoint)
      .map(res => res.json());

then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()

.map() is used to convert the observable (received from http request)to any form like .json(), .text() as stated in Angular's official website,

.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view

this.myService.getConfig().subscribe(res => {
   console.log(res);
   this.data = res;
});

git checkout all the files

  • If you are in base directory location of your tracked files then git checkout . will works otherwise it won't work

How to escape the % (percent) sign in C's printf?

If there are no formats in the string, you can use puts (or fputs):

puts("hello%");

if there is a format in the string:

printf("%.2f%%", 53.2);

As noted in the comments, puts appends a \n to the output and fputs does not.

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

I had to make few modifications in order to make it with in IE8 (didn't test with other IE flavours)

1) document.frames[param] seem to accept a number, not ID

printIframe(0, 'print');

function printIframe(num, id)
{
  var iframe = document.frames ? document.frames[num] : document.getElementById(id);
  var ifWin = iframe.contentWindow || iframe;

  ifWin.focus();
  ifWin.printPage();

  return false;
}

2) I had a print dialog displayed upon page load and also there was a link to "Click here to start printing" (if it didn't start automatically). In order to get it work I had to add focus() call

<script type="text/javascript">
  $(function(){
    printPage();
  });

  function printPage()
  {
    focus();
    print();
  }
</script>

Comparing HTTP and FTP for transferring files

Many firewalls drop outbound connections which are not to ports 80 or 443 (http & https); some even drop connections to those ports that are not HTTP(S). FTP may or may not be allowed, not to speak of the active/PASV modes.

Also, HTTP/1.1 allows for much better partial requests ("only send from byte 123456 to the end of file"), conditional requests and caching ("only send if content changed/if last-modified-date changed") and content compression (gzip).

HTTP is much easier to use through a proxy.

From my anecdotal evidence, HTTP is easier to make work with dropped/slow/flaky connections; e.g. it is not needed to (re)establish a login session before (re)initiating transfer.

OTOH, HTTP is stateless, so you'd have to do authentication and building a trail of "who did what when" yourself.

The only difference in speed I've noticed is transferring lots of small files: HTTP with pipelining is faster (reduces round-trips, esp. noticeable on high-latency networks).

Note that HTTP/2 offers even more optimizations, whereas the FTP protocol has not seen any updates for decades (and even extensions to FTP have insignificant uptake by users). So, unless you are transferring files through a time machine, HTTP seems to have won.

(Tangentially: there are protocols that are better suited for file transfer, such as rsync or BitTorrent, but those don't have as much mindshare, whereas HTTP is Everywhere™)

An unhandled exception occurred during the execution of the current web request. ASP.NET

Here is the code with line 156, it has try and catch above it

    /// <summary>
    /// Execute a SQL Query statement, using the default SQL connection for the application
    /// </summary>
    /// <param name="query">SQL query to execute</param>
    /// <returns>DataTable of results</returns>
    public static DataTable Query(string query)
    {
        DataTable results = new DataTable();
        string configConnectionString = "ApplicationServices";

        System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
        System.Configuration.ConnectionStringSettings connString;

        if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
        {
            connString = WebConfig.ConnectionStrings.ConnectionStrings[configConnectionString];

            if (connString != null)
            {
                try
                {
                    using (SqlConnection conn = new SqlConnection(connString.ToString()))
                    using (SqlCommand cmd = new SqlCommand(query, conn))
                    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
                        dataAdapter.Fill(results);

                    return results;
                }
                catch (Exception ex)
                {
                    throw new SqlException(string.Format("SqlException occurred during query execution: ", ex));
                }
            }
            else
            {
                throw new SqlException(string.Format("Connection string for " + configConnectionString + "is null."));
            }
        }
        else
        {
            throw new SqlException(string.Format("No connection strings found in Web.config file."));
        }
    }

TypeError: 'list' object is not callable in python

Why does TypeError: 'list' object is not callable appear?

Explanation:

It is because you defined list as a variable before (i am pretty sure), so it would be a list, not the function anymore, that's why everyone shouldn't name variables functions, the below is the same as what you're doing now:

>>> [1,2,3]()
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    [1,2,3]()
TypeError: 'list' object is not callable
>>>  

So you need it to be the default function of list, how to detect if it is? just use:

>>> list
<class 'list'>
>>> list = [1,2,3]
>>> list
[1, 2, 3]
>>> list()
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    list()
TypeError: 'list' object is not callable
>>> 

How do i detect whether a variable name is a function? well, just simple see if it has a different color, or use a code like:

>>> 'list' in dir(__builtins__)
True
>>> 'blah' in dir(__builtins__)
False
>>> 

After this, you should know why does TypeError: 'list' object is not callable appear.

Okay, so now...

How to fix this TypeError: 'list' object is not callable error?

Code:

You have to either do __builtins__.list():

>>> list = [1,2,3]
>>> __builtins__.list()
[]
>>> 

Or use []:

>>> list = [1,2,3]
>>> []
[]
>>> 

Or remove list variable from memory:

>>> list = [1,2,3]
>>> del list
>>> list()
[]
>>> 

Or just rename the variable:

>>> lst = [1,2,3]
>>> list()
[]
>>> 

P.S. Last one is the most preferable i guess :-)

There are a whole bunch of solutions that work.

References:

'id' is a bad variable name in Python

How do I use a keyword as a variable name?

How to use reserved keyword as the name of variable in python?

How to increase editor font size?

We have to be more careful when doing this. For the first time I have changed the font size of menu by mistake instead of font. First create your own scheme by going to File-->Settings-->Colors & Fonts and then you can make changes to your own scheme. The final procedure is to go to settings(File-->Settings) and then select Editor and Colors & Fontsin the left bar menu. Then select the arrow on the left side of Colors & Fonts and then select Font in the left menu bar. You will get options to change your values. Remember you can only change values to your own sheme.

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

Please keep your

<form method="POST" action="XYZ">

@RequestMapping(value="/XYZ", method=RequestMethod.POST)
    public void handleSave(@RequestParam String action){

Your form action attribute value must match to value of @RequestMapping, So that Spring MVC can resolve it.

Also, as you told it is giving 404 after changing, for this, can you please check whether control is entering inside handleSave() method.

I think, as you are not returning any thing from handleSave() method, you have to look at it.

if it still not work, can you please post your spring logs.

Also, make sure that your request should come like

/PORTAL/save

if there is anything between like PORTAL/jsp/save the mention in @RequestMapping(value="/jsp/save")

Convert a list to a string in C#

Maybe you are trying to do

string combindedString = string.Join( ",", myList.ToArray() );

You can replace "," with what you want to split the elements in the list by.

Edit: As mention in the comments you could also do

string combindedString = string.Join( ",", myList);

Reference:

Join<T>(String, IEnumerable<T>) 
Concatenates the members of a collection, using the specified separator between each member.

Eclipse reports rendering library more recent than ADT plug-in

Please try once uninstalling from Help-->Installation details

and try again installing using http://dl-ssl.google.com/android/eclipse/

How to split a String by space

While the accepted answer is good, be aware that you will end up with a leading empty string if your input string starts with a white space. For example, with:

String str = " Hello I'm your String";
String[] splitStr = str.split("\\s+");

The result will be:

splitStr[0] == "";
splitStr[1] == "Hello";
splitStr[2] == "I'm";
splitStr[3] == "Your";
splitStr[4] == "String";

So you might want to trim your string before splitting it:

String str = " Hello I'm your String";
String[] splitStr = str.trim().split("\\s+");

[edit]

In addition to the trim caveat, you might want to consider the unicode non-breaking space character (U+00A0). This character prints just like a regular space in string, and often lurks in copy-pasted text from rich text editors or web pages. They are not handled by .trim() which tests for characters to remove using c <= ' '; \s will not catch them either.

Instead, you can use \p{Blank} but you need to enable unicode character support as well which the regular split won't do. For example, this will work: Pattern.compile("\\p{Blank}", UNICODE_CHARACTER_CLASS).split(words) but it won't do the trim part.

The following demonstrates the problem and provides a solution. It is far from optimal to rely on regex for this, but now that Java has 8bit / 16bit byte representation, an efficient solution for this becomes quite long.

public class SplitStringTest
{
    static final Pattern TRIM_UNICODE_PATTERN = Pattern.compile("^\\p{Blank}*(.*)\\p{Blank}$", UNICODE_CHARACTER_CLASS);
    static final Pattern SPLIT_SPACE_UNICODE_PATTERN = Pattern.compile("\\p{Blank}", UNICODE_CHARACTER_CLASS);

    public static String[] trimSplitUnicodeBySpace(String str)
    {
        Matcher trimMatcher = TRIM_UNICODE_PATTERN.matcher(str);
        boolean ignore = trimMatcher.matches(); // always true but must be called since it does the actual matching/grouping
        return SPLIT_SPACE_UNICODE_PATTERN.split(trimMatcher.group(1));
    }

    @Test
    void test()
    {
        String words = " Hello I'm\u00A0your String\u00A0";
        // non-breaking space here --^ and there -----^

        String[] split = words.split(" ");
        String[] trimAndSplit = words.trim().split(" ");
        String[] splitUnicode = SPLIT_SPACE_UNICODE_PATTERN.split(words);
        String[] trimAndSplitUnicode = trimSplitUnicodeBySpace(words);

        System.out.println("words: [" + words + "]");
        System.out.println("split: [" + Arrays.stream(split).collect(Collectors.joining("][")) + "]");
        System.out.println("trimAndSplit: [" + Arrays.stream(trimAndSplit).collect(Collectors.joining("][")) + "]");
        System.out.println("splitUnicode: [" + Arrays.stream(splitUnicode).collect(Collectors.joining("][")) + "]");
        System.out.println("trimAndSplitUnicode: [" + Arrays.stream(trimAndSplitUnicode).collect(Collectors.joining("][")) + "]");
    }
}

Results in:

words: [ Hello I'm your String ]
split: [][Hello][I'm your][String ]
trimAndSplit: [Hello][I'm your][String ]
splitUnicode: [][Hello][I'm][your][String]
trimAndSplitUnicode: [Hello][I'm][your][String]

Show Image View from file path?

Labeeb is right about why you need to set image using path if your resources are already laying inside the resource folder ,

This kind of path is needed only when your images are stored in SD-Card .

And try the below code to set Bitmap images from a file stored inside a SD-Card .

File imgFile = new  File("/sdcard/Images/test_image.jpg");

if(imgFile.exists()){

    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

    myImage.setImageBitmap(myBitmap);

}

And include this permission in the manifest file:

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

How to display an unordered list in two columns?

Here is an easy way to make a multiple column list using nothing more than simple CSS. The style tags can obviously be put into a CSS if desired.

<p>Materials List</p>
<ul style="display: inline-block; float: left">
    <u>Item Description<u>
    <li>1/2" x 4' wood dowel</li>
    <li>1/2" x 12"  PVC pipe</li>
    <li>1/2" PVC pipe end cap</li>
    <li>7/16" x 3" light duty expansion spring</li>
    <li>6" plastic zip ties</li>
    <li>Light weight antenna</li>
</ul>
<div style="display: inline-block; margin-left: 1em">
    <u>Qty</u>
    <div style="text-indent: 0.5em">3</div>
    <div style="text-indent: 0.5em">1</div>
    <div style="text-indent: 0.5em">1</div>
    <div style="text-indent: 0.5em">2</div>
    <div style="text-indent: 0.5em">8</div>
    <div style="text-indent: 0.5em">1</div>
</div>
<p></p>

What is the C# Using block and why should I use it?

It is really just some syntatic sugar that does not require you to explicity call Dispose on members that implement IDisposable.

How to change the MySQL root account password on CentOS7?

All,

Here a little bit twist with mysql-community-server 5.7 I share some steps, how to reset mysql5.7 root password or set password. it will work centos7 and RHEL7 as well.

step1. 1st stop your databases

service mysqld stop

step2. 2nd modify /etc/my.cnf file add "skip-grant-tables"

vi /etc/my.cnf

[mysqld] skip-grant-tables

step3. 3rd start mysql

service mysqld start

step4. select mysql default database

mysql -u root

mysql>use mysql;

step4. set a new password

mysql> update user set authentication_string=PASSWORD("yourpassword") where User='root';

step5 restart mysql database

service mysqld restart

 mysql -u root -p

enjoy :)

java.math.BigInteger cannot be cast to java.lang.Long

You need to add an alias for the count to your query and then use the addScalar() method as the default for list() method in Hibernate seams to be BigInteger for numeric SQL types. Here is an example:

List<Long> sqlResult = session.createSQLQuery("SELECT column AS num FROM table")
    .addScalar("num", StandardBasicTypes.LONG).list();

did you specify the right host or port? error on Kubernetes

I got this issue when using " Bash on Windows " with azure kubernetes

az aks get-credentials -n <myCluster>-g <myResourceGroup>

The config file is autogenerated and placed in '~/.kube/config' file as per OS (which is windows in my case)

To solve this - Run from Bash commandline cp <yourWindowsPathToConfigPrintedFromAbobeCommand> ~/.kube/config

Changing MongoDB data store directory

For me, the user was mongod instead of mongodb

sudo chown mongod:mongod /newlocation

You can see the logs for errors if the service fails:

/var/log/mongodb/mongod.log

jQuery: How to get the event object in an event handler function without passing it as an argument?

Since the event object "evt" is not passed from the parameter, is it still possible to obtain this object?

No, not reliably. IE and some other browsers make it available as window.event (not $(window.event)), but that's non-standard and not supported by all browsers (famously, Firefox does not).

You're better off passing the event object into the function:

<a href="#" onclick="myFunc(event, 1,2,3)">click</a>

That works even on non-IE browsers because they execute the code in a context that has an event variable (and works on IE because event resolves to window.event). I've tried it in IE6+, Firefox, Chrome, Safari, and Opera. Example: http://jsbin.com/iwifu4

But your best bet is to use modern event handling:

HTML:

<a href="#">click</a>

JavaScript using jQuery (since you're using jQuery):

$("selector_for_the_anchor").click(function(event) {
    // Call `myFunc`
    myFunc(1, 2, 3);

    // Use `event` here at the event handler level, for instance
    event.stopPropagation();
});

...or if you really want to pass event into myFunc:

$("selector_for_the_anchor").click(function(event) {
    myFunc(event, 1, 2, 3);
});

The selector can be anything that identifies the anchor. You have a very rich set to choose from (nearly all of CSS3, plus some). You could add an id or class to the anchor, but again, you have other choices. If you can use where it is in the document rather than adding something artificial, great.

Resolving require paths with webpack

resolve.alias should work exactly the way you described, so I'm providing this as an answer to help mitigate any confusion that may result from the suggestion in the original question that it does not work.

a resolve configuration like the one below will give you the desired results:

// used to resolve absolute path to project's root directory (where web pack.config.js should be located)
var path = require( 'path' );
...
{
  ...
  resolve: {
    // add alias for application code directory
    alias:{
      mydir: path.resolve( __dirname, 'path', 'to', 'mydir' )
    },
    extensions: [ '', '.js' ]
  }
}

require( 'mydir/myfile.js' ) will work as expected. If it does not, there must be some other issue.

If you have multiple modules that you want to add to the search path, resolve.root makes sense, but if you just want to be able to reference components within your application code without relative paths, alias seems to be the most straight-forward and explicit.

An important advantage of alias is that it gives you the opportunity to namespace your requires which can add clarity to your code; just like it is easy to see from other requires what module is being referenced, alias allows you to write descriptive requires that make it obvious you're requiring internal modules, e.g. require( 'my-project/component' ). resolve.root just plops you into the desired directory without giving you the opportunity to namespace it further.

./configure : /bin/sh^M : bad interpreter

Following on from Richard's comment. Here's the easy way to convert your file to UNIX line endings. If you're like me you created it in Windows Notepad and then tried to run it in Linux - bad idea.

  1. Download and install yourself a copy of Notepad++ (free).
  2. Open your script file in Notepad++.
  3. File menu -> Save As ->
  4. Save as type: Unix script file (*.sh;*.bsh)
  5. Copy the new .sh file to your Linux system
  6. Maxe it executable with: chmod 755 the_script_filename
  7. Run it with: ./the_script_filename

Any other problems try this link.

Set keyboard caret position in html textbox

I found an easy way to fix this issue, tested in IE and Chrome:

function setCaret(elemId, caret)
 {
   var elem = document.getElementById(elemId);
   elem.setSelectionRange(caret, caret);
 }

Pass text box id and caret position to this function.

html select option separator

If it's WebKit-only, you can use <hr> to create a real separator.

http://code.google.com/p/chromium/issues/detail?id=99534

JS jQuery - check if value is in array

You are comparing a jQuery object (jQuery('input:first')) to strings (the elements of the array).
Change the code in order to compare the input's value (wich is a string) to the array elements:

if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)

The inArray method returns -1 if the element wasn't found in the array, so as your bonus answer to how to determine if an element is not in an array, use this :

if(jQuery.inArray(el,arr) == -1){
    // the element is not in the array
};

Login to remote site with PHP cURL

I had same question and I found this answer on this website.

And I changed it just a little bit (the curl_close at last line)

$username = 'myuser';
$password = 'mypass';
$loginUrl = 'http://www.example.com/login/';

//init curl
$ch = curl_init();

//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);

// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);

//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, 'user='.$username.'&pass='.$password);

//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//execute the request (the login)
$store = curl_exec($ch);

//the login is now done and you can continue to get the
//protected content.

//set the URL to the protected file
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/protected/download.zip');

//execute the request
$content = curl_exec($ch);

curl_close($ch);

//save the data to disk
file_put_contents('~/download.zip', $content);

I think this was what you were looking for.Am I right?


And one useful related question. About how to keep a session alive in cUrl: https://stackoverflow.com/a/13020494/2226796

Where is localhost folder located in Mac or Mac OS X?

If you use apachectl to start or stop, then you can find it with this command

apachectl -t -D DUMP_RUN_CFG

gcc makefile error: "No rule to make target ..."

One of frequent mistakes might be typo in another file name.

You example is quite straightforward but what may sometimes confuse are messages of make itself. Lets consider an example.

My folder contents is:

$ ls -1
another_file
index.md
makefile

Whereas my makefile looks like

all: index.html

%.html: %.md wrong_path_to_another_file
    @echo $@ $<

Although I do have index.md where it should be and there is no mistake in the name of it, the message from make will be

make: *** No rule to make target `index.html', needed by `all'.  Stop.

To be honest the message is confusing. It just says, that there is no rule. In fact, it means that the rule is wrong, but due to wildcard (pattern) rules make cannot determine what exactly caused the issue.

Lets alter makefile a little, which is to say replace patterns with explicit rules:

index.html: index.md wrong_path_to_another_file

And now the message we get will be:

make: *** No rule to make target `wrong_path_to_another_file', needed by `index.html'.  Stop.

Miracle! The following might be concluded:

  • Messages of make depends on rules and does not always point to the root of problems

  • There might be other problems in your makefile different from specified by this message

Now we've come up with the idea of checking other dependencies in a rule as well:

all: index.html

%.html: %.md another_file
    @echo $@ $<

Only this will provide us with the desired result:

$ make
index.html index.md

How do I import a Swift file from another Swift file?

Instead of requiring explicit imports, the Swift compiler implicitly searches for .swiftmodule files of dependency Swift libraries.

Xcode can build swift modules for you, or refer to the railsware blog for command line instructions for swiftc.

"Cannot GET /" with Connect on Node.js

The easiest way to serve static files is to use "harp". It can be found here. You can serve up your files from the location you want via node is:

var harp = require("harp")
harp.server(projectPath [,args] [,callback])

Hope this helps.

Matrix Multiplication in pure Python?

Here's some short and simple code for matrix/vector routines in pure Python that I wrote many years ago:

'''Basic Table, Matrix and Vector functions for Python 2.2
   Author:   Raymond Hettinger    
'''

Version = 'File MATFUNC.PY, Ver 183, Date 12-Dec-2002,14:33:42'

import operator, math, random
NPRE, NPOST = 0, 0                    # Disables pre and post condition checks

def iszero(z):  return abs(z) < .000001
def getreal(z):
    try:
        return z.real
    except AttributeError:
        return z
def getimag(z):
    try:
        return z.imag
    except AttributeError:
        return 0
def getconj(z):
    try:
        return z.conjugate()
    except AttributeError:
        return z


separator = [ '', '\t', '\n', '\n----------\n', '\n===========\n' ]

class Table(list):
    dim = 1
    concat = list.__add__      # A substitute for the overridden __add__ method
    def __getslice__( self, i, j ):
        return self.__class__( list.__getslice__(self,i,j) )
    def __init__( self, elems ):
        list.__init__( self, elems )
        if len(elems) and hasattr(elems[0], 'dim'): self.dim = elems[0].dim + 1
    def __str__( self ):
        return separator[self.dim].join( map(str, self) )
    def map( self, op, rhs=None ):
        '''Apply a unary operator to every element in the matrix or a binary operator to corresponding
        elements in two arrays.  If the dimensions are different, broadcast the smaller dimension over
        the larger (i.e. match a scalar to every element in a vector or a vector to a matrix).'''
        if rhs is None:                                                 # Unary case
            return self.dim==1 and self.__class__( map(op, self) ) or self.__class__( [elem.map(op) for elem in self] )
        elif not hasattr(rhs,'dim'):                                    # List / Scalar op
            return self.__class__( [op(e,rhs) for e in self] )
        elif self.dim == rhs.dim:                                       # Same level Vec / Vec or Matrix / Matrix
            assert NPRE or len(self) == len(rhs), 'Table operation requires len sizes to agree'
            return self.__class__( map(op, self, rhs) )
        elif self.dim < rhs.dim:                                        # Vec / Matrix
            return self.__class__( [op(self,e) for e in rhs]  )
        return self.__class__( [op(e,rhs) for e in self] )         # Matrix / Vec
    def __mul__( self, rhs ):  return self.map( operator.mul, rhs )
    def __div__( self, rhs ):  return self.map( operator.div, rhs )
    def __sub__( self, rhs ):  return self.map( operator.sub, rhs )
    def __add__( self, rhs ):  return self.map( operator.add, rhs )
    def __rmul__( self, lhs ):  return self*lhs
    def __rdiv__( self, lhs ):  return self*(1.0/lhs)
    def __rsub__( self, lhs ):  return -(self-lhs)
    def __radd__( self, lhs ):  return self+lhs
    def __abs__( self ): return self.map( abs )
    def __neg__( self ): return self.map( operator.neg )
    def conjugate( self ): return self.map( getconj )
    def real( self ): return self.map( getreal  )
    def imag( self ): return self.map( getimag )
    def flatten( self ):
        if self.dim == 1: return self
        return reduce( lambda cum, e: e.flatten().concat(cum), self, [] )
    def prod( self ):  return reduce(operator.mul, self.flatten(), 1.0)
    def sum( self ):  return reduce(operator.add, self.flatten(), 0.0)
    def exists( self, predicate ):
        for elem in self.flatten():
            if predicate(elem):
                return 1
        return 0
    def forall( self, predicate ):
        for elem in self.flatten():
            if not predicate(elem):
                return 0
        return 1
    def __eq__( self, rhs ):  return (self - rhs).forall( iszero )

class Vec(Table):
    def dot( self, otherVec ):  return reduce(operator.add, map(operator.mul, self, otherVec), 0.0)
    def norm( self ):  return math.sqrt(abs( self.dot(self.conjugate()) ))
    def normalize( self ):  return self / self.norm()
    def outer( self, otherVec ):  return Mat([otherVec*x for x in self])
    def cross( self, otherVec ):
        'Compute a Vector or Cross Product with another vector'
        assert len(self) == len(otherVec) == 3, 'Cross product only defined for 3-D vectors'
        u, v = self, otherVec
        return Vec([ u[1]*v[2]-u[2]*v[1], u[2]*v[0]-u[0]*v[2], u[0]*v[1]-u[1]*v[0] ])
    def house( self, index ):
        'Compute a Householder vector which zeroes all but the index element after a reflection'
        v = Vec( Table([0]*index).concat(self[index:]) ).normalize()
        t = v[index]
        sigma = 1.0 - t**2
        if sigma != 0.0:
            t = v[index] = t<=0 and t-1.0 or -sigma / (t + 1.0)
            v /= t
        return v, 2.0 * t**2 / (sigma + t**2)
    def polyval( self, x ):
        'Vec([6,3,4]).polyval(5) evaluates to 6*x**2 + 3*x + 4 at x=5'
        return reduce( lambda cum,c: cum*x+c, self, 0.0 )
    def ratval( self, x ):
        'Vec([10,20,30,40,50]).ratfit(5) evaluates to (10*x**2 + 20*x + 30) / (40*x**2 + 50*x + 1) at x=5.'
        degree = len(self) / 2
        num, den = self[:degree+1], self[degree+1:] + [1]
        return num.polyval(x) / den.polyval(x)

class Matrix(Table):
    __slots__ = ['size', 'rows', 'cols']
    def __init__( self, elems ):
        'Form a matrix from a list of lists or a list of Vecs'
        Table.__init__( self, hasattr(elems[0], 'dot') and elems or map(Vec,map(tuple,elems)) )
        self.size = self.rows, self.cols = len(elems), len(elems[0])
    def tr( self ):
        'Tranpose elements so that Transposed[i][j] = Original[j][i]'
        return Mat(zip(*self))
    def star( self ):
        'Return the Hermetian adjoint so that Star[i][j] = Original[j][i].conjugate()'
        return self.tr().conjugate()
    def diag( self ):
        'Return a vector composed of elements on the matrix diagonal'
        return Vec( [self[i][i] for i in range(min(self.size))] )
    def trace( self ): return self.diag().sum()
    def mmul( self, other ):
        'Matrix multiply by another matrix or a column vector '
        if other.dim==2: return Mat( map(self.mmul, other.tr()) ).tr()
        assert NPRE or self.cols == len(other)
        return Vec( map(other.dot, self) )
    def augment( self, otherMat ):
        'Make a new matrix with the two original matrices laid side by side'
        assert self.rows == otherMat.rows, 'Size mismatch: %s * %s' % (`self.size`, `otherMat.size`)
        return Mat( map(Table.concat, self, otherMat) )
    def qr( self, ROnly=0 ):
        'QR decomposition using Householder reflections: Q*R==self, Q.tr()*Q==I(n), R upper triangular'
        R = self
        m, n = R.size
        for i in range(min(m,n)):
            v, beta = R.tr()[i].house(i)
            R -= v.outer( R.tr().mmul(v)*beta )
        for i in range(1,min(n,m)): R[i][:i] = [0] * i
        R = Mat(R[:n])
        if ROnly: return R
        Q = R.tr().solve(self.tr()).tr()       # Rt Qt = At    nn  nm  = nm
        self.qr = lambda r=0, c=`self`: not r and c==`self` and (Q,R) or Matrix.qr(self,r) #Cache result
        assert NPOST or m>=n and Q.size==(m,n) and isinstance(R,UpperTri) or m<n and Q.size==(m,m) and R.size==(m,n)
        assert NPOST or Q.mmul(R)==self and Q.tr().mmul(Q)==eye(min(m,n))
        return Q, R
    def _solve( self, b ):
        '''General matrices (incuding) are solved using the QR composition.
        For inconsistent cases, returns the least squares solution'''
        Q, R = self.qr()
        return R.solve( Q.tr().mmul(b) )
    def solve( self, b ):
        'Divide matrix into a column vector or matrix and iterate to improve the solution'
        if b.dim==2: return Mat( map(self.solve, b.tr()) ).tr()
        assert NPRE or self.rows == len(b), 'Matrix row count %d must match vector length %d' % (self.rows, len(b))
        x = self._solve( b )
        diff = b - self.mmul(x)
        maxdiff = diff.dot(diff)
        for i in range(10):
            xnew = x + self._solve( diff )
            diffnew = b - self.mmul(xnew)
            maxdiffnew = diffnew.dot(diffnew)
            if maxdiffnew >= maxdiff:  break
            x, diff, maxdiff = xnew, diffnew, maxdiffnew
            #print >> sys.stderr, i+1, maxdiff
        assert NPOST or self.rows!=self.cols or self.mmul(x) == b
        return x
    def rank( self ):  return Vec([ not row.forall(iszero) for row in self.qr(ROnly=1) ]).sum()

class Square(Matrix):
    def lu( self ):
        'Factor a square matrix into lower and upper triangular form such that L.mmul(U)==A'
        n = self.rows
        L, U = eye(n), Mat(self[:])
        for i in range(n):
            for j in range(i+1,U.rows):
                assert U[i][i] != 0.0, 'LU requires non-zero elements on the diagonal'
                L[j][i] = m = 1.0 * U[j][i] / U[i][i]
                U[j] -= U[i] * m
        assert NPOST or isinstance(L,LowerTri) and isinstance(U,UpperTri) and L*U==self
        return L, U
    def __pow__( self, exp ):
        'Raise a square matrix to an integer power (i.e. A**3 is the same as A.mmul(A.mmul(A))'
        assert NPRE or exp==int(exp) and exp>0, 'Matrix powers only defined for positive integers not %s' % exp
        if exp == 1: return self
        if exp&1: return self.mmul(self ** (exp-1))
        sqrme = self ** (exp/2)
        return sqrme.mmul(sqrme)
    def det( self ):  return self.qr( ROnly=1 ).det()
    def inverse( self ):  return self.solve( eye(self.rows) )
    def hessenberg( self ):
        '''Householder reduction to Hessenberg Form (zeroes below the diagonal)
        while keeping the same eigenvalues as self.'''
        for i in range(self.cols-2):
            v, beta = self.tr()[i].house(i+1)
            self -= v.outer( self.tr().mmul(v)*beta )
            self -= self.mmul(v).outer(v*beta)
        return self
    def eigs( self ):
        'Estimate principal eigenvalues using the QR with shifts method'
        origTrace, origDet = self.trace(), self.det()
        self = self.hessenberg()
        eigvals = Vec([])
        for i in range(self.rows-1,0,-1):
            while not self[i][:i].forall(iszero):
                shift = eye(i+1) * self[i][i]
                q, r = (self - shift).qr()
                self = r.mmul(q) + shift
            eigvals.append( self[i][i] )
            self = Mat( [self[r][:i] for r in range(i)] )
        eigvals.append( self[0][0] )
        assert NPOST or iszero( (abs(origDet) - abs(eigvals.prod())) / 1000.0 )
        assert NPOST or iszero( origTrace - eigvals.sum() )
        return Vec(eigvals)

class Triangular(Square):
    def eigs( self ):  return self.diag()
    def det( self ):  return self.diag().prod()

class UpperTri(Triangular):
    def _solve( self, b ):
        'Solve an upper triangular matrix using backward substitution'
        x = Vec([])
        for i in range(self.rows-1, -1, -1):
            assert NPRE or self[i][i], 'Backsub requires non-zero elements on the diagonal'
            x.insert(0, (b[i] - x.dot(self[i][i+1:])) / self[i][i] )
        return x

class LowerTri(Triangular):
    def _solve( self, b ):
        'Solve a lower triangular matrix using forward substitution'
        x = Vec([])
        for i in range(self.rows):
            assert NPRE or self[i][i], 'Forward sub requires non-zero elements on the diagonal'
            x.append( (b[i] - x.dot(self[i][:i])) / self[i][i] )
        return x

def Mat( elems ):
    'Factory function to create a new matrix.'
    m, n = len(elems), len(elems[0])
    if m != n: return Matrix(elems)
    if n <= 1: return Square(elems)
    for i in range(1, len(elems)):
        if not iszero( max(map(abs, elems[i][:i])) ):
            break
    else: return UpperTri(elems)
    for i in range(0, len(elems)-1):
        if not iszero( max(map(abs, elems[i][i+1:])) ):
            return Square(elems)
    return LowerTri(elems)


def funToVec( tgtfun, low=-1, high=1, steps=40, EqualSpacing=0 ):
    '''Compute x,y points from evaluating a target function over an interval (low to high)
    at evenly spaces points or with Chebyshev abscissa spacing (default) '''
    if EqualSpacing:
        h = (0.0+high-low)/steps
        xvec = [low+h/2.0+h*i for i in range(steps)]
    else:
        scale, base = (0.0+high-low)/2.0, (0.0+high+low)/2.0
        xvec = [base+scale*math.cos(((2*steps-1-2*i)*math.pi)/(2*steps)) for i in range(steps)]
    yvec = map(tgtfun, xvec)
    return Mat( [xvec, yvec] )

def funfit( (xvec, yvec), basisfuns ):
    'Solves design matrix for approximating to basis functions'
    return Mat([ map(form,xvec) for form in basisfuns ]).tr().solve(Vec(yvec))

def polyfit( (xvec, yvec), degree=2 ):
    'Solves Vandermonde design matrix for approximating polynomial coefficients'
    return Mat([ [x**n for n in range(degree,-1,-1)] for x in xvec ]).solve(Vec(yvec))

def ratfit( (xvec, yvec), degree=2 ):
    'Solves design matrix for approximating rational polynomial coefficients (a*x**2 + b*x + c)/(d*x**2 + e*x + 1)'
    return Mat([[x**n for n in range(degree,-1,-1)]+[-y*x**n for n in range(degree,0,-1)] for x,y in zip(xvec,yvec)]).solve(Vec(yvec))

def genmat(m, n, func):
    if not n: n=m
    return Mat([ [func(i,j) for i in range(n)] for j in range(m) ])

def zeroes(m=1, n=None):
    'Zero matrix with side length m-by-m or m-by-n.'
    return genmat(m,n, lambda i,j: 0)

def eye(m=1, n=None):
    'Identity matrix with side length m-by-m or m-by-n'
    return genmat(m,n, lambda i,j: i==j)

def hilb(m=1, n=None):
    'Hilbert matrix with side length m-by-m or m-by-n.  Elem[i][j]=1/(i+j+1)'
    return genmat(m,n, lambda i,j: 1.0/(i+j+1.0))

def rand(m=1, n=None):
    'Random matrix with side length m-by-m or m-by-n'
    return genmat(m,n, lambda i,j: random.random())

if __name__ == '__main__':
    import cmath
    a = Table([1+2j,2,3,4])
    b = Table([5,6,7,8])
    C = Table([a,b])
    print 'a+b', a+b
    print '2+a', 2+a
    print 'a/5.0', a/5.0
    print '2*a+3*b', 2*a+3*b
    print 'a+C', a+C
    print '3+C', 3+C
    print 'C+b', C+b
    print 'C.sum()', C.sum()
    print 'C.map(math.cos)', C.map(cmath.cos)
    print 'C.conjugate()', C.conjugate()
    print 'C.real()', C.real()

    print zeroes(3)
    print eye(4)
    print hilb(3,5)

    C = Mat( [[1,2,3], [4,5,1,], [7,8,9]] )
    print C.mmul( C.tr()), '\n'
    print C ** 5, '\n'
    print C + C.tr(), '\n'

    A = C.tr().augment( Mat([[10,11,13]]).tr() ).tr()
    q, r = A.qr()
    assert q.mmul(r) == A
    assert q.tr().mmul(q)==eye(3)
    print 'q:\n', q, '\nr:\n', r, '\nQ.tr()&Q:\n', q.tr().mmul(q), '\nQ*R\n', q.mmul(r), '\n'
    b = Vec([50, 100, 220, 321])
    x = A.solve(b)
    print 'x:  ', x
    print 'b:  ', b
    print 'Ax: ', A.mmul(x)

    inv = C.inverse()
    print '\ninverse C:\n', inv, '\nC * inv(C):\n', C.mmul(inv)
    assert C.mmul(inv) == eye(3)

    points = (xvec,yvec) = funToVec(lambda x: math.sin(x)+2*math.cos(.7*x+.1), low=0, high=3, EqualSpacing=1)
    basis = [lambda x: math.sin(x), lambda x: math.exp(x), lambda x: x**2]
    print 'Func coeffs:', funfit( points, basis )
    print 'Poly coeffs:', polyfit( points, degree=5 )
    points = (xvec,yvec) = funToVec(lambda x: math.sin(x)+2*math.cos(.7*x+.1), low=0, high=3)
    print 'Rational coeffs:', ratfit( points )

    print polyfit(([1,2,3,4], [1,4,9,16]), 2)

    mtable = Vec([1,2,3]).outer(Vec([1,2]))
    print mtable, mtable.size

    A = Mat([ [2,0,3], [1,5,1], [18,0,6] ])
    print 'A:'
    print A
    print 'eigs:'
    print A.eigs()
    print 'Should be:', Vec([11.6158, 5.0000, -3.6158])
    print 'det(A)'
    print A.det()

    c = Mat( [[1,2,30],[4,5,10],[10,80,9]] )     # Failed example from Konrad Hinsen
    print 'C:\n', c
    print c.eigs()
    print 'Should be:', Vec([-8.9554, 43.2497, -19.2943])

    A = Mat([ [1,2,3,4], [4,5,6,7], [2,1,5,0], [4,2,1,0] ] )    # Kincaid and Cheney p.326
    print 'A:\n', A
    print A.eigs()
    print 'Should be:', Vec([3.5736, 0.1765, 11.1055, -3.8556])

    A = rand(3)
    q,r = A.qr()
    s,t = A.qr()
    print q is s                # Test caching
    print r is t
    A[1][1] = 1.1               # Invalidate the cache
    u,v = A.qr()
    print q is u                # Verify old result not used
    print r is v
    print u.mmul(v) == A        # Verify new result

    print 'Test qr on 3x5 matrix'
    a = rand(3,5)
    q,r = a.qr()
    print q.mmul(r) == a
    print q.tr().mmul(q) == eye(3)

How to refresh or show immediately in datagridview after inserting?

Try below piece of code.

this.dataGridView1.RefreshEdit();

How to save traceback / sys.exc_info() values in a variable?

sys.exc_info() returns a tuple with three values (type, value, traceback).

  1. Here type gets the exception type of the Exception being handled
  2. value is the arguments that are being passed to constructor of exception class
  3. traceback contains the stack information like where the exception occurred etc.

For Example, In the following program

try:

    a = 1/0

except Exception,e:

    exc_tuple = sys.exc_info()

Now If we print the tuple the values will be this.

  1. exc_tuple[0] value will be "ZeroDivisionError"
  2. exc_tuple[1] value will be "integer division or modulo by zero" (String passed as parameter to the exception class)
  3. exc_tuple[2] value will be "trackback object at (some memory address)"

The above details can also be fetched by simply printing the exception in string format.

print str(e)

How do you debug PHP scripts?

I use Netbeans with XDebug and the Easy XDebug FireFox Add-on

The add-on is essential when you debug MVC projects, because the normal way XDebug runs in Netbeans is to register the dbug session via the url. With the add-on installed in FireFox, you would set your Netbeans project properties -> Run Configuratuion -> Advanced and select "Do Not Open Web Browser" You can now set your break points and start the debugging session with Ctrl-F5 as usual. Open FireFox and right-click the Add-on icon in the right bottom corner to start monitoring for breakpoints. When the code reaches the breakpoint it will stop and you can inspect your variable states and call-stack.

How do you build a Singleton in Dart?

I use this simple pattern on dart and previously on Swift. I like that it's terse and only one way of using it.

class Singleton {
  static Singleton shared = Singleton._init();
  Singleton._init() {
    // init work here
  }

  void doSomething() {
  }
}

Singleton.shared.doSomething();

Generating statistics from Git repository

Just yesterday I've added my git-analytics docker-compose file, which builds up several containers to start analyzing multiple git repositories against each other.

It is able to show you commit statistics over time about the author and also several diff statistics.

You can use the provided angular client and also kibana to visualize the statistics.

https://github.com/alexejsailer/git-analytics-docker

It will be improved over time.

Angular Client Screenshot

Angular Client Screenshot

Kibana Client Screenshot

Kibana Client Screenshot]

How do I create a crontab through a script

(I don't have enough reputation to comment, so I'm adding at as an answer: feel free to add it as as comment next to his answer)

Joe Casadonte's one-liner is perfect, except if you run with set -e, i.e. if your script is set to fail on error, and if there are no cronjobs yet. In that case, the one-liner will NOT create the cronjob, but will NOT stop the script. The silent failure can be very misleading.

The reason is that crontab -l returns with a 1 return code, causing the subsequent command (the echo) not to be executed... thus the cronjob is not created. But since they are executed as a subprocess (because of the parenthesis) they don't stop the script.

(Interestingly, if you run the same command again, it will work: once you have executed crontab - once, crontab -l still outputs nothing, but it doesn't return an error anymore (you don't get the no crontab for <user> message anymore). So the subsequent echo is executed and the crontab is created)

In any case, if you run with set -e, the line must be:

(crontab -l 2>/dev/null || true; echo "*/5 * * * * /path/to/job -with args") | crontab -

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

When I had this problem, I had literally just forgot to fill in a parameter value in the XAML of the code.

For some reason though, the exception would send me to the CS of the WPF program rather than the XAML. No idea why.

How to get build time stamp from Jenkins build variables?

This answer below shows another method using "regexp feature of the Description Setter Plugin" which solved my problem as I could not install new plugins on Jenkins due to permission issues:

Use build timestamp in setting build description Jenkins

Short form for Java if statement

name = city.getName()!=null?city.getName():"N/A"

Recyclerview inside ScrollView not scrolling smoothly

You can use this way either :

Add this line to your recyclerView xml file :

android:nestedScrollingEnabled="false"

Or in java code :

RecyclerView.setNestedScrollingEnabled(false);

Hope this helped .

Using SVG as background image

Set Background svg with content/cart at center

.login-container {
  justify-content: center;
  align-items: center;
  display: flex;
  height: 100vh; 
  background-image: url(/assets/images/login-bg.svg);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

Return number of rows affected by UPDATE statements

This is exactly what the OUTPUT clause in SQL Server 2005 onwards is excellent for.

EXAMPLE

CREATE TABLE [dbo].[test_table](
    [LockId] [int] IDENTITY(1,1) NOT NULL,
    [StartTime] [datetime] NULL,
    [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed 
WHERE
    StartTime > '2009 JUL 09'

Results in the following being returned

    LockId StartTime                EndTime
-------------------------------------------------------
4      2011-07-01 00:00:00.000  2009-07-10 00:00:00.000
5      2011-07-01 00:00:00.000  2009-07-11 00:00:00.000
6      2011-07-01 00:00:00.000  2009-07-12 00:00:00.000
7      2011-07-01 00:00:00.000  2009-07-13 00:00:00.000

In your particular case, since you cannot use aggregate functions with OUTPUT, you need to capture the output of INSERTED.* in a table variable or temporary table and count the records. For example,

DECLARE @temp TABLE (
  [LockId] [int],
  [StartTime] [datetime] NULL,
  [EndTime] [datetime] NULL 
)

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* INTO @temp
WHERE
    StartTime > '2009 JUL 09'


-- now get the count of affected records
SELECT COUNT(*) FROM @temp

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

One is a static import (<%=@ include...>"), the other is a dynamic one (jsp:include). It will affect for example the path you gonna have to specify for your included file. A little research on Google will tell you more.

How to change the Content of a <textarea> with JavaScript

Although many correct answers have already been given, the classical (read non-DOM) approach would be like this:

document.forms['yourform']['yourtextarea'].value = 'yourvalue';

where in the HTML your textarea is nested somewhere in a form like this:

<form name="yourform">
    <textarea name="yourtextarea" rows="10" cols="60"></textarea>
</form>

And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.

How can I insert vertical blank space into an html document?

Read up some on css, it's fun: http://www.w3.org/Style/Examples/007/units.en.html

<style>
  .bottom-three {
     margin-bottom: 3cm;
  }
</style>


<p class="bottom-three">
   This is the first question?
</p>
<p class="bottom-three">
   This is the second question?
</p>

How to raise a ValueError?

>>> response='bababa'
...  if "K" in response.text:
...     raise ValueError("Not found")

What is the native keyword in Java for?

As SLaks answered, the native keyword is for calling native code.

It also used by GWT for implementing javascript methods.

Remove a CLASS for all child elements

This should work:

$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`

Deleting rows with MySQL LEFT JOIN

This script worked for me:

DELETE t
FROM table t
INNER JOIN join_table jt ON t.fk_column = jt.id
WHERE jt.comdition_column…;

How to add items to a spinner in Android?

I've found another option: spinner definition in the layout file

<Spinner android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:drawSelectorOnTop="true"
    android:prompt="@string/spin"
    android:entries="@array/spinnerItems"
/>

Items definition in the file array.xml:

<resources>
    <string-array name="spinnerItems">
        <item>item1</item>
        <item>item2</item>
        <item>item3</item>
        <item>item4</item>
    </string-array>
</resources>

Link to the full source of the code

How to get a cookie from an AJAX response?

xhr.getResponseHeader('Set-Cookie');

It won't work for me.

I use this

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
} 

success: function(output, status, xhr) {
    alert(getCookie("MyCookie"));
},

http://www.w3schools.com/js/js_cookies.asp

Getting Chrome to accept self-signed localhost certificate

None of the answers above helped me on Windows 10 when testing locally on

https://localhost:<port>.

However I found this page, indicating another flag to pass:

https://www.chromium.org/blink/serviceworker/service-worker-faq

If you want to test on https://localhost with a self-signed certificate, do:

$ ./chrome --allow-insecure-localhost https://localhost

That did not get rid of the red warning, but it did enable me to use https-only feature like service workers and web push notifications.

Insert default value when parameter is null

Try an if statement ...

if @value is null 
    insert into t (value) values (default)
else
    insert into t (value) values (@value)

How to vertically center a "div" element for all browsers using CSS?

Centering only vertically

If you don't care about Internet Explorer 6 and 7, you can use a technique that involves two containers.

The outer container:

  • should have display: table;

The inner container:

  • should have display: table-cell;
  • should have vertical-align: middle;

The content box:

  • should have display: inline-block;

You can add any content you want to the content box without caring about its width or height!

Demo:

_x000D_
_x000D_
body {
    margin: 0;
}

.outer-container {
    position: absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
}

.centered-content {
    display: inline-block;
    background: #fff;
    padding: 20px;
    border: 1px solid #000;
}
_x000D_
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        Malcolm in the Middle
     </div>
   </div>
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!


Centering horizontally and vertically

If you want to center both horizontally and vertically, you also need the following.

The inner container:

  • should have text-align: center;

The content box:

  • should re-adjust the horizontal text-alignment to for example text-align: left; or text-align: right;, unless you want text to be centered

Demo:

_x000D_
_x000D_
body {
    margin: 0;
}

.outer-container {
    position: absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding: 20px;
    border: 1px solid #000;
}
_x000D_
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
         Malcolm in the Middle
     </div>
   </div>
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

Hide div element when screen size is smaller than a specific size

I don't know about CSS but this Javascript code should work:

    function getBrowserSize(){
       var w, h;

         if(typeof window.innerWidth != 'undefined')
         {
          w = window.innerWidth; //other browsers
          h = window.innerHeight;
         } 
         else if(typeof document.documentElement != 'undefined' && typeof      document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) 
         {
          w =  document.documentElement.clientWidth; //IE
          h = document.documentElement.clientHeight;
         }
         else{
          w = document.body.clientWidth; //IE
          h = document.body.clientHeight;
         }
       return {'width':w, 'height': h};
}

if(parseInt(getBrowserSize().width) < 1026){
 document.getElementById("fadeshow1").style.display = "none";
}

Hash Table/Associative Array in VBA

Here we go... just copy the code to a module, it's ready to use

Private Type hashtable
    key As Variant
    value As Variant
End Type

Private GetErrMsg As String

Private Function CreateHashTable(htable() As hashtable) As Boolean
    GetErrMsg = ""
    On Error GoTo CreateErr
        ReDim htable(0)
        CreateHashTable = True
    Exit Function

CreateErr:
    CreateHashTable = False
    GetErrMsg = Err.Description
End Function

Private Function AddValue(htable() As hashtable, key As Variant, value As Variant) As Long
    GetErrMsg = ""
    On Error GoTo AddErr
        Dim idx As Long
        idx = UBound(htable) + 1

        Dim htVal As hashtable
        htVal.key = key
        htVal.value = value

        Dim i As Long
        For i = 1 To UBound(htable)
            If htable(i).key = key Then Err.Raise 9999, , "Key [" & CStr(key) & "] is not unique"
        Next i

        ReDim Preserve htable(idx)

        htable(idx) = htVal
        AddValue = idx
    Exit Function

AddErr:
    AddValue = 0
    GetErrMsg = Err.Description
End Function

Private Function RemoveValue(htable() As hashtable, key As Variant) As Boolean
    GetErrMsg = ""
    On Error GoTo RemoveErr

        Dim i As Long, idx As Long
        Dim htTemp() As hashtable
        idx = 0

        For i = 1 To UBound(htable)
            If htable(i).key <> key And IsEmpty(htable(i).key) = False Then
                ReDim Preserve htTemp(idx)
                AddValue htTemp, htable(i).key, htable(i).value
                idx = idx + 1
            End If
        Next i

        If UBound(htable) = UBound(htTemp) Then Err.Raise 9998, , "Key [" & CStr(key) & "] not found"

        htable = htTemp
        RemoveValue = True
    Exit Function

RemoveErr:
    RemoveValue = False
    GetErrMsg = Err.Description
End Function

Private Function GetValue(htable() As hashtable, key As Variant) As Variant
    GetErrMsg = ""
    On Error GoTo GetValueErr
        Dim found As Boolean
        found = False

        For i = 1 To UBound(htable)
            If htable(i).key = key And IsEmpty(htable(i).key) = False Then
                GetValue = htable(i).value
                Exit Function
            End If
        Next i
        Err.Raise 9997, , "Key [" & CStr(key) & "] not found"

    Exit Function

GetValueErr:
    GetValue = ""
    GetErrMsg = Err.Description
End Function

Private Function GetValueCount(htable() As hashtable) As Long
    GetErrMsg = ""
    On Error GoTo GetValueCountErr
        GetValueCount = UBound(htable)
    Exit Function

GetValueCountErr:
    GetValueCount = 0
    GetErrMsg = Err.Description
End Function

To use in your VB(A) App:

Public Sub Test()
    Dim hashtbl() As hashtable
    Debug.Print "Create Hashtable: " & CreateHashTable(hashtbl)
    Debug.Print ""
    Debug.Print "ID Test   Add V1: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
    Debug.Print "ID Test   Add V2: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
    Debug.Print "ID Test 1 Add V1: " & AddValue(hashtbl, "Hallo.1", "Testwert 1")
    Debug.Print "ID Test 2 Add V1: " & AddValue(hashtbl, "Hallo-2", "Testwert 2")
    Debug.Print "ID Test 3 Add V1: " & AddValue(hashtbl, "Hallo 3", "Testwert 3")
    Debug.Print ""
    Debug.Print "Test 1 Removed V1: " & RemoveValue(hashtbl, "Hallo_1")
    Debug.Print "Test 1 Removed V2: " & RemoveValue(hashtbl, "Hallo_1")
    Debug.Print "Test 2 Removed V1: " & RemoveValue(hashtbl, "Hallo-2")
    Debug.Print ""
    Debug.Print "Value Test 3: " & CStr(GetValue(hashtbl, "Hallo 3"))
    Debug.Print "Value Test 1: " & CStr(GetValue(hashtbl, "Hallo_1"))
    Debug.Print ""
    Debug.Print "Hashtable Content:"

    For i = 1 To UBound(hashtbl)
        Debug.Print CStr(i) & ": " & CStr(hashtbl(i).key) & " - " & CStr(hashtbl(i).value)
    Next i

    Debug.Print ""
    Debug.Print "Count: " & CStr(GetValueCount(hashtbl))
End Sub

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

Concept behind putting wait(),notify() methods in Object class

wait - wait method tells the current thread to give up monitor and go to sleep.

notify - Wakes up a single thread that is waiting on this object's monitor.

So you see wait() and notify() methods work at the monitor level, thread which is currently holding the monitor is asked to give up that monitor through wait() method and through notify method (or notifyAll) threads which are waiting on the object's monitor are notified that threads can wake up.

Important point to note here is that monitor is assigned to an object not to a particular thread. That's one reason why these methods are in Object class. To reiterate threads wait on an Object's monitor (lock) and notify() is also called on an object to wake up a thread waiting on the Object's monitor.

Response.Redirect to new window

The fixform trick is neat, but:

  1. You may not have access to the code of what loads in the new window.

  2. Even if you do, you are depending on the fact that it always loads, error free.

  3. And you are depending on the fact that the user won't click another button before the other page gets a chance to load and run fixform.

I would suggest doing this instead:

OnClientClick="aspnetForm.target ='_blank';setTimeout('fixform()', 500);"

And set up fixform on the same page, looking like this:

function fixform() {
   document.getElementById("aspnetForm").target = '';
}

How to start an Intent by passing some parameters to it?

putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.

Syntax: intent.putExtra("key", value);

Eg: intent.putExtra("full_name", "Vishnu Sivan");

Intent intent=getIntent() : It gets the Intent from the previous activity.

fullname = intent.getStringExtra(“full_name”) : This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.

Sample Code:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);

Toolbar navigation icon never set

(The answer to user802421)

private void setToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_action_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }
}

toolbar.xml

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/toolbar_height"
    android:background="?attr/colorPrimaryDark" />

HTML Tags in Javascript Alert() method

You can add HTML into an alert string, but it will not render as HTML. It will just be displayed as a plain string. Simple answer: no.

How do I get a div to float to the bottom of its container?

Stu's answer comes the closest to working so far, but it still doesn't take into account the fact that your outer div's height may change, based on the way the text wraps inside of it. So, repositioning the inner div (by changing the height of the "pipe") only once won't be enough. That change has to occur inside of a loop, so you can continually check whether you've achieved the right positioning yet, and readjust if needed.

The CSS from the previous answer is still perfectly valid:

#outer {
    position: relative; 
}

#inner {
    float:right;
    position:absolute;
    bottom:0;
    right:0;
    clear:right
}

.pipe {
    width:0px; 
    float:right

}

However, the Javascript should look more like this:

var innerBottom;
var totalHeight;
var hadToReduce = false;
var i = 0;
jQuery("#inner").css("position","static");
while(true) {

    // Prevent endless loop
    i++;
    if (i > 5000) { break; }

    totalHeight = jQuery('#outer').outerHeight();
    innerBottom = jQuery("#inner").position().top + jQuery("#inner").outerHeight();
    if (innerBottom < totalHeight) {
        if (hadToReduce !== true) { 
            jQuery(".pipe").css('height', '' + (jQuery(".pipe").height() + 1) + 'px');
        } else { break; }
    } else if (innerBottom > totalHeight) {
        jQuery(".pipe").css('height', '' + (jQuery(".pipe").height() - 1) + 'px');
        hadToReduce = true;
    } else { break; }
}

CONVERT Image url to Base64

Here's the Typescript version of Abubakar Ahmad's answer

function imageTo64(
  url: string, 
  callback: (path64: string | ArrayBuffer) => void
): void {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();

  xhr.onload = (): void => {
    const reader = new FileReader();
    reader.readAsDataURL(xhr.response);
    reader.onloadend = (): void => callback(reader.result);
  }
}

How to iterate over a column vector in Matlab?

for i=1:length(list)
  elm = list(i);
  //do something with elm.

Making PHP var_dump() values display one line per value

For me the right answer was

echo '<pre>' . var_export($var, true) . '</pre>';

Since var_dump($var) and var_export($var) do not return a string, you have to use var_export($var, true) to force var_export to return the result as a value.

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

At the current version of Spring-Boot (1.4.1.RELEASE) , each pooling datasource implementation has its own prefix for properties.

For instance, if you are using tomcat-jdbc:

spring.datasource.tomcat.max-wait=10000

You can find the explanation out here

spring.datasource.max-wait=10000

this have no effect anymore.

How can I trigger a Bootstrap modal programmatically?

If you are looking for a programmatical modal creation, you might love this:

http://nakupanda.github.io/bootstrap3-dialog/

Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.

The source was not found, but some or all event logs could not be searched

Inaccessible logs: Security

A new event source needs to have a unique name across all logs including Security (which needs admin privilege when it's being read).

So your app will need admin privilege to create a source. But that's probably an overkill.

I wrote this powershell script to create the event source at will. Save it as *.ps1 and run it with any privilege and it will elevate itself.

# CHECK OR RUN AS ADMIN

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{   
    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process powershell -Verb runAs -ArgumentList $arguments
    Break
}

# CHECK FOR EXISTENCE OR CREATE

$source = "My Service Event Source";
$logname = "Application";

if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
    [System.Diagnostics.EventLog]::CreateEventSource($source, $logname);
    Write-Host $source -f white -nonewline; Write-Host " successfully added." -f green;
}
else
{
    Write-Host $source -f white -nonewline; Write-Host " already exists.";
}

# DONE

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

Angular: How to download a file from HttpClient?

It took me a while to implement the other responses, as I'm using Angular 8 (tested up to 10). I ended up with the following code (heavily inspired by Hasan).

Note that for the name to be set, the header Access-Control-Expose-Headers MUST include Content-Disposition. To set this in django RF:

http_response = HttpResponse(package, content_type='application/javascript')
http_response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
http_response['Access-Control-Expose-Headers'] = "Content-Disposition"

In angular:

  // component.ts
  // getFileName not necessary, you can just set this as a string if you wish
  getFileName(response: HttpResponse<Blob>) {
    let filename: string;
    try {
      const contentDisposition: string = response.headers.get('content-disposition');
      const r = /(?:filename=")(.+)(?:")/
      filename = r.exec(contentDisposition)[1];
    }
    catch (e) {
      filename = 'myfile.txt'
    }
    return filename
  }

  
  downloadFile() {
    this._fileService.downloadFile(this.file.uuid)
      .subscribe(
        (response: HttpResponse<Blob>) => {
          let filename: string = this.getFileName(response)
          let binaryData = [];
          binaryData.push(response.body);
          let downloadLink = document.createElement('a');
          downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: 'blob' }));
          downloadLink.setAttribute('download', filename);
          document.body.appendChild(downloadLink);
          downloadLink.click();
        }
      )
  }

  // service.ts
  downloadFile(uuid: string) {
    return this._http.get<Blob>(`${environment.apiUrl}/api/v1/file/${uuid}/package/`, { observe: 'response', responseType: 'blob' as 'json' })
  }

Convert timestamp in milliseconds to string formatted time in Java

Doing

logEvent.timeStamp / (1000*60*60)

will give you hours, not minutes. Try:

logEvent.timeStamp / (1000*60)

and you will end up with the same answer as

TimeUnit.MILLISECONDS.toMinutes(logEvent.timeStamp)

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SQL Management Studio you can:

  1. Right click on the result set grid, select 'Save Result As...' and save in.

  2. On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.

If you need to automate it, use bcp tool.

Android read text raw resource file

1.First create a Directory folder and name it raw inside the res folder 2.create a .txt file inside the raw directory folder you created earlier and give it any name eg.articles.txt.... 3.copy and paste the text you want inside the .txt file you created"articles.txt" 4.dont forget to include a textview in your main.xml MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gettingtoknowthe_os);

    TextView helloTxt = (TextView)findViewById(R.id.gettingtoknowos);
    helloTxt.setText(readTxt());

    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();//to exclude the ActionBar
}

private String readTxt() {

    //getting the .txt file
    InputStream inputStream = getResources().openRawResource(R.raw.articles);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    try {
        int i = inputStream.read();
        while (i != -1) {
            byteArrayOutputStream.write(i);
            i = inputStream.read();
        }
        inputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return byteArrayOutputStream.toString();
}

Hope it worked!

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

This suggestion is based on pixel manipulation in canvas 2d context.

From MDN:

You can directly manipulate pixel data in canvases at the byte level

To manipulate pixels we'll use two functions here - getImageData and putImageData.

getImageData usage:

var myImageData = context.getImageData(left, top, width, height);

The putImageData syntax:

context.putImageData(myImageData, x, y); 

Where context is your canvas 2d context, and x and y are the position on the canvas.

So to get red green blue and alpha values, we'll do the following:

var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];

Where x is the horizontal offset, y is the vertical offset.

The code making image half-transparent:

var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload  = function() {
   c.drawImage(img, 0, 0);
   var ImageData = c.getImageData(0,0,img.width,img.height);
   for(var i=0;i<img.height;i++)
      for(var j=0;j<img.width;j++)
         ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
   c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';

You can make you own "shaders" - see full MDN article here

Node.js: printing to console without a trailing newline?

util.print can be used also. Read: http://nodejs.org/api/util.html#util_util_print

util.print([...])# A synchronous output function. Will block the process, cast each argument to a string then output to stdout. Does not place newlines after each argument.

An example:

// get total length
var len = parseInt(response.headers['content-length'], 10);
var cur = 0;

// handle the response
response.on('data', function(chunk) {
  cur += chunk.length;
  util.print("Downloading " + (100.0 * cur / len).toFixed(2) + "% " + cur + " bytes\r");
});

reducing number of plot ticks

When a log scale is used the number of major ticks can be fixed with the following command

import matplotlib.pyplot as plt

....

plt.locator_params(numticks=12)
plt.show()

The value set to numticks determines the number of axis ticks to be displayed.

Credits to @bgamari's post for introducing the locator_params() function, but the nticks parameter throws an error when a log scale is used.

Horizontal ListView in Android?

You can use RecyclerView in the support library. RecyclerView is a generalized version of ListView that supports:

  • A layout manager for positioning items
  • Default animations for common item operations

Android Recycler View Docs

Branch from a previous commit using Git

A quick way to do it on your Github repo would be as followed:

  • Find the specific commit from your branch
  • Beside the SHA id, click on 'Browse the repo at this point in the history'
  • Here you can create a new branch from this commit enter image description here

In Windows cmd, how do I prompt for user input and use the result in another command?

Dollar signs around the variable do not work on my Vista machine, but percent signs do. Also note that a trailing space on the "set" line will show up between the prompt and user input.

What is the use of the init() usage in JavaScript?

NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass instead of myClass.

Either you can call init from your constructor function:

var myObj = new MyClass(2, true);

function MyClass(v1, v2) 
{
    // ...

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // ...

    this.init(); // <------------ added this
}

Or more simply you could just copy the body of the init function to the end of the constructor function. No need to actually have an init function at all if it's only called once.

When should a class be Comparable and/or Comparator?

My annotation lib for implementing Comparable and Comparator:

public class Person implements Comparable<Person> {         
    private String firstName;  
    private String lastName;         
    private int age;         
    private char gentle;         

    @Override         
    @CompaProperties({ @CompaProperty(property = "lastName"),              
        @CompaProperty(property = "age",  order = Order.DSC) })           
    public int compareTo(Person person) {                 
        return Compamatic.doComparasion(this, person);         
    }  
} 

Click the link to see more examples. compamatic

How do I fix MSB3073 error in my post-build event?

In my case, the dll I was creating by building the project was still in use in the background. I killed the application and then xcopy worked fine as expected.

Artisan migrate could not find driver

In Windows and PHP 7.4.5 go to php.ini and uncomment this line

extension=pdo_mysql

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

How to fix symbol lookup error: undefined symbol errors in a cluster environment

yum update

helped me out. After I had

wget: symbol lookup error: wget: undefined symbol: psl_latest

CSS transition between left -> right and top -> bottom positions

In more modern browsers (including IE 10+) you can now use calc():

.moveto {
  top: 0px;
  left: calc(100% - 50px);
}

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

DirBuster is such a hacking script that guesses a bunch of common names as nsanders had mentioned. It literally brute forces lists of common words and file endings (.html, .php) and over time figures out the directory structure of such sites, this could discover the page as you described but would also discover many others.

How can I import a database with MySQL from terminal?

After struggling for sometime I found the information in https://tommcfarlin.com/importing-a-large-database/

  1. Connect to Mysql (let's use root for both username and password):

    mysql -uroot -proot
    
  2. Connect to the database (let's say it is called emptyDatabase (your should get a confirmation message):

    connect emptyDatabase
    

3 Import the source code, lets say the file is called mySource.sql and it is in a folder called mySoureDb under the profile of a user called myUser:

source /Users/myUser/mySourceDB/mySource.sql

Running a CMD or BAT in silent mode

I have proposed in StackOverflow question a way to run a batch file in the background (no DOS windows displayed)

That should answer your question.

Here it is:


From your first script, call your second script with the following line:

wscript.exe invis.vbs run.bat %*

Actually, you are calling a vbs script with:

  • the [path]\name of your script
  • all the other arguments needed by your script (%*)

Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

See the question for the full invis.vbs script:

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False
                                                         ^
                             means "invisible window" ---| 

Update after Tammen's feedback:

If you are in a DOS session and you want to launch another script "in the background", a simple /b (as detailed in the same aforementioned question) can be enough:

You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window.

Making Python loggers output all messages to stdout in addition to log file

Here's an extremely simple example:

import logging
l = logging.getLogger("test")

# Add a file logger
f = logging.FileHandler("test.log")
l.addHandler(f)

# Add a stream logger
s = logging.StreamHandler()
l.addHandler(s)

# Send a test message to both -- critical will always log
l.critical("test msg")

The output will show "test msg" on stdout and also in the file.

How to round down to nearest integer in MySQL?

if you need decimals can use this

DECLARE @Num NUMERIC(18, 7) = 19.1471985
SELECT FLOOR(@Num * 10000) / 10000

Output: 19.147100 Clear: 985 Add: 00

OR use this:

SELECT SUBSTRING(CONVERT(VARCHAR, @Num), 1, CHARINDEX('.', @Num) + 4)

Output: 19.1471 Clear: 985

Trying to get property of non-object - CodeIgniter

To access the elements in the array, use array notation: $product['prodname']

$product->prodname is object notation, which can only be used to access object attributes and methods.

How I can check whether a page is loaded completely or not in web driver?

Simple ready2use snippet, working perfectly for me

static void waitForPageLoad(WebDriver wdriver) {
    WebDriverWait wait = new WebDriverWait(wdriver, 60);

    Predicate<WebDriver> pageLoaded = new Predicate<WebDriver>() {

        @Override
        public boolean apply(WebDriver input) {
            return ((JavascriptExecutor) input).executeScript("return document.readyState").equals("complete");
        }

    };
    wait.until(pageLoaded);
}

Bind event to right mouse click

document.oncontextmenu = function() {return false;}; //disable the browser context menu
$('selector-name')[0].oncontextmenu = function(){} //set jquery element context menu 

Find document with array that contains a specific value

I feel like $all would be more appropriate in this situation. If you are looking for person that is into sushi you do :

PersonModel.find({ favoriteFood : { $all : ["sushi"] }, ...})

As you might want to filter more your search, like so :

PersonModel.find({ favoriteFood : { $all : ["sushi", "bananas"] }, ...})

$in is like OR and $all like AND. Check this : https://docs.mongodb.com/manual/reference/operator/query/all/

Increase max execution time for php

Use mod_php7.c instead of mod_php5.c for PHP 7

Example

<IfModule mod_php7.c>
   php_value max_execution_time 500
</IfModule>

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook. The actual C# command was

excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
    Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, 
    Excel.XlSaveConflictResolution.xlUserResolution, true, 
    Missing.Value, Missing.Value, Missing.Value);

I hope this helps someone else in the future.


Missing.Value is found in the System.Reflection namespace.

How to implement an STL-style iterator and avoid common pitfalls?

I was/am in the same boat as you for different reasons (partly educational, partly constraints). I had to re-write all the containers of the standard library and the containers had to conform to the standard. That means, if I swap out my container with the stl version, the code would work the same. Which also meant that I had to re-write the iterators.

Anyway, I looked at EASTL. Apart from learning a ton about containers that I never learned all this time using the stl containers or through my undergraduate courses. The main reason is that EASTL is more readable than the stl counterpart (I found this is simply because of the lack of all the macros and straight forward coding style). There are some icky things in there (like #ifdefs for exceptions) but nothing to overwhelm you.

As others mentioned, look at cplusplus.com's reference on iterators and containers.

How to programmatically take a screenshot on Android?

As a reference, one way to capture the screen (and not just your app activity) is to capture the framebuffer (device /dev/graphics/fb0). To do this you must either have root privileges or your app must be an app with signature permissions ("A permission that the system grants only if the requesting application is signed with the same certificate as the application that declared the permission") - which is very unlikely unless you compiled your own ROM.

Each framebuffer capture, from a couple of devices I have tested, contained exactly one screenshot. People have reported it to contain more, I guess it depends on the frame/display size.

I tried to read the framebuffer continuously but it seems to return for a fixed amount of bytes read. In my case that is (3 410 432) bytes, which is enough to store a display frame of 854*480 RGBA (3 279 360 bytes). Yes, the frame, in binary, outputted from fb0 is RGBA in my device. This will most likely depend from device to device. This will be important for you to decode it =)

In my device /dev/graphics/fb0 permissions are so that only root and users from group graphics can read the fb0.

graphics is a restricted group so you will probably only access fb0 with a rooted phone using su command.

Android apps have the user id (uid) = app_## and group id (guid) = app_## .

adb shell has uid = shell and guid = shell, which has much more permissions than an app. You can actually check those permissions at /system/permissions/platform.xml

This means you will be able to read fb0 in the adb shell without root but you will not read it within the app without root.

Also, giving READ_FRAME_BUFFER and/or ACCESS_SURFACE_FLINGER permissions on AndroidManifest.xml will do nothing for a regular app because these will only work for 'signature' apps.

Also check this closed thread for more details.

MySQL: Selecting multiple fields into multiple variables in a stored procedure

==========Advise==========

@martin clayton Answer is correct, But this is an advise only.

Please avoid the use of ambiguous variable in the stored procedure.

Example :

SELECT Id, dateCreated
INTO id, datecreated
FROM products
WHERE pName = iName

The above example will cause an error (null value error)

Example give below is correct. I hope this make sense.

Example :

SELECT Id, dateCreated
INTO val_id, val_datecreated
FROM products
WHERE pName = iName

You can also make them unambiguous by referencing the table, like:

[ Credit : maganap ]

SELECT p.Id, p.dateCreated INTO id, datecreated FROM products p 
WHERE pName = iName

Android ImageButton with a selected state?

This works for me:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- NOTE: order is important (the first matching state(s) is what is rendered) -->
    <item 
        android:state_selected="true" 
        android:drawable="@drawable/info_icon_solid_with_shadow" />
    <item 
        android:drawable="@drawable/info_icon_outline_with_shadow" />
 </selector>

And then in java:

//assign the image in code (or you can do this in your layout xml with the src attribute)
imageButton.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable....));

//set the click listener
imageButton.setOnClickListener(new OnClickListener() {

    public void onClick(View button) {
        //Set the button's appearance
        button.setSelected(!button.isSelected());

        if (button.isSelected()) {
            //Handle selected state change
        } else {
            //Handle de-select state change
        }

    }

});

For smooth transition you can also mention animation time:

<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime">

Relative frequencies / proportions with dplyr

You can use count() function, which has however a different behaviour depending on the version of dplyr:

  • dplyr 0.7.1: returns an ungrouped table: you need to group again by am

  • dplyr < 0.7.1: returns a grouped table, so no need to group again, although you might want to ungroup() for later manipulations

dplyr 0.7.1

mtcars %>%
  count(am, gear) %>%
  group_by(am) %>%
  mutate(freq = n / sum(n))

dplyr < 0.7.1

mtcars %>%
  count(am, gear) %>%
  mutate(freq = n / sum(n))

This results into a grouped table, if you want to use it for further analysis, it might be useful to remove the grouped attribute with ungroup().

Possible to make labels appear when hovering over a point in matplotlib?

A slight edit on an example provided in http://matplotlib.org/users/shell.html:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')

line, = ax.plot(np.random.rand(100), '-', picker=5)  # 5 points tolerance


def onpick(event):
    thisline = event.artist
    xdata = thisline.get_xdata()
    ydata = thisline.get_ydata()
    ind = event.ind
    print('onpick points:', *zip(xdata[ind], ydata[ind]))


fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

This plots a straight line plot, as Sohaib was asking

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Upgrade your mysql-connector" lib package with your mysql version like below i am using 8.0.13 version and in pom I changed the version:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
    <version>8.0.13</version>
</dependency>

My problem has resolved after this.

How much RAM is SQL Server actually using?

Related to your question, you may want to consider limiting the amount of RAM SQL Server has access to if you are using it in a shared environment, i.e., on a server that hosts more than just SQL Server:

  1. Start > All Programs > Microsoft SQL Server 2005: SQL Server Management Studio.
  2. Connect using whatever account has admin rights.
  3. Right click on the database > Properties.
  4. Select "Memory" from the left pane and then change the "Server memory options" to whatever you feel should be allocated to SQL Server.

This will help alleviate SQL Server from consuming all the server's RAM.

How to rename a pane in tmux?

For those who want to easily rename their panes, this is what I have in my .tmux.conf

set -g default-command '                      \
function renamePane () {                      \
  read -p "Enter Pane Name: " pane_name;      \
  printf "\033]2;%s\033\\r:r" "${pane_name}"; \
};                                            \
export -f renamePane;                         \
bash -i'
set -g pane-border-status top
set -g pane-border-format "#{pane_index} #T #{pane_current_command}"
bind-key -T prefix R send-keys "renamePane" C-m

Panes are automatically named with their index, machine name and current command. To change the machine name you can run <C-b>R which will prompt you to enter a new name.

*Pane renaming only works when you are in a shell.

How to add element to C++ array?

Initialize all your array elements to null first, then look for the null to find the empty slot

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

If you support IE, for versions of Internet Explorer 8 and above, this:

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />

Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.

If you separate with semi-colon, it sets compatibility levels for different versions. For example:

<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />

Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

For this:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

It forces the browser the render at whatever the most recent version's standards are.

For more information, there is plenty to read about on MSDN,

Preventing multiple clicks on button

disable the button on click, enable it after the operation completes

$(document).ready(function () {
    $("#btn").on("click", function() {
        $(this).attr("disabled", "disabled");
        doWork(); //this method contains your logic
    });
});

function doWork() {
    alert("doing work");
    //actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
    //I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
    setTimeout('$("#btn").removeAttr("disabled")', 1500);
}

working example

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

If copy-dependencies, unpack, pack, etc., are important for your project you shouldn't ignore it. You have to enclose your <plugins> in <pluginManagement> tested with Eclipse Indigo SR1, maven 2.2.1

jQuery checkbox checked state changed event

Is very simple, this is the way I use:

JQuery:

$(document).on('change', '[name="nameOfCheckboxes[]"]', function() {
    var checkbox = $(this), // Selected or current checkbox
        value = checkbox.val(); // Value of checkbox

    if (checkbox.is(':checked'))
    {
        console.log('checked');
    }else
    {
        console.log('not checked');
    }
});

Regards!

Meaning of Choreographer messages in Logcat

In my case I have these messages when I show the sherlock action bar inderterminate progressbar. Since its not my library, I decided to hide the Choreographer outputs.

You can hide the Choreographer outputs onto the Logcat view, using this filter expression :

tag:^((?!Choreographer).*)$

I used a regex explained elsewhere : Regular expression to match a line that doesn't contain a word?

Filter object properties by key in ES6

If you are OK with using ES6 syntax, I find that the cleanest way to do this, as noted here and here is:

const data = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

const { item2, ...newData } = data;

Now, newData contains:

{
  item1: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

Or, if you have the key stored as a string:

const key = 'item2';
const { [key]: _, ...newData } = data;

In the latter case, [key] is converted to item2 but since you are using a const assignment, you need to specify a name for the assignment. _ represents a throw away value.

More generally:

const { item2, ...newData } = data; // Assign item2 to item2
const { item2: someVarName, ...newData } = data; // Assign item2 to someVarName
const { item2: _, ...newData } = data; // Assign item2 to _
const { ['item2']: _, ...newData } = data; // Convert string to key first, ...

Not only does this reduce your operation to a one-liner but it also doesn't require you to know what the other keys are (those that you want to preserve).

A simple utility function would look like this:

function removePropFromObject(obj, prop) {
  const { [prop]: _, ...rest } = obj
  return { ...rest }
}

Close dialog on click (anywhere)

Facing the same problem, I have created a small plugin that enables to close a dialog when clicking outside of it whether it a modal or non-modal dialog. It supports one or multiple dialogs on the same page.

More information on my website here: http://www.coheractio.com/blog/closing-jquery-ui-dialog-widget-when-clicking-outside

Laurent

Compare given date with today

If you do things with time and dates Carbon is you best friend;

Install the package then:

$theDay = Carbon::make("2010-01-21 00:00:00.0");

$theDay->isToday();
$theDay->isPast();
$theDay->isFuture();
if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))

lt = less than, gt = greater than

As in the question:

$theDay->gt(Carbon::today()) ? true : false;

and much more;

What are the differences between .so and .dylib on osx?

Just an observation I just made while building naive code on OSX with cmake:

cmake ... -DBUILD_SHARED_LIBS=OFF ...

creates .so files

while

cmake ... -DBUILD_SHARED_LIBS=ON ...

creates .dynlib files.

Perhaps this helps anyone.

How to set the timeout for a TcpClient?

As Simon Mourier mentioned, it's possible to use ConnectAsync TcpClient's method with Task in addition and stop operation as soon as possible.
For example:

// ...
client = new TcpClient(); // Initialization of TcpClient
CancellationToken ct = new CancellationToken(); // Required for "*.Task()" method
if (client.ConnectAsync(this.ip, this.port).Wait(1000, ct)) // Connect with timeout of 1 second
{

    // ... transfer

    if (client != null) {
        client.Close(); // Close the connection and dispose a TcpClient object
        Console.WriteLine("Success");
        ct.ThrowIfCancellationRequested(); // Stop asynchronous operation after successull connection(...and transfer(in needed))
    }
}
else
{
    Console.WriteLine("Connetion timed out");
}
// ...

Also, I would recommended checking the AsyncTcpClient C# library with some examples provided like Server <> Client.

Remove border from buttons

You can also try background:none;border:0px to buttons.

also the css selectors are div#yes button{..} and div#no button{..} . hopes it helps

Difference between Eclipse Europa, Helios, Galileo

Each version has some improvements in certain technologies. For users the biggest difference is whether or not to execute certain plugins, because some were made only for a particular version of Eclipse.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Create a custom callback in JavaScript

My 2 cent. Same but different...

<script>
    dosomething("blaha", function(){
        alert("Yay just like jQuery callbacks!");
    });


    function dosomething(damsg, callback){
        alert(damsg);
        if(typeof callback == "function") 
        callback();
    }
</script>

How do you get the length of a string?

same way you do it in javascript:

"something".length

What does "Use of unassigned local variable" mean?

Because if none of the if statements evaluate to true then the local variable will be unassigned. Throw an else statement in there and assign some values to those variables in case the if statements don't evaluate to true. Post back here if that doesn't make the error go away.

Your other option is to initialize the variables to some default value when you declare them at the beginning of your code.

How to make circular background using css?

It can be done using the border-radius property. basically, you need to set the border-radius to exactly half of the height and width to get a circle.

JSFiddle

HTML

<div id="container">
    <div id="inner">
    </div>
</div>

CSS

#container
{
    height:400px;
    width:400px;
    border:1px black solid;
}

#inner
{
    height:200px;
    width:200px;
    background:black;
    -moz-border-radius: 100px;
    -webkit-border-radius: 100px;
    border-radius: 100px;
    margin-left:25%;
    margin-top:25%;
}

How to convert int to char with leading zeros?

I like to use

DECLARE @Length int
DECLARE @Number int
SET @Length = 9
SET @Number = 4

select right( POWER(10, @Length) + @Number, @Length)

this gives me

000000004

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Before increasing the max_connections variable, you have to check how many non-interactive connection you have by running show processlist command.

If you have many sleep connection, you have to decrease the value of the "wait_timeout" variable to close non-interactive connection after waiting some times.

  • To show the wait_timeout value:

SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+

| Variable_name | Value |

+---------------+-------+

| wait_timeout | 28800 |

+---------------+-------+

the value is in second, it means that non-interactive connection still up to 8 hours.

  • To change the value of "wait_timeout" variable:

SET session wait_timeout=600; Query OK, 0 rows affected (0.00 sec)

After 10 minutes if the sleep connection still sleeping the mysql or MariaDB drop that connection.

Getting the source HTML of the current page from chrome extension

Inject a script into the page you want to get the source from and message it back to the popup....

manifest.json

{
  "name": "Get pages source",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Get pages source from a popup",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["tabs", "<all_urls>"]
}

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>

popup.js

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

function onWindowLoad() {

  var message = document.querySelector('#message');

  chrome.tabs.executeScript(null, {
    file: "getPagesSource.js"
  }, function() {
    // If you try and inject into an extensions page or the webstore/NTP you'll get an error
    if (chrome.runtime.lastError) {
      message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
    }
  });

}

window.onload = onWindowLoad;

getPagesSource.js

// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);

function DOMtoString(document_root) {
    var html = '',
        node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            html += node.outerHTML;
            break;
        case Node.TEXT_NODE:
            html += node.nodeValue;
            break;
        case Node.CDATA_SECTION_NODE:
            html += '<![CDATA[' + node.nodeValue + ']]>';
            break;
        case Node.COMMENT_NODE:
            html += '<!--' + node.nodeValue + '-->';
            break;
        case Node.DOCUMENT_TYPE_NODE:
            // (X)HTML documents are identified by public identifiers
            html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
            break;
        }
        node = node.nextSibling;
    }
    return html;
}

chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoString(document)
});

Set encoding and fileencoding to utf-8 in Vim

You can set the variable 'fileencodings' in your .vimrc.

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

See :help filencodings

If you often work with e.g. cp1252, you can add it there:

set fileencodings=ucs-bom,utf-8,cp1252,default,latin9

Use of Custom Data Types in VBA

It looks like you want to define Truck as a Class with properties NumberOfAxles, AxleWeights & AxleSpacings.

This can be defined in a CLASS MODULE (here named clsTrucks)

Option Explicit

Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double


Public Property Get truckID() As String
    truckID = tID
End Property

Public Property Let truckID(value As String)
    tID = value
End Property

Public Property Get truckNumberOfAxles() As Double
    truckNumberOfAxles = tNumberOfAxles
End Property

Public Property Let truckNumberOfAxles(value As Double)
    tNumberOfAxles = value
End Property

Public Property Get truckAxleSpacings() As Double
    truckAxleSpacings = tAxleSpacings
End Property

Public Property Let truckAxleSpacings(value As Double)
    tAxleSpacings = value
End Property

then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.

Option Explicit

Public TruckCollection As New Collection

Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long

    'Add 5 trucks
    For i = 1 To 5
        Set tempTruck = New clsTrucks
        'Random data
        tempTruck.truckID = "Truck" & i
        tempTruck.truckAxleSpacings = 13.5 + i
        tempTruck.truckNumberOfAxles = 20.5 + i

        'tempTruck.truckID is the collection key
        TruckCollection.Add tempTruck, tempTruck.truckID
    Next i

    'retrieve 5 trucks
    For i = 1 To 5
        'retrieve by collection index
        Debug.Print TruckCollection(i).truckAxleSpacings
        'retrieve by key
        Debug.Print TruckCollection("Truck" & i).truckAxleSpacings

    Next i

End Sub

There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash

bash 4 (recursive)

shopt -s globstar
for xls in /path/**/*.xls
do
  xls2csv "$xls" "${xls%.xls}.csv"
done

How to keep a VMWare VM's clock in sync?

I'll answer for Windows guests. If you have VMware Tools installed, then the taskbar's notification area (near the clock) has an icon for VMware Tools. Double-click that and set your options.

If you don't have VMware Tools installed, you can still set the clock's option for internet time to sync with some NTP server. If your physical machine serves the NTP protocol to your guest machines then you can get that done with host-only networking. Otherwise you'll have to let your guests sync with a genuine NTP server out on the internet, for example time.windows.com.

Excel Formula: Count cells where value is date

Here is how I was able to trick Excel to count expired certifications in a list. I didn't have a set date, or date range, just current date. "TODAY()" doesn't work in these for Excel 2013. It sees it as text or condition, not the date value. So these previous didn't work for me. So the word problem/scenario: How many people are expired in this list?

Use: =IFERROR(D5-TODAY(),0) Where D5 is the date to be interrogated.

Then use: =IF(J5>=1,1,0) Where J5 is the cell where the first equation is producing either a positive or negative number. This set, I have hidden on the side of the visible sheet, then I just sum the total for the number of unexpired members.

How to make a round button?

Fully rounded circle shape.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#FFFFFF" />
    <stroke
        android:width="1dp"
        android:color="#F0F0F0" />
    <corners
        android:radius="90dp"/>
</shape>

Happy Coding!

How do I check CPU and Memory Usage in Java?

JMX, The MXBeans (ThreadMXBean, etc) provided will give you Memory and CPU usages.

OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
operatingSystemMXBean.getSystemCpuLoad();

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

serialize/deserialize java 8 java.time with Jackson JSON mapper

If you're having this issue because of GraphQL Java Tools and trying to marshal an Java Instant from a date string, you need to setup your SchemaParser to use an ObjectMapper with certain configurations:

In your GraphQLSchemaBuilder class, inject ObjectMapper and add this modules:

        ObjectMapper objectMapper = 
    new ObjectMapper().registerModule(new JavaTimeModule())
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

and add it to the options:

final SchemaParserOptions options = SchemaParserOptions.newOptions()
            .objectMapperProvider(fieldDefinition -> objectMapper)
            .typeDefinitionFactory(new YourTypeDefinitionFactory())
            .build();

See https://github.com/graphql-java-kickstart/graphql-spring-boot/issues/32

Build a basic Python iterator

All answers on this page are really great for a complex object. But for those containing builtin iterable types as attributes, like str, list, set or dict, or any implementation of collections.Iterable, you can omit certain things in your class.

class Test(object):
    def __init__(self, string):
        self.string = string

    def __iter__(self):
        # since your string is already iterable
        return (ch for ch in self.string)
        # or simply
        return self.string.__iter__()
        # also
        return iter(self.string)

It can be used like:

for x in Test("abcde"):
    print(x)

# prints
# a
# b
# c
# d
# e

Xcode "Build and Archive" from command line

With Xcode 4.2 you can use the -scheme flag to do this:

xcodebuild -scheme <SchemeName> archive

After this command the Archive will show up in the Xcode Organizer.

How to get substring of NSString?

Here's a slightly less complicated answer:

NSString *myString = @"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];

See also substringWithRange and substringFromIndex

sed fails with "unknown option to `s'" error

The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g", containing way too many slashes.

Since sed can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:

replacement="/my/path"
sed --expression "s@pattern@$replacement@"

Note that this is not bullet proof: if the replacement string later contains @ it will break for the same reason, and any backslash sequences like \1 will still be interpreted according to sed rules. Using | as a delimiter is also a nice option as it is similar in readability to /.

How to convert date to string and to date again?

Use DateFormat#parse(String):

Date date = dateFormat.parse("2013-10-22");

Getting strings recognized as variable names in R

What works best for me is using quote() and eval() together.

For example, let's print each column using a for loop:

Columns <- names(dat)
for (i in 1:ncol(dat)){
  dat[, eval(quote(Columns[i]))] %>% print
}

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

import codecs
import shutil
import sys

s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
    sys.stdout.write(s)

shutil.copyfileobj(sys.stdin, sys.stdout)

The type WebMvcConfigurerAdapter is deprecated

I have been working on Swagger equivalent documentation library called Springfox nowadays and I found that in the Spring 5.0.8 (running at present), interface WebMvcConfigurer has been implemented by class WebMvcConfigurationSupport class which we can directly extend.

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

public class WebConfig extends WebMvcConfigurationSupport { }

And this is how I have used it for setting my resource handling mechanism as follows -

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

How to tackle daylight savings using TimeZone in Java

In java, DateFormatter by default uses DST,To avoid day Light saving (DST) you need to manually do a trick,
first you have to get the DST offset i.e. for how many millisecond DST applied, for ex somewhere DST is also for 45 minutes and for some places it is for 30 min
but in most cases DST is of 1 hour
you have to use Timezone object and check with the date whether it is falling under DST or not and then you have to manually add offset of DST into it. for eg:

 TimeZone tz = TimeZone.getTimeZone("EST");
 boolean isDST = tz.inDaylightTime(yourDateObj);
 if(isDST){
 int sec= tz.getDSTSavings()/1000;// for no. of seconds
 Calendar cal= Calendar.getInstance();
 cal.setTime(yourDateObj);
 cal.add(Calendar.Seconds,sec);
 System.out.println(cal.getTime());// your Date with DST neglected
  }

java.io.IOException: Broken pipe

The most common reason I've had for a "broken pipe" is that one machine (of a pair communicating via socket) has shut down its end of the socket before communication was complete. About half of those were because the program communicating on that socket had terminated.

If the program sending bytes sends them out and immediately shuts down the socket or terminates itself, it is possible for the socket to cease functioning before the bytes have been transmitted and read.

Try putting pauses anywhere you are shutting down the socket and before you allow the program to terminate to see if that helps.

FYI: "pipe" and "socket" are terms that get used interchangeably sometimes.

Server Discovery And Monitoring engine is deprecated

I want to add to this thread that it may also have to do with other dependencies.

For instance, nothing I updated or set for NodeJS, MongoDB or Mongoose were the issue - however - connect-mongodb-session had been updated and starting slinging the same error. The solution, in this case, was to simply rollback the version of connect-mongodb-session from version 2.3.0 to 2.2.0.

enter image description here

What is the best way to implement constants in Java?

The number one mistake you can make is creating a globally accessible class called with a generic name, like Constants. This simply gets littered with garbage and you lose all ability to figure out what portion of your system uses these constants.

Instead, constants should go into the class which "owns" them. Do you have a constant called TIMEOUT? It should probably go into your Communications() or Connection() class. MAX_BAD_LOGINS_PER_HOUR? Goes into User(). And so on and so forth.

The other possible use is Java .properties files when "constants" can be defined at run-time, but not easily user changeable. You can package these up in your .jars and reference them with the Class resourceLoader.