Programs & Examples On #Prediction

For questions related to statistical prediction, especially for programming tasks.

ValueError: Wrong number of items passed - Meaning and suggestions?

In general, the error ValueError: Wrong number of items passed 3, placement implies 1 suggests that you are attempting to put too many pigeons in too few pigeonholes. In this case, the value on the right of the equation

results['predictedY'] = predictedY

is trying to put 3 "things" into a container that allows only one. Because the left side is a dataframe column, and can accept multiple items on that (column) dimension, you should see that there are too many items on another dimension.

Here, it appears you are using sklearn for modeling, which is where gaussian_process.GaussianProcess() is coming from (I'm guessing, but correct me and revise the question if this is wrong).

Now, you generate predicted values for y here:

predictedY, MSE = gp.predict(testX, eval_MSE = True)

However, as we can see from the documentation for GaussianProcess, predict() returns two items. The first is y, which is array-like (emphasis mine). That means that it can have more than one dimension, or, to be concrete for thick headed people like me, it can have more than one column -- see that it can return (n_samples, n_targets) which, depending on testX, could be (1000, 3) (just to pick numbers). Thus, your predictedY might have 3 columns.

If so, when you try to put something with three "columns" into a single dataframe column, you are passing 3 items where only 1 would fit.

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

Despite the plethora of wrong answers here that attempt to circumvent the error by numerically manipulating the predictions, the root cause of your error is a theoretical and not computational issue: you are trying to use a classification metric (accuracy) in a regression (i.e. numeric prediction) model (LinearRegression), which is meaningless.

Just like the majority of performance metrics, accuracy compares apples to apples (i.e true labels of 0/1 with predictions again of 0/1); so, when you ask the function to compare binary true labels (apples) with continuous predictions (oranges), you get an expected error, where the message tells you exactly what the problem is from a computational point of view:

Classification metrics can't handle a mix of binary and continuous target

Despite that the message doesn't tell you directly that you are trying to compute a metric that is invalid for your problem (and we shouldn't actually expect it to go that far), it is certainly a good thing that scikit-learn at least gives you a direct and explicit warning that you are attempting something wrong; this is not necessarily the case with other frameworks - see for example the behavior of Keras in a very similar situation, where you get no warning at all, and one just ends up complaining for low "accuracy" in a regression setting...

I am super-surprised with all the other answers here (including the accepted & highly upvoted one) effectively suggesting to manipulate the predictions in order to simply get rid of the error; it's true that, once we end up with a set of numbers, we can certainly start mingling with them in various ways (rounding, thresholding etc) in order to make our code behave, but this of course does not mean that our numeric manipulations are meaningful in the specific context of the ML problem we are trying to solve.

So, to wrap up: the problem is that you are applying a metric (accuracy) that is inappropriate for your model (LinearRegression): if you are in a classification setting, you should change your model (e.g. use LogisticRegression instead); if you are in a regression (i.e. numeric prediction) setting, you should change the metric. Check the list of metrics available in scikit-learn, where you can confirm that accuracy is used only in classification.

Compare also the situation with a recent SO question, where the OP is trying to get the accuracy of a list of models:

models = []
models.append(('SVM', svm.SVC()))
models.append(('LR', LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
#models.append(('SGDRegressor', linear_model.SGDRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('BayesianRidge', linear_model.BayesianRidge())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('LassoLars', linear_model.LassoLars())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('ARDRegression', linear_model.ARDRegression())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('PassiveAggressiveRegressor', linear_model.PassiveAggressiveRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('TheilSenRegressor', linear_model.TheilSenRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('LinearRegression', linear_model.LinearRegression())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets

where the first 6 models work OK, while all the rest (commented-out) ones give the same error. By now, you should be able to convince yourself that all the commented-out models are regression (and not classification) ones, hence the justified error.

A last important note: it may sound legitimate for someone to claim:

OK, but I want to use linear regression and then just round/threshold the outputs, effectively treating the predictions as "probabilities" and thus converting the model into a classifier

Actually, this has already been suggested in several other answers here, implicitly or not; again, this is an invalid approach (and the fact that you have negative predictions should have already alerted you that they cannot be interpreted as probabilities). Andrew Ng, in his popular Machine Learning course at Coursera, explains why this is a bad idea - see his Lecture 6.1 - Logistic Regression | Classification at Youtube (explanation starts at ~ 3:00), as well as section 4.2 Why Not Linear Regression [for classification]? of the (highly recommended and freely available) textbook An Introduction to Statistical Learning by Hastie, Tibshirani and coworkers...

How do I set browser width and height in Selenium WebDriver?

It's easy. Here is the full code.

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("Your URL")
driver.set_window_size(480, 320)

Make sure chrome driver is in your system path.

Download Excel file via AJAX MVC

I may sound quite naive, and may attract quite a criticism, but here's how I did it,
(It doesn't involve ajax for export, but it doesn't do a full postback either )

Thanks for this post and this answer.
Create a simple controller

public class HomeController : Controller
{               
   /* A demo action
    public ActionResult Index()
    {           
        return View(model);
    }
   */
    [HttpPost]
    public FileResult ExportData()
    {
        /* An example filter
        var filter = TempData["filterKeys"] as MyFilter;
        TempData.Keep();            */
        var someList = db.GetDataFromDb(/*filter*/) // filter as an example

    /*May be here's the trick, I'm setting my filter in TempData["filterKeys"] 
     in an action,(GetFilteredPartial() illustrated below) when 'searching' for the data,
     so do not really need ajax here..to pass my filters.. */

     //Some utility to convert list to Datatable
     var dt = Utility.ConvertToDataTable(someList); 

      //  I am using EPPlus nuget package 
      using (ExcelPackage pck = new ExcelPackage())
      {
          ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
          ws.Cells["A1"].LoadFromDataTable(dt, true);

            using (var memoryStream = new MemoryStream())
            {                   
              pck.SaveAs(memoryStream);
              return File(memoryStream.ToArray(),
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              "ExportFileName.xlsx");                    
            }                
        }   
    }

    //This is just a supporting example to illustrate setting up filters ..        
   /* [HttpPost]
    public PartialViewResult GetFilteredPartial(MyFilter filter)
    {            
        TempData["filterKeys"] = filter;
        var filteredData = db.GetConcernedData(filter);
        var model = new MainViewModel();
        model.PartialViewModel = filteredData;

        return PartialView("_SomePartialView", model);
    } */     
} 

And here are the Views..

/*Commenting out the View code, in order to focus on the imp. code     
 @model Models.MainViewModel
 @{Layout...}     

      Some code for, say, a partial View  
      <div id="tblSampleBody">
        @Html.Partial("_SomePartialView", Model.PartialViewModel)
      </div>
  */                                                       
//The actual part.. Just **posting** this bit of data from the complete View...
//Here, you are not posting the full Form..or the complete View
   @using (Html.BeginForm("ExportData", "Home", FormMethod.Post))
    {
        <input type="submit" value="Export Data" />
    }
//...
//</div>

/*And you may require to pass search/filter values.. as said in the accepted answer..
That can be done while 'searching' the data.. and not while
 we need an export..for instance:-             

<script>             
  var filterData = {
      SkipCount: someValue,
      TakeCount: 20,
      UserName: $("#UserName").val(),
      DepartmentId: $("#DepartmentId").val(),     
   }

  function GetFilteredData() {
       $("#loader").show();
       filterData.SkipCount = 0;
       $.ajax({
          url: '@Url.Action("GetFilteredPartial","Home")',
          type: 'POST',
          dataType: "html",
          data: filterData,
          success: function (dataHTML) {
          if ((dataHTML === null) || (dataHTML == "")) {
              $("#tblSampleBody").html('<tr><td>No Data Returned</td></tr>');
                $("#loader").hide();
            } else {
                $("#tblSampleBody").html(dataHTML);                    
                $("#loader").hide();
            }
        }
     });
   }    
</script>*/

The whole point of the trick seems that, we are posting a form (a part of the Razor View ) upon which we are calling an Action method, which returns: a FileResult, and this FileResult returns the Excel File..
And for posting the filter values, as said, ( and if you require to), I am making a post request to another action, as has been attempted to describe..

Print raw string from variable? (not getting the answers)

You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');

Best way to store time (hh:mm) in a database

Store the ticks as a long/bigint, which are currently measured in milliseconds. The updated value can be found by looking at the TimeSpan.TicksPerSecond value.

Most databases have a DateTime type that automatically stores the time as ticks behind the scenes, but in the case of some databases e.g. SqlLite, storing ticks can be a way to store the date.

Most languages allow the easy conversion from Ticks ? TimeSpan ? Ticks.

Example

In C# the code would be:

long TimeAsTicks = TimeAsTimeSpan.Ticks;

TimeAsTimeSpan = TimeSpan.FromTicks(TimeAsTicks);

Be aware though, because in the case of SqlLite, which only offers a small number of different types, which are; INT, REAL and VARCHAR It will be necessary to store the number of ticks as a string or two INT cells combined. This is, because an INT is a 32bit signed number whereas BIGINT is a 64bit signed number.

Note

My personal preference however, would be to store the date and time as an ISO8601 string.

Angular.js: set element height on page load

To avoid check on every digest cycle, we can change the height of the div when the window height gets changed.

http://jsfiddle.net/zbjLh/709/

<div ng-app="miniapp" resize>
  Testing
</div>

.

var app = angular.module('miniapp', []);

app.directive('resize', function ($window) {
    return function (scope, element) {
        var w = angular.element($window);
        var changeHeight = function() {element.css('height', (w.height() -20) + 'px' );};  
            w.bind('resize', function () {        
              changeHeight();   // when window size gets changed             
        });  
        changeHeight(); // when page loads          
    }
})

How to convert Double to int directly?

double myDb = 12.3;
int myInt = (int) myDb;

Result is: myInt = 12

Print array without brackets and commas

Replace the brackets and commas with empty space.

String formattedString = myArrayList.toString()
    .replace(",", "")  //remove the commas
    .replace("[", "")  //remove the right bracket
    .replace("]", "")  //remove the left bracket
    .trim();           //remove trailing spaces from partially initialized arrays

Java Loop every minute

ScheduledExecutorService

The Answer by Lee is close, but only runs once. The Question seems to be asking to run indefinitely until an external state changes (until the response from a web site/service changes).

The ScheduledExecutorService interface is part of the java.util.concurrent package built into Java 5 and later as a more modern replacement for the old Timer class.

Here is a complete example. Call either scheduleAtFixedRate or scheduleWithFixedDelay.

ScheduledExecutorService executor = Executors.newScheduledThreadPool ( 1 );

Runnable r = new Runnable () {
    @Override
    public void run () {
        try {  // Always wrap your Runnable with a try-catch as any uncaught Exception causes the ScheduledExecutorService to silently terminate.
            System.out.println ( "Now: " + Instant.now () );  // Our task at hand in this example: Capturing the current moment in UTC.
            if ( Boolean.FALSE ) {  // Add your Boolean test here to see if the external task is fonud to be completed, as described in this Question.
                executor.shutdown ();  // 'shutdown' politely asks ScheduledExecutorService to terminate after previously submitted tasks are executed.
            }

        } catch ( Exception e ) {
            System.out.println ( "Oops, uncaught Exception surfaced at Runnable in ScheduledExecutorService." );
        }
    }
};

try {
    executor.scheduleAtFixedRate ( r , 0L , 5L , TimeUnit.SECONDS ); // ( runnable , initialDelay , period , TimeUnit )
    Thread.sleep ( TimeUnit.MINUTES.toMillis ( 1L ) ); // Let things run a minute to witness the background thread working.
} catch ( InterruptedException ex ) {
    Logger.getLogger ( App.class.getName () ).log ( Level.SEVERE , null , ex );
} finally {
    System.out.println ( "ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed." );
    executor.shutdown ();
}

Expect output like this:

Now: 2016-12-27T02:52:14.951Z
Now: 2016-12-27T02:52:19.955Z
Now: 2016-12-27T02:52:24.951Z
Now: 2016-12-27T02:52:29.951Z
Now: 2016-12-27T02:52:34.953Z
Now: 2016-12-27T02:52:39.952Z
Now: 2016-12-27T02:52:44.951Z
Now: 2016-12-27T02:52:49.953Z
Now: 2016-12-27T02:52:54.953Z
Now: 2016-12-27T02:52:59.951Z
Now: 2016-12-27T02:53:04.952Z
Now: 2016-12-27T02:53:09.951Z
ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed.
Now: 2016-12-27T02:53:14.951Z

jQuery find file extension (from string)

You can use a combination of substring and lastIndexOf

Sample

var fileName = "test.jpg";
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1); 

Detecting scroll direction

I personally use this code to detect scroll direction in javascript... Just you have to define a variable to store lastscrollvalue and then use this if&else

let lastscrollvalue;

function headeronscroll() {

    // document on which scroll event will occur
    var a = document.querySelector('.refcontainer'); 

    if (lastscrollvalue == undefined) {

        lastscrollvalue = a.scrollTop;

        // sets lastscrollvalue
    } else if (a.scrollTop > lastscrollvalue) {

        // downscroll rules will be here
        lastscrollvalue = a.scrollTop;

    } else if (a.scrollTop < lastscrollvalue) {

        // upscroll rules will be here
        lastscrollvalue = a.scrollTop;

    }
}

How to unpublish an app in Google Play Developer Console

To unpublish your app on the Google Play store:

  1. Go to https://market.android.com/publish/Home, and log in to your Google Play account.
  2. Click on the application you want to delete.
  3. Click on the Store Presence menu, and click the “Pricing and Distribution” item.
  4. Click Unpublish

How to get selected option using Selenium WebDriver with Java

On the following option:

WebElement option = select.getFirstSelectedOption();
option.getText();

If from the method getText() you get a blank, you can get the string from the value of the option using the method getAttribute:

WebElement option = select.getFirstSelectedOption();
option.getAttribute("value");

Reading output of a command into an array in Bash

You can use

my_array=( $(<command>) )

to store the output of command <command> into the array my_array.

You can access the length of that array using

my_array_length=${#my_array[@]}

Now the length is stored in my_array_length.

How to implode array with key and value without foreach in PHP

You could use http_build_query, like this:

<?php
  $a=array("item1"=>"object1", "item2"=>"object2");
  echo http_build_query($a,'',', ');
?>

Output:

item1=object1, item2=object2 

Demo

Explicitly select items from a list or tuple

>>> map(myList.__getitem__, (2,2,1,3))
('baz', 'baz', 'bar', 'quux')

You can also create your own List class which supports tuples as arguments to __getitem__ if you want to be able to do myList[(2,2,1,3)].

What's the best way to validate an XML file against an XSD file?

The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a javax.xml.validation.Validator.

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import java.net.URL;
import org.xml.sax.SAXException;
//import java.io.File; // if you use File
import java.io.IOException;
...
URL schemaFile = new URL("http://host:port/filename.xsd");
// webapp example xsd: 
// URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
// local file example:
// File schemaFile = new File("/location/to/localfile.xsd"); // etc.
Source xmlFile = new StreamSource(new File("web.xml"));
SchemaFactory schemaFactory = SchemaFactory
    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
  Schema schema = schemaFactory.newSchema(schemaFile);
  Validator validator = schema.newValidator();
  validator.validate(xmlFile);
  System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
  System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
} catch (IOException e) {}

The schema factory constant is the string http://www.w3.org/2001/XMLSchema which defines XSDs. The above code validates a WAR deployment descriptor against the URL http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd but you could just as easily validate against a local file.

You should not use the DOMParser to validate a document (unless your goal is to create a document object model anyway). This will start creating DOM objects as it parses the document - wasteful if you aren't going to use them.

Extension mysqli is missing, phpmyadmin doesn't work

If you run PHPMyAdmin on localhost uncomment in file /etc/php5/apache2/php.ini this line:

mysqli.allow_local_infile = On

Restart Apache:

sudo /etc/init.d/apache2 restart

A generic error occurred in GDI+, JPEG Image to MemoryStream

OK I seem to have found the cause just by sheer luck and its nothing wrong with that particular method, it's further back up the call stack.

Earlier I resize the image and as part of that method I return the resized object as follows. I have inserted two calls to the above method and a direct save to a file.

// At this point the new bitmap has no MimeType
// Need to output to memory stream
using (var m = new MemoryStream())
{
       dst.Save(m, format);

       var img = Image.FromStream(m);

       //TEST
       img.Save("C:\\test.jpg");
       var bytes = PhotoEditor.ConvertImageToByteArray(img);


       return img;
 }

It appears that the memory stream that the object was created on has to be open at the time the object is saved. I am not sure why this is. Is anyone able to enlighten me and how I can get around this.

I only return from a stream because after using the resize code similar to this the destination file has an unknown mime type (img.RawFormat.Guid) and Id like the Mime type to be correct on all image objects as it makes it hard write generic handling code otherwise.

EDIT

This didn't come up in my initial search but here's the answer from Jon Skeet

remove duplicates from sql union

Using UNION automatically removes duplicate rows unless you specify UNION ALL: http://msdn.microsoft.com/en-us/library/ms180026(SQL.90).aspx

How to filter JSON Data in JavaScript or jQuery?

The values can be retrieved during the parsing:

_x000D_
_x000D_
var yahoo = [], j = `[{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]`_x000D_
_x000D_
var data = JSON.parse(j, function(key, value) { _x000D_
      if ( value.website === "yahoo" ) yahoo.push(value); _x000D_
      return value; })_x000D_
_x000D_
console.log( yahoo )
_x000D_
_x000D_
_x000D_

Rails: Check output of path helper from console

You can show them with rake routes directly.

In a Rails console, you can call app.post_path. This will work in Rails ~= 2.3 and >= 3.1.0.

How do I see what character set a MySQL database / table / column is?

To see default collation of the database:

USE db_name;
SELECT @@character_set_database, @@collation_database;

To see collation of the table:

SHOW TABLE STATUS where name like 'table_name';

To see collation of the columns:

SHOW FULL COLUMNS FROM table_name;

To see the default character set of a table

SHOW CREATE TABLE table_name;

Input and Output binary streams using JERSEY?

Using Jersey 2.16 File download is very easy.

Below is the example for the ZIP file

@GET
@Path("zipFile")
@Produces("application/zip")
public Response getFile() {
    File f = new File(ZIP_FILE_PATH);

    if (!f.exists()) {
        throw new WebApplicationException(404);
    }

    return Response.ok(f)
            .header("Content-Disposition",
                    "attachment; filename=server.zip").build();
}

R: Print list to a text file

Format won't be completely the same, but it does write the data to a text file, and R will be able to reread it using dget when you want to retrieve it again as a list.

dput(mylist, "mylist.txt")

Logical XOR operator in C++?

(A || B) && !(A && B)

The first part is A OR B, which is the Inclusive OR; the second part is, NOT A AND B. Together you get A or B, but not both A and B.

This will provide the XOR proved in the truth table below.

|-----|-----|-----------|
|  A  |  B  |  A XOR B  |
|-----|-----|-----------|
|  T  |  T  |   False   |
|-----|-----|-----------|
|  T  |  F  |   True    |
|-----|-----|-----------|
|  F  |  T  |   True    |
|-----|-----|-----------|
|  F  |  F  |   False   |
|-----|-----|-----------|

How can I get dictionary key as variable directly in Python (not by searching from value)?

You could simply use * which unpacks the dictionary keys. Example:

d = {'x': 1, 'y': 2}
t = (*d,)
print(t) # ('x', 'y')

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid

I had this error with Visual Studion 2019, my project was NopCommerce 4.30 which is an ASP.Net Core 3.1 project. I added page "gouden-munten-buitenland" to be the starting page and I only got the error when going to that page. Turned out that Visual Studio generated an invalid applicationHost.config :

<applicationPools>
    ....
    <add name="gouden-munten-buitenland AppPool" autoStart="true" />
    <add name="gouden-munten-buitenland AppPool 2" autoStart="true" /> <!-- WRONG -->
    <add name="Nop.Web AppPool" managedRuntimeVersion="" />
    <applicationPoolDefaults managedRuntimeVersion="v4.0">
    <processModel loadUserProfile="true" setProfileEnvironment="false" />
    </applicationPoolDefaults>
</applicationPools>

and

<sites>
    ....
    <site name="Nop.Web" id="2">
    ...
    <application path="/gouden-munten-buitenland/gouden-munten-buitenland" applicationPool="gouden-munten-buitenland AppPool">
        <virtualDirectory path="/" physicalPath="C:\Usr\Stephan\Wrk\Kevelam\kNop.430\Presentation\Nop.Web" />
    </application>
    <application path="/gouden-munten-buitenland" applicationPool="gouden-munten-buitenland AppPool 2">
        <virtualDirectory path="/" physicalPath="C:\Usr\Stephan\Wrk\Kevelam\kNop.430\Presentation\Nop.Web" />
    </application> <!-- WRONG -->
    ....
    </site>
    ...
</sites>

I removed the nodes identified as 'WRONG' and then it worked.

How do I make Git ignore file mode (chmod) changes?

If you want to set filemode to false in config files recursively (including submodules) : find -name config | xargs sed -i -e 's/filemode = true/filemode = false/'

Why fragments, and when to use fragments instead of activities?

Activities are the full screen components in the app with the toolbar, everything else are preferably Fragments. One full screen parent activity with a toolbar can have multiple panes, scrollable pages, dialogs, etc. (all fragments), all of which can be accessed from the parent and communicate via the parent.

Example:

Activity A, Activity B, Activity C:

  • All activities need to have same code repeated, to show a basic toolbar for example, or inherit from a parent activity (becomes cumbersome to manage).
  • To move from one activity to the other, either all of them need to be in memory (overhead) or one needs to be destroyed for the other to open.
  • Communication between activities can be done via Intents.

vs

Activity A, Fragment 1, Fragment 2, Fragment 3:

  • No code repetition, all screens have toolbars etc. from that one activity.
  • Several ways to move from one fragment to next - view pager, multi pane etc.
  • Activity has most data, so minimal inter-fragment communication needed. If still necessary, can be done via interfaces easily.
  • Fragments do not need to be full screen, lots of flexibility in designing them.
  • Fragments do not need to inflate layout if views are not necessary.
  • Several activities can use the same fragment.

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Running AngularJS initialization code when view is loaded

Since AngularJS 1.5 we should use $onInit which is available on any AngularJS component. Taken from the component lifecycle documentation since v1.5 its the preffered way:

$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {

    //default state
    $scope.name = '';

    //all your init controller goodness in here
    this.$onInit = function () {
      $scope.name = 'Superhero';
    }
});

