Programs & Examples On #Anti piracy

How are software license keys generated?

When I originally wrote this answer it was under an assumption that the question was regarding 'offline' validation of licence keys. Most of the other answers address online verification, which is significantly easier to handle (most of the logic can be done server side).

With offline verification the most difficult thing is ensuring that you can generate a huge number of unique licence keys, and still maintain a strong algorithm that isnt easily compromised (such as a simple check digit)

I'm not very well versed in mathematics, but it struck me that one way to do this is to use a mathematical function that plots a graph

The plotted line can have (if you use a fine enough frequency) thousands of unique points, so you can generate keys by picking random points on that graph and encoding the values in some way

enter image description here

As an example, we'll plot this graph, pick four points and encode into a string as "0,-500;100,-300;200,-100;100,600"

We'll encrypt the string with a known and fixed key (horribly weak, but it serves a purpose), then convert the resulting bytes through Base32 to generate the final key

The application can then reverse this process (base32 to real number, decrypt, decode the points) and then check each of those points is on our secret graph.

Its a fairly small amount of code which would allow for a huge number of unique and valid keys to be generated

It is however very much security by obscurity. Anyone taking the time to disassemble the code would be able to find the graphing function and encryption keys, then mock up a key generator, but its probably quite useful for slowing down casual piracy.

List of macOS text editors and code editors

I purchased Textmate because I liked it so much, one of the few apps I paid for. Other editors are just not worth it. If you are going for an IDE, eclipse or netbeans are great and free.

bootstrap 3 navbar collapse button not working

In my case the issue was due to how I build my Nav bar. I was doing it through a jQuery plugin so I can quickly build Bootstrap components through javascript.

To cut a long story short binding the data elements of the button through jQuery .data() resulted in a collapse button that didn't work, doing it via .attr() fixed the issue.

This doesn't work:

$this.addClass("navbar navbar-default")
  .append($("<div />").addClass("container-fluid")
    .append($("<div />").addClass("navbar-header")
      .append($("<button />").addClass("navbar-toggle collapsed")
        .attr("type","button")
        .attr("aria-expanded", "false")
        .data("target","#" + id)
        .data("toggle","collapse")
        .html("<span class='sr-only'>Toggle navigation</span>"
            + "<span class='icon-bar'></span>"
            + "<span class='icon-bar'></span>"
            + "<span class='icon-bar'></span>"))
        .append($("<a href='#' />").addClass("navbar-brand")
          .append(document.createTextNode(settings.label))))
    .append($("<div />").addClass("collapse navbar-collapse").attr("id",id)));

But this does (with the changes left in comments):

$this.addClass("navbar navbar-default")
  .append($("<div />").addClass("container-fluid")
    .append($("<div />").addClass("navbar-header")
      .append($("<button />").addClass("navbar-toggle collapsed")
        .attr("type","button")
        .attr("aria-expanded", "false")
        .attr("data-target", "#" + id) //.data("target","#" + id)
        .attr("data-toggle", "collapse") // .data("toggle","collapse")
        .html("<span class='sr-only'>Toggle navigation</span>"
            + "<span class='icon-bar'></span>"
            + "<span class='icon-bar'></span>"
            + "<span class='icon-bar'></span>"))
        .append($("<a href='#' />").addClass("navbar-brand")
          .append(document.createTextNode(settings.label))))
    .append($("<div />").addClass("collapse navbar-collapse").attr("id",id)));

I can only assume that this is related to the way jQuery binds .data(), it doesn't write the attributes out to the elements, but just attaches them to the jQuery object. Using the .data() version resulted in HTML:

<button class="navbar-toggle collapsed" aria-expanded="false" type="button" >

Where as the .attr() version gives:

<button class="navbar-toggle collapsed" aria-expanded="false" type="button" data-toggle="collapse" data-target="#6a2034fe-8922-4edd-920e-6bd0ea0b2caf">

It seems that Bootstrap needs the data-nnn attribute in the HTML.

Load image with jQuery and append it to the DOM

With jQuery 3.x use something like:

$('<img src="'+ imgPath +'">').on('load', function() {
  $(this).width(some).height(some).appendTo('#some_target');
});

How can I get a value from a map?

map.at("key") throws exception if missing key

If k does not match the key of any element in the container, the function throws an out_of_range exception.

http://www.cplusplus.com/reference/map/map/at/

HTML form input tag name element array with JavaScript

1.) First off, what is the correct terminology for an array created on the end of the name element of an input tag in a form?

"Oftimes Confusing PHPism"

As far as JavaScript is concerned a bunch of form controls with the same name are just a bunch of form controls with the same name, and form controls with names that include square brackets are just form controls with names that include square brackets.

The PHP naming convention for form controls with the same name is sometimes useful (when you have a number of groups of controls so you can do things like this:

<input name="name[1]">
<input name="email[1]">
<input name="sex[1]" type="radio" value="m">
<input name="sex[1]" type="radio" value="f">

<input name="name[2]">
<input name="email[2]">
<input name="sex[2]" type="radio" value="m">
<input name="sex[2]" type="radio" value="f">

) but does confuse some people. Some other languages have adopted the convention since this was originally written, but generally only as an optional feature. For example, via this module for JavaScript.

2.) How do I get the information from that array with JavaScript?

It is still just a matter of getting the property with the same name as the form control from elements. The trick is that since the name of the form controls includes square brackets, you can't use dot notation and have to use square bracket notation just like any other JavaScript property name that includes special characters.

Since you have multiple elements with that name, it will be a collection rather then a single control, so you can loop over it with a standard for loop that makes use of its length property.

var myForm = document.forms.id_of_form;
var myControls = myForm.elements['p_id[]'];
for (var i = 0; i < myControls.length; i++) {
    var aControl = myControls[i];
}

Multiple values in single-value context

No, you cannot directly access the first value.

I suppose a hack for this would be to return an array of values instead of "item" and "err", and then just do item, _ := Get(1)[0] but I would not recommend this.

Jquery Ajax, return success/error from mvc.net controller

Use Json class instead of Content as shown following:

    //  When I want to return an error:
    if (!isFileSupported)
    {
        Response.StatusCode = (int) HttpStatusCode.BadRequest;
        return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
    }
    else
    {
        //  When I want to return sucess:
        Response.StatusCode = (int)HttpStatusCode.OK; 
        return Json("Message sent!", MediaTypeNames.Text.Plain);
    }

Also set contentType:

contentType: 'application/json; charset=utf-8',

JavaScript: Object Rename Key

Your way is optimized, in my opinion. But you will end up with reordered keys. Newly created key will be appended at the end. I know you should never rely on key order, but if you need to preserve it, you will need to go through all keys and construct new object one by one, replacing the key in question during that process.

Like this:

var new_o={};
for (var i in o)
{
   if (i==old_key) new_o[new_key]=o[old_key];
   else new_o[i]=o[i];
}
o=new_o;

What is the Windows equivalent of the diff command?

Well, on Windows I happily run diff and many other of the GNU tools. You can do it with cygwin, but I personally prefer GnuWin32 because it is a much lighter installation experience.

So, my answer is that the Windows equivalent of diff, is none other than diff itself!

How to POST a FORM from HTML to ASPX page

The Request.Form.Keys collection will be empty if none of your html inputs have NAMEs. It's easy to forget to put them there after you've been doing .NET for a while. Just name them and you'll be good to go.

How to force Sequential Javascript Execution?

Well, setTimeout, per its definition, will not hold up the thread. This is desirable, because if it did, it'd freeze the entire UI for the time it was waiting. if you really need to use setTimeout, then you should be using callback functions:

function myfunction() {
    longfunctionfirst(shortfunctionsecond);
}

function longfunctionfirst(callback) {
    setTimeout(function() {
        alert('first function finished');
        if(typeof callback == 'function')
            callback();
    }, 3000);
};

function shortfunctionsecond() {
    setTimeout('alert("second function finished");', 200);
};

If you are not using setTimeout, but are just having functions that execute for very long, and were using setTimeout to simulate that, then your functions would actually be synchronous, and you would not have this problem at all. It should be noted, though, that AJAX requests are asynchronous, and will, just as setTimeout, not hold up the UI thread until it has finished. With AJAX, as with setTimeout, you'll have to work with callbacks.

How do I create a right click context menu in Java Swing?

There's a section on Bringing Up a Popup Menu in the How to Use Menus article of The Java Tutorials which explains how to use the JPopupMenu class.

The example code in the tutorial shows how to add MouseListeners to the components which should display a pop-up menu, and displays the menu accordingly.

(The method you describe is fairly similar to the way the tutorial presents the way to show a pop-up menu on a component.)

Insert node at a certain position in a linked list C++

For inserting at a particular position k, you need to traverse the list till the position k-1 and then do the insert.

[You need not create a new node to traverse to that position as you did in your code] You should traverse from the head node.

Synchronous request in Node.js

I'd use a recursive function with a list of apis

var APIs = [ '/api_1.php', '/api_2.php', '/api_3.php' ];
var host = 'www.example.com';

function callAPIs ( host, APIs ) {
  var API = APIs.shift();
  http.get({ host: host, path: API }, function(res) { 
    var body = '';
    res.on('data', function (d) {
      body += d; 
    });
    res.on('end', function () {
      if( APIs.length ) {
        callAPIs ( host, APIs );
      }
    });
  });
}

callAPIs( host, APIs );

edit: request version

var request = require('request');
var APIs = [ '/api_1.php', '/api_2.php', '/api_3.php' ];
var host = 'www.example.com';
var APIs = APIs.map(function (api) {
  return 'http://' + host + api;
});

function callAPIs ( host, APIs ) {
  var API = APIs.shift();
  request(API, function(err, res, body) { 
    if( APIs.length ) {
      callAPIs ( host, APIs );
    }
  });
}

callAPIs( host, APIs );

edit: request/async version

var request = require('request');
var async = require('async');
var APIs = [ '/api_1.php', '/api_2.php', '/api_3.php' ];
var host = 'www.example.com';
var APIs = APIs.map(function (api) {
  return 'http://' + host + api;
});

async.eachSeries(function (API, cb) {
  request(API, function (err, res, body) {
    cb(err);
  });
}, function (err) {
  //called when all done, or error occurs
});

android.view.InflateException: Binary XML file: Error inflating class fragment

I couldn't solve my problem using provided answers. Finally I changed this:

<fragment
android:id="@+id/fragment_food_image_gallery"
android:name="ir.smartrestaurant.ui.fragment.ImageGalleryFragment"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout="@layout/fragment_image_gallery"
tools:layout="@layout/fragment_image_gallery" />

to this :

<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="200dp" />

,

private void showGallery() {
    ImageGalleryFragment fragment = new ImageGalleryFragment()
    getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment)
                .commit();
    }

and it works.
If you are using it inside fragment, use getChildFragmentManager instead of getSupportFragmentManager.

Remove all HTMLtags in a string (with the jquery text() function)

If you need to remove the HTML but does not know if it actually contains any HTML tags, you can't use the jQuery method directly because it returns empty wrapper for non-HTML text.

$('<div>Hello world</div>').text(); //returns "Hello world"
$('Hello world').text(); //returns empty string ""

You must either wrap the text in valid HTML:

$('<div>' + 'Hello world' + '</div>').text();

Or use method $.parseHTML() (since jQuery 1.8) that can handle both HTML and non-HTML text:

var html = $.parseHTML('Hello world'); //parseHTML return HTMLCollection
var text = $(html).text(); //use $() to get .text() method

Plus parseHTML removes script tags completely which is useful as anti-hacking protection for user inputs.

$('<p>Hello world</p><script>console.log(document.cookie)</script>').text();
//returns "Hello worldconsole.log(document.cookie)"

$($.parseHTML('<p>Hello world</p><script>console.log(document.cookie)</script>')).text();
//returns "Hello world"

User Get-ADUser to list all properties and export to .csv

@AnsgarWiechers - it's not my experience that querying everything and then pruning the result is more efficient when you're doing a targeted search of known accounts. Although, yes, it is also more efficient to select just the properties you need to return.

The below examples are based on a domain in the range of 20,000 account objects.

measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st }
...
Seconds           : 16
Milliseconds      : 208

measure-command {$userlist | get-aduser -Properties DisplayName,st}
...
Seconds           : 3
Milliseconds      : 496

In the second example, $userlist contains 368 account names (just strings, not pre-fetched account objects).

Note that if I include the where clause per your suggestion to prune to the actually desired results, it's even more expensive.

measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st |where {$userlist -Contains $_.samaccountname } }
...
Seconds           : 17
Milliseconds      : 876

Indexed attributes seem to have similar performance (I tried just returning displayName).

Even if I return all user account properties in my set, it's more efficient. (Adding a select statement to the below brings it down by a half-second).

measure-command {$userlist | get-aduser -Properties *}
...
Seconds           : 12
Milliseconds      : 75

I can't find a good document that was written in ye olde days about AD queries to link to, but you're hitting every account in your search scope to return the properties. This discusses the basics of doing effective AD queries - scoping and filtering: https://msdn.microsoft.com/en-us/library/ms808539.aspx#efficientadapps_topic01

When your search scope is "*", you're still building a (big) list of the objects and iterating through each one. An LDAP search filter is always more efficient to build the list first (or a narrow search base, which is again building a smaller list to query).

Running Java Program from Command Line Linux

If your Main class is in a package called FileManagement, then try:

java -cp . FileManagement.Main

in the parent folder of the FileManagement folder.

If your Main class is not in a package (the default package) then cd to the FileManagement folder and try:

java -cp . Main

More info about the CLASSPATH and how the JRE find classes:

How to include a PHP variable inside a MySQL statement

That's the easy answer:

$query="SELECT * FROM CountryInfo WHERE Name = '".$name."'";