>> Fiddle Demo


An advanced example of using component lifecycle:

The component lifecycle gives us the ability to handle component stuff in a good way. It allows us to create events for e.g. "init", "change" or "destroy" of an component. In that way we are able to manage stuff which is depending on the lifecycle of an component. This little example shows to register & unregister an $rootScope event listener $on. By knowing, that an event $on binded on $rootScope will not be undinded when the controller loses its reference in the view or getting destroyed we need to destroy a $rootScope.$on listener manually. A good place to put that stuff is $onDestroy lifecycle function of an component:

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope, $rootScope) {

  var registerScope = null;

  this.$onInit = function () {
    //register rootScope event
    registerScope = $rootScope.$on('someEvent', function(event) {
        console.log("fired");
    });
  }

  this.$onDestroy = function () {
    //unregister rootScope event by calling the return function
    registerScope();
  }
});

>> Fiddle demo

How to copy and paste code without rich text formatting?

I wrote an unpublished java app to monitor the clipboard, replacing items that offered text along with other richer formats, with items only offering the plain text format.

How to parse data in JSON format?

Following is simple example that may help you:

json_string = """
{
    "pk": 1, 
    "fa": "cc.ee", 
    "fb": {
        "fc": "", 
        "fd_id": "12345"
    }
}"""

import json
data = json.loads(json_string)
if data["fa"] == "cc.ee":
    data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)

The output for the above code will be:

{"pk": 1, "fb": {"new_key": "cc.ee was present!", "fd_id": "12345", 
 "fc": ""}, "fa": "cc.ee"}

Note that you can set the ident argument of dump to print it like so (for example,when using print json.dumps(data , indent=4)):

{
    "pk": 1, 
    "fb": {
        "new_key": "cc.ee was present!", 
        "fd_id": "12345", 
        "fc": ""
    }, 
    "fa": "cc.ee"
}

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

SQL QUERY replace NULL value in a row with a value from the previous known value

UPDATE TABLE
   SET number = (SELECT MAX(t.number)
                  FROM TABLE t
                 WHERE t.number IS NOT NULL
                   AND t.date < date)
 WHERE number IS NULL

Hibernate, @SequenceGenerator and allocationSize

I too faced this issue in Hibernate 5:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE)
@SequenceGenerator(name = SEQUENCE, sequenceName = SEQUENCE)
private Long titId;

Got a warning like this below:

Found use of deprecated [org.hibernate.id.SequenceHiLoGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead. See Hibernate Domain Model Mapping Guide for details.

Then changed my code to SequenceStyleGenerator:

@Id
@GenericGenerator(name="cmrSeq", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @Parameter(name = "sequence_name", value = "SEQUENCE")}
)
@GeneratedValue(generator = "sequence_name")
private Long titId;

This solved my two issues:

  1. The deprecated warning is fixed
  2. Now the id is generated as per the oracle sequence.

How to secure phpMyAdmin

In newer versions of phpMyAdmin access permissions for user-names + ip-addresses can be set up inside the phpMyAdmin's config.inc.php file. This is a much better and more robust method of restricting access (over hard-coding URLs and IP addresses into Apache's httpd.conf).

Here is a full example of how to switch to white-listing all users (no one outside this list will be allowed access), and also how to restrict user root to the local system and network only.

$cfg['Servers'][$i]['AllowDeny']['order'] = 'deny,allow';
$cfg['Servers'][$i]['AllowDeny']['rules'] = array(
    'deny % from all', // deny everyone by default, then -

    'allow % from 127.0.0.1', // allow all local users
    'allow % from ::1',

    //'allow % from SERVER_ADDRESS', // allow all from server IP

    // allow user:root access from these locations (local network)
    'allow root from localhost',
    'allow root from 127.0.0.1',
    'allow root from 10.0.0.0/8',
    'allow root from 172.16.0.0/12',
    'allow root from 192.168.0.0/16',

    'allow root from ::1',

    // add more usernames and their IP (or IP ranges) here -    
    );

Source: How to Install and Secure phpMyAdmin on localhost for Windows

This gives you much more fine-grained access restrictions than Apache's URL permissions or an .htaccess file can provide, at the MySQL user name level.

Make sure that the user you are login in with, has its MySQL Host: field set to 127.0.0.1 or ::1, as phpMyAdmin and MySQL are on the same system.

How to open .SQLite files

If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:

sqlite3 database.sqlite

Replace database.sqlite with your database file. Then, if the database is small enough, you can view the entire contents with:

sqlite> .dump

Or you can list the tables:

sqlite> .tables

Regular SQL works here as well:

sqlite> select * from some_table;

Replace some_table as appropriate.

How can I get the content of CKEditor using JQuery?

version 4.6

CKEDITOR.instances.editor.getData()

Google Maps API OVER QUERY LIMIT per second limit


This approach is not correct beacuse of Google Server Overload. For more informations see https://gis.stackexchange.com/questions/15052/how-to-avoid-google-map-geocode-limit#answer-15365


By the way, if you wish to proceed anyway, here you can find a code that let you load multiple markers ajax sourced on google maps avoiding OVER_QUERY_LIMIT error.

I've tested on my onw server and it works!:

var lost_addresses = [];
    geocode_count  = 0;
    resNumber = 0;
    map = new GMaps({
       div: '#gmap_marker',
       lat: 43.921493,
       lng: 12.337646,
    });

function loadMarkerTimeout(timeout) {
    setTimeout(loadMarker, timeout)
}

function loadMarker() { 
    map.setZoom(6);         
    $.ajax({
            url: [Insert here your URL] ,
            type:'POST',
            data: {
                "action":   "loadMarker"
            },
            success:function(result){

                /***************************
                 * Assuming your ajax call
                 * return something like: 
                 *   array(
                 *      'status' => 'success',
                 *      'results'=> $resultsArray
                 *   );
                 **************************/

                var res=JSON.parse(result);
                if(res.status == 'success') {
                    resNumber = res.results.length;
                    //Call the geoCoder function
                    getGeoCodeFor(map, res.results);
                }
            }//success
    });//ajax
};//loadMarker()

$().ready(function(e) {
  loadMarker();
});

//Geocoder function
function getGeoCodeFor(maps, addresses) {
        $.each(addresses, function(i,e){                
                GMaps.geocode({
                    address: e.address,
                    callback: function(results, status) {
                            geocode_count++;        

                            if (status == 'OK') {       

                                //if the element is alreay in the array, remove it
                                lost_addresses = jQuery.grep(lost_addresses, function(value) {
                                    return value != e;
                                });


                                latlng = results[0].geometry.location;
                                map.addMarker({
                                        lat: latlng.lat(),
                                        lng: latlng.lng(),
                                        title: 'MyNewMarker',
                                    });//addMarker
                            } else if (status == 'ZERO_RESULTS') {
                                //alert('Sorry, no results found');
                            } else if(status == 'OVER_QUERY_LIMIT') {

                                //if the element is not in the losts_addresses array, add it! 
                                if( jQuery.inArray(e,lost_addresses) == -1) {
                                    lost_addresses.push(e);
                                }

                            } 

                            if(geocode_count == addresses.length) {
                                //set counter == 0 so it wont's stop next round
                                geocode_count = 0;

                                setTimeout(function() {
                                    getGeoCodeFor(maps, lost_addresses);
                                }, 2500);
                            }
                    }//callback
                });//GeoCode
        });//each
};//getGeoCodeFor()

Example:

_x000D_
_x000D_
map = new GMaps({_x000D_
  div: '#gmap_marker',_x000D_
  lat: 43.921493,_x000D_
  lng: 12.337646,_x000D_
});_x000D_
_x000D_
var jsonData = {  _x000D_
   "status":"success",_x000D_
   "results":[  _x000D_
  {  _x000D_
     "customerId":1,_x000D_
     "address":"Via Italia 43, Milano (MI)",_x000D_
     "customerName":"MyAwesomeCustomer1"_x000D_
  },_x000D_
  {  _x000D_
     "customerId":2,_x000D_
     "address":"Via Roma 10, Roma (RM)",_x000D_
     "customerName":"MyAwesomeCustomer2"_x000D_
  }_x000D_
   ]_x000D_
};_x000D_
   _x000D_
function loadMarkerTimeout(timeout) {_x000D_
  setTimeout(loadMarker, timeout)_x000D_
}_x000D_
_x000D_
function loadMarker() { _x000D_
  map.setZoom(6);_x000D_
 _x000D_
  $.ajax({_x000D_
    url: '/echo/html/',_x000D_
    type: "POST",_x000D_
    data: jsonData,_x000D_
    cache: false,_x000D_
    success:function(result){_x000D_
_x000D_
      var res=JSON.parse(result);_x000D_
      if(res.status == 'success') {_x000D_
        resNumber = res.results.length;_x000D_
        //Call the geoCoder function_x000D_
        getGeoCodeFor(map, res.results);_x000D_
      }_x000D_
    }//success_x000D_
  });//ajax_x000D_
  _x000D_
};//loadMarker()_x000D_
_x000D_
$().ready(function(e) {_x000D_
  loadMarker();_x000D_
});_x000D_
_x000D_
//Geocoder function_x000D_
function getGeoCodeFor(maps, addresses) {_x000D_
  $.each(addresses, function(i,e){    _x000D_
    GMaps.geocode({_x000D_
      address: e.address,_x000D_
      callback: function(results, status) {_x000D_
        geocode_count++;  _x000D_
        _x000D_
        console.log('Id: '+e.customerId+' | Status: '+status);_x000D_
        _x000D_
        if (status == 'OK') {  _x000D_
_x000D_
          //if the element is alreay in the array, remove it_x000D_
          lost_addresses = jQuery.grep(lost_addresses, function(value) {_x000D_
            return value != e;_x000D_
          });_x000D_
_x000D_
_x000D_
          latlng = results[0].geometry.location;_x000D_
          map.addMarker({_x000D_
            lat: latlng.lat(),_x000D_
            lng: latlng.lng(),_x000D_
            title: e.customerName,_x000D_
          });//addMarker_x000D_
        } else if (status == 'ZERO_RESULTS') {_x000D_
          //alert('Sorry, no results found');_x000D_
        } else if(status == 'OVER_QUERY_LIMIT') {_x000D_
_x000D_
          //if the element is not in the losts_addresses array, add it! _x000D_
          if( jQuery.inArray(e,lost_addresses) == -1) {_x000D_
            lost_addresses.push(e);_x000D_
          }_x000D_
_x000D_
        } _x000D_
_x000D_
        if(geocode_count == addresses.length) {_x000D_
          //set counter == 0 so it wont's stop next round_x000D_
          geocode_count = 0;_x000D_
_x000D_
          setTimeout(function() {_x000D_
            getGeoCodeFor(maps, lost_addresses);_x000D_
          }, 2500);_x000D_
        }_x000D_
      }//callback_x000D_
    });//GeoCode_x000D_
  });//each_x000D_
};//getGeoCodeFor()
_x000D_
#gmap_marker {_x000D_
  min-height:250px;_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
  position: relative; _x000D_
  overflow: hidden;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.24/gmaps.min.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
<div id="gmap_marker"></div> <!-- /#gmap_marker -->
_x000D_
_x000D_
_x000D_

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

How do I use Ruby for shell scripting?

As the others have said already, your first line should be

#!/usr/bin/env ruby

And you also have to make it executable: (in the shell)

chmod +x test.rb

Then follows the ruby code. If you open a file

File.open("file", "r") do |io|
    # do something with io
end

the file is opened in the current directory you'd get with pwd in the shell.

The path to your script is also simple to get. With $0 you get the first argument of the shell, which is the relative path to your script. The absolute path can be determined like that:

#!/usr/bin/env ruby
require 'pathname'
p Pathname.new($0).realpath()

For file system operations I almost always use Pathname. This is a wrapper for many of the other file system related classes. Also useful: Dir, File...

Moving x-axis to the top of a plot in matplotlib

You've got to do some extra massaging if you want the ticks (not labels) to show up on the top and bottom (not just the top). The only way I could do this is with a minor change to unutbu's code:

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
ax.xaxis.set_ticks_position('both') # THIS IS THE ONLY CHANGE

ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()

Output:

enter image description here

Declaring variables inside loops, good practice or bad practice?

Chapter 4.8 Block Structure in K&R's The C Programming Language 2.Ed.:

An automatic variable declared and initialized in a block is initialized each time the block is entered.

I might have missed seeing the relevant description in the book like:

An automatic variable declared and initialized in a block is allocated only one time before the block is entered.

But a simple test can prove the assumption held:

 #include <stdio.h>                                                                                                    

 int main(int argc, char *argv[]) {                                                                                    
     for (int i = 0; i < 2; i++) {                                                                                     
         for (int j = 0; j < 2; j++) {                                                                                 
             int k;                                                                                                    
             printf("%p\n", &k);                                                                                       
         }                                                                                                             
     }                                                                                                                 
     return 0;                                                                                                         
 }                                                                                                                     

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

It's the index column, pass pd.to_csv(..., index=False) to not write out an unnamed index column in the first place, see the to_csv() docs.

Example:

In [37]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
pd.read_csv(io.StringIO(df.to_csv()))

Out[37]:
   Unnamed: 0         a         b         c
0           0  0.109066 -1.112704 -0.545209
1           1  0.447114  1.525341  0.317252
2           2  0.507495  0.137863  0.886283
3           3  1.452867  1.888363  1.168101
4           4  0.901371 -0.704805  0.088335

compare with:

In [38]:
pd.read_csv(io.StringIO(df.to_csv(index=False)))

Out[38]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

You could also optionally tell read_csv that the first column is the index column by passing index_col=0:

In [40]:
pd.read_csv(io.StringIO(df.to_csv()), index_col=0)

Out[40]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

On delete cascade with doctrine2

Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.

CREATE TABLE contacts
 (contact_id BIGINT AUTO_INCREMENT NOT NULL,
 name VARCHAR(75) NOT NULL,
 PRIMARY KEY(contact_id)) ENGINE = InnoDB;

CREATE TABLE phone_numbers
 (phone_id BIGINT AUTO_INCREMENT NOT NULL,
  phone_number CHAR(10) NOT NULL,
 contact_id BIGINT NOT NULL,
 PRIMARY KEY(phone_id),
 UNIQUE(phone_number)) ENGINE = InnoDB;

ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;

By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.

INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);

Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.

DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */

To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.

<?php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="contacts")
 */
class Contact 
{

    /**
     *  @Id
     *  @Column(type="integer", name="contact_id") 
     *  @GeneratedValue
     */
    protected $id;  

    /** 
     * @Column(type="string", length="75", unique="true") 
     */ 
    protected $name; 

    /** 
     * @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
     */ 
    protected $phonenumbers; 

    public function __construct($name=null)
    {
        $this->phonenumbers = new ArrayCollection();

        if (!is_null($name)) {

            $this->name = $name;
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function addPhonenumber(Phonenumber $p)
    {
        if (!$this->phonenumbers->contains($p)) {

            $this->phonenumbers[] = $p;
            $p->setContact($this);
        }
    }

    public function removePhonenumber(Phonenumber $p)
    {
        $this->phonenumbers->remove($p);
    }
}

<?php
namespace Entities;

/**
 * @Entity
 * @Table(name="phonenumbers")
 */
class Phonenumber 
{

    /**
    * @Id
    * @Column(type="integer", name="phone_id") 
    * @GeneratedValue
    */
    protected $id; 

    /**
     * @Column(type="string", length="10", unique="true") 
     */  
    protected $number;

    /** 
     * @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
     * @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
     */ 
    protected $contact; 

    public function __construct($number=null)
    {
        if (!is_null($number)) {

            $this->number = $number;
        }
    }

    public function setPhonenumber($number)
    {
        $this->number = $number;
    }

    public function setContact(Contact $c)
    {
        $this->contact = $c;
    }
} 
?>

<?php

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

$contact = new Contact("John Doe"); 

$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1); 
$contact->addPhonenumber($phone2); 

$em->persist($contact);
try {

    $em->flush();
} catch(Exception $e) {

    $m = $e->getMessage();
    echo $m . "<br />\n";
}

If you now do

# doctrine orm:schema-tool:create --dump-sql

you will see that the same SQL will be generated as in the first, raw-SQL example

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

make sure your user has attributes on its role. for example:

postgres=# \du
                             List of roles
 Role name |                   Attributes                   | Member of 
-----------+------------------------------------------------+-----------
 flux      |                                                | {}
 postgres  | Superuser, Create role, Create DB, Replication | {}

after performing the following command:

postgres=# ALTER ROLE flux WITH Superuser;
ALTER ROLE
postgres=# \du
                             List of roles
 Role name |                   Attributes                   | Member of 
-----------+------------------------------------------------+-----------
 flux      | Superuser                                      | {}
postgres  | Superuser, Create role, Create DB, Replication | {}

it fixed the problem.

see tutorial for roles and stuff here: https://www.digitalocean.com/community/tutorials/how-to-use-roles-and-manage-grant-permissions-in-postgresql-on-a-vps--2

How can I uninstall Ruby on ubuntu?

Uninstall the make install software when make uninstall invalid.