and you define $name whatever you want.
And another way, the complex way, is like that:

$query = " SELECT '" . $GLOBALS['Name'] . "' .* " .
         " FROM CountryInfo " .
         " INNER JOIN District " .
         " ON District.CountryInfoId = CountryInfo.CountryInfoId " .
         " INNER JOIN City " .
         " ON City.DistrictId = District.DistrictId " .
         " INNER JOIN '" . $GLOBALS['Name'] . "' " .
         " ON '" . $GLOBALS['Name'] . "'.CityId = City.CityId " .
         " WHERE CountryInfo.Name = '" . $GLOBALS['CountryName'] .
         "'";

How to plot all the columns of a data frame in R

I'm surprised that no one mentioned matplot. It's pretty convenient in case you don't need to plot each line in separate axes. Just one command:

matplot(y = data, type = 'l', lty = 1)

Use ?matplot to see all the options.

To add the legend, you can set color palette and then add it:

mypalette = rainbow(ncol(data))
matplot(y = data, type = 'l', lty = 1, col = mypalette)
legend(legend = colnames(data), x = "topright", y = "topright", lty = 1, lwd = 2, col = mypalette)

Read a file in Node.js

Use path.join(__dirname, '/start.html');

var fs = require('fs'),
    path = require('path'),    
    filePath = path.join(__dirname, 'start.html');

fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
    if (!err) {
        console.log('received data: ' + data);
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write(data);
        response.end();
    } else {
        console.log(err);
    }
});

Android Studio Google JAR file causing GC overhead limit exceeded error

Android Studio 3.5.3

Find the Memory Settings (Cmd + Shift + A on Mac or click on Help and start typing "Memory Settings") under Preferences/ Settings and increase the IDE Heap Size and/ or the Daemon Heap Size to your satisfaction enter image description here

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

The request header contains some POST data. No matter what you do, when you reload the page, the rquest would be sent again.

The simple solution is to redirect to a new (if not the same) page. This pattern is very common in web applications, and is called Post/Redirect/Get. It's typical for all forms to do a POST, then if successful, you should do a redirect.

Try as much as possible to always separate (in different files) your view script (html mostly) from your controller script (business logic and stuff). In this way, you would always post data to a seperate controller script and then redirect back to a view script which when rendered, will contain no POST data in the request header.

Check if cookies are enabled

Answer on an old question, this new post is posted on April the 4th 2013

To complete the answer of @misza, here a advanced method to check if cookies are enabled without page reloading. The problem with @misza is that it not always work when the php ini setting session.use_cookies is not true. Also the solution does not check if a session is already started.

I made this function and test it many times with in different situations and does the job very well.

    function suGetClientCookiesEnabled() // Test if browser has cookies enabled
    {
      // Avoid overhead, if already tested, return it
      if( defined( 'SU_CLIENT_COOKIES_ENABLED' ))
       { return SU_CLIENT_COOKIES_ENABLED; }

      $bIni = ini_get( 'session.use_cookies' ); 
      ini_set( 'session.use_cookies', 1 ); 

      $a = session_id();
      $bWasStarted = ( is_string( $a ) && strlen( $a ));
      if( !$bWasStarted )
      {
        @session_start();
        $a = session_id();
      }

   // Make a copy of current session data
  $aSesDat = (isset( $_SESSION ))?$_SESSION:array();
   // Now we destroy the session and we lost the data but not the session id 
   // when cookies are enabled. We restore the data later. 
  @session_destroy(); 
   // Restart it
  @session_start();

   // Restore copy
  $_SESSION = $aSesDat;

   // If no cookies are enabled, the session differs from first session start
  $b = session_id();
  if( !$bWasStarted )
   { // If not was started, write data to the session container to avoid data loss
     @session_write_close(); 
   }

   // When no cookies are enabled, $a and $b are not the same
  $b = ($a === $b);
  define( 'SU_CLIENT_COOKIES_ENABLED', $b );

  if( !$bIni )
   { @ini_set( 'session.use_cookies', 0 ); }

  //echo $b?'1':'0';
  return $b;
    }

Usage:

if( suGetClientCookiesEnabled())
 { echo 'Cookies are enabled!'; }
else { echo 'Cookies are NOT enabled!'; }

Important note: The function temporarily modify the ini setting of PHP when it not has the correct setting and restore it when it was not enabled. This is only to test if cookies are enabled. It can get go wrong when you start a session and the php ini setting session.use_cookies has an incorrect value. To be sure that the session is working correctly, check and/or set it before start a session, for example:

   if( suGetClientCookiesEnabled())
     { 
       echo 'Cookies are enabled!'; 
       ini_set( 'session.use_cookies', 1 ); 
       echo 'Starting session';
       @start_session(); 

     }
    else { echo 'Cookies are NOT enabled!'; }

SQL LEFT JOIN Subquery Alias

You didn't select post_id in the subquery. You have to select it in the subquery like this:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 

How do I make an html link look like a button?

Much belated answer:

I've been wrestling with this on and off since I first started working in ASP. Here's the best I've come up with:

Concept: I create a custom control that has a tag. Then in the button I put an onclick event that sets document.location to the desired value with JavaScript.

I called the control ButtonLink, so that I could easily get if confused with LinkButton.

aspx:

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="ButtonLink.ascx.vb" Inherits="controls_ButtonLink" %>

<asp:Button runat="server" ID="button"/>

code behind:

Partial Class controls_ButtonLink
Inherits System.Web.UI.UserControl

Dim _url As String
Dim _confirm As String

Public Property NavigateUrl As String
    Get
        Return _url
    End Get
    Set(value As String)
        _url = value
        BuildJs()
    End Set
End Property
Public Property confirm As String
    Get
        Return _confirm
    End Get
    Set(value As String)
        _confirm = value
        BuildJs()
    End Set
End Property
Public Property Text As String
    Get
        Return button.Text
    End Get
    Set(value As String)
        button.Text = value
    End Set
End Property
Public Property enabled As Boolean
    Get
        Return button.Enabled
    End Get
    Set(value As Boolean)
        button.Enabled = value
    End Set
End Property
Public Property CssClass As String
    Get
        Return button.CssClass
    End Get
    Set(value As String)
        button.CssClass = value
    End Set
End Property

Sub BuildJs()
    ' This is a little kludgey in that if the user gives a url and a confirm message, we'll build the onclick string twice.
    ' But it's not that big a deal.
    If String.IsNullOrEmpty(_url) Then
        button.OnClientClick = Nothing
    ElseIf String.IsNullOrEmpty(_confirm) Then
        button.OnClientClick = String.Format("document.location='{0}';return false;", ResolveClientUrl(_url))
    Else
        button.OnClientClick = String.Format("if (confirm('{0}')) {{document.location='{1}';}} return false;", _confirm, ResolveClientUrl(_url))
    End If
End Sub
End Class

Advantages of this scheme: It looks like a control. You write a single tag for it, <ButtonLink id="mybutton" navigateurl="blahblah"/>

The resulting button is a "real" HTML button and so looks just like a real button. You don't have to try to simulate the look of a button with CSS and then struggle with different looks on different browsers.

While the abilities are limited, you can easily extend it by adding more properties. It's likely that most properties would just have to "pass thru" to the underlying button, like I did for text, enabled and cssclass.

If anybody's got a simpler, cleaner or otherwise better solution, I'd be happy to hear it. This is a pain, but it works.

twitter bootstrap typeahead ajax example

I did some modifications on the jquery-ui.min.js:

//Line 319 ORIG:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").appendTo(d(...
// NEW:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").addClass("typeahead").addClass("dropdown-menu").appendTo(d(...

// Line 328 ORIG:
this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr...
// NEW:this.element.attr....

// Line 329 ORIG:
this.active=a.eq(0).children("a")
this.active.children("a")
// NEW:
this.active=a.eq(0).addClass("active").children("a")
this.active.removeClass("active").children("a")`

and add following css

.dropdown-menu {
    max-width: 920px;
}
.ui-menu-item {
    cursor: pointer;        
}

Works perfect.

How do I rename the android package name?

Lets address the two use cases

**Rename a package name or Trim a package **

com.mycompany.mystupidapplicationname to com.mycompany.brandname

or

com.someothercompany.mystupidapplicationname to com.someothercompany.mystupidapplicationname

or

com.someothercompany.mystupidapplicationname to someothercompany.brandname

  1. Select Package in the drop down in Android Studio

Select package in dropdown

  1. Right click on the package which contains your MainActivity and refractor it

enter image description here

  1. Select Rename Package and everything will work like a charm

But this will only rename the last part of package name

  1. To rename the first or second part of package name . Create a new dummy file in the part of package which you want to rename. the file will be created inside mycompany.com.myapplicationame. Then move the file inside mycompany(right click => move) to make mycompany appear in tree view. This will make that part part of the tree view and will you help you to do a right click and rename that part.

enter image description here

  1. Delete the dummy file

  2. To Trim a package , simply right click and move the package part inside its grand parent

How to send a PUT/DELETE request in jQuery?

$.ajax will work.

$.ajax({
   url: 'script.php',
   type: 'PUT',
   success: function(response) {
     //...
   }
});

how does unix handle full path name with space and arguments?

You can either quote it like your Windows example above, or escape the spaces with backslashes:

 "/foo folder with space/foo" --help
 /foo\ folder\ with\ space/foo --help

What does <a href="#" class="view"> mean?

Don't forget to look at the Javascript as well. My guess is that there is custom Javascript code getting executed when you click on the link and it's that Javascript that is generating the URL and navigating to it.

Two models in one view in ASP MVC 3

Just create a single view Model with all the needed information in it, normaly what I do is create a model for every view so I can be specific on every view, either that or make a parent model and inherit it. OR make a model which includes both the views.

Personally I would just add them into one model but thats the way I do it:

public class xViewModel
{
    public int PersonID { get; set; }
    public string PersonName { get; set; }
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

@model project.Models.Home.xViewModel

@using(Html.BeginForm())
{
    @Html.EditorFor(x => x.PersonID)
    @Html.EditorFor(x => x.PersonName)
    @Html.EditorFor(x => x.OrderID)
    @Html.EditorFor(x => x.TotalSum)
}

Is there a way to ignore a single FindBugs warning?

As others Mentioned, you can use the @SuppressFBWarnings Annotation. If you don't want or can't add another Dependency to your code, you can add the Annotation to your Code yourself, Findbugs dosn't care in which Package the Annotation is.

@Retention(RetentionPolicy.CLASS)
public @interface SuppressFBWarnings {
    /**
     * The set of FindBugs warnings that are to be suppressed in
     * annotated element. The value can be a bug category, kind or pattern.
     *
     */
    String[] value() default {};

    /**
     * Optional documentation of the reason why the warning is suppressed
     */
    String justification() default "";
}

Source: https://sourceforge.net/p/findbugs/feature-requests/298/#5e88

How to check that a JCheckBox is checked?

By using itemStateChanged(ItemListener) you can track selecting and deselecting checkbox (and do whatever you want based on it):

myCheckBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...
        };
    }
});

Java Swing itemStateChanged docu should help too. By using isSelected() method you can just test if actual is checkbox selected:

if(myCheckBox.isSelected()){_do_something_if_selected_}

How do I disable a Pylint warning?

Edit "C:\Users\Your User\AppData\Roaming\Code\User\settings.json" and add 'python.linting.pylintArgs' with its lines at the end as shown below:

{
    "team.showWelcomeMessage": false,
    "python.dataScience.sendSelectionToInteractiveWindow": true,
    "git.enableSmartCommit": true,
    "powershell.codeFormatting.useCorrectCasing": true,
    "files.autoSave": "onWindowChange",
    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django",
        "--errors-only"
    ],
}

How do I pull files from remote without overwriting local files?

You can stash your local changes first, then pull, then pop the stash.

git stash
git pull origin master
git stash pop

Anything that overrides changes from remote will have conflicts which you will have to manually resolve.

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

See Apple’s Info.plist reference for full details (thanks @gnasher729).

You can add exceptions for specific domains in your Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>testdomain.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
            <false/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSRequiresCertificateTransparency</key>
            <false/>
        </dict>
    </dict>
</dict>

All the keys for each excepted domain are optional. The speaker did not elaborate on any of the keys, but I think they’re all reasonably obvious.

(Source: WWDC 2015 session 703, “Privacy and Your App”, 30:18)

You can also ignore all app transport security restrictions with a single key, if your app has a good reason to do so:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

If your app does not have a good reason, you may risk rejection:

Setting NSAllowsArbitraryLoads to true will allow it to work, but Apple was very clear in that they intend to reject apps who use this flag without a specific reason. The main reason to use NSAllowsArbitraryLoads I can think of would be user created content (link sharing, custom web browser, etc). And in this case, Apple still expects you to include exceptions that enforce the ATS for the URLs you are in control of.

If you do need access to specific URLs that are not served over TLS 1.2, you need to write specific exceptions for those domains, not use NSAllowsArbitraryLoads set to yes. You can find more info in the NSURLSesssion WWDC session.

Please be careful in sharing the NSAllowsArbitraryLoads solution. It is not the recommended fix from Apple.

kcharwood (thanks @marco-tolman)

Good Linux (Ubuntu) SVN client

I sometimes use kdesvn for work directly against a repository.

I often use Subclipse when working on projects via Eclipse.

But most of all I use good ol' CLI. With some aliases and bash scripts to back it up, it really is the most concise, reliable method of using svn.

I have tried NautilusSVN (no relation to NaughtySVN) and svn-workbench and found them too problematic or lacking in functionality. I know I tried RapidSVN at some point but I must not have been impressed as it was quickly uninstalled, but I don't remember anything about it.

Converting Python dict to kwargs?

** operator would be helpful here.

** operator will unpack the dict elements and thus **{'type':'Event'} would be treated as type='Event'

func(**{'type':'Event'}) is same as func(type='Event') i.e the dict elements would be converted to the keyword arguments.

FYI

* will unpack the list elements and they would be treated as positional arguments.

func(*['one', 'two']) is same as func('one', 'two')

Is nested function a good approach when required by only one function?

I found this question because I wanted to pose a question why there is a performance impact if one uses nested functions. I ran tests for the following functions using Python 3.2.5 on a Windows Notebook with a Quad Core 2.5 GHz Intel i5-2530M processor

def square0(x):
    return x*x

def square1(x):
    def dummy(y):
        return y*y
    return x*x

def square2(x):
    def dummy1(y):
        return y*y
    def dummy2(y):
        return y*y
    return x*x

def square5(x):
    def dummy1(y):
        return y*y
    def dummy2(y):
        return y*y
    def dummy3(y):
        return y*y
    def dummy4(y):
        return y*y
    def dummy5(y):
        return y*y
    return x*x

I measured the following 20 times, also for square1, square2, and square5:

s=0
for i in range(10**6):
    s+=square0(i)

and got the following results

>>> 
m = mean, s = standard deviation, m0 = mean of first testcase
[m-3s,m+3s] is a 0.997 confidence interval if normal distributed

square? m     s       m/m0  [m-3s ,m+3s ]
square0 0.387 0.01515 1.000 [0.342,0.433]
square1 0.460 0.01422 1.188 [0.417,0.503]
square2 0.552 0.01803 1.425 [0.498,0.606]
square5 0.766 0.01654 1.979 [0.717,0.816]
>>> 

square0 has no nested function, square1 has one nested function, square2 has two nested functions and square5 has five nested functions. The nested functions are only declared but not called.

So if you have defined 5 nested funtions in a function that you don't call then the execution time of the function is twice of the function without a nested function. I think should be cautious when using nested functions.

The Python file for the whole test that generates this output can be found at ideone.

How to set custom header in Volley Request

It looks like you override public Map<String, String> getHeaders(), defined in Request, to return your desired HTTP headers.

C++ Array Of Pointers

I would do it something along these lines:

class Foo{
...
};

int main(){
  Foo* arrayOfFoo[100]; //[1]

  arrayOfFoo[0] = new Foo; //[2]
}

[1] This makes an array of 100 pointers to Foo-objects. But no Foo-objects are actually created.

[2] This is one possible way to instantiate an object, and at the same time save a pointer to this object in the first position of your array.

.NET 4.0 has a new GAC, why?

Yes since there are 2 distinct Global Assembly Cache (GAC), you will have to manage each of them individually.

In .NET Framework 4.0, the GAC went through a few changes. The GAC was split into two, one for each CLR.

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. There was no need in the previous two framework releases to split GAC. The problem of breaking older applications in Net Framework 4.0.

To avoid issues between CLR 2.0 and CLR 4.0 , the GAC is now split into private GAC’s for each runtime.The main change is that CLR v2.0 applications now cannot see CLR v4.0 assemblies in the GAC.

Source

Why?

It seems to be because there was a CLR change in .NET 4.0 but not in 2.0 to 3.5. The same thing happened with 1.1 to 2.0 CLR. It seems that the GAC has the ability to store different versions of assemblies as long as they are from the same CLR. They do not want to break old applications.

See the following information in MSDN about the GAC changes in 4.0.

For example, if both .NET 1.1 and .NET 2.0 shared the same GAC, then a .NET 1.1 application, loading an assembly from this shared GAC, could get .NET 2.0 assemblies, thereby breaking the .NET 1.1 application

The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. As a result of this, there was no need in the previous two framework releases to split the GAC. The problem of breaking older (in this case, .NET 2.0) applications resurfaces in Net Framework 4.0 at which point CLR 4.0 released. Hence, to avoid interference issues between CLR 2.0 and CLR 4.0, the GAC is now split into private GACs for each runtime.

As the CLR is updated in future versions you can expect the same thing. If only the language changes then you can use the same GAC.

Remove non-numeric characters (except periods and commas) from a string

Simplest way to truly remove all non-numeric characters:

echo preg_replace('/\D/', '', $string);

\D represents "any character that is not a decimal digit"

http://php.net/manual/en/regexp.reference.escape.php

R barplot Y-axis scale too short

barplot(data)

enter image description here

barplot(data, yaxp=c(0, max(data), 5))

enter image description here

yaxp=c(minY-axis, maxY-axis, Interval)

How to pass in a react component into another react component to transclude the first component's content?

Late to the game, but here's a powerful HOC pattern for overriding a component by providing it as a prop. It's simple and elegant.

Suppose MyComponent renders a fictional A component but you want to allow for a custom override of A, in this example B, which wraps A in a <div>...</div> and also appends "!" to the text prop:

import A from 'fictional-tooltip';

const MyComponent = props => (
  <props.A text="World">Hello</props.A>
);
MyComponent.defaultProps = { A };

const B = props => (
  <div><A {...props} text={props.text + '!'}></div>
);

ReactDOM.render(<MyComponent A={B}/>);

String "true" and "false" to boolean

ActiveRecord provides a clean way of doing this.

def is_true?(string)
  ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(string)
end

ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES has all of the obvious representations of True values as strings.

java SSL and cert keystore

you can also mention the path at runtime using -D properties as below

-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts 
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks

In my apache spark application, I used to provide the path of certs and keystore using --conf option and extraJavaoptions in spark-submit as below

--conf 'spark.driver.extraJavaOptions= 
-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts 
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks' 

How do I trap ctrl-c (SIGINT) in a C# console app

The Console.CancelKeyPress event is used for this. This is how it's used:

public static void Main(string[] args)
{
    Console.CancelKeyPress += delegate {
        // call methods to clean up
    };

    while (true) {}
}

When the user presses Ctrl + C the code in the delegate is run and the program exits. This allows you to perform cleanup by calling necessairy methods. Note that no code after the delegate is executed.

There are other situations where this won't cut it. For example, if the program is currently performing important calculations that can't be immediately stopped. In that case, the correct strategy might be to tell the program to exit after the calculation is complete. The following code gives an example of how this can be implemented:

class MainClass
{
    private static bool keepRunning = true;

    public static void Main(string[] args)
    {
        Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
            e.Cancel = true;
            MainClass.keepRunning = false;
        };

        while (MainClass.keepRunning) {
            // Do your work in here, in small chunks.
            // If you literally just want to wait until ctrl-c,
            // not doing anything, see the answer using set-reset events.
        }
        Console.WriteLine("exited gracefully");
    }
}

The difference between this code and the first example is that e.Cancel is set to true, which means the execution continues after the delegate. If run, the program waits for the user to press Ctrl + C. When that happens the keepRunning variable changes value which causes the while loop to exit. This is a way to make the program exit gracefully.

How do I tokenize a string sentence in NLTK?

As @PavelAnossov answered, the canonical answer, use the word_tokenize function in nltk:

from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)

If your sentence is truly simple enough:

Using the string.punctuation set, remove punctuation then split using the whitespace delimiter:

import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y

Is there a difference between "==" and "is"?

Python difference between is and equals(==)

The is operator may seem like the same as the equality operator but they are not same.

The is checks if both the variables point to the same object whereas the == sign checks if the values for the two variables are the same.

So if the is operator returns True then the equality is definitely True, but the opposite may or may not be True.

Here is an example to demonstrate the similarity and the difference.

>>> a = b = [1,2,3]
>>> c = [1,2,3]
>>> a == b
True
>>> a == c
True
>>> a is b
True
>>> a is c
False
>>> a = [1,2,3]
>>> b = [1,2]
>>> a == b
False
>>> a is b
False
>>> del a[2]
>>> a == b
True
>>> a is b
False
Tip: Avoid using is operator for immutable types such as strings and numbers, the result is unpredictable.

How to enter quotes in a Java string?

Not sure what language you're using (you didn't specify), but you should be able to "escape" the quotation mark character with a backslash: "\"ROM\""

Copying an array of objects into another array in javascript

I suggest using concat() if you are using nodeJS. In all other cases, I have found that slice(0) works fine.

Difference between spring @Controller and @RestController annotation

@Controller returns View. @RestController returns ResponseBody.

How to update/refresh specific item in RecyclerView

you just have to add following code in alert dialog box on save click

          recyclerData.add(position, updateText.getText().toString());
          recyclerAdapter.notifyItemChanged(position);

Rails 4: assets not loading in production

location ~ ^/assets/ {
  expires 1y;
  add_header Cache-Control public;
  add_header ETag "";
}

This fixed the problem for me in production. Put it into the nginx config.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

PostgreSQL, checking date relative to "today"

You could also check using the age() function

select * from mytable where age( mydate, now() ) > '1 year';

age() wil return an interval.

For example age( '2015-09-22', now() ) will return -1 years -7 days -10:56:18.274131

See postgresql documentation

How to print a double with two decimals in Android?

For Displaying digit upto two decimal places there are two possibilities - 1) Firstly, you only want to display decimal digits if it's there. For example - i) 12.10 to be displayed as 12.1, ii) 12.00 to be displayed as 12. Then use-

DecimalFormat formater = new DecimalFormat("#.##"); 

2) Secondly, you want to display decimal digits irrespective of decimal present For example -i) 12.10 to be displayed as 12.10. ii) 12 to be displayed as 12.00.Then use-

DecimalFormat formater = new DecimalFormat("0.00"); 

Integer division with remainder in JavaScript?

You can use the function parseInt to get a truncated result.

parseInt(a/b)

To get a remainder, use mod operator:

a%b

parseInt have some pitfalls with strings, to avoid use radix parameter with base 10

parseInt("09", 10)

In some cases the string representation of the number can be a scientific notation, in this case, parseInt will produce a wrong result.

parseInt(100000000000000000000000000000000, 10) // 1e+32

This call will produce 1 as result.

Django - iterate number in for loop of a template

Django provides it. You can use either:

  • {{ forloop.counter }} index starts at 1.
  • {{ forloop.counter0 }} index starts at 0.

In template, you can do:

{% for item in item_list %}
    {{ forloop.counter }} # starting index 1
    {{ forloop.counter0 }} # starting index 0

    # do your stuff
{% endfor %}

More info at: for | Built-in template tags and filters | Django documentation

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

First you should learn about loops, in this case most suitable is for loop. For instance let's initialize whole table with increasing values starting with 0:

final int SIZE = 10;
int[] array = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
    array[i] = i;
}

Now you can modify it to initialize your table with values as per your assignment. But what happen if you replace condition i < SIZE with i < 11? Well, you will get IndexOutOfBoundException, as you try to access (at some point) an object under index 10, but the highest index in 10-element array is 9. So you are trying, in other words, to find friend's home with number 11, but there are only 10 houses in the street.

In case of the code you presented, well, there must be more of it, as you can not get this error (exception) from that code.

What is the C# equivalent of NaN or IsNumeric?

I like the extension method, but don't like throwing exceptions if possible. I opted for an extension method taking the best of 2 answers here.

    /// <summary>
    /// Extension method that works out if a string is numeric or not
    /// </summary>
    /// <param name="str">string that may be a number</param>
    /// <returns>true if numeric, false if not</returns>
    public static bool IsNumeric(this String str)
    {
        double myNum = 0;
        if (Double.TryParse(str, out myNum))
        {
            return true;
        }
        return false;
    }

ASP.NET page life cycle explanation

There are 10 events in ASP.NET page life cycle, and the sequence is:

  1. Init
  2. Load view state
  3. Post back data
  4. Load
  5. Validate
  6. Events
  7. Pre-render
  8. Save view state
  9. Render
  10. Unload

Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.

ASP.NET life cycle

Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010

Where is Python language used?

Your categorization is not correct:

php, asp and ColdFusion are mostly used for websites, that is correct, but .net is definetly much more than asp you can build desktop applications, too (Paint.NET). I don't know about ColdFusion, but PHP can also be used to write desktop applications.

On the other hand C,C++ are not really often used for web programming, But it can be used for web programming (cgit). Java is definetly a language to develop web applications (spring and much more).

Python is a scripting language like PHP, Perl, Ruby and so much more. It can be used for web programming (django, Zope, Google App Engine, and much more). But it also can be used for desktop applications (Blender 3D, or even for games pygame).

Python can also be translated into binary code like java.

How to create empty text file from a batch file?

You can also use SET to create a null byte file as follows

set x=x > EmptyFile.txt

Or if you don't want to create an extra variable reassign an existing variable like

set PROMPT=%PROMPT% > EmptyFile.txt

or like this:

set "PROMPT=%PROMPT%" > EmptyFile.txt

PHP __get and __set magic methods

Intenta con:

__GET($k){
 return $this->$k;
}

_SET($k,$v){
 return $this->$k = $v;
}

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

According to the API the constructor which would accept year, month, and so on is deprecated. Instead you should use the Constructor which accepts a long. You could use a Calendar implementation to construct the date you want and access the time-representation as a long, for example with the getTimeInMillis method.

Octave/Matlab: Adding new elements to a vector

Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5;
tic;
x = rand(big,1);
toc

x = zeros(big,1);
tic;
for ii = 1:big
    x(ii) = rand;
end
toc

x = []; 
tic; 
for ii = 1:big
    x(end+1) = rand; 
end; 
toc 

x = []; 
tic; 
for ii = 1:big
    x = [x rand]; 
end; 
toc

   Elapsed time is 0.004611 seconds.
   Elapsed time is 0.016448 seconds.
   Elapsed time is 0.034107 seconds.
   Elapsed time is 12.341434 seconds.

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.

So I guess the speed advantage only applies to more recent versions of Matlab

java.net.SocketException: Connection reset

Connection reset simply means that a TCP RST was received. This happens when your peer receives data that it can't process, and there can be various reasons for that.

The simplest is when you close the socket, and then write more data on the output stream. By closing the socket, you told your peer that you are done talking, and it can forget about your connection. When you send more data on that stream anyway, the peer rejects it with an RST to let you know it isn't listening.

In other cases, an intervening firewall or even the remote host itself might "forget" about your TCP connection. This could happen if you don't send any data for a long time (2 hours is a common time-out), or because the peer was rebooted and lost its information about active connections. Sending data on one of these defunct connections will cause a RST too.


Update in response to additional information:

Take a close look at your handling of the SocketTimeoutException. This exception is raised if the configured timeout is exceeded while blocked on a socket operation. The state of the socket itself is not changed when this exception is thrown, but if your exception handler closes the socket, and then tries to write to it, you'll be in a connection reset condition. setSoTimeout() is meant to give you a clean way to break out of a read() operation that might otherwise block forever, without doing dirty things like closing the socket from another thread.

Swift's guard keyword

From Apple documentation:

Guard Statement

A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.

Synatx:

guard condition else {
    statements
}

Advantage:

1. By using guard statement we can get rid of deeply nested conditionals whose sole purpose is validating a set of requirements.

2. It was designed specifically for exiting a method or function early.

if you use if let below is the code how it looks.

  let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

        if error == nil {
            if let  statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 {
                if let data = data {

                    //Process Data Here.
                    print("Data: \(data)")

                } else {
                    print("No data was returned by the request!")
                }
            } else {
                print("Your request returned a status code other than 2XX!")
            }
        } else {
            print("Error Info: \(error.debugDescription)")
        }
    }
    task.resume()

Using guard you can transfer control out of a scope if one or more conditions aren't met.

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            /* GUARD: was there an error? */
            guard (error == nil) else {
                print("There was an error with your request: \(error)")
                return
            }

            /* GUARD: Did we get a successful 2XX response? */
            guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
                print("Your request returned a status code other than 2XX!")
                return
            }

            /* GUARD: was there any data returned? */
            guard let data = data else {
                print("No data was returned by the request!")
                return
            }

            //Process Data Here.
            print("Data: \(data)")
}
task.resume()

Reference:

1. Swift 2: Exit Early With guard 2. Udacity 3. Guard Statement

How to create a simple http proxy in node.js?

Super simple and readable, here's how you create a local proxy server to a local HTTP server with just Node.js (tested on v8.1.0). I've found it particular useful for integration testing so here's my share:

/**
 * Once this is running open your browser and hit http://localhost
 * You'll see that the request hits the proxy and you get the HTML back
 */

'use strict';

const net = require('net');
const http = require('http');

const PROXY_PORT = 80;
const HTTP_SERVER_PORT = 8080;

let proxy = net.createServer(socket => {
    socket.on('data', message => {
        console.log('---PROXY- got message', message.toString());

        let serviceSocket = new net.Socket();

        serviceSocket.connect(HTTP_SERVER_PORT, 'localhost', () => {
            console.log('---PROXY- Sending message to server');
            serviceSocket.write(message);
        });

        serviceSocket.on('data', data => {
            console.log('---PROXY- Receiving message from server', data.toString();
            socket.write(data);
        });
    });
});

let httpServer = http.createServer((req, res) => {
    switch (req.url) {
        case '/':
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end('<html><body><p>Ciao!</p></body></html>');
            break;
        default:
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end('404 Not Found');
    }
});

proxy.listen(PROXY_PORT);
httpServer.listen(HTTP_SERVER_PORT);

https://gist.github.com/fracasula/d15ae925835c636a5672311ef584b999

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

  1. Download gecko driver from the seleniumhq website (Now it is on GitHub and you can download it from Here) .
    1. You will have a zip (or tar.gz) so extract it.
    2. After extraction you will have geckodriver.exe file (appropriate executable in linux).
    3. Create Folder in C: named SeleniumGecko (Or appropriate)
    4. Copy and Paste geckodriver.exe to SeleniumGecko
    5. Set the path for gecko driver as below

.

System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

How to implement my very own URI scheme on Android

Complementing the @DanielLew answer, to get the values of the parameteres you have to do this:

URI example: myapp://path/to/what/i/want?keyOne=valueOne&keyTwo=valueTwo

in your activity:

Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
  Uri uri = intent.getData();
  String valueOne = uri.getQueryParameter("keyOne");
  String valueTwo = uri.getQueryParameter("keyTwo");
}

How to add action listener that listens to multiple buttons

I use "e.getActionCommand().contains(CharSecuence s)", since I´m coming from an MVC context, and the Button is declared in the View class, but the actionPerformed call occurs in the controller.

public View() {
    ....
    buttonPlus = new Button("+");
    buttonMinus = new Button("-");
    ....
}

public void addController(ActionListener controller) {
    buttonPlus.addActionListener(controller);
    buttonMinus.addActionListener(controller);
}

My controller class implements ActionListener, and so, when overriding actionPerformed:

public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().contains("+")) {
        //do some action on the model
    } else if (e.getActionCommand().contains("-")) {
       //do some other action on the model
    }
}

I hope this other answer is also useful.

Is there a way to check which CSS styles are being used or not used on a web page?

Install the CSS Usage add-on for Firebug and run it on that page. It will tell you which styles are being used and not used by that page.

Getting the parent of a directory in Bash

Motivation for another answer

I like very short, clear, guaranteed code. Bonus point if it does not run an external program, since the day you need to process a huge number of entries, it will be noticeably faster.

Principle

Not sure about what guarantees you have and want, so offering anyway.

If you have guarantees you can do it with very short code. The idea is to use bash text substitution feature to cut the last slash and whatever follows.

Answer from simple to more complex cases of the original question.

If path is guaranteed to end without any slash (in and out)

P=/home/smith/Desktop/Test ; echo "${P%/*}"
/home/smith/Desktop

If path is guaranteed to end with exactly one slash (in and out)

P=/home/smith/Desktop/Test/ ; echo "${P%/*/}/"
/home/smith/Desktop/

If input path may end with zero or one slash (not more) and you want output path to end without slash

for P in \
    /home/smith/Desktop/Test \
    /home/smith/Desktop/Test/
do
    P_ENDNOSLASH="${P%/}" ; echo "${P_ENDNOSLASH%/*}"
done

/home/smith/Desktop
/home/smith/Desktop

If input path may have many extraneous slashes and you want output path to end without slash

for P in \
    /home/smith/Desktop/Test \
    /home/smith/Desktop/Test/ \
    /home/smith///Desktop////Test// 
do
    P_NODUPSLASH="${P//\/*(\/)/\/}"
    P_ENDNOSLASH="${P_NODUPSLASH%%/}"
    echo "${P_ENDNOSLASH%/*}";   
done

/home/smith/Desktop
/home/smith/Desktop
/home/smith/Desktop

Regex - Does not contain certain Characters

^[^<>]+$

The caret in the character class ([^) means match anything but, so this means, beginning of string, then one or more of anything except < and >, then the end of the string.

How do I rename both a Git local and remote branch name?

There is no direct method,

  1. Rename Local Branch,

    My current branch is master

    git branch -m master_renamed #master_renamed is new name of master

  2. Delete remote branch,

    git push origin --delete master #origin is remote_name

  3. Push renamed branch into remote,

    git push origin master_renamed

That's it...

Best way to encode Degree Celsius symbol into web page?

If using Java-JSP, What worked for me is to paste below in JSP page

<%@ page contentType="text/html; charset=UTF-8" %>

How to pass optional arguments to a method in C++?

With the introduction of std::optional in C++17 you can pass optional arguments:

#include <iostream>
#include <string>
#include <optional>

void myfunc(const std::string& id, const std::optional<std::string>& param = std::nullopt)
{
    std::cout << "id=" << id << ", param=";

    if (param)
        std::cout << *param << std::endl;
    else
        std::cout << "<parameter not set>" << std::endl;
}

int main() 
{
    myfunc("first");
    myfunc("second" , "something");
}

Output:

id=first param=<parameter not set>
id=second param=something

See https://en.cppreference.com/w/cpp/utility/optional

How to access the last value in a vector?

To answer this not from an aesthetical but performance-oriented point of view, I've put all of the above suggestions through a benchmark. To be precise, I've considered the suggestions

  • x[length(x)]
  • mylast(x), where mylast is a C++ function implemented through Rcpp,
  • tail(x, n=1)
  • dplyr::last(x)
  • x[end(x)[1]]]
  • rev(x)[1]

and applied them to random vectors of various sizes (10^3, 10^4, 10^5, 10^6, and 10^7). Before we look at the numbers, I think it should be clear that anything that becomes noticeably slower with greater input size (i.e., anything that is not O(1)) is not an option. Here's the code that I used:

Rcpp::cppFunction('double mylast(NumericVector x) { int n = x.size(); return x[n-1]; }')
options(width=100)
for (n in c(1e3,1e4,1e5,1e6,1e7)) {
  x <- runif(n);
  print(microbenchmark::microbenchmark(x[length(x)],
                                       mylast(x),
                                       tail(x, n=1),
                                       dplyr::last(x),
                                       x[end(x)[1]],
                                       rev(x)[1]))}

It gives me

Unit: nanoseconds
           expr   min      lq     mean  median      uq   max neval
   x[length(x)]   171   291.5   388.91   337.5   390.0  3233   100
      mylast(x)  1291  1832.0  2329.11  2063.0  2276.0 19053   100
 tail(x, n = 1)  7718  9589.5 11236.27 10683.0 12149.0 32711   100
 dplyr::last(x) 16341 19049.5 22080.23 21673.0 23485.5 70047   100
   x[end(x)[1]]  7688 10434.0 13288.05 11889.5 13166.5 78536   100
      rev(x)[1]  7829  8951.5 10995.59  9883.0 10890.0 45763   100
Unit: nanoseconds
           expr   min      lq     mean  median      uq    max neval
   x[length(x)]   204   323.0   475.76   386.5   459.5   6029   100
      mylast(x)  1469  2102.5  2708.50  2462.0  2995.0   9723   100
 tail(x, n = 1)  7671  9504.5 12470.82 10986.5 12748.0  62320   100
 dplyr::last(x) 15703 19933.5 26352.66 22469.5 25356.5 126314   100
   x[end(x)[1]] 13766 18800.5 27137.17 21677.5 26207.5  95982   100
      rev(x)[1] 52785 58624.0 78640.93 60213.0 72778.0 851113   100
Unit: nanoseconds
           expr     min        lq       mean    median        uq     max neval
   x[length(x)]     214     346.0     583.40     529.5     720.0    1512   100
      mylast(x)    1393    2126.0    4872.60    4905.5    7338.0    9806   100
 tail(x, n = 1)    8343   10384.0   19558.05   18121.0   25417.0   69608   100
 dplyr::last(x)   16065   22960.0   36671.13   37212.0   48071.5   75946   100
   x[end(x)[1]]  360176  404965.5  432528.84  424798.0  450996.0  710501   100
      rev(x)[1] 1060547 1140149.0 1189297.38 1180997.5 1225849.0 1383479   100
Unit: nanoseconds
           expr     min        lq        mean    median         uq      max neval
   x[length(x)]     327     584.0     1150.75     996.5     1652.5     3974   100
      mylast(x)    2060    3128.5     7541.51    8899.0     9958.0    16175   100
 tail(x, n = 1)   10484   16936.0    30250.11   34030.0    39355.0    52689   100
 dplyr::last(x)   19133   47444.5    55280.09   61205.5    66312.5   105851   100
   x[end(x)[1]] 1110956 2298408.0  3670360.45 2334753.0  4475915.0 19235341   100
      rev(x)[1] 6536063 7969103.0 11004418.46 9973664.5 12340089.5 28447454   100
Unit: nanoseconds
           expr      min         lq         mean      median          uq       max neval
   x[length(x)]      327      722.0      1644.16      1133.5      2055.5     13724   100
      mylast(x)     1962     3727.5      9578.21      9951.5     12887.5     41773   100
 tail(x, n = 1)     9829    21038.0     36623.67     43710.0     48883.0     66289   100
 dplyr::last(x)    21832    35269.0     60523.40     63726.0     75539.5    200064   100
   x[end(x)[1]] 21008128 23004594.5  37356132.43  30006737.0  47839917.0 105430564   100
      rev(x)[1] 74317382 92985054.0 108618154.55 102328667.5 112443834.0 187925942   100

This immediately rules out anything involving rev or end since they're clearly not O(1) (and the resulting expressions are evaluated in a non-lazy fashion). tail and dplyr::last are not far from being O(1) but they're also considerably slower than mylast(x) and x[length(x)]. Since mylast(x) is slower than x[length(x)] and provides no benefits (rather, it's custom and does not handle an empty vector gracefully), I think the answer is clear: Please use x[length(x)].

What's your most controversial programming opinion?

Arrays should by default be 1-based rather than 0-based. This is not necessarily the case with system implementation languages, but languages like Java swallowed more C oddities than they should have. "Element 1" should be the first element, not the second, to avoid confusion.

Computer science is not software development. You wouldn't hire an engineer who studied only physics, after all.

Learn as much mathematics as is feasible. You won't use most of it, but you need to be able to think that way to be good at software.

The single best programming language yet standardized is Common Lisp, even if it is verbose and has zero-based arrays. That comes largely from being designed as a way to write computations, rather than as an abstraction of a von Neumann machine.

At least 90% of all comparative criticism of programming languages can be reduced to "Language A has feature C, and I don't know how to do C or something equivalent in Language B, so Language A is better."

"Best practices" is the most impressive way to spell "mediocrity" I've ever seen.

Laravel Eloquent Sum of relation's column

Also using query builder

DB::table("rates")->get()->sum("rate_value")

To get summation of all rate value inside table rates.

To get summation of user products.

DB::table("users")->get()->sum("products")

How to create a static library with g++?

Create a .o file:

g++ -c header.cpp

add this file to a library, creating library if necessary:

ar rvs header.a header.o

use library:

g++ main.cpp header.a

How to compile and run C/C++ in a Unix console/Mac terminal?

Use a makefile. Even for very small (= one-file) projects, the effort is probably worth it because you can have several sets of compiler settings to test things. Debugging and deployment works much easier this way.

Read the make manual, it seems quite long at first glance but most sections you can just skim over. All in all it took me a few hours and made me much more productive.

How can I create C header files

Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.

If a header file contains a function, and is included by multiple .c files, each .c file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.

It is technically possible to create static functions in a header file for inclusion in multiple .c files. Though this is generally not done because it breaks from the convention that code is found in .c files and declarations are found in .h files.

See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.

How to identify object types in java

Use value instanceof YourClass

Why is C so fast, and why aren't other languages as fast or faster?

C is not always faster.

C is slower than, for example Modern Fortran.

C is often slower than Java for some things. ( Especially after the JIT compiler has had a go at your code)

C lets pointer aliasing happen, which means some good optimizations are not possible. Particularly when you have multiple execution units, this causes data fetch stalls. Ow.

The assumption that pointer arithmetic works really causes slow bloated performance on some CPU families (PIC particularly!) It used to suck the big one on segmented x86.

Basically, when you get a vector unit, or a parallelizing compiler, C stinks and modern Fortran runs faster.

C programmer tricks like thunking ( modifying the executable on the fly) cause CPU prefetch stalls.

You get the drift ?

And our good friend, the x86, executes an instruction set that these days bears little relationship to the actual CPU architecture. Shadow registers, load-store optimizers, all in the CPU. So C is then close to the virtual metal. The real metal, Intel don't let you see. (Historically VLIW CPU's were a bit of a bust so, maybe that's no so bad.)

If you program in C on a high-performance DSP (maybe a TI DSP ?), the compiler has to do some tricky stuff to unroll the C across the multiple parallel execution units. So in that case C isn't close to the metal, but it is close to the compiler, which will do whole program optimization. Weird.

And finally, some CPUs (www.ajile.com) run Java bytecodes in hardware. C would a PITA to use on that CPU.

What are NDF Files?

An NDF file is a user defined secondary database file of Microsoft SQL Server with an extension .ndf, which store user data. Moreover, when the size of the database file growing automatically from its specified size, you can use .ndf file for extra storage and the .ndf file could be stored on a separate disk drive. Every NDF file uses the same filename as its corresponding MDF file. We cannot open an .ndf file in SQL Server Without attaching its associated .mdf file.

Javascript extends class

Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.

The simplest method is probably functional inheritance but there are pros and cons.

Is it possible to move/rename files in Git and maintain their history?

git log --follow [file]

will show you the history through renames.

Fixed page header overlaps in-page anchors

It feels somewhat hacky to my purist mind but as a css-only solution you can add padding to the active anchored element using the :target selector:

_x000D_
_x000D_
html, body {height:100%; min-height:100%; margin:0;}_x000D_
body {min-height:200%;}_x000D_
header {display:inline-block; position:fixed; font-size:1.5em; height:100px; top:0; left:0; right:0; line-height:100px; background:black; text-align:center;}_x000D_
header a {color:#fff;}_x000D_
section {padding:30px; margin:20px;}_x000D_
section:first-of-type, section:target {padding-top:130px;}
_x000D_
<header><a href="#one">#One</a> <a href="#two">#two</a> <a href="#three">#three</a></header>_x000D_
<section id="one"><h1>One</h1>Aenean lacinia bibendum nulla sed consectetur. Nullam id dolor id nibh ultricies vehicula ut id elit. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.</section>_x000D_
<section id="two"><h1>Two</h1>Aenean lacinia bibendum nulla sed consectetur. Nullam id dolor id nibh ultricies vehicula ut id elit. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.</section>_x000D_
<section id="three"><h1>Three</h1>Aenean lacinia bibendum nulla sed consectetur. Nullam id dolor id nibh ultricies vehicula ut id elit. Integer posuere erat a ante venenatis dapibus posuere velit aliquet.</section>
_x000D_
_x000D_
_x000D_

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Here is a variant of Hogan's answer which I use in SQL Server Express 2012:

SELECT RIGHT(CONCAT('000', field), 3)

Instead of worrying if the field is a string or not, I just CONCAT it, since it'll output a string anyway. Additionally if the field can be a NULL, using ISNULL might be required to avoid function getting NULL results.

SELECT RIGHT(CONCAT('000', ISNULL(field,'')), 3)

One liner to check if element is in the list

There is a boolean contains(Object obj) method within the List interface.

You should be able to say:

if (list.contains("a")) {
    System.out.println("It's there");
}

According to the javadoc:

boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

Convert a number range to another range, maintaining ratio

NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin

Or a little more readable:

OldRange = (OldMax - OldMin)  
NewRange = (NewMax - NewMin)  
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin

Or if you want to protect for the case where the old range is 0 (OldMin = OldMax):

OldRange = (OldMax - OldMin)
if (OldRange == 0)
    NewValue = NewMin
else
{
    NewRange = (NewMax - NewMin)  
    NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
}

Note that in this case we're forced to pick one of the possible new range values arbitrarily. Depending on context, sensible choices could be: NewMin (see sample), NewMax or (NewMin + NewMax) / 2

What is pipe() function in Angular

RxJS Operators are functions that build on the observables foundation to enable sophisticated manipulation of collections.

For example, RxJS defines operators such as map(), filter(), concat(), and flatMap().

You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.

The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.

What is the backslash character (\\)?

It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.

e.g.

System.out.println("printing \"this\" in quotes");

outputs

printing "this" in quotes

Round up value to nearest whole number in SQL UPDATE

You could use the ceiling function; this portion of SQL code :

select ceiling(45.01), ceiling(45.49), ceiling(45.99);

will get you "46" each time.

For your update, so, I'd say :

Update product SET price = ceiling(45.01)

BTW : On MySQL, ceil is an alias to ceiling ; not sure about other DB systems, so you might have to use one or the other, depending on the DB you are using...

Quoting the documentation :

CEILING(X)

Returns the smallest integer value not less than X.

And the given example :

mysql> SELECT CEILING(1.23);
        -> 2
mysql> SELECT CEILING(-1.23);
        -> -1

Webpack.config how to just copy the index.html to the dist folder

You could use the CopyWebpackPlugin. It's working just like this:

module.exports = {
  plugins: [
    new CopyWebpackPlugin([{
      from: './*.html'
    }])
  ]
}

..The underlying connection was closed: An unexpected error occurred on a receive

The underlying connection was closed: An unexpected error occurred on a receive.

This problem occurs when the server or another network device unexpectedly closes an existing Transmission Control Protocol (TCP) connection. This problem may occur when a time-out value on the server or on the network device is set too low. To resolve this problem, see resolutions A, D, E, F, and O. The problem can also occur if the server resets the connection unexpectedly, such as if an unhandled exception crashes the server process. Analyze the server logs to see if this may be the issue.

Resolution

To resolve this problem, make sure that you are using the most recent version of the .NET Framework.

Add a method to the class to override the GetWebRequest method. This change lets you access the HttpWebRequest object. If you are using Microsoft Visual C#, the new method must be similar to the following.

class MyTestService:TestService.TestService
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);
        //Setting KeepAlive to false
        webRequest.KeepAlive = false;
        return webRequest;
    }
}

Excerpt from KB915599: You receive one or more error messages when you try to make an HTTP request in an application that is built on the .NET Framework 1.1 Service Pack 1.

Save base64 string as PDF at client side with JavaScript

_x000D_
_x000D_
dataURItoBlob(dataURI) {_x000D_
      const byteString = window.atob(dataURI);_x000D_
      const arrayBuffer = new ArrayBuffer(byteString.length);_x000D_
      const int8Array = new Uint8Array(arrayBuffer);_x000D_
      for (let i = 0; i < byteString.length; i++) {_x000D_
        int8Array[i] = byteString.charCodeAt(i);_x000D_
      }_x000D_
      const blob = new Blob([int8Array], { type: 'application/pdf'});_x000D_
      return blob;_x000D_
    }_x000D_
_x000D_
// data should be your response data in base64 format_x000D_
_x000D_
const blob = this.dataURItoBlob(data);_x000D_
const url = URL.createObjectURL(blob);_x000D_
_x000D_
// to open the PDF in a new window_x000D_
window.open(url, '_blank');
_x000D_
_x000D_
_x000D_

Hex-encoded String to Byte Array

Java SE 6 or Java EE 5 provides a method to do this now so there is no need for extra libraries.

The method is DatatypeConverter.parseHexBinary

In this case it can be used as follows:

String str = "9B7D2C34A366BF890C730641E6CECF6F";
byte[] bytes = DatatypeConverter.parseHexBinary(str);

The class also provides type conversions for many other formats that are generally used in XML.

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

Probably you were using old PHP version until and now upgraded PHP thats the reason it was working without any error till now from years. until PHP4 there was no error if you are using variable without defining it but as of PHP5 onwards it throws errors for codes like mentioned in question.

How to dismiss a Twitter Bootstrap popover by clicking outside?

$('html').on('mouseup', function(e) {
    if(!$(e.target).closest('.popover').length) {
        $('.popover').each(function(){
            $(this.previousSibling).popover('hide');
        });
    }
});

This closes all popovers if you click anywhere except on a popover

UPDATE for Bootstrap 4.1

$("html").on("mouseup", function (e) {
    var l = $(e.target);
    if (l[0].className.indexOf("popover") == -1) {
        $(".popover").each(function () {
            $(this).popover("hide");
        });
    }
});

Javascript: Setting location.href versus location

Even if both work, I would use the latter. location is an object, and assigning a string to an object doesn't bode well for readability or maintenance.

How to get some values from a JSON string in C#?

Create a class like this:

public class Data
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string First_Name {get; set;}
    public string Last_Name {get; set;}
    public string Username {get; set;}
    public string Gender {get; set;}
    public string Locale {get; set;}
}

(I'm not 100% sure, but if that doesn't work you'll need use [DataContract] and [DataMember] for DataContractJsonSerializer.)

Then create JSonSerializer:

private static readonly XmlObjectSerializer Serializer = new DataContractJsonSerializer(typeof(Data));

and deserialize object:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
using(var stream = new MemoryStream(byteArray))
{
    (Data)Serializer.ReadObject(stream);
}

jQuery: Return data after ajax call success

you can add async option to false and return outside the ajax call.

function testAjax() {
    var result="";
    $.ajax({
      url:"getvalue.php",
      async: false,  
      success:function(data) {
         result = data; 
      }
   });
   return result;
}

Change tab bar item selected color in a storyboard

XCode 8.2, iOS 10, Swift 3: now there's an unselectedItemTintColor attribute for tabBar:

self.tabBar.unselectedItemTintColor = UIColor(red: 0/255.0, green: 200/255.0, blue: 0/255.0, alpha: 1.0)

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

How do we check if a pointer is NULL pointer?

Well, this question was asked and answered way back in 2011, but there is nullptrin C++11. That's all I'm using currently.

You can read more from Stack Overflow and also from this article.

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

1. Solution

Open Sublime Text console ? paste in opened field:

sublime.packages_path()

? Enter. You get result in console output.


2. Relevance

This answer is relevant for April 2018. In the future, the data of this answer may be obsolete.


3. Not recommended

I'm not recommended @osiris answer. Arguments:

  1. In new versions of Sublime Text and/or operating systems (e.g. Sublime Text 4, macOS 14) paths may be changed.
  2. It doesn't take portable Sublime Text on Windows. In portable Sublime Text on Windows another path of Packages folder.
  3. It less simple.

4. Additional link

SFTP in Python? (platform independent)

PyFilesystem with its sshfs is one option. It uses Paramiko under the hood and provides a nicer paltform independent interface on top.

import fs

sf = fs.open_fs("sftp://[user[:password]@]host[:port]/[directory]")
sf.makedir('my_dir')

or

from fs.sshfs import SSHFS
sf = SSHFS(...

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

Java ResultSet how to check if there are any results

if(resultSet.first) {

} else { 
    system.out.println("No raw or resultSet is empty");
}

Because if ResultSet has no raw then resultSet.first returns false.

Alternate table row color using CSS?

_x000D_
_x000D_
$(document).ready(function()_x000D_
{_x000D_
  $("tr:odd").css({_x000D_
    "background-color":"#000",_x000D_
    "color":"#fff"});_x000D_
});
_x000D_
tbody td{_x000D_
  padding: 30px;_x000D_
}_x000D_
_x000D_
tbody tr:nth-child(odd){_x000D_
  background-color: #4C8BF5;_x000D_
  color: #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table border="1">_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>5</td>_x000D_
<td>6</td>_x000D_
<td>7</td>_x000D_
<td>8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>9</td>_x000D_
<td>10</td>_x000D_
<td>11</td>_x000D_
<td>13</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

There is a CSS selector, really a pseudo-selector, called nth-child. In pure CSS you can do the following:

tr:nth-child(even) {
    background-color: #000000;
}

Note: No support in IE 8.

Or, if you have jQuery:

$(document).ready(function()
{
  $("tr:even").css("background-color", "#000000");
});

How to shrink temp tablespace in oracle?

Oh My Goodness! Look at the size of my temporary table space! Or... how to shrink temporary tablespaces in Oracle.

Yes I ran a query to see how big my temporary tablespace is:

SQL> SELECT tablespace_name, file_name, bytes
2  FROM dba_temp_files WHERE tablespace_name like 'TEMP%';

TABLESPACE_NAME   FILE_NAME                                 BYTES
----------------- -------------------------------- --------------
TEMP              /the/full/path/to/temp01.dbf     13,917,200,000

The first question you have to ask is why the temporary tablespace is so large. You may know the answer to this off the top of your head. It may be due to a large query that you just run with a sort that was a mistake (I have done that more than once.) It may be due to some other exceptional circumstance. If that is the case then all you need to do to clean up is to shrink the temporary tablespace and move on in life.

But what if you don't know? Before you decide to shrink you may need to do some investigation into the causes of the large tablespace. If this happens on a regular basis then it is possible that your database just needs that much space.

The dynamic performance view

V$TEMPSEG_USAGE

can be very useful in determining the cause.

Maybe you just don't care about the cause and you just need to shrink it. This is your third day on the job. The data in the database is only 200MiB if data and the temporary tablespace is 13GiB - Just shrink it and move on. If it grows again then we will look into the cause. In the mean time I am out of space on that disk volume and I just need the space back.

Let's take a look at shrinking it. It will depend a little on what version of Oracle you are running and how the temporary tablespace was set up.
Oracle will do it's best to keep you from making any horrendous mistakes so we will just try the commands and if they don't work we will shrink in a new way.

First let's try to shrink the datafile. If we can do that then we get back the space and we can worry about why it grew tomorrow.

SQL>
SQL> alter database tempfile '/the/full/path/to/temp01.dbf' resize 256M; 
alter database tempfile '/the/full/path/to/temp01.dbf' resize 256M
*   
ERROR at line 1:
ORA-03297: file contains used data beyond requested RESIZE value

Depending on the error message you may want to try this with different sizes that are smaller than the current site of the file. I have had limited success with this. Oracle will only shrink the file if the temporary tablespace is at the head of the file and if it is smaller than the size you specify. Some old Oracle documentation (they corrected this) said that you could issue the command and the error message would tell you what size you could shrink to. By the time I started working as a DBA this was not true. You just had to guess and re-run the command a bunch of times and see if it worked.

Alright. That didn't work. How about this.

SQL> alter tablespace YOUR_TEMP_TABLESPACE_NAME shrink space keep 256M;

If you are in 11g (Maybee in 10g too) this is it! If it works you may want to go back to the previous command and give it some more tries.

But what if that fails. If the temporary tablespace is the default temporary that was set up when the database was installed then you may need to do a lot more work. At this point I usually re-evaluate if I really need that space back. After all disk space only costs $X.XX a GiB. Usually I don't want to make changes like this during production hours. That means working at 2AM AGAIN! (Not that I really object to working at 2AM - it is just that... Well I like to sleep too. And my wife likes to have me at home at 2AM... not roaming the downtown streets at 4AM trying to remember where I parked my car 3 hours earlier. I have heard of that "telecommuting" thing. I just worry that I will get half way through and then my internet connectivity will fail - then I have to rush downtown to fix it all before folks show up in the morning to use the database.)

Ok... Back to the serious stuff... If the temporary tablespace you want to shrink is your default temporary tablespace, you will have to first create a new temporary tablespace, set it as the default temporary tablespace then drop your old default temporary tablespace and recreate it. Afterwords drop the second temporary table created.

SQL> CREATE TEMPORARY TABLESPACE temp2
2  TEMPFILE '/the/full/path/to/temp2_01.dbf' SIZE 5M REUSE
3  AUTOEXTEND ON NEXT 1M MAXSIZE unlimited
4  EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;

Tablespace created.

SQL> ALTER DATABASE DEFAULT TEMPORARY TABLESPACE temp2;

Database altered.

SQL> DROP TABLESPACE temp INCLUDING CONTENTS AND DATAFILES;

Tablespace dropped.


SQL> CREATE TEMPORARY TABLESPACE temp
2  TEMPFILE '/the/full/path/to/temp01.dbf' SIZE 256M REUSE
3  AUTOEXTEND ON NEXT 128M MAXSIZE unlimited
4  EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;

Tablespace created.

SQL> ALTER DATABASE DEFAULT TEMPORARY TABLESPACE temp;

Database altered.

SQL> DROP TABLESPACE temp2 INCLUDING CONTENTS AND DATAFILES;

Tablespace dropped.

Hopefully one of these things will help!

'Conda' is not recognized as internal or external command

In addition to adding C:\Users\yourusername\Anaconda3 and C:\Users\yourusername\Anaconda3\Scripts, as recommended by Raja (above), also add C:\Users\yourusername\Anaconda3\Library\bin to your path variable. This will prevent an SSL error that is bound to happen if you're performing this on a fresh install of Anaconda.

how do you filter pandas dataframes by multiple columns

You can filter by multiple columns (more than two) by using the np.logical_and operator to replace & (or np.logical_or to replace |)

Here's an example function that does the job, if you provide target values for multiple fields. You can adapt it for different types of filtering and whatnot:

def filter_df(df, filter_values):
    """Filter df by matching targets for multiple columns.

    Args:
        df (pd.DataFrame): dataframe
        filter_values (None or dict): Dictionary of the form:
                `{<field>: <target_values_list>}`
            used to filter columns data.
    """
    import numpy as np
    if filter_values is None or not filter_values:
        return df
    return df[
        np.logical_and.reduce([
            df[column].isin(target_values) 
            for column, target_values in filter_values.items()
        ])
    ]

Usage:

df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 2, 3, 4]})

filter_df(df, {
    'a': [1, 2, 3],
    'b': [1, 2, 4]
})

Remove pandas rows with duplicate indices

Remove duplicates (Keeping First)

idx = np.unique( df.index.values, return_index = True )[1]
df = df.iloc[idx]

Remove duplicates (Keeping Last)

df = df[::-1]
df = df.iloc[ np.unique( df.index.values, return_index = True )[1] ]

Tests: 10k loops using OP's data

numpy method - 3.03 seconds
df.loc[~df.index.duplicated(keep='first')] - 4.43 seconds
df.groupby(df.index).first() - 21 seconds
reset_index() method - 29 seconds

Create Excel files from C# without office

Unless you have Excel installed on the Server/PC or use an external tool (which is possible without using Excel Interop, see Create Excel (.XLS and .XLSX) file from C#), it will fail. Using the interop requires Excel to be installed.

Assign null to a SqlParameter

My code, working in real project Look the ternary operator beafore make the sqlparameter this is the best way for me, withou problems:

    public bool Key_AddExisting
    (
          string clave
        , int? idHito_FileServer
        , int? idTipoDocumental_Almacen
        , string tipoExp_CHJ
        , int idTipoExp_Verti2
        , int idMov_Verti2
    )
    {
        List<SqlParameter> pars = new List<SqlParameter>()
        {
              new SqlParameter { ParameterName = "@Clave", Value = clave }
    LOOK -> , idHito_FileServer == null ? new SqlParameter { ParameterName = "@IdHito_FileServer", Value = DBNull.Value } : new SqlParameter { ParameterName = "@IdHito_FileServer", Value = idHito_FileServer }
    LOOK -> , idTipoDocumental_Almacen == null ? new SqlParameter { ParameterName = "@IdTipoDocumental_Almacen", Value = DBNull.Value } : new SqlParameter { ParameterName = "@IdTipoDocumental_Almacen", Value = idTipoDocumental_Almacen }
            , new SqlParameter { ParameterName = "@TipoExp_CHJ", Value = tipoExp_CHJ }
            , new SqlParameter { ParameterName = "@IdTipoExp_Verti2", Value = idTipoExp_Verti2 }
            , new SqlParameter { ParameterName = "@IdMov_Verti2", Value = idMov_Verti2 }
        };

        string sql = "INSERT INTO [dbo].[Enlaces_ClavesCHJ_MovimientosVerti2] " +
            "( " +
            "  [Clave] " +
            ", [IdHito_FileServer] " +
            ", [IdTipoDocumental_Almacen] " +
            ", [TipoExp_CHJ] " +
            ", [IdTipoExp_Verti2] " +
            ", [IdMov_Verti2] " +
            ") " +
            "VALUES" +
            "( " +
            "  @Clave" +
            ", @IdHito_FileServer" +
            ", @IdTipoDocumental_Almacen" +
            ", @TipoExp_CHJ" +
            ", @IdTipoExp_Verti2" +
            ", @IdMov_Verti2" +
            ")";

        return DbBasic.ExecNonQuery(ref this.conn, sql, pars);
    }

How to quickly and conveniently create a one element arraylist

Fixed size List

The easiest way, that I know of, is to create a fixed-size single element List with Arrays.asList(T...) like

// Returns a List backed by a varargs T.
return Arrays.asList(s);

Variable size List

If it needs vary in size you can construct an ArrayList and the fixed-sizeList like

return new ArrayList<String>(Arrays.asList(s));

and (in Java 7+) you can use the diamond operator <> to make it

return new ArrayList<>(Arrays.asList(s));

Single Element List

Collections can return a list with a single element with list being immutable:

Collections.singletonList(s)

The benefit here is IDEs code analysis doesn't warn about single element asList(..) calls.

How do I hide anchor text without hiding the anchor?

Mini tip:

I had the following scenario:

<a href="/page/">My link text
:after
</a>

I hided the text with font-size: 0, so I could use a FontAwesome icon for it. This worked on Chrome 36, Firefox 31 and IE9+.

I wouldn't recommend color: transparent because the text stil exists and is selectable. Using line-height: 0px didn't allow me to use :after. Maybe because my element was a inline-block.

Visibility: hidden: Didn't allow me to use :after.

text-indent: -9999px;: Also moved the :after element

CakePHP find method with JOIN

Otro example, custom Data Pagination for JOIN

CODE in Controller CakePHP 2.6 is OK:

$this->SenasaPedidosFacturadosSds->recursive = -1;
    // Filtro
    $where = array(
        'joins' => array(
            array(
                'table' => 'usuarios',
                'alias' => 'Usuarios',
                'type' => 'INNER',
                'conditions' => array(
                    'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
                )
            ),
            array(
                'table' => 'senasa_pedidos',
                'alias' => 'SenasaPedidos',
                'type' => 'INNER',
                'conditions' => array(
                    'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
                )
            ),
            array(
                'table' => 'clientes',
                'alias' => 'Clientes',
                'type' => 'INNER',
                'conditions' => array(
                    'Clientes.id_cliente = SenasaPedidos.clientes_id'
                )
            ),
        ),
        'fields'=>array(
            'SenasaPedidosFacturadosSds.*',
            'Usuarios.usuario_id',
            'Usuarios.apellido_nombre',
            'Usuarios.senasa_establecimientos_id',
            'Clientes.id_cliente',
            'Clientes.consolida_doc_sanitaria',
            'Clientes.requiere_senasa',
            'Clientes.razon_social',
            'SenasaPedidos.id',
            'SenasaPedidos.domicilio_entrega',
            'SenasaPedidos.sds',
            'SenasaPedidos.pt_ptr'
        ),
        'conditions'=>array(
            'Clientes.requiere_senasa'=>1
        ),
        'order' => 'SenasaPedidosFacturadosSds.created DESC',
        'limit'=>100
    );
    $this->paginate = $where;
    // Get datos
    $data = $this->Paginator->paginate();
    exit(debug($data));

OR Example 2, NOT active conditions:

$this->SenasaPedidosFacturadosSds->recursive = -1;
    // Filtro
    $where = array(
        'joins' => array(
            array(
                'table' => 'usuarios',
                'alias' => 'Usuarios',
                'type' => 'INNER',
                'conditions' => array(
                    'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
                )
            ),
            array(
                'table' => 'senasa_pedidos',
                'alias' => 'SenasaPedidos',
                'type' => 'INNER',
                'conditions' => array(
                    'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
                )
            ),
            array(
                'table' => 'clientes',
                'alias' => 'Clientes',
                'type' => 'INNER',
                'conditions' => array(
                    'Clientes.id_cliente = SenasaPedidos.clientes_id',
                    'Clientes.requiere_senasa = 1'
                )
            ),
        ),
        'fields'=>array(
            'SenasaPedidosFacturadosSds.*',
            'Usuarios.usuario_id',
            'Usuarios.apellido_nombre',
            'Usuarios.senasa_establecimientos_id',
            'Clientes.id_cliente',
            'Clientes.consolida_doc_sanitaria',
            'Clientes.requiere_senasa',
            'Clientes.razon_social',
            'SenasaPedidos.id',
            'SenasaPedidos.domicilio_entrega',
            'SenasaPedidos.sds',
            'SenasaPedidos.pt_ptr'
        ),
        //'conditions'=>array(
        //    'Clientes.requiere_senasa'=>1
        //),
        'order' => 'SenasaPedidosFacturadosSds.created DESC',
        'limit'=>100
    );
    $this->paginate = $where;
    // Get datos
    $data = $this->Paginator->paginate();
    exit(debug($data));

Python read JSON file and modify

falsetru's solution is nice, but has a little bug:

Suppose original 'id' length was larger than 5 characters. When we then dump with the new 'id' (134 with only 3 characters) the length of the string being written from position 0 in file is shorter than the original length. Extra chars (such as '}') left in file from the original content.

I solved that by replacing the original file.

import json
import os

filename = 'data.json'
with open(filename, 'r') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.

os.remove(filename)
with open(filename, 'w') as f:
    json.dump(data, f, indent=4)

scp from Linux to Windows

Download pscp from Putty download page, then use it from Windows Command Line CMD as follows:

pscp username_linux_machine@ip_of_linux_machine:/home/ubuntu/myfile.ext C:\Users\Name\Downloads

Copying starts once you enter the password for the Linux machine.

Disable Copy or Paste action for text box?

Check this fiddle.

 $('#email').bind("cut copy paste",function(e) {
     e.preventDefault();
 });

You need to bind what should be done on cut, copy and paste. You prevent default behavior of the action.

You can find a detailed explanation here.

LINQ query on a DataTable

Example on how to achieve this provided below:

DataSet dataSet = new DataSet(); //Create a dataset
dataSet = _DataEntryDataLayer.ReadResults(); //Call to the dataLayer to return the data

//LINQ query on a DataTable
var dataList = dataSet.Tables["DataTable"]
              .AsEnumerable()
              .Select(i => new
              {
                 ID = i["ID"],
                 Name = i["Name"]
               }).ToList();

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I found the problem that was causing the HTTP error.

In the setFalse() function that is triggered by the Save button my code was trying to submit the form that contained the button.

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit();
            document.submitForm.submit();

when I remove the document.submitForm.submit(); it works:

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit()

@Roger Lindsjö Thank you for spotting my error where I wasn't passing on the right parameter!

How to get a float result by dividing two integer values using T-SQL?

It's not necessary to cast both of them. Result datatype for a division is always the one with the higher data type precedence. Thus the solution must be:

SELECT CAST(1 AS float) / 3

or

SELECT 1 / CAST(3 AS float)

Using a dispatch_once singleton model in Swift

There is a better way to do it. You can declare a global variable in your class above the class declaration like this:

var tpScopeManagerSharedInstance = TPScopeManager()

This just calls your default init or whichever init and global variables are dispatch_once by default in Swift. Then in whichever class you want to get a reference, you just do this:

var refrence = tpScopeManagerSharedInstance
// or you can just access properties and call methods directly
tpScopeManagerSharedInstance.someMethod()

So basically you can get rid of the entire block of shared instance code.

JTable won't show column headers

    public table2() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 485, 218);
    setTitle("jtable");
    getContentPane().setLayout(null);

    String data[][] = { { "Row1/1", "Row1/2", "Row1/3" },
            { "Row2/1", "Row2/2", "Row2/3" },
            { "Row3/1", "Row3/2", "Row3/3" },
            { "Row4/1", "Row4/2", "Row4/3" }, };

    String header[] = { "Column 1", "Column 2", "Column 3" };

    // Table
    JTable table = new JTable(data,header);


    // ScrollPane
    JScrollPane scrollPane = new JScrollPane(table);
    scrollPane.setBounds(36, 37, 407, 79);
    getContentPane().add(scrollPane);

   }

}

try this!!

Mysql Compare two datetime fields

Do you want to order it?

Select * From temp where mydate > '2009-06-29 04:00:44' ORDER BY mydate;

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

The backgroundTint attribute will help you to add a tint(shade) to the background. You can provide a color value for the same in the form of - "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

The backgroundTintMode on the other hand will help you to apply the background tint. It must have constant values like src_over, src_in, src_atop, etc.

Refer this to get a clear idea of the the constant values that can be used. Search for the backgroundTint attribute and the description along with various attributes will be available.

How do I copy a 2 Dimensional array in Java?

/**
 * Clones the provided array
 * 
 * @param src
 * @return a new clone of the provided array
 */
public static int[][] cloneArray(int[][] src) {
    int length = src.length;
    int[][] target = new int[length][src[0].length];
    for (int i = 0; i < length; i++) {
        System.arraycopy(src[i], 0, target[i], 0, src[i].length);
    }
    return target;
}

Is it possible to modify this code to support n-dimensional arrays of Objects?

You would need to support arbitrary lengths of arrays and check if the src and destination have the same dimensions, and you would also need to copy each element of each array recursively, in case the Object was also an array.

It's been a while since I posted this, but I found a nice example of one way to create an n-dimensional array class. The class takes zero or more integers in the constructor, specifying the respective size of each dimension. The class uses an underlying flat array Object[] and calculates the index of each element using the dimensions and an array of multipliers. (This is how arrays are done in the C programming language.)

Copying an instance of NDimensionalArray would be as easy as copying any other 2D array, though you need to assert that each NDimensionalArray object has equal dimensions. This is probably the easiest way to do it, since there is no recursion, and this makes representation and access much simpler.

Remove border from IFrame

In your stylesheet add

{
  padding:0px;
  margin:0px;
  border: 0px

}

This is also a viable option.

Correct way to write line to file?

One can also use the io module as in:

import io
my_string = "hi there"

with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
    f.write(my_string)

535-5.7.8 Username and Password not accepted

If you still cannot solve the problem after you turn on the less secure apps. The other possible reason which might cause this error is you are not using gmail account.

-    : user_name  =>  '[email protected]' ,  # It can not be used since it is not a gmail address 
+    : user_name  =>  '[email protected]' ,  # since it's a gmail address

Refer to here.

Also, bear in mind that it might take some times to enable the less secure apps. I have to do it several times (before it works, every time I access the link it will shows that it is off) and wait for a while until it really work.

Conversion of a datetime2 data type to a datetime data type results out-of-range value

The Entity Framework 4 works with the datetime2 data type so in db the corresponding field must be datetime2 for SQL Server 2008.

To achive the solution there are two ways.

  1. To use the datetime data type in Entity Framwork 4 you have to switch the ProviderManifestToken in the edmx-file to "2005".
  2. If you set corresponding field as Allow Null (it converts it to NULLABLE) so then EF automatically uses date objects as datetime.

Change old commit message on Git

If you don't want to deal with interactive mode then do this:

Update your last pushed commit

git commit --amend -m "New commit message."

Push your new commit message (this will replace the old last commit message to this new one)

git push origin --force **branch-name**

More on this - https://linuxize.com/post/change-git-commit-message/

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

One possibility I have not seen mentioned. If the project you are importing uses android product flavors, you may have a mistake in your missingDimenstionStrategy.

In your :app build.gradle (the one code that is failing to resolve the dependency), ensure you have correctly set the specific flavor of the product that you are depending on. This allows all your later dependency code (e..g implementation, api, etc) to know which precise build it depends on

 defaultConfig {
        ...<snip unrelated>...

        // Ensure you specify the flavor you depend on!!
        // If dep has multiple flavor dimensions, you need to specify them all
        missingDimensionStrategy 'classpath', 'gms17'
    }

PHP: Count a stdClass object

count() function works with array. But if you want to count object's length then you can use this method.

$total = $obj->length;

insert vertical divider line between two nested divs, not full height

Try this. I set the blue box to float right, gave left and right a fixed height, and added a white border on the right of the left div. Also added rounded corners to more match your example (These won't work in ie 8 or less). I also took out the position: relative. You don't need it. Block level elements are set to position relative by default.

See it here: http://jsfiddle.net/ZSgLJ/

#left {
  float: left;
  width: 44%;
  margin: 0;
  padding: 0;
  border-right: 1px solid white;
  height:400px;
}

#right {
  position: relative;
  float: right;
  width: 49%;
  margin: 0;
  padding: 0;
  height:400px;
}

#blue_box {
  background-color:blue;
  border-radius: 10px;
  -moz-border-radius:10px;
  -webkit-border-radius: 10px;
  width: 45%;
  min-width: 400px;
  max-width: 600px;
  padding: 2%;
  float: right;
}

Set folder for classpath

Use the command as

java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>

The above command will set the mentioned paths to classpath only once for executing the class named TestClass.

If you want to execute more then one classes, then you can follow this

set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"

After this you can execute as many classes as you want just by simply typing

java <your-class-name>

The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)

If you want to set the classpth only once so that it could work for everytime, then do as follows

1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
    a.  Variable Name-     classpath
    b.  Variable Value-    .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.

Remember this will work every time. You don't need to explicitly set the classpath again and again.

NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.

Hope this will help you.

What is the best way to calculate a checksum for a file that is on my machine?

On MySQL.com, MD5s are listed alongside each file that you can download. For instance, MySQL "Windows Essentials" 5.1 is 528c89c37b3a6f0bd34480000a56c372.

You can download md5 (md5.exe), a command line tool that will calculate the MD5 of any file that you have locally. MD5 is just like any other cryptographic hash function, which means that a given array of bytes will always produce the same hash. That means if your downloaded MySQL zip file (or whatever) has the same MD5 as they post on their site, you have the exact same file.

regex for zip-code

^\d{5}(?:[-\s]\d{4})?$
  • ^ = Start of the string.
  • \d{5} = Match 5 digits (for condition 1, 2, 3)
  • (?:…) = Grouping
  • [-\s] = Match a space (for condition 3) or a hyphen (for condition 2)
  • \d{4} = Match 4 digits (for condition 2, 3)
  • …? = The pattern before it is optional (for condition 1)
  • $ = End of the string.

Regex AND operator

It is impossible for both (?=foo) and (?=baz) to match at the same time. It would require the next character to be both f and b simultaneously which is impossible.

Perhaps you want this instead:

(?=.*foo)(?=.*baz)

This says that foo must appear anywhere and baz must appear anywhere, not necessarily in that order and possibly overlapping (although overlapping is not possible in this specific case because the letters themselves don't overlap).

error: use of deleted function

The error message clearly says that the default constructor has been deleted implicitly. It even says why: the class contains a non-static, const variable, which would not be initialized by the default ctor.

class X {
    const int x;
};

Since X::x is const, it must be initialized -- but a default ctor wouldn't normally initialize it (because it's a POD type). Therefore, to get a default ctor, you need to define one yourself (and it must initialize x). You can get the same kind of situation with a member that's a reference:

class X { 
    whatever &x;
};

It's probably worth noting that both of these will also disable implicit creation of an assignment operator as well, for essentially the same reason. The implicit assignment operator normally does members-wise assignment, but with a const member or reference member, it can't do that because the member can't be assigned. To make assignment work, you need to write your own assignment operator.

This is why a const member should typically be static -- when you do an assignment, you can't assign the const member anyway. In a typical case all your instances are going to have the same value so they might as well share access to a single variable instead of having lots of copies of a variable that will all have the same value.

It is possible, of course, to create instances with different values though -- you (for example) pass a value when you create the object, so two different objects can have two different values. If, however, you try to do something like swapping them, the const member will retain its original value instead of being swapped.

Install NuGet via PowerShell script

Here's a short PowerShell script to do what you probably expect:

$sourceNugetExe = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
$targetNugetExe = "$rootPath\nuget.exe"
Invoke-WebRequest $sourceNugetExe -OutFile $targetNugetExe
Set-Alias nuget $targetNugetExe -Scope Global -Verbose

Note that Invoke-WebRequest cmdlet arrived with PowerShell v3.0. This article gives the idea.

Is it possible to create a 'link to a folder' in a SharePoint document library?

i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.

Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.

.url files can be made by saving a favourite with internet exploiter.

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

A common thing when this happens is if you've simply forgotten to include the type in your script calls. You'll have to set it explicitly, as it is - according to W3 - required:

type (content-type): This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.

Still it seems that browsers have a a default value of plain/text.

Example:

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>

You could as well set a default for that file extension in your Apache configuration:

<IfModule mod_mime.c>
    AddType text/javascript .js
</IfModule>

Side-by-side plots with ggplot2

Using the patchwork package, you can simply use + operator:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))


p1 + p2

patchwork

Other operators include / to stack plots to place plots side by side, and () to group elements. For example you can configure a top row of 3 plots and a bottom row of one plot with (p1 | p2 | p3) /p. For more examples, see the package documentation.

How to get base64 encoded data from html image

You can also use the FileReader class :

    var reader = new FileReader();
    reader.onload = function (e) {
        var data = this.result;
    }
    reader.readAsDataURL( file );

Copy a variable's value into another

I solved it myself for the time being. The original value has only 2 sub-properties. I reformed a new object with the properties from a and then assigned it to b. Now my event handler updates only b, and my original a stays as it is.

var a = { key1: 'value1', key2: 'value2' },
    b = a;

$('#revert').on('click', function(e){
    //FAIL!
    b = a;

    //WIN
    b = { key1: a.key1, key2: a.key2 };
});

This works fine. I have not changed a single line anywhere in my code except for the above, and it works just how I wanted it to. So, trust me, nothing else was updating a.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Another, and more streamlined, approach to deserializing a camel-cased JSON string to a pascal-cased POCO object is to use the CamelCasePropertyNamesContractResolver.

It's part of the Newtonsoft.Json.Serialization namespace. This approach assumes that the only difference between the JSON object and the POCO lies in the casing of the property names. If the property names are spelled differently, then you'll need to resort to using JsonProperty attributes to map property names.

using Newtonsoft.Json; 
using Newtonsoft.Json.Serialization;

. . .

private User LoadUserFromJson(string response) 
{
    JsonSerializerSettings serSettings = new JsonSerializerSettings();
    serSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    User outObject = JsonConvert.DeserializeObject<User>(jsonValue, serSettings);

    return outObject; 
}

Datepicker: How to popup datepicker when click on edittext

 selectDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DatePickerDialog  mdiDialog =new DatePickerDialog(mContext,new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        Toast.makeText(getApplicationContext(),year+ " "+monthOfYear+" "+dayOfMonth,Toast.LENGTH_LONG).show();


                    }
                }, year, month, date);
                mdiDialog.show();

            }

        });

Set View Width Programmatically

in code add below line:

spin27.setLayoutParams(new LinearLayout.LayoutParams(200, 120));

Fixed positioning in Mobile Safari

See Google's solution to this problem. You basically have to scroll content yourself using JavaScript. Sencha Touch also provides a library for getting this behavior in a very performant manor.

Extract Google Drive zip from Google colab notebook

TO unzip a file to a directory:

!unzip path_to_file.zip -d path_to_directory

Node.js: Python not found exception due to node-sass and node-gyp

node-gyp requires old Python 2 - link

If you don't have it installed - check other answers about installing windows-build-tools.

If you are like me and have both old and new Python versions installed, chances are that node-gyp tries to use Python 3. And that results in the following SyntaxError: invalid syntax error.

I found an article about having two Python versions installed. And they recommend renaming Python 2.* executable to python2.exe - link.

So it looks like node-gyp is expecting to find old Python 2 executable renamed. Hence the error message:

...
gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` failed Error: not found: python2
...