  • make install will create file '.installed.list'
  • Choose to clean up the files described in .installed.list (need to be careful if you have multiple versions)
  • Case: ruby2.4 switch to ruby2.3, thinking directly delete all ruby software, and then re-make install 2.3, see: Ruby # Installation Guide
  • make install -> .installed.list
  • see .installed.list file, delete all install files.

rm -rf /usr/local/include/ruby-*
rm -rf /usr/local/lib/ruby
rm /usr/local/bin/erb /usr/local/bin/gem /usr/local/bin/irb /usr/local/bin/rdoc /usr/local/bin/ri /usr/local/bin/ruby
rm /usr/local/share/man/man1/erb.1 /usr/local/share/man/man1/irb.1 /usr/local/share/man/man1/ri.1 /usr/local/share/man/man1/ruby.1
rm /usr/local/lib/libruby-static.a
rm -rf /usr/local/lib/pkgconfig/ruby-*
which ruby
pkg-config --list-all|grep ruby

OperationalError: database is locked

In my case, I added a new record manually saved and again through shell tried to add new record this time it works perfectly check it out.

In [7]: from main.models import Flight

In [8]: f = Flight(origin="Florida", destination="Alaska", duration=10)

In [9]: f.save()

In [10]: Flight.objects.all() 
Out[10]: <QuerySet [<Flight: Flight object (1)>, <Flight: Flight object (2)>, <Flight: Flight object (3)>, <Flight: Flight object (4)>]>

What's the fastest way to loop through an array in JavaScript?

"Best" as in pure performance? or performance AND readability?

Pure performance "best" is this, which uses a cache and the ++prefix operator (my data: http://jsperf.com/caching-array-length/189)

for (var i = 0, len = myArray.length; i < len; ++i) {
  // blah blah
}

I would argue that the cache-less for-loop is the best balance in execution time and programmer reading time. Every programmer that started with C/C++/Java won't waste a ms having to read through this one

for(var i=0; i < arr.length; i++){
  // blah blah
}

How to make --no-ri --no-rdoc the default for gem install?

# /home/{user}/.gemrc

---
:update_sources: true
:sources:
- http://gems.rubyforge.org/
- http://gems.github.com
:benchmark: false
:bulk_threshold: 1000
:backtrace: false
:verbose: true
gem: --no-ri --no-rdoc

http://webonrails.com/2008/12/03/skiping-installation-of-ri-and-rdoc-documentation-while-installing-gems/

Create a button with rounded border

new OutlineButton(  
 child: new Text("blue outline") ,
   borderSide: BorderSide(color: Colors.blue),
  ),

// this property adds outline border color

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

typedef fixed length array

From R..'s answer:

However, this is probably a very bad idea, because the resulting type is an array type, but users of it won't see that it's an array type. If used as a function argument, it will be passed by reference, not by value, and the sizeof for it will then be wrong.

Users who don't see that it's an array will most likely write something like this (which fails):

#include <stdio.h>

typedef int twoInts[2];

void print(twoInts *twoIntsPtr);
void intermediate (twoInts twoIntsAppearsByValue);

int main () {
    twoInts a;
    a[0] = 0;
    a[1] = 1;
    print(&a);
    intermediate(a);
    return 0;
}
void intermediate(twoInts b) {
    print(&b);
}

void print(twoInts *c){
    printf("%d\n%d\n", (*c)[0], (*c)[1]);
}

It will compile with the following warnings:

In function ‘intermediate’:
warning: passing argument 1 of ‘print’ from incompatible pointer type [enabled by default]
    print(&b);
     ^
note: expected ‘int (*)[2]’ but argument is of type ‘int **’
    void print(twoInts *twoIntsPtr);
         ^

And produces the following output:

0
1
-453308976
32767

Is it possible to add an HTML link in the body of a MAILTO link

Please check below javascript in IE. Don't know if other modern browser will work or not.

<html>
    <head>
        <script type="text/javascript">
            function OpenOutlookDoc(){
                try {

                    var outlookApp = new ActiveXObject("Outlook.Application");
                    var nameSpace = outlookApp.getNameSpace("MAPI");
                    mailFolder = nameSpace.getDefaultFolder(6);
                    mailItem = mailFolder.Items.add('IPM.Note.FormA');
                    mailItem.Subject="a subject test";
                    mailItem.To = "[email protected]";
                    mailItem.HTMLBody = "<b>bold</b>";
                    mailItem.display (0); 
                }
                catch(e){
                    alert(e);
                    // act on any error that you get
                }
            }
        </script>
    </head>
    <body>
        <a href="javascript:OpenOutlookDoc()">Click</a>
    </body>
</html>

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

How to update json file with python

The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.

The easiest solution would be to close the file after you've read it in, then reopen it for writing.

with open("replayScript.json", "r") as jsonFile:
    data = json.load(jsonFile)

data["location"] = "NewPath"

with open("replayScript.json", "w") as jsonFile:
    json.dump(data, jsonFile)

Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.

with open("replayScript.json", "r+") as jsonFile:
    data = json.load(jsonFile)

    data["location"] = "NewPath"

    jsonFile.seek(0)  # rewind
    json.dump(data, jsonFile)
    jsonFile.truncate()

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Came here looking for a solution to a similar issue, which I just introduced by changing Schannel settings of our IIS server using "IIS Crypto" by Nartac... By disabling the SHA-1 hash, the local SQL Server was not able to be reached anymore, even though I didn't use an encrypted connection (not useful for an ASP.Net site accessing a local SQL Express instance using shared memory).

The 'SHA' hash algorithm needs to be active for SQL Server to connect

Thanks Count Zero for pointing me in the right direction :-)

So, lesson learned: do not disable SHA-1 on your IIS server if you have a local SQL Server instance.

Truncate/round whole number in JavaScript?

Convert the number to a string and throw away everything after the decimal.

trunc = function(n) { return Number(String(n).replace(/\..*/, "")) }

trunc(-1.5) === -1

trunc(1.5) === 1

Edit 2013-07-10

As pointed out by minitech and on second thought the string method does seem a bit excessive. So comparing the various methods listed here and elsewhere:

function trunc1(n){ return parseInt(n, 10); }
function trunc2(n){ return n - n % 1; }
function trunc3(n) { return Math[n > 0 ? "floor" : "ceil"](n); }
function trunc4(n) { return Number(String(n).replace(/\..*/, "")); }

function getRandomNumber() { return Math.random() * 10; }

function test(func, desc) {
    var t1, t2;
    var ave = 0;
    for (var k = 0; k < 10; k++) {
        t1 = new Date().getTime();
        for (var i = 0; i < 1000000; i++) {
            window[func](getRandomNumber());
        }
        t2 = new Date().getTime();
        ave += t2 - t1;
    }
    console.info(desc + " => " + (ave / 10));
}

test("trunc1", "parseInt");
test("trunc2", "mod");
test("trunc3", "Math");
test("trunc4", "String");

The results, which may vary based on the hardware, are as follows:

parseInt => 258.7
mod      => 246.2
Math     => 243.8
String   => 1373.1

The Math.floor / ceil method being marginally faster than parseInt and mod. String does perform poorly compared to the other methods.

Get first n characters of a string

$yourString = "bla blaaa bla blllla bla bla";
$out = "";
if(strlen($yourString) > 22) {
    while(strlen($yourString) > 22) {
        $pos = strrpos($yourString, " ");
        if($pos !== false && $pos <= 22) {
            $out = substr($yourString,0,$pos);
            break;
        } else {
            $yourString = substr($yourString,0,$pos);
            continue;
        }
    }
} else {
    $out = $yourString;
}
echo "Output String: ".$out;

How to detect page zoom level in all modern browsers?

Your calculations are still based on a number of CSS pixels. They're just a different size on the screen now. That's the point of full page zoom.

What would you want to happen on a browser on a 192dpi device which therefore normally displayed four device pixels for each pixel in an image? At 50% zoom this device now displays one image pixel in one device pixel.

Changing column names of a data frame

Similar to the others:

cols <- c("premium","change","newprice")
colnames(dataframe) <- cols

Quite simple and easy to modify.

Get a list of checked checkboxes in a div using jQuery

I needed the count of all checkboxes which are checked. Instead of writing a loop i did this

$(".myCheckBoxClass:checked").length;

Compare it with the total number of checkboxes to see if they are equal. Hope it will help someone

Order columns through Bootstrap4

This can also be achieved with the CSS "Order" property and a media query.

Something like this:

@media only screen and (max-width: 768px) {
    #first {
        order: 2;
    }
    #second {
        order: 4;
    }
    #third {
        order: 1;
    }
    #fourth {
        order: 3;
    }
}

CodePen Link: https://codepen.io/preston206/pen/EwrXqm

How to create and use resources in .NET

Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.

How to create a resource:

In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.

  • Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list.
  • Click the "Resources" tab.
  • The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options.
  • Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.
  • At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.

How to use a resource:

Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.

There is a static class called Properties.Resources that gives you access to all your resources, so my code ended up being as simple as:

paused = !paused;
if (paused)
    notifyIcon.Icon = Properties.Resources.RedIcon;
else
    notifyIcon.Icon = Properties.Resources.GreenIcon;

Done! Finished! Everything is simple when you know how, isn't it?

How to do associative array/hashing in JavaScript

Since every object in JavaScript behaves like - and is generally implemented as - a hashtable, I just go with that...

var hashSweetHashTable = {};

How to create a HTML Cancel button that redirects to a URL

<button onclick=\"window.location='{$_SERVER['PHP_SELF']}';return false;\">Reset</button>

Not enough rep to Vote Up for Kostyan. Here's my final solution (needed a reset button).

Thanks again to Kostyan for answering the question as asked without suggesting a "workaround" (time-consuming) method to "construct a button" with styles.

This is a Button (which the viewer expects to see) and it works exactly as requested. And it mingles with the other buttons on the page. Without complexity.

I did remove the "type=cancel" which apparently was useless. So even less code. :)

Make a directory and copy a file

You can use the shell for this purpose.

Set shl = CreateObject("WScript.Shell") 
shl.Run "cmd mkdir YourDir" & copy "

Rendering HTML inside textarea

An addendum to this. You can use character entities (such as changing <div> to &lt;div&gt;) and it will render in the textarea. But when it is saved, the value of the textarea is the text as rendered. So you don't need to de-encode. I just tested this across browsers (ie back to 11).

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

Where can I find Android source code online?

I've found a way to get only the Contacts application:

git clone https://android.googlesource.com/platform/packages/apps/Contacts

which is good enough for me for now, but doesn't answer the question of browsing the code on the web.

What is the difference between JVM, JDK, JRE & OpenJDK?

JDK (Java Development Kit)

Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc…

Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method.

You need JDK, if at all you want to write your own programs, and to compile them. For running java programs, JRE is sufficient.

JRE is targeted for execution of Java files

i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.

JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file.

JRE (Java Runtime Environment)

Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system

The Java Virtual Machine provides a platform-independent way of executing code; That mean compile once in any machine and run it any where(any machine).

JVM (Java Virtual Machine)

As we all aware when we compile a Java file, output is not an ‘exe’ but it’s a ‘.class’ file. ‘.class’ file consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.

The JVM is called “virtual” because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs.

There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesn’t mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesn’t define any specific way to do this.

Import existing source code to GitHub

As JB quite rightly points out, it's made incredibly easy on GitHub by simply following the instructions.

Here's an example of the instructions displayed after setting up a new repository on GitHub using http://github.com/new when you're logged in.

Global setup:

 Set up Git:
  git config --global user.name "Name"
  git config --global user.email [email protected]


Next steps:

  mkdir audioscripts
  cd audioscripts
  git init
  touch README
  git add README
  git commit -m 'first commit'
  git remote add origin [email protected]:ktec/audioscripts.git
  git push -u origin master


Existing Git repository?

  cd existing_git_repo
  git remote add origin [email protected]:ktec/audioscripts.git
  git push -u origin master


Importing a Subversion repository?

  Check out the guide for step-by-step instructions.

It couldn't be easier!!

Counting duplicates in Excel

If you perhaps also want to eliminate all of the duplicates and keep only a single one of each

Change the formula =COUNTIF(A:A,A2) to =COUNIF($A$2:A2,A2) and drag the formula down. Then autofilter for anything greater than 1 and you can delete them.

Get nth character of a string in Swift programming language

Attention: Please see Leo Dabus' answer for a proper implementation for Swift 4 and Swift 5.

Swift 4 or later

The Substring type was introduced in Swift 4 to make substrings faster and more efficient by sharing storage with the original string, so that's what the subscript functions should return.

Try it out here

extension StringProtocol {
    subscript(offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] }
    subscript(range: Range<Int>) -> SubSequence {
        let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
        return self[startIndex..<index(startIndex, offsetBy: range.count)]
    }
    subscript(range: ClosedRange<Int>) -> SubSequence {
        let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
        return self[startIndex..<index(startIndex, offsetBy: range.count)]
    }
    subscript(range: PartialRangeFrom<Int>) -> SubSequence { self[index(startIndex, offsetBy: range.lowerBound)...] }
    subscript(range: PartialRangeThrough<Int>) -> SubSequence { self[...index(startIndex, offsetBy: range.upperBound)] }
    subscript(range: PartialRangeUpTo<Int>) -> SubSequence { self[..<index(startIndex, offsetBy: range.upperBound)] }
}

To convert the Substring into a String, you can simply do String(string[0..2]), but you should only do that if you plan to keep the substring around. Otherwise, it's more efficient to keep it a Substring.

It would be great if someone could figure out a good way to merge these two extensions into one. I tried extending StringProtocol without success, because the index method does not exist there. Note: This answer has been already edited, it is properly implemented and now works for substrings as well. Just make sure to use a valid range to avoid crashing when subscripting your StringProtocol type. For subscripting with a range that won't crash with out of range values you can use this implementation


Why is this not built-in?

The error message says "see the documentation comment for discussion". Apple provides the following explanation in the file UnavailableStringAPIs.swift:

Subscripting strings with integers is not available.

The concept of "the ith character in a string" has different interpretations in different libraries and system components. The correct interpretation should be selected according to the use case and the APIs involved, so String cannot be subscripted with an integer.

Swift provides several different ways to access the character data stored inside strings.

  • String.utf8 is a collection of UTF-8 code units in the string. Use this API when converting the string to UTF-8. Most POSIX APIs process strings in terms of UTF-8 code units.

  • String.utf16 is a collection of UTF-16 code units in string. Most Cocoa and Cocoa touch APIs process strings in terms of UTF-16 code units. For example, instances of NSRange used with NSAttributedString and NSRegularExpression store substring offsets and lengths in terms of UTF-16 code units.

  • String.unicodeScalars is a collection of Unicode scalars. Use this API when you are performing low-level manipulation of character data.

  • String.characters is a collection of extended grapheme clusters, which are an approximation of user-perceived characters.

Note that when processing strings that contain human-readable text, character-by-character processing should be avoided to the largest extent possible. Use high-level locale-sensitive Unicode algorithms instead, for example, String.localizedStandardCompare(), String.localizedLowercaseString, String.localizedStandardRangeOfString() etc.

Using querySelectorAll to retrieve direct children

I would like to add that you can extend the compatibility of :scope by just assigning a temporary attribute to the current node.

let node = [...];
let result;

node.setAttribute("foo", "");
result = window.document.querySelectorAll("[foo] > .bar");
// And, of course, you can also use other combinators.
result = window.document.querySelectorAll("[foo] + .bar");
result = window.document.querySelectorAll("[foo] ~ .bar");
node.removeAttribute("foo");

change PATH permanently on Ubuntu

Try to add export PATH=$PATH:/home/me/play in ~/.bashrc file.