Once I renamed C:\Python27\python.exe to C:\Python27\python2.exe it worked without errors.

Of course, both C:\Python27\ and C:\Python39\ have to be in PATH variable. And no need in setting old Python version in npm config. Your default Python still will be the new one.

Create a custom event in Java

The following is not exactly the same but similar, I was searching for a snippet to add a call to the interface method, but found this question, so I decided to add this snippet for those who were searching for it like me and found this question:

 public class MyClass
 {
        //... class code goes here

        public interface DataLoadFinishedListener {
            public void onDataLoadFinishedListener(int data_type);
        }

        private DataLoadFinishedListener m_lDataLoadFinished;

        public void setDataLoadFinishedListener(DataLoadFinishedListener dlf){
            this.m_lDataLoadFinished = dlf;
        }



        private void someOtherMethodOfMyClass()
        {
            m_lDataLoadFinished.onDataLoadFinishedListener(1);
        }    
    }

Usage is as follows:

myClassObj.setDataLoadFinishedListener(new MyClass.DataLoadFinishedListener() {
            @Override
            public void onDataLoadFinishedListener(int data_type) {
                }
            });

Changing capitalization of filenames in Git

Sometimes you want to change the capitalization of a lot of file names on a case insensitive filesystem (e.g. on OS X or Windows). Doing git mv commands will tire quickly. To make things a bit easier this is what I do:

  1. Move all files outside of the directory to, let’s, say the desktop.
  2. Do a git add . -A to remove all files.
  3. Rename all files on the desktop to the proper capitalization.
  4. Move all the files back to the original directory.
  5. Do a git add .. Git should see that the files are renamed.

Now you can make a commit saying you have changed the file name capitalization.

MVC 4 @Scripts "does not exist"

If you added to your web.config and it still shows message, then you need to close your project and reopen it, now it will exist and @Styles.Render("") and @Scripts.Render() will work fine.

Type converting slices of interfaces

In Go, there is a general rule that syntax should not hide complex/costly operations. Converting a string to an interface{} is done in O(1) time. Converting a []string to an interface{} is also done in O(1) time since a slice is still one value. However, converting a []string to an []interface{} is O(n) time because each element of the slice must be converted to an interface{}.

The one exception to this rule is converting strings. When converting a string to and from a []byte or a []rune, Go does O(n) work even though conversions are "syntax".

There is no standard library function that will do this conversion for you. You could make one with reflect, but it would be slower than the three line option.

Example with reflection:

func InterfaceSlice(slice interface{}) []interface{} {
    s := reflect.ValueOf(slice)
    if s.Kind() != reflect.Slice {
        panic("InterfaceSlice() given a non-slice type")
    }

    // Keep the distinction between nil and empty slice input
    if s.IsNil() {
        return nil
    }

    ret := make([]interface{}, s.Len())

    for i:=0; i<s.Len(); i++ {
        ret[i] = s.Index(i).Interface()
    }

    return ret
}