Regex doesn't work in String.matches()

java's implementation of regexes try to match the whole string

that's different from perl regexes, which try to find a matching part

if you want to find a string with nothing but lower case characters, use the pattern [a-z]+

if you want to find a string containing at least one lower case character, use the pattern .*[a-z].*

Java : How to determine the correct charset encoding of a stream

As far as I know, there is no general library in this context to be suitable for all types of problems. So, for each problem you should test the existing libraries and select the best one which satisfies your problem’s constraints, but often none of them is appropriate. In these cases you can write your own Encoding Detector! As I have wrote ...

I’ve wrote a meta java tool for detecting charset encoding of HTML Web pages, using IBM ICU4j and Mozilla JCharDet as the built-in components. Here you can find my tool, please read the README section before anything else. Also, you can find some basic concepts of this problem in my paper and in its references.

Bellow I provided some helpful comments which I’ve experienced in my work:

  • Charset detection is not a foolproof process, because it is essentially based on statistical data and what actually happens is guessing not detecting
  • icu4j is the main tool in this context by IBM, imho
  • Both TikaEncodingDetector and Lucene-ICU4j are using icu4j and their accuracy had not a meaningful difference from which the icu4j in my tests (at most %1, as I remember)
  • icu4j is much more general than jchardet, icu4j is just a bit biased to IBM family encodings while jchardet is strongly biased to utf-8
  • Due to the widespread use of UTF-8 in HTML-world; jchardet is a better choice than icu4j in overall, but is not the best choice!
  • icu4j is great for East Asian specific encodings like EUC-KR, EUC-JP, SHIFT_JIS, BIG5 and the GB family encodings
  • Both icu4j and jchardet are debacle in dealing with HTML pages with Windows-1251 and Windows-1256 encodings. Windows-1251 aka cp1251 is widely used for Cyrillic-based languages like Russian and Windows-1256 aka cp1256 is widely used for Arabic
  • Almost all encoding detection tools are using statistical methods, so the accuracy of output strongly depends on the size and the contents of the input
  • Some encodings are essentially the same just with a partial differences, so in some cases the guessed or detected encoding may be false but at the same time be true! As about Windows-1252 and ISO-8859-1. (refer to the last paragraph under the 5.2 section of my paper)

How do I obtain the frequencies of each value in an FFT?

I have used the following:

public static double Index2Freq(int i, double samples, int nFFT) {
  return (double) i * (samples / nFFT / 2.);
}

public static int Freq2Index(double freq, double samples, int nFFT) {
  return (int) (freq / (samples / nFFT / 2.0));
}

The inputs are:

  • i: Bin to access
  • samples: Sampling rate in Hertz (i.e. 8000 Hz, 44100Hz, etc.)
  • nFFT: Size of the FFT vector

How to submit a form on enter when the textarea has focus?

<form id="myform">
    <input type="textbox" id="field"/>
    <input type="button" value="submit">
</form>

<script>
    $(function () {
        $("#field").keyup(function (event) {
            if (event.which === 13) {
                document.myform.submit();
            }
        }
    });
</script>

Select method of Range class failed via VBA

This is how you get around that in an easy non-complicated way.
Instead of using sheet(x).range use Activesheet.range("range").select

How to use store and use session variables across pages?

Reasoning from the comments to this question, it appears a lack of an adjusted session.save_path causes this misbehavior of PHP’s session handler. Just specify a directory (outside your document root directory) that exists and is both readable and writeable by PHP to fix this.

String.format() to format double in java

If you want to format it with manually set symbols, use this:

DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator('.');
decimalFormatSymbols.setGroupingSeparator(',');
DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", decimalFormatSymbols);
System.out.println(decimalFormat.format(1237516.2548)); //1,237,516.25

Locale-based formatting is preferred, though.

Select statement to find duplicates on certain fields

To get the list of fields for which there are multiple records, you can use..

select field1,field2,field3, count(*)
  from table_name
  group by field1,field2,field3
  having count(*) > 1

Check this link for more information on how to delete the rows.

http://support.microsoft.com/kb/139444

There should be a criterion for deciding how you define "first rows" before you use the approach in the link above. Based on that you'll need to use an order by clause and a sub query if needed. If you can post some sample data, it would really help.

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:

import numpy as np
from sklearn import linear_model
from sklearn import svm

classifiers = [
    svm.SVR(),
    linear_model.SGDRegressor(),
    linear_model.BayesianRidge(),
    linear_model.LassoLars(),
    linear_model.ARDRegression(),
    linear_model.PassiveAggressiveRegressor(),
    linear_model.TheilSenRegressor(),
    linear_model.LinearRegression()]

trainingData    = np.array([ [2.3, 4.3, 2.5],  [1.3, 5.2, 5.2],  [3.3, 2.9, 0.8],  [3.1, 4.3, 4.0]  ])
trainingScores  = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData  = np.array([ [2.5, 2.4, 2.7],  [2.7, 3.2, 1.2] ])

for item in classifiers:
    print(item)
    clf = item
    clf.fit(trainingData, trainingScores)
    print(clf.predict(predictionData),'\n')

How to format DateTime to 24 hours time?

Console.WriteLine(curr.ToString("HH:mm"));

Rename column SQL Server 2008

Try:

EXEC sp_rename 'TableName.OldName', 'NewName', 'COLUMN'

How to disable logging on the standard error stream in Python?

I don't know the logging module very well, but I'm using it in the way that I usually want to disable only debug (or info) messages. You can use Handler.setLevel() to set the logging level to CRITICAL or higher.

Also, you could replace sys.stderr and sys.stdout by a file open for writing. See http://docs.python.org/library/sys.html#sys.stdout. But I wouldn't recommend that.

How to dynamic filter options of <select > with jQuery?

I'm not sure why you have more than one option with the same value, but this works

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('input').change(function() {_x000D_
    var filter = $(this).val();_x000D_
    $('option').each(function() {_x000D_
      if ($(this).val() == filter) {_x000D_
        $(this).show();_x000D_
      } else {_x000D_
        $(this).hide();_x000D_
      }_x000D_
      $('select').val(filter);_x000D_
    })_x000D_
  })_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
   <option value="something1">something1</option>_x000D_
   <option value="something1">something1</option>_x000D_
   <option value="something2">something2</option>_x000D_
   <option value="something2">something2</option>_x000D_
   <option value="something2">something2</option>_x000D_
   <option value="something3">something3</option>_x000D_
   <option value="something3">something3</option>_x000D_
   <option value="something3">something3</option>_x000D_
</select>_x000D_
<input type="text" placeholder="something1">
_x000D_
_x000D_
_x000D_

How to upgrade Angular CLI project?

Just use the build-in feature of Angular CLI

ng update

to update to the latest version.

Difference between Activity Context and Application Context

I found this table super useful for deciding when to use different types of Contexts:

enter image description here

  1. An application CAN start an Activity from here, but it requires that a new task be created. This may fit specific use cases, but can create non-standard back stack behaviors in your application and is generally not recommended or considered good practice.
  2. This is legal, but inflation will be done with the default theme for the system on which you are running, not what’s defined in your application.
  3. Allowed if the receiver is null, which is used for obtaining the current value of a sticky broadcast, on Android 4.2 and above.

Original article here.

Read only file system on Android

On my Samsung galaxy mini S5570 (after got root on cellphone):

Fist, as root, I ran:

systemctl start adb

as a normal user:

adb shell 
su 

Grant root permissions on touch screen

mount 

list all mount points that we have and we can see, in my case, that /dev/stl12 was mounted on /system as ro (ready only), so we just need do:

mount -o rw,remount /dev/stl12 /system

Xcode variables

Here's a list of the environment variables. I think you might want CURRENT_VARIANT. See also BUILD_VARIANTS.

beyond top level package error in relative import

Not sure in python 2.x but in python 3.6, assuming you are trying to run the whole suite, you just have to use -t

-t, --top-level-directory directory Top level directory of project (defaults to start directory)

So, on a structure like

project_root
  |
  |----- my_module
  |          \
  |           \_____ my_class.py
  |
  \ tests
      \___ test_my_func.py

One could for example use:

python3 unittest discover -s /full_path/project_root/tests -t /full_path/project_root/

And still import the my_module.my_class without major dramas.

Proper use of const for defining functions in JavaScript

It has been three years since this question was asked, but I am just now coming across it. Since this answer is so far down the stack, please allow me to repeat it:

Q: I am interested if there are any limits to what types of values can be set using const in JavaScript—in particular functions. Is this valid? Granted it does work, but is it considered bad practice for any reason?

I was motivated to do some research after observing one prolific JavaScript coder who always uses const statement for functions, even when there is no apparent reason/benefit.

In answer to "is it considered bad practice for any reason?" let me say, IMO, yes it is, or at least, there are advantages to using function statement.

It seems to me that this is largely a matter of preference and style. There are some good arguments presented above, but none so clear as is done in this article:

Constant confusion: why I still use JavaScript function statements by medium.freecodecamp.org/Bill Sourour, JavaScript guru, consultant, and teacher.

I urge everyone to read that article, even if you have already made a decision.

Here's are the main points:

Function statements have two clear advantages over [const] function expressions:

Advantage #1: Clarity of intent

When scanning through thousands of lines of code a day, it’s useful to be able to figure out the programmer’s intent as quickly and easily as possible.

Advantage #2: Order of declaration == order of execution

Ideally, I want to declare my code more or less in the order that I expect it will get executed.

This is the showstopper for me: any value declared using the const keyword is inaccessible until execution reaches it.

What I’ve just described above forces us to write code that looks upside down. We have to start with the lowest level function and work our way up.

My brain doesn’t work that way. I want the context before the details.

Most code is written by humans. So it makes sense that most people’s order of understanding roughly follows most code’s order of execution.

How to name variables on the fly?

It seems to me that you might be better off with a list rather than using orca1, orca2, etc, ... then it would be orca[1], orca[2], ...

Usually you're making a list of variables differentiated by nothing but a number because that number would be a convenient way to access them later.

orca <- list()
orca[1] <- "Hi"
orca[2] <- 59

Otherwise, assign is just what you want.

Rename all files in directory from $filename_h to $filename_half?

Use the rename utility:

rc@bvm3:/tmp/foo $ touch 05_h.png 06_h.png
rc@bvm3:/tmp/foo $ rename 's/_h/_half/' * 
rc@bvm3:/tmp/foo $ ls -l
total 0
-rw-r--r-- 1 rc rc 0 2011-09-17 00:15 05_half.png
-rw-r--r-- 1 rc rc 0 2011-09-17 00:15 06_half.png

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

In order for System.loadLibrary() to work, the library (on Windows, a DLL) must be in a directory somewhere on your PATH or on a path listed in the java.library.path system property (so you can launch Java like java -Djava.library.path=/path/to/dir).

Additionally, for loadLibrary(), you specify the base name of the library, without the .dll at the end. So, for /path/to/something.dll, you would just use System.loadLibrary("something").

You also need to look at the exact UnsatisfiedLinkError that you are getting. If it says something like:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no foo in java.library.path

then it can't find the foo library (foo.dll) in your PATH or java.library.path. If it says something like:

Exception in thread "main" java.lang.UnsatisfiedLinkError: com.example.program.ClassName.foo()V

then something is wrong with the library itself in the sense that Java is not able to map a native Java function in your application to its actual native counterpart.

To start with, I would put some logging around your System.loadLibrary() call to see if that executes properly. If it throws an exception or is not in a code path that is actually executed, then you will always get the latter type of UnsatisfiedLinkError explained above.

As a sidenote, most people put their loadLibrary() calls into a static initializer block in the class with the native methods, to ensure that it is always executed exactly once:

class Foo {

    static {
        System.loadLibrary('foo');
    }

    public Foo() {
    }

}

Unable to copy file - access to the path is denied

I also had same problem. I got error messages that related to cannot copy since access to path denied. In my case all my dll's and xml files and so on are place at D:\TFS\Example\Bin\Debug folder.

I right clicked on Bin folder and clicked Properties and saw that Read-only check box is checked under Attributes.

I un-checked Read only check box and cliked Apply and clicked OK on the new popup that is shown.

I went back to Visual Studio and build my solution which was giving me error messages.

Voilaa.. This time it build successfully without errors.

I donot know whether this is perfect but I did this to solve my issue.

Markdown: continue numbered list

Source;

<span>1.</span> item 1<br/>
<span>2.</span> item 2
```
Code block
```
<span>3.</span> item 3


Result;

1. item 1
2. item 2 Code block 3. item 3

Connecting to SQL Server with Visual Studio Express Editions

My guess is that with VWD your solutions are more likely to be deployed to third party servers, many of which do not allow for a dynamically attached SQL Server database file. Thus the allowing of the other connection type.

This difference in IDE behavior is one of the key reasons for upgrading to a full version.

Different between parseInt() and valueOf() in java?

Look at Java sources: valueOf is using parseInt :

/**
 * Parses the specified string as a signed decimal integer value.
 *
 * @param string
 *            the string representation of an integer value.
 * @return an {@code Integer} instance containing the integer value
 *         represented by {@code string}.
 * @throws NumberFormatException
 *             if {@code string} cannot be parsed as an integer value.
 * @see #parseInt(String)
 */
public static Integer valueOf(String string) throws NumberFormatException {
    return valueOf(parseInt(string));
}

parseInt returns int

/**
 * Parses the specified string as a signed decimal integer value. The ASCII
 * character \u002d ('-') is recognized as the minus sign.
 *
 * @param string
 *            the string representation of an integer value.
 * @return the primitive integer value represented by {@code string}.
 * @throws NumberFormatException
 *             if {@code string} cannot be parsed as an integer value.
 */
public static int parseInt(String string) throws NumberFormatException {
    return parseInt(string, 10);
}

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

PostgreSQL Error: Relation already exists

Another reason why you might get errors like "relation already exists" is if the DROP command did not execute correctly.

One reason this can happen is if there are other sessions connected to the database which you need to close first.

Android Studio: Application Installation Failed

Happened to me as well: At the first time, it says- Failure [INSTALL_FAILED_CONFLICTING_PROVIDER] At the second time, it says- DELETE_FAILED_INTERNAL_ERROR

This because of the new 'com.google.android.gms' version 8.3.0

Changing it back to 8.1.0 solved the problem in my case

Android SDK manager won't open

Alright, I had the same problem, and none of these answers worked for me (I'm running Windows 8). I tried running tools/android.bat and noticed I got some errors there. I investigated further and it seems there is something wrong in the code that finds your Java path.

This is how you fix it:

  1. Open up tools/android.bat in your favorite text editor
  2. Search for this piece of code:

    set java_exe=
    call lib\find_java.bat
    if not defined java_exe goto :EOF
    
  3. Replace it with this:

    set java_exe=D:\Program Files\Java\jdk1.7.0_07\bin\java.exe 
    

    where the path is the path to your Java exe.

  4. Run android.bat

(in my case I had to specify the path to java_exe in step 3 with no quotes to make it work.)

What are the "spec.ts" files generated by Angular CLI for?

The .spec.ts files are for unit tests for individual components. You can run Karma task runner through ng test. In order to see code coverage of unit test cases for particular components run ng test --code-coverage

Show div on scrollDown after 800px

You've got a few things going on there. One, why a class? Do you actually have multiple of these on the page? The CSS suggests you can't. If not you should use an ID - it's faster to select both in CSS and jQuery:

<div id=bottomMenu>You read it all.</div>

Second you've got a few crazy things going on in that CSS - in particular the z-index is supposed to just be a number, not measured in pixels. It specifies what layer this tag is on, where each higher number is closer to the user (or put another way, on top of/occluding tags with lower z-indexes).

The animation you're trying to do is basically .fadeIn(), so just set the div to display: none; initially and use .fadeIn() to animate it:

$('#bottomMenu').fadeIn(2000);

.fadeIn() works by first doing display: (whatever the proper display property is for the tag), opacity: 0, then gradually ratcheting up the opacity.

Full working example:

http://jsfiddle.net/b9chris/sMyfT/

CSS:

#bottomMenu {
    display: none;
    position: fixed;
    left: 0; bottom: 0;
    width: 100%; height: 60px;
    border-top: 1px solid #000;
    background: #fff;
    z-index: 1;
}

JS:

var $win = $(window);

function checkScroll() {
    if ($win.scrollTop() > 100) {
        $win.off('scroll', checkScroll);
        $('#bottomMenu').fadeIn(2000);
    }
}

$win.scroll(checkScroll);

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

The column of the first matrix and the row of the second matrix should be equal and the order should be like this only

column of first matrix = row of second matrix

and do not follow the below step

row of first matrix  = column of second matrix

it will throw an error

How to remove a file from the index in git?

Depending on your workflow, this may be the kind of thing that you need rarely enough that there's little point in trying to figure out a command-line solution (unless you happen to be working without a graphical interface for some reason).

Just use one of the GUI-based tools that support index management, for example:

  • git gui <-- uses the Tk windowing framework -- similar style to gitk
  • git cola <-- a more modern-style GUI interface

These let you move files in and out of the index by point-and-click. They even have support for selecting and moving portions of a file (individual changes) to and from the index.


How about a different perspective: If you mess up while using one of the suggested, rather cryptic, commands:

  • git rm --cached [file]
  • git reset HEAD <file>

...you stand a real chance of losing data -- or at least making it hard to find. Unless you really need to do this with very high frequency, using a GUI tool is likely to be safer.


Working without the index

Based on the comments and votes, I've come to realize that a lot of people use the index all the time. I don't. Here's how:

  • Commit my entire working copy (the typical case): git commit -a
  • Commit just a few files: git commit (list of files)
  • Commit all but a few modified files: git commit -a then amend via git gui
  • Graphically review all changes to working copy: git difftool --dir-diff --tool=meld

How prevent CPU usage 100% because of worker process in iis

If it is not necessary turn off 'Enable 32-bit Applications' from your respective application pool of your website.

This worked for me on my local machine

How to push a single file in a subdirectory to Github (not master)

If you commit one file and push your revision, it will not transfer the whole repository, it will push changes.

Get month and year from date cells Excel

Please try something like:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

You seem to have three main possible scenarios:

  1. Space-separated date with time as text (eg as A1 below)
  2. Hyphen-separated date as text (eg as A2 below)
  3. Formatted date index (as A4 and A5 below)

ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.

I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.

Case #1

This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.

This with =FIND which looks for a space (" ") in C1, starting with the eighth character within C1 counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.

Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.

So

=VALUE(LEFT(C1,FIND(" ",C1,8))) 

returns 40671 in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.

Case #2

If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:

=RIGHT(C2,4)  

Takes the last four characters of C2, hence 2011 in this example.

=MID(C2,4,2) 

Starting at the fourth character, takes the next two characters of C2, hence 05 in this example (representing May).

=LEFT(C2,2))  