Your best option though is just to use the lines of code you gave in your question:

b := make([]interface{}, len(a))
for i := range a {
    b[i] = a[i]
}

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

segmentation fault : 11

What system are you running on? Do you have access to some sort of debugger (gdb, visual studio's debugger, etc.)?

That would give us valuable information, like the line of code where the program crashes... Also, the amount of memory may be prohibitive.

Additionally, may I recommend that you replace the numeric limits by named definitions?

As such:

#define DIM1_SZ 1000
#define DIM2_SZ 1000000

Use those whenever you wish to refer to the array dimension limits. It will help avoid typing errors.

How do I clear the content of a div using JavaScript?

Just Javascript (as requested)

Add this function somewhere on your page (preferably in the <head>)

function clearBox(elementID)
{
    document.getElementById(elementID).innerHTML = "";
}

Then add the button on click event:

<button onclick="clearBox('cart_item')" />

In JQuery (for reference)

If you prefer JQuery you could do:

$("#cart_item").html("");

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

Cannot attach the file *.mdf as database

Just change database name from web.config project level file and then update database.

connectionString = Data Source =(LocalDb)\MSSQLLocalDB;AttachDbFilename="|DataDirectory|\aspnet-Project name-20180413070506.mdf";Initial Catalog="aspnet--20180413070506";Integrated

Change the bold digit to some other number:

connectionString = Data Source==(LocalDb)\MSSQLLocalDB;AttachDbFilename="|DataDirectory|\aspnet-Project name-20180413070507.mdf";Initial Catalog="aspnet--20180413070507";Integrated

Insert multiple values using INSERT INTO (SQL Server 2005)

In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.

 INSERT INTO TableName ( Column1, Column2 ) VALUES
    ( Value1, Value2 ), ( Value1, Value2 )

Another way

INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2

Is there any difference between "!=" and "<>" in Oracle Sql?

At university we were taught 'best practice' was to use != when working for employers, though all the operators above have the same functionality.

How can I ssh directly to a particular directory?

I know this has been answered ages ago but I found the question while trying to incorporate an ssh login in a bash script and once logged in run a few commands and log back out and continue with the bash script. The simplest way I found which hasnt been mentioned elsewhere because it is so trivial is to do this.

#!/bin/bash

sshpass -p "password" ssh user@server 'cd /path/to/dir;somecommand;someothercommand;exit;'

How do I find the difference between two values without knowing which is larger?

Although abs(x - y) or equivalently abs(y - x) is preferred, if you are curious about a different answer, the following one-liners also work:

  • max(x - y, y - x)

  • -min(x - y, y - x)

  • max(x, y) - min(x, y)

  • (x - y) * math.copysign(1, x - y), or equivalently (d := x - y) * math.copysign(1, d) in Python =3.8

  • functools.reduce(operator.sub, sorted([x, y], reverse=True))

expected assignment or function call: no-unused-expressions ReactJS

In my case it is happened due to curly braces of function if you use jsx then you need to change curly braces to Parentheses, see below code

const [countries] = useState(["USA", "UK", "BD"])

I tried this but not work, don't know why

 {countries.map((country) => {
        <MenuItem value={country}>{country}</MenuItem>
  })}

But when I change Curly Braces to parentheses and Its working fine for me

  {countries.map((country) => ( //Changes is here instead of {
        <MenuItem value={country}>{country}</MenuItem>
  ))} //and here instead of }
             

Hopefully it will help you too...

Get Locale Short Date Format using javascript

Try this:

new Date().toLocaleFormat("%x");

All formats for this function can be found here: http://pubs.opengroup.org/onlinepubs/007908799/xsh/strftime.html

Why does my 'git branch' have no master?

If you create a new repository from the Github web GUI, you sometimes get the name 'main' instead of 'master'. By using the command git status from your terminal you'd see which location you are. In some cases, you'd see origin/main.

If you are trying to push your app to a cloud service via CLI then use 'main', not 'master'.

example: git push heroku main

Set up a scheduled job?

I use celery to create my periodical tasks. First you need to install it as follows:

pip install django-celery

Don't forget to register django-celery in your settings and then you could do something like this:

from celery import task
from celery.decorators import periodic_task
from celery.task.schedules import crontab
from celery.utils.log import get_task_logger
@periodic_task(run_every=crontab(minute="0", hour="23"))
def do_every_midnight():
 #your code

Where do I configure log4j in a JUnit test class?

The LogManager class determines which log4j config to use in a static block which runs when the class is loaded. There are three options intended for end-users:

  1. If you specify log4j.defaultInitOverride to false, it will not configure log4j at all.
  2. Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to java:

    -Dlog4j.configuration=<path to properties file>

    in your test runner configuration.

  3. Allow log4j to scan the classpath for a log4j config file during your test. (the default)

See also the online documentation.

Should __init__() call the parent class's __init__()?

In Anon's answer:
"If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__ , you must call it yourself, since that will not happen automatically"

It's incredible: he is wording exactly the contrary of the principle of inheritance.


It is not that "something from super's __init__ (...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__ is overriden by the definition of the derived-clas __init__

So then, WHY defining a derived_class' __init__ , since it overrides what is aimed at when someone resorts to inheritance ??

It's because one needs to define something that is NOT done in the base-class' __init__ , and the only possibility to obtain that is to put its execution in a derived-class' __init__ function.
In other words, one needs something in base-class' __init__ in addition to what would be automatically done in the base-classe' __init__ if this latter wasn't overriden.
NOT the contrary.


Then, the problem is that the desired instructions present in the base-class' __init__ are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__ , in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__ . That's exactly what is said in the official doc:

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments).
http://docs.python.org/tutorial/classes.html#inheritance

That's all the story:

  • when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__ function in the derived class

  • when the aim is to REPLACE the initialization performed by the base-class, __init__ must be defined in the derived-class

  • when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__ must be defined , comprising an explicit call to the base-class __init__


What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.

CHECK constraint in MySQL is not working

Check constraints are supported as of version 8.0.15 (yet to be released)

https://bugs.mysql.com/bug.php?id=3464

[23 Jan 16:24] Paul Dubois

Posted by developer: Fixed in 8.0.15.

Previously, MySQL permitted a limited form of CHECK constraint syntax, but parsed and ignored it. MySQL now implements the core features of table and column CHECK constraints, for all storage engines. Constraints are defined using CREATE TABLE and ALTER TABLE statements.

Assign command output to variable in batch file

This post has a method to achieve this

from (zvrba) You can do it by redirecting the output to a file first. For example:

echo zz > bla.txt
set /p VV=<bla.txt
echo %VV%

Freely convert between List<T> and IEnumerable<T>

List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myEnumerable.ToList();

How do I perform a JAVA callback between classes?

In this particular case, the following should work:

serverConnectionHandler = new ServerConnections(_address) {
    public void newConnection(Socket _socket) {
        System.out.println("A function of my child class was called.");
    }
};

It's an anonymous subclass.

Full Screen Theme for AppCompat