Takes the first two characters of C2, hence 08 in this example (representing the 8th day of the month). Date is not a text function so does not need to be wrapped in =VALUE.

Taken together

=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2)) 

also returns 40671 in this example, but from different input from Case #1.

Case #3

Is simple because already a date serial number, so just

=C2  

is sufficient.


Put the above together to cover all three cases in a single formula:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:

SO23928568 example

How to position a DIV in a specific coordinates?

Script its left and top properties as the number of pixels from the left edge and top edge respectively. It must have position: absolute;

var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';

Or do it as a function so you can attach it to an event like onmousedown

function placeDiv(x_pos, y_pos) {
  var d = document.getElementById('yourDivId');
  d.style.position = "absolute";
  d.style.left = x_pos+'px';
  d.style.top = y_pos+'px';
}

Remove trailing comma from comma-separated string

You can try with this, it worked for me:

if (names.endsWith(",")) {
    names = names.substring(0, names.length() - 1);
}

Or you can try with this too:

string = string.replaceAll(", $", "");

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Cast the result as TIME and the result will be in time format for duration of the interval.

select CAST(job_end - job_start) AS TIME(0)) from tableA

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

Favicon not showing up in Google Chrome

Cache

Clear your cache. http://support.google.com/chrome/bin/answer.py?hl=en&answer=95582 And test another browser.

Some where able to get an updated favicon by adding an URL parameter: ?v=1 after the link href which changes the resource link and therefore loads the favicon without cache (thanks @Stanislav).

<link rel="icon" type="image/x-icon" href="favicon.ico?v=2"  />

Favicon Usage

How did you import the favicon? How you should add it.

Normal favicon:

<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

PNG/GIF favicon:

<link rel="icon" type="image/gif" href="favicon.gif" />
<link rel="icon" type="image/png" href="favicon.png" />

in the <head> Tag.

Chrome local problem

Another thing could be the problem that chrome can't display favicons, if it's local (not uploaded to a webserver). Only if the file/icon would be in the downloads directory chrome is allowed to load this data - more information about this can be found here: local (file://) website favicon works in Firefox, not in Chrome or Safari- why?

Renaming

Try to rename it from favicon.{whatever} to {yourfaviconname}.{whatever} but I would suggest you to still have the normal favicon. This has solved my issue on IE.

Base64 approach

Found another solution for this which works great! I simply added my favicon as Base64 Encoded Image directly inside the tag like this:

<link href="data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AIaDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wCGg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8AhoOC/////wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wCGg4L/////AHCMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/////wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wBTlsIAU5bCAFOWwgBTlsIAU5bCM1OWwnP///8AhoOC/////wD///8A////AP///wD///8A////AP///wD///8AU5bCBlOWwndTlsLHU5bC+FOWwv1TlsLR////AP///wD///8A////AP///wD///8A////AP///wD///8A////AFOWwvtTlsLuU5bCu1OWwlc2k9cANpPXqjaT19H///8A////AP///wD///8A////AP///wD///8A////AP///wBTlsIGNpPXADaT1wA2k9dINpPX8TaT1+40ktpDH4r2tB+K9hL///8A////AP///wD///8A////AP///wD///8A////ADaT1wY2k9e7NpPX/TaT16AfivYGH4r23R+K9u4tg/WQLoL1mP///wD///8A////AP///wD///8A////AP///wA2k9fuNpPX5zaT1zMfivYGH4r23R+K9uwjiPYXLoL1+S6C9W7///8A////AP///wD///8A////AP///wD///8ANpPXLjaT1wAfivYGH4r22x+K9usfivYSLoL1oC6C9esugvUA////AP///wD///8A////AP///wD///8A////AP///wD///8AH4r2zx+K9usfivYSLoL1DC6C9fwugvVXLoL1AP///wD///8A////AP///wD///8A////AP///wD///8A////AB+K9kgfivYMH4r2AC6C9bEugvXhLoL1AC6C9QD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAugvXyLoL1SC6C9QAugvUA////AP//AADgBwAA7/cAAOgXAADv9wAA6BcAAO+XAAD4HwAA+E8AAPsDAAD8AQAA/AEAAP0DAAD/AwAA/ycAAP/nAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP8AAAAA////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/wAAAAD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP/4+vsA4ujuAOLo7gDi6O4A4ujuAN3k6wDZ4OgA2eDoANng6ADZ4OgA2eDoANng6ADW3uYAJS84APj6+wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/9Xd5QBwjKgAcIyoRnCMqGRwjKhxcIyogHCMqI9wjKidcIyoq3CMqLlwjKjHcIyo1HCMqLhogpwA/f7+AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/xtHcAHCMqABwjKjAcIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo4EdZawD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+2xNMAcIyoAHCMqJhwjKjPcIyowHCMqLFwjKijcoymlXSMpIh0jKR6co2mbG+OqGFqj61zXZO4AeXv9gCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/6i5ygDF0dwAIiozACQyPQAoP1AALlBmADhlggBblLkGVJbBPFOWwnxTlsK5U5bC9FOWwv9TlsIp3erzAISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAALztHAAAAAAAuU2sAU5bCClOWwkNTlsKAU5bCwFOWwvhTlsL/U5bC/1OWwv9TlsL/U5bC/ViVvVcXOFAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAALDhEALVFoAFOWwjpTlsL6U5bC/1OWwv9TlsL/U5bC/1OWwvxTlsLIV5W+i2CRs0xHi71TKYzUnyuM0gIJHi4AAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAACtNZABTlsIAU5bCD1OWwv1TlsL6U5bCxFOWwoRVlsBHZJKwDCNObAA8icJAKYzUwimM1P8pjNT/KYzUWCaCxgALLUsAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAApS2EAU5bCAFOWwgBTlsIAU5bCNVOWwgg+cJEAIT1QABU/XQA1isg4KYzUuymM1P8pjNT/KYzU/ymM1LAti9E0JYvmDhdouAAAAAAAAAAAAP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AFyk1AE+PuQBTlsIAU5bCAER7nwAmRVoADBojABRFaQAwi80xKYzUsymM1P8pjNT/KYzU/ymM1LgsjNE2MovXFB+K9MUfivbBH4r2BgcdNAARQH8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAQIDABIgKgAPGiIABRMcABdQeQAti9AqKYzUrCmM1P8pjNT/KYzU/ymM1MAqjNM9HmqmACWK7SIfivbZH4r2/x+K9vsuiudAFE2YACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAABhQfABtejgAoitEAKYzUACmM1JQpjNT/KYzU/ymM1MgpjNREH2mgABlosQAfivY0H4r26R+K9v8fivbyKIrtR0CB1SggevTQIHr0Nv///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAACBwsAJX2+ACmM1AApjNQAKYzUGSmM1MYpjNRMInWxABNHdQAcfuEAH4r2Sx+K9vUfivb/H4r25iGK9DE2gt4EIHr0yyB69P8gevTQ////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAOMUsAKYzUACmM1AApjNQAJX6/ABE7WgAUWJwAH4r2AB+K9mYfivb9H4r2/x+K9tYfivYfG27RACB69HsgevT/IHr0+yB69DL///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAfaJ4AJ4XKABVGagAKKkoAG3raAB+K9gEfivaEH4r2/x+K9v8fivbCH4r2EB133wAgevQsIHr0+SB69P8gevSAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAUSGwAFERwAElCOAB+J9QAfivYAH4r2lx+K9v8fivb/H4r2qR+K9gYefuoAIHr0BSB69M4gevT/IHr00CB69AUgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAkqSgAfivYAH4r2AB+K9gAfivZLH4r2/R+K9osfivYBH4PwACB69AAgevSAIHr0/yB69PkgevQwIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEiAAB+K9gAfivYAH4r2AB+K9gAfivYsH4r2AB+G8wAge/QAIHr0MCB69PsgevT/IHr0eyB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAXZrYAH4r2AB+K9gAfivYAH4r2AB+K9gAfifUAIHz0ACB69AcgevTQIHr0/yB69MwgevQEIHr0ACB69AAgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAIDAB6E6gAfivYAH4r2AB+K9gAfivYAH4r2ACB+9QAgevQAIHr0fCB69P8gevT5IHr0LCB69AAgevQAIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAABBAcAEUqDAB6E6wAfivYAH4r2AB+K9gAggPUAIHr0ACB69AAgevQTIHr0qCB69HYgevQAIHr0ACB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP////////////////wAAH/8AAB//P/+f/z//n/8wAZ//MAGf/z//n/8wAZ//MAGf/zAAn/8/gJ//+AD///AAf//wEH//+cA///8AH//8BB///BgH//xwB///4If//4EP//+CD///hh///9w////4P///+H////j////////////" rel="icon" type="image/x-icon" />

Used this page here for this: http://www.motobit.com/util/base64-decoder-encoder.asp

Generate favicons

I can really suggest you this page: http://www.favicon-generator.org/ to create all types of favicons you need.

Difference between socket and websocket?

To answer your questions.

  1. Even though they achieve (in general) similar things, yes, they are really different. WebSockets typically run from browsers connecting to Application Server over a protocol similar to HTTP that runs over TCP/IP. So they are primarily for Web Applications that require a permanent connection to its server. On the other hand, plain sockets are more powerful and generic. They run over TCP/IP but they are not restricted to browsers or HTTP protocol. They could be used to implement any kind of communication.
  2. No. There is no reason.

How can I view an old version of a file with Git?

You can use git show with a path from the root of the repository (./ or ../ for relative pathing):

$ git show REVISION:path/to/file

Replace REVISION with your actual revision (could be a Git commit SHA, a tag name, a branch name, a relative commit name, or any other way of identifying a commit in Git)

For example, to view the version of file <repository-root>/src/main.c from 4 commits ago, use:

$ git show HEAD~4:src/main.c

Git for Windows requires forward slashes even in paths relative to the current directory. For more information, check out the man page for git-show.

.Net: How do I find the .NET version?

clrver is an excellent one. Just execute it in the .NET prompt and it will list all available framework versions.

How to render an array of objects in React?

Try this:

_x000D_
_x000D_
class First extends React.Component {
  constructor (props){
    super(props);

  }

  render() {
     const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>;
    
    return (
      <div>
      {listItems}
      </div>
    );
  }
} 
_x000D_
_x000D_
_x000D_

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

I tried some of your solutions. This one :

margin: 0px -100%;
padding: 0 100%;

is by far the best, since we don't need extra css for smaller screen. I made a codePen to show the results : I used a parent div with a background image, and a child divon div with inner content.

https://codepen.io/yuyazz/pen/BaoqBBq

Node.js/Express routing with get params

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

Retrieve data from a ReadableStream object?

Note that you can only read a stream once, so in some cases, you may need to clone the response in order to repeatedly read it:

fetch('example.json')
  .then(res=>res.clone().json())
  .then( json => console.log(json))

fetch('url_that_returns_text')
  .then(res=>res.clone().text())
  .then( text => console.log(text))

Returning Month Name in SQL Server Query

basically this ...

declare @currentdate datetime = getdate()
select left(datename(month,DATEADD(MONTH, -1, GETDATE())),3)
union all
select left(datename(month,(DATEADD(MONTH, -2, GETDATE()))),3)
union all
select left(datename(month,(DATEADD(MONTH, -3, GETDATE()))),3)

AVD Manager - Cannot Create Android Virtual Device

If you have changed the SDK Path somehow it will not be able to find the SDKs you installed even though it is listing them fine.

I solved by openig Android SDK Manager and in that dialog choosing the menu Tools -> Manage AVDs. And when you open Manage AVDs directly from the toolbar of Eclipse you should Refresh to see the AVD you created.

How to assign name for a screen?

The easiest way use screen with name

screen -S 'name' 'application'
  • Ctrl+a, d = exit and leave application open

Return to screen:

screen -r 'name'

for example using lynx with screen

Create screen:

screen -S lynx lynx

Ctrl+a, d =exit

later you can return with:

screen -r lynx

How can I make grep print the lines below and above each matching line?

grep's -A 1 option will give you one line after; -B 1 will give you one line before; and -C 1 combines both to give you one line both before and after, -1 does the same.

how to check if the input is a number or not in C?

Using scanf is very easy, this is an example :

if (scanf("%d", &val_a_tester) == 1) {
    ... // it's an integer
}

How to remove underline from a name on hover

try this:

legend.green-color a:hover{
    text-decoration: none;
}

CSS - How to Style a Selected Radio Buttons Label?

If you really want to put the checkboxes inside the label, try adding an extra span tag, eg.

HTML

<div class="radio-toolbar">
 <label><input type="radio" value="all" checked><span>All</span></label>
 <label><input type="radio" value="false"><span>Open</span></label>
 <label><input type="radio" value="true"><span>Archived</span></label>
</div>

CSS

.radio-toolbar input[type="radio"]:checked ~ * { 
    background:pink !important;
}

That will set the backgrounds for all siblings of the selected radio button.

How can I make content appear beneath a fixed DIV element?

Having just struggled with this and disliking some of the "hackier" solutions, I found this to be useful and clean:

#floatingMenu{
  position: sticky;
  top: 0;
}