Issues arise among before and after versions of Android 4.0 (API level 14).

from here I created my own solution.

@SuppressLint("NewApi")
@Override
protected void onResume()
{
    super.onResume();

    if (Build.VERSION.SDK_INT < 16)
    {
        // Hide the status bar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // Hide the action bar
        getSupportActionBar().hide();
    }
    else
    {
        // Hide the status bar
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        / Hide the action bar
        getActionBar().hide();
    }
}

I write this code in onResume() method because if you exit from your app and then you reopen it, the action bar remains active! (and so this fix the problem)

I hope it was helpful ;)

In MVC, how do I return a string result?

public ActionResult GetAjaxValue()
{
   return Content("string value");
}

Clearing the terminal screen?

There is no way to clear the screen but, a really easy way to fake it can be printing as much Serial.println(); as you need to keep all the old data out of the screen.

FirebaseInstanceIdService is deprecated

FirebaseinstanceIdService is deprecated. So have to use "FirebaseMessagingService"

Sea the image please:

enter image description here

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("NEW_TOKEN",s);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }
}

Calling filter returns <filter object at ... >

It's an iterator returned by the filter function.

If you want a list, just do

list(filter(f, range(2, 25)))

Nonetheless, you can just iterate over this object with a for loop.

for e in filter(f, range(2, 25)):
    do_stuff(e)

What is an instance variable in Java?

An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new), whereas a class variable is a member of the class itself.

Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.

What’s the difference between a class variable and an instance variable?

This test class illustrates the difference:

public class Test {
   
    public static String classVariable = "I am associated with the class";
    public String instanceVariable = "I am associated with the instance";
    
    public void setText(String string){
        this.instanceVariable = string;
    }
    
    public static void setClassText(String string){
        classVariable = string;
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        
        // Change test1's instance variable
        test1.setText("Changed");
        System.out.println(test1.instanceVariable); // Prints "Changed"
        // test2 is unaffected
        System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
        
        // Change class variable (associated with the class itself)
        Test.setClassText("Changed class text");
        System.out.println(Test.classVariable); // Prints "Changed class text"
        
        // Can access static fields through an instance, but there still is only one
        // (not best practice to access static variables through instance)
        System.out.println(test1.classVariable); // Prints "Changed class text"
        System.out.println(test2.classVariable); // Prints "Changed class text"
    }
}

reCAPTCHA ERROR: Invalid domain for site key

I guess the quickest way is just to disable the domain check while you're developing it enter image description here

Reversing a String with Recursion in Java

Best Solution what I found.

public class Manager
{
    public static void main(String[] args)
    {
        System.out.println("Sameer after reverse : " 
                         + Manager.reverse("Sameer"));
        System.out.println("Single Character a after reverse : " 
                         + Manager.reverse("a"));
        System.out.println("Null Value after reverse : "
                         + Manager.reverse(null));
        System.out.println("Rahul after reverse : "
                         + Manager.reverse("Rahul"));
    }

    public static String reverse(String args)
    {
        if(args == null || args.length() < 1 
                                || args.length() == 1)
        {
            return args;
        }
        else
        {
                return "" + 
                               args.charAt(args.length()-1) + 
                               reverse(args.substring(0, args.length()-1));                                  
        }
    }
}

Output:C:\Users\admin\Desktop>java Manager Sameer after reverse : reemaS Single Character a after reverse : a Null Value after reverse : null Rahul after reverse : luhaR

How to format a JavaScript date

May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20

what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",

Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11

Big-oh vs big-theta

Because my keyboard has an O key.
It does not have a T or an O key.

I suspect most people are similarly lazy and use O when they mean T because it's easier to type.