How can I add a table of contents to a Jupyter / JupyterLab notebook?

How about using a Browser plugin that gives you an overview of ANY html page. I have tried the following:

They both work pretty well for IPython Notebooks. I was reluctant to use the previous solutions as they seem a bit unstable and ended up using these extensions.

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

How to show PIL images on the screen?

I tested this and it works fine for me:

from PIL import Image
im = Image.open('image.jpg')
im.show()

I get conflicting provisioning settings error when I try to archive to submit an iOS app

For those coming from Ionic or Cordova, you can try the following: Disconnect your ios devices from the computer before ios cordova build ios --release (seems to change the targeted device for xcode signing).

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Please use SqlBulkCopyColumnMapping.

Example:

private void SaveFileToDatabase(string filePath)
{
    string strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MHMRA_TexMedEvsConnectionString"].ConnectionString.ToString();

    String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
    //Create Connection to Excel work book 
    using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
    {
        //Create OleDbCommand to fetch data from Excel 
        using (OleDbCommand cmd = new OleDbCommand("Select * from [Crosswalk$]", excelConnection))
        {
            excelConnection.Open();
            using (OleDbDataReader dReader = cmd.ExecuteReader())
            {
                using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
                {
                    //Give your Destination table name 
                    sqlBulk.DestinationTableName = "PaySrcCrosswalk";

                    // this is a simpler alternative to explicit column mappings, if the column names are the same on both sides and data types match
                    foreach(DataColumn column in dt.Columns) {
                         s.ColumnMappings.Add(new SqlBulkCopyColumnMapping(column.ColumnName, column.ColumnName));
                     }
                   
                    sqlBulk.WriteToServer(dReader);
                }
            }
        }
    }
}  

In SQL Server, what does "SET ANSI_NULLS ON" mean?

Set ANSI NULLS OFF will make NULL = NULL comparision return true. EG :

        SET ANSI_NULLS OFF
        select * from sys.tables
        where principal_id = Null

will return some result as displayed below: zcwInvoiceDeliveryType 744547 NULL zcExpenseRptStatusTrack 2099048 NULL ZCVendorPermissions 2840564 NULL ZCWOrgLevelClientFee 4322525 NULL

While this query will not return any results:

        SET ANSI_NULLS ON 
        select * from sys.tables
        where principal_id = Null

Value Change Listener to JTextField

it was the update version of Codemwnci. his code is quite fine and works great except the error message. To avoid error you must change the condition statement.

  // Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedUpdate(DocumentEvent e) {
    warn();
  }
  public void removeUpdate(DocumentEvent e) {
    warn();
  }
  public void insertUpdate(DocumentEvent e) {
    warn();
  }

  public void warn() {
     if (textField.getText().length()>0){
       JOptionPane.showMessageDialog(null,
          "Error: Please enter number bigger than 0", "Error Massage",
          JOptionPane.ERROR_MESSAGE);
     }
  }
});

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

Remove all whitespaces from NSString

That is for removing any space that is when you getting text from any text field but if you want to remove space between string you can use

xyz =[xyz.text stringByReplacingOccurrencesOfString:@" " withString:@""];

It will replace empty space with no space and empty field is taken care of by below method:

searchbar.text=[searchbar.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

Hive External Table Skip First Row

Just for those who have already created the table with the header. Here is the alter command for the same. This is useful in case you already have the table and want the first row to be ignored without dropping and recreating. It also helps with people to familiarize with ALTER as a option with TBLPROPERTIES.

ALTER TABLE tablename SET TBLPROPERTIES ("skip.header.line.count"="1");

Styling JQuery UI Autocomplete

You can overwrite the classes in your own css using !important, e.g. if you want to get rid of the rounded corners.

.ui-corner-all
{
border-radius: 0px !important;
}

PHP is_numeric or preg_match 0-9 validation

is_numeric would accept "-0.5e+12" as a valid ID.

How to Store Historical Data

You can use MSSQL Server Auditing feature. From version SQL Server 2012 you will find this feature in all editions:

http://technet.microsoft.com/en-us/library/cc280386.aspx

Multiple files upload (Array) with CodeIgniter 2.0

I have used below code in my custom library
call that from my controller like below,

function __construct() {<br />
   &nbsp;&nbsp;&nbsp; parent::__construct();<br />
   &nbsp;&nbsp;&nbsp;   $this->load->library('CommonMethods');<br />
}<br />

$config = array();<br />
$config['upload_path'] = 'assets/upload/images/';<br />
$config['allowed_types'] = 'gif|jpg|png|jpeg';<br />
$config['max_width'] = 150;<br />
$config['max_height'] = 150;<br />
$config['encrypt_name'] = TRUE;<br />
$config['overwrite'] = FALSE;<br />

// upload multiplefiles<br />
$fileUploadResponse = $this->commonmethods->do_upload_multiple_files('profile_picture', $config);

/**
 * do_upload_multiple_files - Multiple Methods
 * @param type $fieldName
 * @param type $options
 * @return type
 */
public function do_upload_multiple_files($fieldName, $options) {

    $response = array();
    $files = $_FILES;
    $cpt = count($_FILES[$fieldName]['name']);
    for($i=0; $i<$cpt; $i++)
    {           
        $_FILES[$fieldName]['name']= $files[$fieldName]['name'][$i];
        $_FILES[$fieldName]['type']= $files[$fieldName]['type'][$i];
        $_FILES[$fieldName]['tmp_name']= $files[$fieldName]['tmp_name'][$i];
        $_FILES[$fieldName]['error']= $files[$fieldName]['error'][$i];
        $_FILES[$fieldName]['size']= $files[$fieldName]['size'][$i];    

        $this->CI->load->library('upload');
        $this->CI->upload->initialize($options);

        //upload the image
        if (!$this->CI->upload->do_upload($fieldName)) {
            $response['erros'][] = $this->CI->upload->display_errors();
        } else {
            $response['result'][] = $this->CI->upload->data();
        }
    }

    return $response;
}

How to remove/ignore :hover css style on touch devices

If Your issue is when you touch/tap on android and whole div covered by blue transparent color! Then you need to just change the

CURSOR : POINTER; to CURSOR : DEFAULT;

use mediaQuery to hide in mobile phone/Tablet.

This works for me.

How to set specific window (frame) size in java swing?

Well, you are using both frame.setSize() and frame.pack().

You should use one of them at one time.

Using setSize() you can give the size of frame you want but if you use pack(), it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.

Try removing frame.pack() from your code or putting it before setting size and then run it.

Opening a .ipynb.txt File

If you have a unix/linux system I'd just rename the file via command line

mv file_name.pynb.txt file_name.ipynb

worked like a charm for me!

How to clear Facebook Sharer cache?

The page to do this is at https://developers.facebook.com/tools/debug/ and has changed slightly since some of the other answers.

Paste your URL in there and hit "Debug". Then hit the "Fetch new scrape information" button under the URL text field and you should be all set. It'll pull the fresh meta tags from your page, but they'll still cache so keep in mind you'll need to do this whenever you change them. This is really critical if you are playing with the meta tags to get FB Shared URLs to format the way you want them to inside of facebook.

error C4996: 'scanf': This function or variable may be unsafe in c programming

You can add "_CRT_SECURE_NO_WARNINGS" in Preprocessor Definitions.

Right-click your project->Properties->Configuration Properties->C/C++ ->Preprocessor->Preprocessor Definitions.

enter image description here

How to store phone numbers on MySQL databases?

I would recommend storing these as numbers in columns of type varchar - one column per "field" (like contry code etc.).

The format should be applied when you interact with a user... that makes it easier to account for format changes for example and will help esp. when your application goes international...

What is the meaning of {...this.props} in Reactjs

It is ES-6 feature. It means you extract all the properties of props in div.{... }

operator is used to extract properties of an object.

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

Using Let's Encrypt certificates

Assuming you've created your certificates and private keys with Let's Encrypt in /etc/letsencrypt/live/you.com:

1. Create a PKCS #12 file

openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out pkcs.p12 \
        -name letsencrypt

This combines your SSL certificate fullchain.pem and your private key privkey.pem into a single file, pkcs.p12.

You'll be prompted for a password for pkcs.p12.

The export option specifies that a PKCS #12 file will be created rather than parsed (according to the manual).

2. Create the Java keystore

keytool -importkeystore -destkeystore keystore.jks -srckeystore pkcs.p12 \
        -srcstoretype PKCS12 -alias letsencrypt

If keystore.jks doesn't exist, it will be created containing the pkcs.12 file created above. Otherwise, you'll import pkcs.12 into the existing keystore.


These instructions are derived from the post "Create a Java Keystore (.JKS) from Let's Encrypt Certificates" on this blog.

Here's more on the different kind of files in /etc/letsencrypt/live/you.com/.

jQuery ajax upload file in asp.net mvc

AJAX file uploads are now possible by passing a FormData object to the data property of the $.ajax request.

As the OP specifically asked for a jQuery implementation, here you go:

<form id="upload" enctype="multipart/form-data" action="@Url.Action("JsonSave", "Survey")" method="POST">
    <input type="file" name="fileUpload" id="fileUpload" size="23" /><br />
    <button>Upload!</button>
</form>
$('#upload').submit(function(e) {
    e.preventDefault(); // stop the standard form submission

    $.ajax({
        url: this.action,
        type: this.method,
        data: new FormData(this),
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
        },
        error: function(xhr, error, status) {
            console.log(error, status);
        }
    });
});
public JsonResult Survey()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        var file = Request.Files[i];
        // save file as required here...
    }
    return Json(new { UploadedFileCount = Request.Files.Count });
}

More information on FormData at MDN

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

Here are more code examples that will produce the argument null exception:

List<Myobj> myList = null;
//from this point on, any linq statement you perform on myList will throw an argument null exception
myList.ToList();
myList.GroupBy(m => m.Id);
myList.Count();
myList.Where(m => m.Id == 0);
myList.Select(m => m.Id == 0);
//etc...

Reading Email using Pop3 in C#

My open source application BugTracker.NET includes a POP3 client that can parse MIME. Both the POP3 code and the MIME code are from other authors, but you can see how it all fits together in my app.

For the MIME parsing, I use http://anmar.eu.org/projects/sharpmimetools/.

See the file POP3Main.cs, POP3Client.cs, and insert_bug.aspx

SQLiteDatabase.query method

db.query(
        TABLE_NAME,
        new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO },
        TABLE_ROW_ID + "=" + rowID,
        null, null, null, null, null
);

TABLE_ROW_ID + "=" + rowID, here = is the where clause. To select all values you will have to give all column names:

or you can use a raw query like this 
db.rawQuery("SELECT * FROM permissions_table WHERE name = 'Comics' ", null);

and here is a good tutorial for database.

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

Are you sure you are on the local an-other-branch when you merge?

git fetch origin an-other-branch
git checkout an-other-branch
git merge origin/an-other-branch

The other explanation:

all the changes from the branch you’re trying to merge have already been merged to the branch you’re currently on.
More specifically it means that the branch you’re trying to merge is a parent of your current branch

if you're ahead of the remote repo by one commit, it's the remote repo that's out of date, not you.

But in your case, if git pull works, that just means you are not on the right branch.

How to retrieve element value of XML using Java?

If you are just looking to get a single value from the XML you may want to use Java's XPath library. For an example see my answer to a previous question:

It would look something like:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

    public static void main(String[] args) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document dDoc = builder.parse("E:/test.xml");

            XPath xPath = XPathFactory.newInstance().newXPath();
            Node node = (Node) xPath.evaluate("/Request/@name", dDoc, XPathConstants.NODE);
            System.out.println(node.getNodeValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Finding what branch a Git commit came from

A poor man's option is to use the tool tig1 on HEAD, search for the commit, and then visually follow the line from that commit back up until a merge commit is seen. The default merge message should specify what branch is getting merged to where :)

1 Tig is an ncurses-based text-mode interface for Git. It functions mainly as a Git repository browser, but it can also assist in staging changes for commit at chunk level and act as a pager for output from various Git commands.

Linux command to print directory structure in the form of a tree

Since it was a successful comment, I am adding it as an answer:
with files:

 find . | sed -e "s/[^-][^\/]*\//  |/g" -e "s/|\([^ ]\)/|-\1/" 

Get all column names of a DataTable into string array using (LINQ/Predicate)

I'd suggest using such extension method:

public static class DataColumnCollectionExtensions
{
    public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
    {
        return source.Cast<DataColumn>();
    }
}

And therefore:

string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();

You may also implement one more extension method for DataTable class to reduce code:

public static class DataTableExtensions
{
    public static IEnumerable<DataColumn> GetColumns(this DataTable source)
    {
        return source.Columns.AsEnumerable();
    }
}

And use it as follows:

string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();

How to implement the --verbose or -v option into a script?

@kindall's solution does not work with my Python version 3.5. @styles correctly states in his comment that the reason is the additional optional keywords argument. Hence my slightly refined version for Python 3 looks like this:

if VERBOSE:
    def verboseprint(*args, **kwargs):
        print(*args, **kwargs)
else:
    verboseprint = lambda *a, **k: None # do-nothing function

How to iterate over a JavaScript object?

Really a PITA this is not part of standard Javascript.

/**
 * Iterates the keys and values of an object.  Object.keys is used to extract the keys.
 * @param object The object to iterate
 * @param fn (value,key)=>{}
 */
function objectForEach(object, fn) {
    Object.keys(object).forEach(key => {
        fn(object[key],key, object)
    })
}

Note: I switched the callback parameters to (value,key) and added a third object to make the API consistent other APIs.

Use it like this

const o = {a:1, b:true};
objectForEach(o, (value, key, obj)=>{
    // do something
});

Java 6 Unsupported major.minor version 51.0

I face the same problem and solved by adding the JAVA_HOME variable with updated version of java in my Ubuntu Machine(16.04). if you are using "Apache Maven 3.3.9" You need to upgrade your JAVA_HOME with java7 or more

Step to Do this

1-sudo vim /etc/environment

2-JAVA_HOME=JAVA Installation Directory (MyCase-/opt/dev/jdk1.7.0_45/)

3-Run echo $JAVA_HOME will give the JAVA_HOME set value

4-Now mvn -version will give the desired output

Apache Maven 3.3.9

Maven home: /usr/share/maven

Java version: 1.7.0_45, vendor: Oracle Corporation

Java home: /opt/dev/jdk1.7.0_45/jre

Default locale: en_US, platform encoding: UTF-8

OS name: "linux", version: "4.4.0-36-generic", arch: "amd64", family: "unix"

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

This should also do the job but this is across SQL and not postgres specific.

select avg(cast(mynumber as numeric)) from my table

Class 'ViewController' has no initializers in swift

I use Xcode 7 and Swift 2. Last, I had made:

class ViewController: UIViewController{ var time: NSTimer //error this here }

Then I fix: class ViewController: UIViewController {

var time: NSTimer!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

override func viewWillAppear(animated: Bool) {
    //self.movetoHome()
    time = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(ViewController.movetoHome), userInfo: nil, repeats: false)
    //performSegueWithIdentifier("MoveToHome", sender: self)
    //presentViewController(<#T##viewControllerToPresent: UIViewController##UIViewController#>, animated: <#T##Bool#>, completion: <#T##(() -> Void)?##(() -> Void)?##() -> Void#>)
}

func movetoHome(){
    performSegueWithIdentifier("MoveToHome", sender: self)
}

}

Resetting a form in Angular 2 after submit

For Angular 2 Final, we now have a new API that cleanly resets the form:

@Component({...})
class App {

    form: FormGroup;
     ...
    reset() {
       this.form.reset();
   }
}

This API not only resets the form values, but also sets the form field states back to ng-pristine and ng-untouched.

Pandas split DataFrame by column value

You can use boolean indexing:

df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
   A  Sales
0  3     10
1  4     20
2  7     30
3  6     40
4  1     50

s = 30

df1 = df[df['Sales'] >= s]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

df2 = df[df['Sales'] < s]
print (df2)
   A  Sales
0  3     10
1  4     20

It's also possible to invert mask by ~:

mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

print (df2)
   A  Sales
0  3     10
1  4     20

print (mask)
0    False
1    False
2     True
3     True
4     True
Name: Sales, dtype: bool

print (~mask)
0     True
1     True
2    False
3    False
4    False
Name: Sales, dtype: bool

PostgreSQL psql terminal command

These are not command line args. Run psql. Manage to log into database (so pass the hostname, port, user and database if needed). And then write it in the psql program.

Example (below are two commands, write the first one, press enter, wait for psql to login, write the second):

psql -h host -p 5900 -U username database
\pset format aligned

Show Image View from file path?

You can use:

ImageView imgView = new ImageView(this);
InputStream is = getClass().getResourceAsStream("/drawable/" + fileName);
imgView.setImageDrawable(Drawable.createFromStream(is, ""));

From Arraylist to Array

assuming v is a ArrayList:

String[] x = (String[]) v.toArray(new String[0]);

Create a simple HTTP server with Java?

I have implemented one link

N.B. for processing json, i used jackson. You can remove that also, if you need

HQL "is null" And "!= null" on an Oracle column

That is a binary operator in hibernate you should use

is not null

Have a look at 14.10. Expressions

Find methods calls in Eclipse project

Go to the method in X.java, and select Open Call Hierarchy from the context menu.

jQuery: set selected value of dropdown list?

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

php $_POST array empty upon form submission

OK, I thought that I should put my case here .... I was getting the post array empty in specific cases .. The form works well, but some times users complain that they hit submit button, and nothing happens ..... After digging for a while, I discovered that my hosting company has a security module that checks users inputs and clears the whole post array (not only the malicious data) if it discovers so. In my example, a math teacher was trying to enter the equation: dy + dx + 0 = 0; and data was wiped completely.

To fix this, I just advise him now to enter the data in the text area as dy + dx + 0 = zero, and now it works .... This can save someone some time ..

PHP - Insert date into mysql

$date=$year."-".$month."-".$day; 
$new_date=date('Y-m-d', strtotime($dob)); 
$status=0;  
$insert_date = date("Y-m-d H:i:s");  
$latest_insert_id=0; 

$insertSql="insert into participationDetail (formId,name,city,emailId,dob,mobile,status,social_media1,social_media2,visa_status,tnc_status,data,gender,insertDate)values('".$formid."','".$name."','".$city."','".$email."','".$new_date."','".$mobile."','".$status."','".$link1."','".$link2."','".$visa_check."','".$tnc_check."','".json_encode($detail_arr,JSON_HEX_APOS)."','".$gender."','".$insert_date."')";

Determine version of Entity Framework I am using?

If you open the references folder and locate system.data.entity, click the item, then check the runtime version number in the Properties explorer, you will see the sub version as well. Mine for instance shows v4.0.30319 with the Version property showing 4.0.0.0.

How to use a SQL SELECT statement with Access VBA

Access 2007 can lose the CurrentDb: see http://support.microsoft.com/kb/167173, so in the event of getting "Object Invalid or no longer set" with the examples, use:

Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")

Add Text on Image using PIL

To add text on an image file, just copy/paste the code below

<?php
$source = "images/cer.jpg";
$image = imagecreatefromjpeg($source);
$output = "images/certificate".rand(1,200).".jpg";
$white = imagecolorallocate($image,255,255,255);
$black = imagecolorallocate($image,7,94,94);
$font_size = 30;
$rotation = 0;
$origin_x = 250;
$origin_y = 450;
$font = __DIR__ ."/font/Roboto-Italic.ttf";
$text = "Dummy";
$text1 = imagettftext($image,$font_size,$rotation,$origin_x,$origin_y,$black,$font,$text);
     imagejpeg($image,$output,99);
?> <img src="<?php echo $output; ?>"> <a href="<?php echo $output;    ?>" download="<?php echo $output; ?>">Download Certificate</a>

NSArray + remove item from array

Here's a more functional approach using Key-Value Coding:

@implementation NSArray (Additions)

- (instancetype)arrayByRemovingObject:(id)object {
    return [self filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != %@", object]];
}

@end

How to do Select All(*) in linq to sql

Do you want to select all rows or all columns?

Either way, you don't actually need to do anything.

The DataContext has a property for each table; you can simply use that property to access the entire table.

For example:

foreach(var line in context.Orders) {
    //Do something
}

Length of string in bash

You can use:

MYSTRING="abc123"
MYLENGTH=$(printf "%s" "$MYSTRING" | wc -c)
  • wc -c or wc --bytes for byte counts = Unicode characters are counted with 2, 3 or more bytes.
  • wc -m or wc --chars for character counts = Unicode characters are counted single until they use more bytes.

Create a file from a ByteArrayOutputStream

You can do it with using a FileOutputStream and the writeTo method.

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
    byteArrayOutputStream.writeTo(outputStream);
}

Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions

Business logic in MVC

It does not make sense to put your business layer in the Model for an MVC project.

Say that your boss decides to change the presentation layer to something else, you would be screwed! The business layer should be a separate assembly. A Model contains the data that comes from the business layer that passes to the view to display. Then on post for example, the model binds to a Person class that resides in the business layer and calls PersonBusiness.SavePerson(p); where p is the Person class. Here's what I do (BusinessError class is missing but would go in the BusinessLayer too):enter image description here

ReactJS: Maximum update depth exceeded error

I know this has plenty of answers but since most of them are old (well, older), none is mentioning approach I grow very fond of really quick. In short:

Use functional components and hooks.

In longer:

Try to use as much functional components instead class ones especially for rendering, AND try to keep them as pure as possible (yes, data is dirty by default I know).

Two bluntly obvious benefits of functional components (there are more):

  • Pureness or near pureness makes debugging so much easier
  • Functional components remove the need for constructor boiler code

Quick proof for 2nd point - Isn't this absolutely disgusting?

constructor(props) {
        super(props);     
        this.toggle= this.toggle.bind(this);
        this.state = {
            details: false
        } 
    }  

If you are using functional components for more then rendering you are gonna need the second part of great duo - hooks. Why are they better then lifecycle methods, what else can they do and much more would take me a lot of space to cover so I recommend you to listen to the man himself: Dan preaching the hooks

In this case you need only two hooks:

A callback hook conveniently named useCallback. This way you are preventing the binding the function over and over when you re-render.

A state hook, called useState, for keeping the state despite entire component being function and executing in its entirety (yes, this is possible due to magic of hooks). Within that hook you will store the value of toggle.

If you read to this part you probably wanna see all I have talked about in action and applied to original problem. Here you go: Demo

For those of you that want only to glance the component and WTF is this about, here you are:

const Item = () => {

    // HOOKZ
  const [isVisible, setIsVisible] = React.useState('hidden');

  const toggle = React.useCallback(() => {
    setIsVisible(isVisible === 'visible' ? 'hidden': 'visible');
  }, [isVisible, setIsVisible]);

    // RENDER
  return (
  <React.Fragment>
    <div style={{visibility: isVisible}}>
        PLACEHOLDER MORE INFO
    </div>
    <button onClick={toggle}>Details</button>
  </React.Fragment>
  )
};

PS: I wrote this in case many people land here with similar problem. Hopefully, they will like what I have shown here, at least well enough to google it a bit more. This is NOT me saying other answers are wrong, this is me saying that since the time they have been written, there is another way (IMHO, a better one) of dealing with this.

How to lookup JNDI resources on WebLogic?

I had a similar problem to this one. It got solved by deleting the java:comp/env/ prefix and using jdbc/myDataSource in the context lookup. Just as someone pointed out in the comments.