Programs & Examples On #Belief propagation

What is the meaning of prepended double colon "::"?

(This answer is mostly for googlers, because OP has solved his problem already.) The meaning of prepended :: - scope resulution operator - has been described in other answers, but I'd like to add why people are using it.

The meaning is "take name from global namespace, not anything else". But why would this need to be spelled explicitly?

Use case - namespace clash

When you have the same name in global namespace and in local/nested namespace, the local one will be used. So if you want the global one, prepend it with ::. This case was described in @Wyatt Anderson's answer, plese see his example.

Use case - emphasise non-member function

When you are writing a member function (a method), calls to other member function and calls to non-member (free) functions look alike:

class A {
   void DoSomething() {
      m_counter=0;
      ...
      Twist(data); 
      ...
      Bend(data);
      ...
      if(m_counter>0) exit(0);
   }
   int m_couner;
   ...
}

But it might happen that Twist is a sister member function of class A, and Bend is a free function. That is, Twist can use and modify m_couner and Bend cannot. So if you want to ensure that m_counter remains 0, you have to check Twist, but you don't need to check Bend.

So to make this stand out more clearly, one can either write this->Twist to show the reader that Twist is a member function or write ::Bend to show that Bend is free. Or both. This is very useful when you are doing or planning a refactoring.

Getting Date or Time only from a DateTime Object

You can also use DateTime.Now.ToString("yyyy-MM-dd") for the date, and DateTime.Now.ToString("hh:mm:ss") for the time.

pros and cons between os.path.exists vs os.path.isdir

os.path.isdir() checks if the path exists and is a directory and returns TRUE for the case.

Similarly, os.path.isfile() checks if the path exists and is a file and returns TRUE for the case.

And, os.path.exists() checks if the path exists and doesn’t care if the path points to a file or a directory and returns TRUE in either of the cases.

Subtract one day from datetime

This should work.

select DATEADD(day, -1, convert(date, GETDATE()))

Center a button in a Linear layout

If you want to center an item in the middle of the screen don't use a LinearLayout as these are meant for displaying a number of items in a row.

Use a RelativeLayout instead.

So replace:

android:layout_gravity="center_vertical|center_horizontal"

for the relevant RelativeLayout option:

android:layout_centerInParent="true"

So your layout file will look like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout01" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageButton android:id="@+id/btnFindMe" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/findme"></ImageButton>

</RelativeLayout>

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


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

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

How to make Apache serve index.php instead of index.html?

As of today (2015, Aug., 1st), Apache2 in Debian Jessie, you need to edit:

root@host:/etc/apache2/mods-enabled$ vi dir.conf 

And change the order of that line, bringing index.php to the first position:

DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm

Get filename in batch for loop

The answer by @AKX works on the command line, but not within a batch file. Within a batch file, you need an extra %, like this:

@echo off
for /R TutorialSteps %%F in (*.py) do echo %%~nF

How to get the range of occupied cells in excel sheet

The only way I could get it to work in ALL scenarios (except Protected sheets) (based on Farham's Answer):

It supports:

  • Scanning Hidden Row / Columns

  • Ignores formatted cells with no data / formula

Code:

// Unhide All Cells and clear formats
sheet.Columns.ClearFormats();
sheet.Rows.ClearFormats();

// Detect Last used Row - Ignore cells that contains formulas that result in blank values
int lastRowIgnoreFormulas = sheet.Cells.Find(
                "*",
                System.Reflection.Missing.Value,
                InteropExcel.XlFindLookIn.xlValues,
                InteropExcel.XlLookAt.xlWhole,
                InteropExcel.XlSearchOrder.xlByRows,
                InteropExcel.XlSearchDirection.xlPrevious,
                false,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value).Row;
// Detect Last Used Column  - Ignore cells that contains formulas that result in blank values
int lastColIgnoreFormulas = sheet.Cells.Find(
                "*",
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value,
                InteropExcel.XlSearchOrder.xlByColumns,
                InteropExcel.XlSearchDirection.xlPrevious,
                false,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value).Column;

// Detect Last used Row / Column - Including cells that contains formulas that result in blank values
int lastColIncludeFormulas = sheet.UsedRange.Columns.Count;
int lastColIncludeFormulas = sheet.UsedRange.Rows.Count;

How to detect the device orientation using CSS media queries?

In Javascript it is better to use screen.width and screen.height. These two values are available in all modern browsers. They give the real dimensions of the screen, even if the browser has been scaled down when the app fires up. window.innerWidth changes when the browser is scaled down, which can't happen on mobile devices but can happen on PCs and laptops.

The values of screen.width and screen.height change when the mobile device flips between portrait and landscape modes, so it is possible to determine the mode by comparing the values. If screen.width is greater than 1280px you're dealing with a PC or laptop.

You can construct an event listener in Javascript to detect when the two values are flipped. The portrait screen.width values to concentrate on are 320px (mainly iPhones), 360px (most other phones), 768px (small tablets) and 800px (regular tablets).

How do I integrate Ajax with Django applications?

AJAX is the best way to do asynchronous tasks. Making asynchronous calls is something common in use in any website building. We will take a short example to learn how we can implement AJAX in Django. We need to use jQuery so as to write less javascript.

This is Contact example, which is the simplest example, I am using to explain the basics of AJAX and its implementation in Django. We will be making POST request in this example. I am following one of the example of this post: https://djangopy.org/learn/step-up-guide-to-implement-ajax-in-django

models.py

Let's first create the model of Contact, having basic details.

from django.db import models

class Contact(models.Model):
    name = models.CharField(max_length = 100)
    email = models.EmailField()
    message = models.TextField()
    timestamp = models.DateTimeField(auto_now_add = True)

    def __str__(self):
        return self.name

forms.py

Create the form for the above model.

from django import forms
from .models import Contact

class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact
        exclude = ["timestamp", ]

views.py

The views look similar to the basic function-based create view, but instead of returning with render, we are using JsonResponse response.

from django.http import JsonResponse
from .forms import ContactForm

def postContact(request):
    if request.method == "POST" and request.is_ajax():
        form = ContactForm(request.POST)
        form.save()
        return JsonResponse({"success":True}, status=200)
    return JsonResponse({"success":False}, status=400)

urls.py

Let's create the route of the above view.

from django.contrib import admin
from django.urls import path
from app_1 import views as app1

urlpatterns = [
    path('ajax/contact', app1.postContact, name ='contact_submit'),
]

template

Moving to frontend section, render the form which was created above enclosing form tag along with csrf_token and submit button. Note that we have included the jquery library.

<form id = "contactForm" method= "POST">{% csrf_token %}
   {{ contactForm.as_p }}
  <input type="submit" name="contact-submit" class="btn btn-primary" />
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Javascript

Let's now talk about javascript part, on the form submit we are making ajax request of type POST, taking the form data and sending to the server side.

$("#contactForm").submit(function(e){
    // prevent from normal form behaviour
        e.preventDefault();
        // serialize the form data  
        var serializedData = $(this).serialize();
        $.ajax({
            type : 'POST',
            url :  "{% url 'contact_submit' %}",
            data : serializedData,
            success : function(response){
            //reset the form after successful submit
                $("#contactForm")[0].reset(); 
            },
            error : function(response){
                console.log(response)
            }
        });
   });

This is just a basic example to get started with AJAX with django, if you want to get dive with several more examples, you can go through this article: https://djangopy.org/learn/step-up-guide-to-implement-ajax-in-django

Error when using scp command "bash: scp: command not found"

Make sure the scp command is available on both sides - both on the client and on the server.

If this is Fedora or Red Hat Enterprise Linux and clones (CentOS), make sure this package is installed:

    yum -y install openssh-clients

If you work with Debian or Ubuntu and clones, install this package:

    apt-get install openssh-client

Again, you need to do this both on the server and the client, otherwise you can encounter "weird" error messages on your client: scp: command not found or similar although you have it locally. This already confused thousands of people, I guess :)

remove borders around html input

It's simple

input {border:0;outline:0;}
input:focus {outline:none!important;}

Media Player called in state 0, error (-38,0)

I got this error when I was trying to get the current position (MediaPlayer.getCurrentPosition()) of media player when it wasn't in the prepared stated. I got around this by Keeping track of its state and only calling the getCurrentPosition() method after onPreparedListener is called.

What is the main purpose of setTag() getTag() methods of View?

I'd like to add few words.

Although using get/setTag(Object) seems to be very useful in the particular case of a ViewHolder pattern, I'd recommend to think twice before using it in other cases. There is almost always another solution with better design.

The main reason is that code like that becomes unsupportable pretty quickly.

  • It is non-obvious for other developers what you designed to store as tag in the view. The methods setTag/getTag are not descriptive at all.

  • It just stores an Object, which requires to be cast when you want to getTag. You can get unexpected crashes later when you decide to change the type of stored object in the tag.

  • Here's a real-life story: We had a pretty big project with a lot of adapters, async operations with views and so on. One developer decided to set/getTag in his part of code, but another one had already set the tag to this view. In the end, someone couldn't find his own tag and was very confused. It cost us several hours to find the bug.

setTag(int key, Object tag) looks much better, cause you can generate unique keys for every tag (using id resources), but there is a significant restriction for Android < 4.0. From Lint docs:

Prior to Android 4.0, the implementation of View.setTag(int, Object) would store the objects in a static map, where the values were strongly referenced. This means that if the object contains any references pointing back to the context, the context (which points to pretty much everything else) will leak. If you pass a view, the view provides a reference to the context that created it. Similarly, view holders typically contain a view, and cursors are sometimes also associated with views.

FirebaseInstanceIdService is deprecated

For kotlin I use the following

val fcmtoken = FirebaseMessaging.getInstance().token.await()

and for the extension functions

public suspend fun <T> Task<T>.await(): T {
    // fast path
    if (isComplete) {
        val e = exception
        return if (e == null) {
            if (isCanceled) {
                throw CancellationException("Task $this was cancelled normally.")
            } else {
                @Suppress("UNCHECKED_CAST")
                result as T
            }
        } else {
            throw e
        }
    }

    return suspendCancellableCoroutine { cont ->
        addOnCompleteListener {
            val e = exception
            if (e == null) {
                @Suppress("UNCHECKED_CAST")
                if (isCanceled) cont.cancel() else cont.resume(result as T)
            } else {
                cont.resumeWithException(e)
            }
        }
    }
}

How to Lazy Load div background images

I know it's not related to the image load but here what I did in one of the job interview test.

HTML

<div id="news-feed">Scroll to see News (Newest First)</div>

CSS

article {
   margin-top: 500px;
   opacity: 0;
   border: 2px solid #864488;
   padding: 5px 10px 10px 5px;
   background-image: -webkit-gradient(
   linear,
   left top,
   left bottom,
   color-stop(0, #DCD3E8),
   color-stop(1, #BCA3CC)
   );
   background-image: -o-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -moz-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -webkit-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: -ms-linear-gradient(bottom, #DCD3E8 0%, #BCA3CC 100%);
   background-image: linear-gradient(to bottom, #DCD3E8 0%, #BCA3CC 100%);
   color: gray;
   font-family: arial;    
}

article h4 {
   font-family: "Times New Roman";
   margin: 5px 1px;
}

.main-news {
   border: 5px double gray;
   padding: 15px;
}

JavaScript

var newsData,
    SortData = '',
    i = 1;

$.getJSON("http://www.stellarbiotechnologies.com/media/press-releases/json", function(data) {

   newsData = data.news;

   function SortByDate(x,y) {
     return ((x.published == y.published) ? 0 : ((x.published < y.published) ? 1 : -1 ));
   }

   var sortedNewsData = newsData.sort(SortByDate);

   $.each( sortedNewsData, function( key, val ) {
     SortData += '<article id="article' + i + '"><h4>Published on: ' + val.published + '</h4><div  class="main-news">' + val.title + '</div></article>';
     i++;    
   });

   $('#news-feed').append(SortData);
});

$(window).scroll(function() {

   var $window = $(window),
       wH = $window.height(),
       wS = $window.scrollTop() + 1

   for (var j=0; j<$('article').length;j++) {
      var eT = $('#article' + j ).offset().top,
          eH = $('#article' + j ).outerHeight();

          if (wS > ((eT + eH) - (wH))) {
             $('#article' + j ).animate({'opacity': '1'}, 500);
          }
    }

});

I am sorting the data by Date and then doing lazy load on window scroll function.

I hope it helps :)

Demo

Avoid browser popup blockers

My use case: In my react app, Upon user click there is an API call performed to the backend. Based on the response, new tab is opened with the api response added as params to the new tab URL (in same domain).

The only caveat in my use case is that it takes more for 1 second for the API response to be received. Hence pop-up blocker shows up (if it is active) when opening up URL in a new tab.

To circumvent the above described issue, here is the sample code,

var new_tab=window.open()
axios.get('http://backend-api').then(response=>{
    const url="http://someurl"+"?response"
    new_tab.location.href=url;
}).catch(error=>{
    //catch error
})

Summary: Create an empty tab (as above line 1) and when the API call is completed, you can fill up the tab with the url and skip the popup blocker.

NSDictionary - Need to check whether dictionary contains key-value pair or not

Just ask it for the objectForKey:@"b". If it returns nil, no object is set at that key.

if ([xyz objectForKey:@"b"]) {
    NSLog(@"There's an object set for key @\"b\"!");
} else {
    NSLog(@"No object set for key @\"b\"");
}

Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

I've found an solution. I use an solution of Steve Gentile, jQuery and ASP.NET MVC – sending JSON to an Action – Revisited.

My ASP.NET MVC view code looks like:

function getplaceholders() {
        var placeholders = $('.ui-sortable');
        var results = new Array();
        placeholders.each(function() {
            var ph = $(this).attr('id');
            var sections = $(this).find('.sort');
            var section;

            sections.each(function(i, item) {
                var sid = $(item).attr('id');
                var o = { 'SectionId': sid, 'Placeholder': ph, 'Position': i };
                results.push(o);
            });
        });
        var postData = { widgets: results };
        var widgets = results;
        $.ajax({
            url: '/portal/Designer.mvc/SaveOrUpdate',
            type: 'POST',
            dataType: 'json',
            data: $.toJSON(widgets),
            contentType: 'application/json; charset=utf-8',
            success: function(result) {
                alert(result.Result);
            }
        });
    };

and my controller action is decorated with an custom attribute

[JsonFilter(Param = "widgets", JsonDataType = typeof(List<PageDesignWidget>))]
public JsonResult SaveOrUpdate(List<PageDesignWidget> widgets

Code for the custom attribute can be found here (the link is broken now).

Because the link is broken this is the code for the JsonFilterAttribute

public class JsonFilter : ActionFilterAttribute
{
    public string Param { get; set; }
    public Type JsonDataType { get; set; }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
        {
            string inputContent;
            using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
            {
                inputContent = sr.ReadToEnd();
            }
            var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);
            filterContext.ActionParameters[Param] = result;
        }
    }
}

JsonConvert.DeserializeObject is from Json.NET

Link: Serializing and Deserializing JSON with Json.NET

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 

how to set default culture info for entire c# application

Not for entire application or particular class.

CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture at all.

Sample code to change cultures for current thread:

CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:

(3.3).ToString(new CultureInfo("fr-FR"))

Android refresh current activity

Try this

Simple way

 Intent intent=new Intent(Current_Activity.this,Current_Activity.class);
    startActivity(intent);
    finish();

How to detect escape key press with pure JS or jQuery?

i think the simplest way is vanilla javascript:

document.onkeyup = function(event) {
   if (event.keyCode === 27){
     //do something here
   }
}

Updated: Changed key => keyCode

Does Git Add have a verbose switch

For some git-commands you can specify --verbose,

git 'command' --verbose

or

git 'command' -v.

Make sure the switch is after the actual git command. Otherwise - it won't work!

Also useful:

git 'command' --dry-run 

Round a floating-point number down to the nearest integer?

Simple

print int(x)

will work as well.

Is it possible to run an .exe or .bat file on 'onclick' in HTML

Here's what I did. I wanted a HTML page setup on our network so I wouldn't have to navigate to various folders to install or upgrade our apps. So what I did was setup a .bat file on our "shared" drive that everyone has access to, in that .bat file I had this code:

start /d "\\server\Software\" setup.exe

The HTML code was:

<input type="button" value="Launch Installer" onclick="window.open('file:///S:Test/Test.bat')" />

(make sure your slashes are correct, I had them the other way and it didn't work)

I preferred to launch the EXE directly but that wasn't possible, but the .bat file allowed me around that. Wish it worked in FF or Chrome, but only IE.

How can I get log4j to delete old rotating log files?

Logs rotate for a reason, so that you only keep so many log files around. In log4j.xml you can add this to your node:

<param name="MaxBackupIndex" value="20"/>

The value tells log4j.xml to only keep 20 rotated log files around. You can limit this to 5 if you want or even 1. If your application isn't logging that much data, and you have 20 log files spanning the last 8 months, but you only need a weeks worth of logs, then I think you need to tweak your log4j.xml "MaxBackupIndex" and "MaxFileSize" params.

Alternatively, if you are using a properties file (instead of the xml) and wish to save 15 files (for example)

log4j.appender.[appenderName].MaxBackupIndex = 15

C# getting the path of %AppData%

For ASP.NET, the Load User Profile setting needs to be set on the app pool but that's not enough. There is a hidden setting named setProfileEnvironment in \Windows\System32\inetsrv\Config\applicationHost.config, which for some reason is turned off by default, instead of on as described in the documentation. You can either change the default or set it on your app pool. All the methods on the Environment class will then return proper values.

Getting full URL of action in ASP.NET MVC

As Paddy mentioned: if you use an overload of UrlHelper.Action() that explicitly specifies the protocol to use, the generated URL will be absolute and fully qualified instead of being relative.

I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I suggest to write a custom extension method for the sake of readability:

/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
    string actionName, string controllerName, object routeValues = null)
{
    string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;

    return url.Action(actionName, controllerName, routeValues, scheme);
}

You can then simply use it like that in your view:

@Url.AbsoluteAction("Action", "Controller")

How do I convert a number to a letter in Java?

if you define a/A as 0

char res;
if (i>25 || i<0){
    res = null;
}
    res = (i) + 65
}
return res;

65 for captitals; 97 for non captitals

Get the first element of each tuple in a list in Python

res_list = [x[0] for x in rows]

c.f. http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

For a discussion on why to prefer comprehensions over higher-order functions such as map, go to http://www.artima.com/weblogs/viewpost.jsp?thread=98196.

What exactly does the "u" do? "git push -u origin master" vs "git push origin master"

git push -u origin master

… is the same as:

git push origin master ; git branch --set-upstream master origin/master

Do the last statement, if you forget the -u!

Or you could force it:

git config branch.master.remote origin
git config branch.master.merge refs/heads/master

If you let the command do it for you, it will pick your mistakes like if you typed a non-existent branch or you didn't git remote add; though that might be what you want. :)

Writing String to Stream and reading it back does not work

After you write to the MemoryStream and before you read it back, you need to Seek back to the beginning of the MemoryStream so you're not reading from the end.

UPDATE

After seeing your update, I think there's a more reliable way to build the stream:

UnicodeEncoding uniEncoding = new UnicodeEncoding();
String message = "Message";

// You might not want to use the outer using statement that I have
// I wasn't sure how long you would need the MemoryStream object    
using(MemoryStream ms = new MemoryStream())
{
    var sw = new StreamWriter(ms, uniEncoding);
    try
    {
        sw.Write(message);
        sw.Flush();//otherwise you are risking empty stream
        ms.Seek(0, SeekOrigin.Begin);

        // Test and work with the stream here. 
        // If you need to start back at the beginning, be sure to Seek again.
    }
    finally
    {
        sw.Dispose();
    }
}

As you can see, this code uses a StreamWriter to write the entire string (with proper encoding) out to the MemoryStream. This takes the hassle out of ensuring the entire byte array for the string is written.

Update: I stepped into issue with empty stream several time. It's enough to call Flush right after you've finished writing.

Batch Files - Error Handling

I generally find the conditional command concatenation operators much more convenient than ERRORLEVEL.

yourCommand && (
  echo yourCommand was successful
) || (
  echo yourCommand failed
)

There is one complication you should be aware of. The error branch will fire if the last command in the success branch raises an error.

yourCommand && (
  someCommandThatMayFail
) || (
  echo This will fire if yourCommand or someCommandThatMayFail raises an error
)

The fix is to insert a harmless command that is guaranteed to succeed at the end of the success branch. I like to use (call ), which does nothing except set the ERRORLEVEL to 0. There is a corollary (call) that does nothing except set the ERRORLEVEL to 1.

yourCommand && (
  someCommandThatMayFail
  (call )
) || (
  echo This can only fire if yourCommand raises an error
)

See Foolproof way to check for nonzero (error) return code in windows batch file for examples of the intricacies needed when using ERRORLEVEL to detect errors.

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

It seems that your action needs k but ModelBinder can not find it (from form, or request or view data or ..) Change your action to this:

public ActionResult DetailsData(int? k)
    {

        EmployeeContext Ec = new EmployeeContext();
        if (k != null)
        {
           Employee emp = Ec.Employees.Single(X => X.EmpId == k.Value);

           return View(emp);
        }
        return View();
    }

Pandas rename column by position?

try this

df.rename(columns={ df.columns[1]: "your value" }, inplace = True)

Reading a string with scanf

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)

Bloomberg Open API

This API has been available for a long time and enables to get access to market data (including live) if you are running a Bloomberg Terminal or have access to a Bloomberg Server, which is chargeable.

The only difference is that the API (not its code) has been open sourced, so it can now be used as a dependency in an open source project for example, without any copyrights issues, which was not the case before.

How to convert any Object to String?

I am try to convert Object type variable into string using this line of code

try this to convert object value to string:

Java Code

 Object dataobject=value;
    //convert object into String  
     String convert= String.valueOf(dataobject);

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

How to check if a file exists in a folder?

This way we can check for an existing file in a particular folder:

 string curFile = @"c:\temp\test.txt";  //Your path
 Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");

RecyclerView onClick

here my way

in activity class:

    public class MyActivity extends AppCompatActivity implements EmployeeAdapter.ClickListener {
    ...
    @Override
    public void onClick(int position) { ... }
    ...
    }

in adapter class:

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    ...
    @Override
    public void onBindViewHolder(){
         holder.textView1.setOnClickListener(v -> clickListener.onClick(position));
    }
    ...
    public interface ClickListener {
        void onClick(int position);
    }
    ...
    }

Expected block end YAML error

With YAML, remember that it is all about the spaces used to define configuration through the hierarchical structures (indents). Many problems encountered whilst parsing YAML documents simply stems from extra spaces (or not enough spaces) before a key value somewhere in the given YAML file.

Could not load type 'XXX.Global'

In my case, a AfterBuild target in the project to compile the web application was the reason for this error.

See here for more info

CSS rotation cross browser with jquery.animate()

Another answer, because jQuery.transit is not compatible with jQuery.easing. This solution comes as an jQuery extension. Is more generic, rotation is a specific case:

$.fn.extend({
    animateStep: function(options) {
        return this.each(function() {
            var elementOptions = $.extend({}, options, {step: options.step.bind($(this))});
            $({x: options.from}).animate({x: options.to}, elementOptions);
        });
    },
    rotate: function(value) {
        return this.css("transform", "rotate(" + value + "deg)");
    }
});

The usage is as simple as:

$(element).animateStep({from: 0, to: 90, step: $.fn.rotate});

Add Items to ListView - Android

Try this one it will work

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}

How to install trusted CA certificate on Android device?

There is a MUCH easier solution to this than posted here, or in related threads. If you are using a webview (as I am), you can achieve this by executing a JAVASCRIPT function within it. If you are not using a webview, you might want to create a hidden one for this purpose. Here's a function that works in just about any browser (or webview) to kickoff ca installation (generally through the shared os cert repository, including on a Droid). It uses a nice trick with iFrames. Just pass the url to a .crt file to this function:

function installTrustedRootCert( rootCertUrl ){
    id = "rootCertInstaller";
    iframe = document.getElementById( id );
    if( iframe != null ) document.body.removeChild( iframe );
    iframe = document.createElement( "iframe" );
    iframe.id = id;
    iframe.style.display = "none";
    document.body.appendChild( iframe );
    iframe.src = rootCertUrl;
}

UPDATE:

The iframe trick works on Droids with API 19 and up, but older versions of the webview won't work like this. The general idea still works though - just download/open the file with a webview and then let the os take over. This may be an easier and more universal solution (in the actual java now):

 public static void installTrustedRootCert( final String certAddress ){
     WebView certWebView = new WebView( instance_ );
     certWebView.loadUrl( certAddress );
 }

Note that instance_ is a reference to the Activity. This works perfectly if you know the url to the cert. In my case, however, I resolve that dynamically with the server side software. I had to add a fair amount of additional code to intercept a redirection url and call this in a manner which did not cause a crash based on a threading complication, but I won't add all that confusion here...

python request with authentication (access_token)

Have you tried the uncurl package (https://github.com/spulec/uncurl)? You can install it via pip, pip install uncurl. Your curl request returns:

>>> uncurl "curl --header \"Authorization:access_token myToken\" https://website.com/id"

requests.get("https://website.com/id",
    headers={
        "Authorization": "access_token myToken"
    },
    cookies={},
)

SQL Server check case-sensitivity?

SQL server determines case sensitivity by COLLATION.

COLLATION can be set at various levels.

  1. Server-level
  2. Database-level
  3. Column-level
  4. Expression-level

Here is the MSDN reference.

One can check the COLLATION at each level as mentioned in Raj More's answer.

Check Server Collation

SELECT SERVERPROPERTY('COLLATION')

Check Database Collation

SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;

Check Column Collation

select table_name, column_name, collation_name
from INFORMATION_SCHEMA.COLUMNS
where table_name = @table_name

Check Expression Collation

For expression level COLLATION you need to look at the expression. :)

It would be generally at the end of the expression as in below example.

SELECT name FROM customer ORDER BY name COLLATE Latin1_General_CS_AI;

Collation Description

For getting description of each COLLATION value try this.

SELECT * FROM fn_helpcollations()

And you should see something like this.

enter image description here

You can always put a WHERE clause to filter and see description only for your COLLATION.

You can find a list of collations here.

How to update Ruby with Homebrew?

open terminal

\curl -sSL https://get.rvm.io | bash -s stable

restart terminal then

rvm install ruby-2.4.2

check ruby version it should be 2.4.2

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You don't have to do anything special, it should just be working.

When I have a fresh rails app with this controller:

class FooController < ApplicationController
  def index
    raise "error"
  end
end

and go to http://127.0.0.1:3000/foo/

I am seeing the exception with a stack trace.

You might not see the whole stacktrace in the console log because Rails (since 2.3) filters lines from the stack trace that come from the framework itself.

See config/initializers/backtrace_silencers.rb in your Rails project

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

Your response must return some sort of Response object. You can't just return an object.

So change it to something like:

return Response::json($promotion);

or my favorite using the helper function:

return response()->json($promotion);

If returning a response doesn't work it may be some sort of encoding issue. See this article: The Response content must be a string or object implementing __toString(), \"boolean\" given."

How to add a button programmatically in VBA next to some sheet cell data?

Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange event:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim clickRng As Range
    Dim lastRow As Long

    lastRow = Range("A1").End(xlDown).Row
    Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A

    If Not Intersect(Target, clickRng) Is Nothing Then
        MyUserForm.Show //Launch custom userform
    End If

End Sub

Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)

Angular2 *ngIf check object array length in template

Maybe slight overkill but created library ngx-if-empty-or-has-items it checks if an object, set, map or array is not empty. Maybe it will help somebody. It has the same functionality as ngIf (then, else and 'as' syntax is supported).

arrayOrObjWithData = ['1'] || {id: 1}

<h1 *ngxIfNotEmpty="arrayOrObjWithData">
  You will see it
</h1>

 or 
 // store the result of async pipe in variable
 <h1 *ngxIfNotEmpty="arrayOrObjWithData$ | async as obj">
  {{obj.id}}
</h1>

 or

noData = [] || {}
<h1 *ngxIfHasItems="noData">
   You will NOT see it
</h1>

Git push failed, "Non-fast forward updates were rejected"

I encountered the same error, just add "--force" to the command, it works

git push origin master --force

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

Error: No module named psycopg2.extensions

In python 3.4, while in a virtual environment, make sure you have the build dependencies first:

sudo apt-get build-dep python3-psycopg2

Then install it:

pip install psycopg2 

How to force NSLocalizedString to use a specific language

For Swift you can override the main.swift file and set the UserDefaults string there before you app runs. This way you do not have to restart the App to see the desired effect.

import Foundation
import UIKit

// Your initialisation code here
let langCultureCode: String = "LANGUAGE_CODE"

UserDefaults.standard.set([langCultureCode], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()

UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(AppDelegate.self))

paired together with the removal of @UIApplicationMain in your AppDelegate.swift file.

Blade if(isset) is not working Laravel

On Controller

$data = ModelName::select('name')->get()->toArray();
return view('viewtemplatename')->with('yourVariableName', $data);

On Blade file

@if(isset($yourVariableName))
//do you work here
@endif

how to concatenate two dictionaries to create a new one in Python?

You can use the update() method to build a new dictionary containing all the items:

dall = {}
dall.update(d1)
dall.update(d2)
dall.update(d3)

Or, in a loop:

dall = {}
for d in [d1, d2, d3]:
  dall.update(d)

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

function convert(str) {
    var date = new Date(str),
        mnth = ("0" + (date.getMonth()+1)).slice(-2),
        day  = ("0" + date.getDate()).slice(-2);
        hours  = ("0" + date.getHours()).slice(-2);
        minutes = ("0" + date.getMinutes()).slice(-2);
    return [ date.getFullYear(), mnth, day, hours, minutes ].join("-");
}

I used this efficiently in angular because i was losing two hours on updating a $scope.STARTevent, and $scope.ENDevent, IN console.log was fine, however saving to mYsql dropped two hours.

var whatSTART = $scope.STARTevent;
whatSTART = convert(whatever);

THIS WILL ALSO work for END

TypeError: $(...).DataTable is not a function

// you can get the Jquery's librairies online with adding  those two rows in your page

 <script type="text/javascript"  src=" https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script> 

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"> 

What does yield mean in PHP?

An interesting aspect, which worth to be discussed here, is yielding by reference. Every time we need to change a parameter such that it is reflected outside of the function, we have to pass this parameter by reference. To apply this to generators, we simply prepend an ampersand & to the name of the generator and to the variable used in the iteration:

 <?php 
 /**
 * Yields by reference.
 * @param int $from
 */
function &counter($from) {
    while ($from > 0) {
        yield $from;
    }
}

foreach (counter(100) as &$value) {
    $value--;
    echo $value . '...';
}

// Output: 99...98...97...96...95...

The above example shows how changing the iterated values within the foreach loop changes the $from variable within the generator. This is because $from is yielded by reference due to the ampersand before the generator name. Because of that, the $value variable within the foreach loop is a reference to the $from variable within the generator function.

sql like operator to get the numbers only

You can use the following to only include valid characters:

SQL

SELECT * FROM @Table
WHERE Col NOT LIKE '%[^0-9.]%'

Results

Col
---------
234.62
6435.23
2

How to loop and render elements in React-native?

render() {
  return (
    <View style={...}>
       {initialArr.map((prop, key) => {
         return (
           <Button style={{borderColor: prop[0]}}  key={key}>{prop[1]}</Button>
         );
      })}
     </View>
  )
}

should do the trick

Searching a string in eclipse workspace

In your Eclipse editor screen, try Control + Shift + R buttons.

Regex to get the words after matching string

Here's a quick Perl script to get what you need. It needs some whitespace chomping.

#!/bin/perl

$sample = <<END;
Subject:
  Security ID:        S-1-5-21-3368353891-1012177287-890106238-22451
  Account Name:       ChamaraKer
  Account Domain:     JIC
  Logon ID:       0x1fffb

Object:
  Object Server:  Security
  Object Type:    File
  Object Name:    D:\\ApacheTomcat\\apache-tomcat-6.0.36\\logs\\localhost.2013- 07-01.log
  Handle ID:  0x11dc
END

my @sample_lines = split /\n/, $sample;
my $path;

foreach my $line (@sample_lines) {
  ($path) = $line =~ m/Object Name:([^s]+)/g;
  if($path) {
    print $path . "\n";
  }
}

How do I print the content of httprequest request?

If you want the content string and this string does not have parameters you can use

    String line = null;
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null){
        System.out.println(line);
    }

Attach event to dynamic elements in javascript

The difference is in how you create and append elements in the DOM.

If you create an element via document.createElement, add an event listener, and append it to the DOM. Your events will fire.

If you create an element as a string like this: html += "<li>test</li>"`, the elment is technically just a string. Strings cannot have event listeners.

One solution is to create each element with document.createElement and then add those to a DOM element directly.

// Sample
let li = document.createElement('li')
document.querySelector('ul').appendChild(li)

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

Just if this helps, I was using Junit5 but the @RunWith(SpringRunner.class) was pointing towards import org.springframework.test.context.junit4.SpringRunner, which was messing around with things and hence was giving the initialization error. I fixed this and it worked.

How to prevent auto-closing of console after the execution of batch file

If you are using Maven and you want to skip the typing and prevent the console from close to see the result you need to use the CALL command in the script, besides just the 'mvn clean install'.

Like this will close the console

ECHO This is the wrong exemple
mvn clean install
pause

Like this the console will stay open

ECHO This is the right exemple
CALL mvn clean install
pause

If you dont use the CALL command neither of the pasts exemples will work. Because for some reason the default behaviour of cmd when calling another batch file (which mvn is in this case) is to essentially replace the current process with it, unlike calling an .exe

Django download a file

Reference:

In view.py Implement function like,

def download(request, id):
    obj = your_model_name.objects.get(id=id)
    filename = obj.model_attribute_name.path
    response = FileResponse(open(filename, 'rb'))
    return response

WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance

To fix this,

  1. you’ll need to reset the permissions back to default:

    sudo chmod 600 ~/.ssh/id_rsa
    sudo chmod 600 ~/.ssh/id_rsa.pub
    

    If you are getting another error:

    • Are you sure you want to continue connecting (yes/no)? yes
    • Failed to add the host to the list of known hosts (/home/geek/.ssh/known_hosts).
  2. This means that the permissions on that file are also set incorrectly, and can be adjusted with this:

    sudo chmod 644 ~/.ssh/known_hosts
    
  1. Finally, you may need to adjust the directory permissions as well:

    sudo chmod 755 ~/.ssh
    

This should get you back up and running.

Why should you use strncpy instead of strcpy?

The strncpy() function is the safer one: you have to pass the maximum length the destination buffer can accept. Otherwise it could happen that the source string is not correctly 0 terminated, in which case the strcpy() function could write more characters to destination, corrupting anything which is in the memory after the destination buffer. This is the buffer-overrun problem used in many exploits

Also for POSIX API functions like read() which does not put the terminating 0 in the buffer, but returns the number of bytes read, you will either manually put the 0, or copy it using strncpy().

In your example code, index is actually not an index, but a count - it tells how many characters at most to copy from source to destination. If there is no null byte among the first n bytes of source, the string placed in destination will not be null terminated

Clicking the back button twice to exit an activity

In Java Activity:

boolean doubleBackToExitPressedOnce = false;

@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce=false;                       
        }
    }, 2000);
} 

In Kotlin Activity:

private var doubleBackToExitPressedOnce = false
override fun onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed()
            return
        }

        this.doubleBackToExitPressedOnce = true
        Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show()

        Handler().postDelayed(Runnable { doubleBackToExitPressedOnce = false }, 2000)
    }

I Think this handler helps to reset the variable after 2 second.

Getting values from query string in an url using AngularJS $location

First make the URL format correct for getting the query string use #?q=string that works for me

http://localhost/codeschool/index.php#?foo=abcd

Inject $location service into the controller

app.controller('MyController', [ '$location', function($location) { 

    var searchObject = $location.search();

    // $location.search(); reutrn object 
    // searchObject = { foo = 'abcd' };

    alert( searchObject.foo );

} ]);

So the out put should be abcd

Insert HTML with React Variable Statements (JSX)

You can also include this HTML in ReactDOM like this:

var thisIsMyCopy = (<p>copy copy copy <strong>strong copy</strong></p>);

ReactDOM.render(<div className="content">{thisIsMyCopy}</div>, document.getElementById('app'));

Here are two links link and link2 from React documentation which could be helpful.

importing a CSV into phpmyadmin

In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :

enter image description here

Timer Interval 1000 != 1 second?

Instead of Tick event, use Elapsed event.

timer.Elapsed += new EventHandler(TimerEventProcessor);

and change the signiture of TimerEventProcessor method;

private void TimerEventProcessor(object sender, ElapsedEventArgs e)
{
  label1.Text = _counter.ToString();
  _counter += 1;
}

Is there any way to debug chrome in any IOS device

Old Answer (July 2016):

You can't directly debug Chrome for iOS due to restrictions on the published WKWebView apps, but there are a few options already discussed in other SO threads:

  1. If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.

  2. WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.

  3. You could try and create a simple WKWebView browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.

There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView, Chrome for iOS would be debuggable.

Update January 2018:

Since my answer back in 2016, some work has been done to improve things.

There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.

Check out the getting started guide in the repo, which is quite detailed.

If you are interesting, you can read up on the background and architecture here.

LD_LIBRARY_PATH vs LIBRARY_PATH

Since I link with gcc why ld is being called, as the error message suggests?

gcc calls ld internally when it is in linking mode.

CSS Border Not Working

Have you tried using Firebug to inspect the rendered HTML, and to see exactly what css is being applied to the various elements? That should pick up css errors like the ones mentioned above, and you can see what styles are being inherited and from where - it is an invaluable too in any css debugging.

Setting Environment Variables for Node to retrieve

As expansion of @ctrlplusb answer,
I would suggest you to also take a look to the env-dot-prop package.

It allows you to set/get properties from process.env using a dot-path.

Let's assume that your process.env contains the following:

process.env = {
  FOO_BAR: 'baz'
  'FOO_': '42'
}

Then you can manipulate the environment variables like that:

const envDotProp = require('env-dot-prop');

console.log(process.env);
//=> {FOO_BAR: 'baz', 'FOO_': '42'}

envDotProp.get('foo');
//=> {bar: 'baz', '': '42'}

envDotProp.get('foo.');
//=> '42'

envDotProp.get('foo.', {parse: true});
//=> 42

envDotProp.set('baz.foo', 'bar');
envDotProp.get('', {parse: true});
//=> {foo: {bar: 'baz', '': 42}, baz: {foo: 'bar'}}

console.log(process.env);
//=> {FOO_BAR: 'baz', 'FOO_': '42', BAZ_FOO: 'bar'}

envDotProp.delete('foo');
envDotProp.get('');
//=> {baz: {foo: 'bar'}}

console.log(process.env);
//=> {BAZ_FOO: 'bar'}

This helps you to parse the environment variables and use them as a config object in your app.
It also helps you implement a 12-factor configuration.

serialize/deserialize java 8 java.time with Jackson JSON mapper

        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jdk8</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>

add these dependencies and enable these modules. that should help

    private static final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();

How to get CRON to call in the correct PATHs

Most likely, cron is running in a very sparse environment. Check the environment variables cron is using by appending a dummy job which dumps env to a file like this:

* * * * * env > env_dump.txt

Compare that with the output of env in a normal shell session.

You can prepend your own environment variables to the local crontab by defining them at the top of your crontab.

Here's a quick fix to prepend $PATH to the current crontab:

# echo PATH=$PATH > tmp.cron
# echo >> tmp.cron
# crontab -l >> tmp.cron
# crontab tmp.cron

The resulting crontab will look similar to chrissygormley's answer, with PATH defined before the crontab rules.

for or while loop to do something n times

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).

In jQuery, what's the best way of formatting a number to 2 decimal places?

If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.

<script type="text/javascript">

    // mini jQuery plugin that formats to two decimal places
    (function($) {
        $.fn.currencyFormat = function() {
            this.each( function( i ) {
                $(this).change( function( e ){
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                });
            });
            return this; //for chaining
        }
    })( jQuery );

    // apply the currencyFormat behaviour to elements with 'currency' as their class
    $( function() {
        $('.currency').currencyFormat();
    });

</script>   
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">

"commence before first target. Stop." error

This means that there is a line which starts with a space, tab, or some other whitespace without having a target in front of it.

The project type is not supported by this installation

For Visual Studio 2010 (prolly also for other versions):

If you are opening an ASP.NET MVC project make sure that the correct MVC version is installed on your PC. If you try to open an ASP.NET MVC 3 project, first close all your visual studio instances and install MVC3: http://www.microsoft.com/en-us/download/details.aspx?id=1491

For other ASP.NET MVC versions download them from www.asp.net/mvc or via Web Platform Installer 4.0.

Converting an int to a binary string representation in Java?

This can be expressed in pseudocode as:

while(n > 0):
    remainder = n%2;
    n = n/2;
    Insert remainder to front of a list or push onto a stack

Print list or stack

CSS ''background-color" attribute not working on checkbox inside <div>

In addition to the currently accepted answer: You can set border and background of a checkbox/radiobutton, but how it is rendered in the end depends on the browser. For example, if you set a red background on a checkbox

  • IE will show a red border instead
  • Opera will show a red background as intended
  • Firefox, Safari and Chrome will do nothing

This German language article compares a few browsers and explains at least the IE behavior. It maybe bit older (still including Netscape), but when you test around you'll notice that not much has changed. Another comparison can be found here.

Can't install Scipy through pip

After opening up an issue with the SciPy team, we found that you need to upgrade pip with:

pip install --upgrade pip

And in Python 3 this works:

python3 -m pip install --upgrade pip

for SciPy to install properly. Why? Because:

Older versions of pip have to be told to use wheels, IIRC with --use-wheel. Or you can upgrade pip itself, then it should pick up the wheels.

Upgrading pip solves the issue, but you might be able to just use the --use-wheel flag as well.

How do you get a timestamp in JavaScript?

If it is for logging purposes, you can use ISOString

new Date().toISOString()

"2019-05-18T20:02:36.694Z"

Generics in C#, using type of a variable as parameter

You can't use it in the way you describe. The point about generic types, is that although you may not know them at "coding time", the compiler needs to be able to resolve them at compile time. Why? Because under the hood, the compiler will go away and create a new type (sometimes called a closed generic type) for each different usage of the "open" generic type.

In other words, after compilation,

DoesEntityExist<int>

is a different type to

DoesEntityExist<string>

This is how the compiler is able to enfore compile-time type safety.

For the scenario you describe, you should pass the type as an argument that can be examined at run time.

The other option, as mentioned in other answers, is that of using reflection to create the closed type from the open type, although this is probably recommended in anything other than extreme niche scenarios I'd say.

What in the world are Spring beans?

In Spring, those objects that form the backbone of your application and that are managed by the Spring IoC container are referred to as beans. A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container;

Change GridView row color based on condition

 protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl_Code = (Label)e.Row.FindControl("lblCode");
            if (lbl_Code.Text == "1")
            {
                e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#f2d9d9");
            }
        }
    }

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

In my case I was trying to require this package, and I was getting the PHP Fatal error: Allowed memory size of.

I found it easy to run like this and you don't have to update the PHP INI file.

example: COMPOSER_MEMORY_LIMIT=-1 composer require huddledigital/zendesk-laravel

Hope this help someone.

Count number of occurrences for each unique value

Yes, you can use GROUP BY:

SELECT time,
       activities,
       COUNT(*)
FROM table
GROUP BY time, activities;

Decimal to Hexadecimal Converter in Java

Here's mine

public static String dec2Hex(int num)
{
    String hex = "";

    while (num != 0)
    {
        if (num % 16 < 10)
            hex = Integer.toString(num % 16) + hex;
        else
            hex = (char)((num % 16)+55) + hex;
        num = num / 16;
    }

    return hex;
}

Understanding the results of Execute Explain Plan in Oracle SQL Developer

In recent Oracle versions the COST represent the amount of time that the optimiser expects the query to take, expressed in units of the amount of time required for a single block read.

So if a single block read takes 2ms and the cost is expressed as "250", the query could be expected to take 500ms to complete.

The optimiser calculates the cost based on the estimated number of single block and multiblock reads, and the CPU consumption of the plan. the latter can be very useful in minimising the cost by performing certain operations before others to try and avoid high CPU cost operations.

This raises the question of how the optimiser knows how long operations take. recent Oracle versions allow the collections of "system statistics", which are definitely not to be confused with statistics on tables or indexes. The system statistics are measurements of the performance of the hardware, mostly importantly:

  1. How long a single block read takes
  2. How long a multiblock read takes
  3. How large a multiblock read is (often different to the maximum possible due to table extents being smaller than the maximum, and other reasons).
  4. CPU performance

These numbers can vary greatly according to the operating environment of the system, and different sets of statistics can be stored for "daytime OLTP" operations and "nighttime batch reporting" operations, and for "end of month reporting" if you wish.

Given these sets of statistics, a given query execution plan can be evaluated for cost in different operating environments, which might promote use of full table scans at some times or index scans at others.

The cost is not perfect, but the optimiser gets better at self-monitoring with every release, and can feedback the actual cost in comparison to the estimated cost in order to make better decisions for the future. this also makes it rather more difficult to predict.

Note that the cost is not necessarily wall clock time, as parallel query operations consume a total amount of time across multiple threads.

In older versions of Oracle the cost of CPU operations was ignored, and the relative costs of single and multiblock reads were effectively fixed according to init parameters.

C# Set collection?

Try HashSet:

The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order...

The capacity of a HashSet(Of T) object is the number of elements that the object can hold. A HashSet(Of T) object's capacity automatically increases as elements are added to the object.

The HashSet(Of T) class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary(Of TKey, TValue) or Hashtable collections. In simple terms, the HashSet(Of T) class can be thought of as a Dictionary(Of TKey, TValue) collection without values.

A HashSet(Of T) collection is not sorted and cannot contain duplicate elements...

How to determine a Python variable's type?

a = "cool"
type(a)

//result 'str'
<class 'str'>
or 
do 
`dir(a)` 
to see the list of inbuilt methods you can have on the variable.

Axios having CORS issue

CORS issue can be simply resolved by following this:

Create a new shortcut of Google Chrome(update browser installation path accordingly) with following value:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:\chrome\temp"

How to custom switch button?

There are two ways to create custom ToggleButton

1) By defining custom background 2) By creating custom button

Check http://www.zoftino.com/android-toggle-button for custom styles

Toggle button with custom background

Define drawable as xml resource like below and set it as background of toggle button. In the below example, drawable toggle_color is a color selector, you need to define this also.

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="4dp"
    android:insetTop="4dp"
    android:insetRight="4dp"
    android:insetBottom="4dp">
    <layer-list android:paddingMode="stack">
        <item>
            <ripple android:color="?attr/android:colorControlHighlight">
                <item>
                    <shape android:shape="rectangle"
                        android:tint="?attr/android:colorButtonNormal">
                        <corners android:radius="8dp"/>
                        <solid android:color="@android:color/white" />
                        <padding android:left="8dp"
                            android:top="6dp"
                            android:right="8dp"
                            android:bottom="6dp" />
                    </shape>
                </item>
            </ripple>
        </item>
        <item android:gravity="left|fill_vertical">
            <shape android:shape="rectangle">
                <corners android:radius="4dp"/>
                <size android:width="8dp" />
                <solid android:color="@color/toggle_color" />
            </shape>
        </item>
        <item android:gravity="right|fill_vertical">
            <shape android:shape="rectangle">
                <corners android:radius="4dp"/>
                <size android:width="8dp" />
                <solid android:color="@color/toggle_color" />
            </shape>
        </item>
    </layer-list>
</inset>

Toggle button with custom button

Create your own images for two state of toggle button (make sure images exist for all sizes of screens) and place them in drawable folder, create selector and set it as button.

   <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/toggle_on" />
    <item android:drawable="@drawable/toggle_off" />
</selector>

How to store Query Result in variable using mysql

Additionally, if you want to set multiple variables at once by one query, you can use the other syntax for setting variables which goes like this: SELECT @varname:=value.

A practical example:

SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Couldn't you just do this?

var things = [
    { id: 1, color: 'yellow' },
    { id: 2, color: 'blue' },
    { id: 3, color: 'red' }
];
$.post('@Url.Action("PassThings")', { things: things },
   function () {
        $('#result').html('"PassThings()" successfully called.');
   });

...and mark your action with

[HttpPost]
public void PassThings(IEnumerable<Thing> things)
{
    // do stuff with things here...
}

MySQL SELECT DISTINCT multiple columns

can this help?

select 
(SELECT group_concat(DISTINCT a) FROM my_table) as a,
(SELECT group_concat(DISTINCT b) FROM my_table) as b,
(SELECT group_concat(DISTINCT c) FROM my_table) as c,
(SELECT group_concat(DISTINCT d) FROM my_table) as d

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

I know the original question lists Cygwin, but here is the solution for CentOS:

curl http://curl.haxx.se/ca/cacert.pem -o /etc/pki/tls/certs/ca-bundle.crt

Source: http://eric.lubow.org/2011/security/fixing-centos-root-certificate-authority-issues/

Remove array element based on object property

You can use lodash's findIndex to get the index of the specific element and then splice using it.

myArray.splice(_.findIndex(myArray, function(item) {
    return item.value === 'money';
}), 1);

Update

You can also use ES6's findIndex()

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

const itemToRemoveIndex = myArray.findIndex(function(item) {
  return item.field === 'money';
});

// proceed to remove an item only if it exists.
if(itemToRemoveIndex !== -1){
  myArray.splice(itemToRemoveIndex, 1);
}

Convert Uri to String and String to Uri

This will get the file path from the MediaProvider, DownloadsProvider, and ExternalStorageProvider, while falling back to the unofficial ContentProvider method you mention.

   /**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @author paulburke
 */
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

You can do it in a simpler way using the DialogResult.cancel method.

Eg:

Dim anInput as String = InputBox("Enter your pin")

If anInput <>"" then

   ' Do something
Elseif DialogResult.Cancel then

  Msgbox("You've canceled")
End if

Appending a vector to a vector

std::copy (b.begin(), b.end(), std::back_inserter(a));

This can be used in case the items in vector a have no assignment operator (e.g. const member).

In all other cases this solution is ineffiecent compared to the above insert solution.

Using Node.JS, how do I read a JSON file into (server) memory?

The easiest way I have found to do this is to just use require and the path to your JSON file.

For example, suppose you have the following JSON file.

test.json

{
  "firstName": "Joe",
  "lastName": "Smith"
}

You can then easily load this in your node.js application using require

var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);

Passive Link in Angular 2 - <a href=""> equivalent

Updated for Angular 5

import { Directive, HostListener, Input } from '@angular/core';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector : '[href]'
})
export class HrefDirective {
  @Input() public href: string | undefined;

  @HostListener('click', ['$event']) public onClick(event: Event): void {
    if (!this.href || this.href === '#' || (this.href && this.href.length === 0)) {
      event.preventDefault();
    }
  }
}

DIV height set as percentage of screen?

If you want it based on the screen height, and not the window height:

const height = 0.7 * screen.height

// jQuery
$('.header').height(height)

// Vanilla JS
document.querySelector('.header').style.height = height + 'px'

// If you have multiple <div class="header"> elements
document.querySelectorAll('.header').forEach(function(node) {
  node.style.height = height + 'px'
})

What is C# analog of C++ std::pair?

Tuples are available since .NET4.0 and support generics:

Tuple<string, int> t = new Tuple<string, int>("Hello", 4);

In previous versions you can use System.Collections.Generic.KeyValuePair<K, V> or a solution like the following:

public class Pair<T, U> {
    public Pair() {
    }

    public Pair(T first, U second) {
        this.First = first;
        this.Second = second;
    }

    public T First { get; set; }
    public U Second { get; set; }
};

And use it like this:

Pair<String, int> pair = new Pair<String, int>("test", 2);
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);

This outputs:

test
2

Or even this chained pairs:

Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>();
pair.First = new Pair<String, int>();
pair.First.First = "test";
pair.First.Second = 12;
pair.Second = true;

Console.WriteLine(pair.First.First);
Console.WriteLine(pair.First.Second);
Console.WriteLine(pair.Second);

That outputs:

test
12
true

How can one display images side by side in a GitHub README.md?

The easiest way I can think of solving this is using the tables included in GitHub's flavored markdown.

To your specific example it would look something like this:

Solarized dark             |  Solarized Ocean
:-------------------------:|:-------------------------:
![](https://...Dark.png)  |  ![](https://...Ocean.png)

This creates a table with Solarized Dark and Ocean as headers and then contains the images in the first row. Obviously you would replace the ... with the real link. The :s are optional (They just center the content in the cells, which is kinda unnecessary in this case). Also you might want to downsize the images so they will display better side-by-side.

Material effect on button with background color

Programmatically applying the colors:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

    ColorStateList colorStateListRipple = new ColorStateList(
            new int[][] {{0}},
            new int[] {Color.WHITE} // ripple color
            );

    RippleDrawable rippleDrawable = (RippleDrawable) myButton.getBackground();
    rippleDrawable.setColor(colorStateListRipple);
    myButton.setBackground(rippleDrawable); // applying the ripple color
}

ColorStateList colorStateList = new ColorStateList(
        new int[][]{
                new int[]{android.R.attr.state_pressed}, // when pressed
                new int[]{android.R.attr.state_enabled}, // normal state color
                new int[]{} // normal state color
        },
        new int[]{
                Color.CYAN, // when pressed
                Color.RED, // normal state color
                Color.RED // normal state color
        }
);

ViewCompat.setBackgroundTintList(myButton, colorStateList); // applying the state colors

How to change the window title of a MATLAB plotting figure?

If you do not want to include that your code script (as advised by others above), then simply you may do the following after generating the figure window:

  1. Go to "Edit" in the figure window

  2. Go to "Figure Properties"

  3. At the bottom, you can type the name you want in "Figure Name" field. You can uncheck "Show Figure Number".

That's all.

Good luck.

Parse rfc3339 date strings in Python?

You should have a look at moment which is a python port of the excellent js lib momentjs.

One advantage of it is the support of ISO 8601 strings formats, as well as a generic "% format" :

import moment
time_string='2012-10-09T19:00:55Z'

m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday

Result:

2012-10-09 19:10
2

Copying an array of objects into another array in javascript

There are two important notes.

  1. Using array.concat() does not work using Angular 1.4.4 and jQuery 3.2.1 (this is my environment).
  2. The array.slice(0) is an object. So if you do something like newArray1 = oldArray.slice(0); newArray2 = oldArray.slice(0), the two new arrays will reference to just 1 array and changing one will affect the other.

Alternatively, using newArray1 = JSON.parse(JSON.stringify(old array)) will only copy the value, thus it creates a new array each time.

How can I multiply and divide using only bit shifting and adding?

The answer by Andrew Toulouse can be extended to division.

The division by integer constants is considered in details in the book "Hacker's Delight" by Henry S. Warren (ISBN 9780201914658).

The first idea for implementing division is to write the inverse value of the denominator in base two.

E.g., 1/3 = (base-2) 0.0101 0101 0101 0101 0101 0101 0101 0101 .....

So, a/3 = (a >> 2) + (a >> 4) + (a >> 6) + ... + (a >> 30) for 32-bit arithmetics.

By combining the terms in an obvious manner we can reduce the number of operations:

b = (a >> 2) + (a >> 4)

b += (b >> 4)

b += (b >> 8)

b += (b >> 16)

There are more exciting ways to calculate division and remainders.

EDIT1:

If the OP means multiplication and division of arbitrary numbers, not the division by a constant number, then this thread might be of use: https://stackoverflow.com/a/12699549/1182653

EDIT2:

One of the fastest ways to divide by integer constants is to exploit the modular arithmetics and Montgomery reduction: What's the fastest way to divide an integer by 3?

How to export JSON from MongoDB using Robomongo

There are a few MongoDB GUIs out there, some of them have built-in support for data exporting. You'll find a comprehensive list of MongoDB GUIs at http://mongodb-tools.com

You've asked about exporting the results of your query, and not about exporting entire collections. Give 3T MongoChef MongoDB GUI a try, this tool has support for your specific use case.

PHP absolute path to root

In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:

 $_SERVER['DOCUMENT_ROOT']

The only problem is that the entries in this variable are provided by the web server and there is no guarantee that all web servers offer them.

how to console.log result of this ajax call?

In Chrome, right click in the console and check 'preserve log on navigation'.

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

When I was faced with the same problem I just had to clean my solution before rebuilding. That took care of it for me.

Run script on mac prompt "Permission denied"

In my case, I had made a stupid typo in the shebang.

So in case someone else on with fat fingers stumbles across this question:

Whoops: #!/usr/local/bin ruby

I meant to write: #!/usr/bin/env ruby

The vague error ZSH gives sent me down the wrong path:

ZSH: zsh: permission denied: ./foo.rb

Bash: bash: ./foo.rb: /usr/local/bin: bad interpreter: Permission denied

how to read a long multiline string line by line in python

This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines() is the way to go. I will leave this answer nevertheless as reference.

Old (incorrect) answer:

s =  \
"""line1
line2
line3
"""

lines = s.split('\n')
print(lines)
for line in lines:
    print(line)

How to get a list of all files that changed between two Git commits?

For files changed between a given SHA and your current commit:

git diff --name-only <starting SHA> HEAD

or if you want to include changed-but-not-yet-committed files:

git diff --name-only <starting SHA>

More generally, the following syntax will always tell you which files changed between two commits (specified by their SHAs or other names):

git diff --name-only <commit1> <commit2>

Split array into chunks

Here's another solution with the reduce() method, though slightly different from other examples. Hopefully my explanation is a bit clearer as well.

_x000D_
_x000D_
var arr = [0, 1, 2, 3, 4, 5, 6, 7];
var chunkSize = 3;

arr = arr.reduce((acc, item, idx) => {
  let group = acc.pop();
  if (group.length == chunkSize) {
    acc.push(group);
    group = [];
  }
  group.push(item);
  acc.push(group);
  return acc;
}, [[]]);

console.log(arr); //Prints [[0, 1, 2], [3, 4, 5], [6, 7]]
_x000D_
_x000D_
_x000D_


Explanation

We call a reducer which, for each item in the array, gets the last item of the accumulator with pop(). Remember that this item is an array which groups up to chunkSize number of items (3 in this example).

If, and only if, this group has the array length equal to chunksize we need to re-insert the group back into the accumulator and create a new group.

We then push the current item into our group array (which may already contain 0, 1 or 2 items from the previous steps). With the current item inserted into the group, we need to re-insert the group back into the larger collection.

The process will repeat until we've iterated through all items in arr.

Note that we have also provided the reducer with the starting value of an empty array inside an array with [[]].

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

This one worked for me:

>> print(df)
                          TotalVolume  Symbol
2016-04-15 09:00:00       108400       2802.T
2016-04-15 09:05:00       50300        2802.T

>> print(df.set_index(pd.to_datetime(df.index.values) - datetime(2016, 4, 15)))

             TotalVolume  Symbol
09:00:00     108400       2802.T
09:05:00     50300        2802.T

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

Hibernate is ignorant of time zone stuff in Dates (because there isn't any), but it's actually the JDBC layer that's causing problems. ResultSet.getTimestamp and PreparedStatement.setTimestamp both say in their docs that they transform dates to/from the current JVM timezone by default when reading and writing from/to the database.

I came up with a solution to this in Hibernate 3.5 by subclassing org.hibernate.type.TimestampType that forces these JDBC methods to use UTC instead of the local time zone:

public class UtcTimestampType extends TimestampType {

    private static final long serialVersionUID = 8088663383676984635L;

    private static final TimeZone UTC = TimeZone.getTimeZone("UTC");

    @Override
    public Object get(ResultSet rs, String name) throws SQLException {
        return rs.getTimestamp(name, Calendar.getInstance(UTC));
    }

    @Override
    public void set(PreparedStatement st, Object value, int index) throws SQLException {
        Timestamp ts;
        if(value instanceof Timestamp) {
            ts = (Timestamp) value;
        } else {
            ts = new Timestamp(((java.util.Date) value).getTime());
        }
        st.setTimestamp(index, ts, Calendar.getInstance(UTC));
    }
}

The same thing should be done to fix TimeType and DateType if you use those types. The downside is you'll have to manually specify that these types are to be used instead of the defaults on every Date field in your POJOs (and also breaks pure JPA compatibility), unless someone knows of a more general override method.

UPDATE: Hibernate 3.6 has changed the types API. In 3.6, I wrote a class UtcTimestampTypeDescriptor to implement this.

public class UtcTimestampTypeDescriptor extends TimestampTypeDescriptor {
    public static final UtcTimestampTypeDescriptor INSTANCE = new UtcTimestampTypeDescriptor();

    private static final TimeZone UTC = TimeZone.getTimeZone("UTC");

    public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
        return new BasicBinder<X>( javaTypeDescriptor, this ) {
            @Override
            protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
                st.setTimestamp( index, javaTypeDescriptor.unwrap( value, Timestamp.class, options ), Calendar.getInstance(UTC) );
            }
        };
    }

    public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
        return new BasicExtractor<X>( javaTypeDescriptor, this ) {
            @Override
            protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
                return javaTypeDescriptor.wrap( rs.getTimestamp( name, Calendar.getInstance(UTC) ), options );
            }
        };
    }
}

Now when the app starts, if you set TimestampTypeDescriptor.INSTANCE to an instance of UtcTimestampTypeDescriptor, all timestamps will be stored and treated as being in UTC without having to change the annotations on POJOs. [I haven't tested this yet]

Finding duplicate values in a SQL table

SELECT * FROM users u where rowid = (select max(rowid) from users u1 where
u.email=u1.email);

How to align center the text in html table row?

The CSS to center text in your td elements is

td {
  text-align: center;
  vertical-align: middle;
}

Subtracting 2 lists in Python

For the one who used to code on Pycharm, it also revives others as well.

 import operator
 Arr1=[1,2,3,45]
 Arr2=[3,4,56,78]
 print(list(map(operator.sub,Arr1,Arr2)))

Transitions on the CSS display property

You can simply use the CSS visibility: hidden/visible instead of display : none/block

div {
    visibility:hidden;
    -webkit-transition: opacity 1s ease-out;
    -moz-transition: opacity 1s ease-out;
    -o-transition: opacity 1s ease-out;
    transition: opacity 1s ease-out;
    opacity: 0;
}

parent:hover > div {
    opacity: 1;
    visibility: visible;
}

Finding all positions of substring in a larger string in C#

It could be done in efficient time complexity using KMP algorithm in O(N + M) where N is the length of text and M is the length of the pattern.

This is the implementation and usage:

static class StringExtensions
{
    public static IEnumerable<int> AllIndicesOf(this string text, string pattern)
    {
        if (string.IsNullOrEmpty(pattern))
        {
            throw new ArgumentNullException(nameof(pattern));
        }
        return Kmp(text, pattern);
    }

    private static IEnumerable<int> Kmp(string text, string pattern)
    {
        int M = pattern.Length;
        int N = text.Length;

        int[] lps = LongestPrefixSuffix(pattern);
        int i = 0, j = 0; 

        while (i < N)
        {
            if (pattern[j] == text[i])
            {
                j++;
                i++;
            }
            if (j == M)
            {
                yield return i - j;
                j = lps[j - 1];
            }

            else if (i < N && pattern[j] != text[i])
            {
                if (j != 0)
                {
                    j = lps[j - 1];
                }
                else
                {
                    i++;
                }
            }
        }
    }

    private static int[] LongestPrefixSuffix(string pattern)
    {
        int[] lps = new int[pattern.Length];
        int length = 0;
        int i = 1;

        while (i < pattern.Length)
        {
            if (pattern[i] == pattern[length])
            {
                length++;
                lps[i] = length;
                i++;
            }
            else
            {
                if (length != 0)
                {
                    length = lps[length - 1];
                }
                else
                {
                    lps[i] = length;
                    i++;
                }
            }
        }
        return lps;
    }

and this is an example of how to use it:

static void Main(string[] args)
    {
        string text = "this is a test";
        string pattern = "is";
        foreach (var index in text.AllIndicesOf(pattern))
        {
            Console.WriteLine(index); // 2 5
        }
    }

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

The following is a more efficient answer to the question rather than hard-coding the style.

To change the day to ordinal number you need to use the following suffix.

DD +     TH = DDTH  result >>>> 4TH

OR to spell the number add SP to the format

DD + SPTH = DDSPTH   result >>> FOURTH

Find my completed answer in this question.

SSRS Field Expression to change the background color of the Cell

You can use SWITCH() function to evaluate multiple criteria to color the cell. The node <BackgroundColor> is the cell fill, <Color> is font color.

Expression:

=SWITCH(
    (
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND (Fields!User_Name.Value.Contains("TOTAL"))
    ), "Black"
    ,(
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND NOT(Fields!User_Name.Value.Contains("TOTAL"))
    ), "#595959"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "#c65911"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND NOT(Fields!OLAP_Cube.Value.Contains("TOTAL")) 
    ), "#ed7d31"
    ,true, "#e7e6e6"
    )

'Daily Totals... CellFill.&[Dark Orange]-[#c65911], TextBold.&[True]'Daily Totals... CellFill.&[Dark Orange]-[#c65911], TextBold.&[True]
'Daily Cube Totals... CellFill.&[Medium Orange]-[#eb6e19]
'Daily User List... CellFill.&[Light Grey]-[#e7e6e6]
'Date Totals All Users Total... CellFill.&[Black]-["black"], TextColor.&[Light Orange]-[#ed7d31]
'Date Totals Per User... CellFill.&[Dark Grey]-[#595959], TextColor.&[Yellow]-["yellow"]
'(ALL OTHER CONDITIONS)
'Daily User List... CellFill.&[Light Grey]-[#e7e6e6]

XML node in report definition file (SSRS-2016 / VS-2015):

                <TablixRow>
                  <Height>0.2in</Height>
                  <TablixCells>
                    <TablixCell>
                      <CellContents>
                        <Textbox Name="Usage_Date1">
                          <CanGrow>true</CanGrow>
                          <KeepTogether>true</KeepTogether>
                          <Paragraphs>
                            <Paragraph>
                              <TextRuns>
                                <TextRun>
                                  <Value>=Fields!Usage_Date.Value</Value>
                                  <Style>
                                    <FontSize>8pt</FontSize>
                                    <FontWeight>=SWITCH(
    (
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "Bold"
    ,true, "Normal"
    )</FontWeight>
                                    <Color>=SWITCH(
    (
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND (Fields!User_Name.Value.Contains("TOTAL"))
    ), "#ed7d31"
    ,(
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND NOT(Fields!User_Name.Value.Contains("TOTAL"))
    ), "Yellow"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "Black"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND NOT(Fields!OLAP_Cube.Value.Contains("TOTAL")) 
    ), "Black"
    ,true, "Black"
    )

'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]
'Daily Cube Totals... CellFill.&amp;[Medium Orange]-[#eb6e19]
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]
'Date Totals All Users Total... CellFill.&amp;[Black]-["black"], TextColor.&amp;[Light Orange]-[#ed7d31]
'Date Totals Per User... CellFill.&amp;[Dark Grey]-[#595959], TextColor.&amp;[Yellow]-["yellow"]
'(ALL OTHER CONDITIONS)
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]</Color>
                                  </Style>
                                </TextRun>
                              </TextRuns>
                              <Style />
                            </Paragraph>
                          </Paragraphs>
                          <rd:DefaultName>Usage_Date1</rd:DefaultName>
                          <Style>
                            <Border>
                              <Color>LightGrey</Color>
                              <Style>Solid</Style>
                            </Border>
                            <BackgroundColor>=SWITCH(
    (
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND (Fields!User_Name.Value.Contains("TOTAL"))
    ), "Black"
    ,(
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND NOT(Fields!User_Name.Value.Contains("TOTAL"))
    ), "#595959"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "#c65911"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND NOT(Fields!OLAP_Cube.Value.Contains("TOTAL")) 
    ), "#ed7d31"
    ,true, "#e7e6e6"
    )

'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]
'Daily Cube Totals... CellFill.&amp;[Medium Orange]-[#eb6e19]
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]
'Date Totals All Users Total... CellFill.&amp;[Black]-["black"], TextColor.&amp;[Light Orange]-[#ed7d31]
'Date Totals Per User... CellFill.&amp;[Dark Grey]-[#595959], TextColor.&amp;[Yellow]-["yellow"]
'(ALL OTHER CONDITIONS)
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]</BackgroundColor>
                            <PaddingLeft>2pt</PaddingLeft>
                            <PaddingRight>2pt</PaddingRight>
                          </Style>
                        </Textbox>
                        <rd:Selected>true</rd:Selected>
                      </CellContents>
                    </TablixCell>

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

jQuery Loop through each div

$('div.target').each(function() {
   /* Measure the width of each image. */
   var test = $(this).find('.scrolling img').width();

   /* Find out how many images there are. */
   var testimg = $(this).find('.scrolling img').length;

   /* Do the maths. */
   var final = (test* testimg)*1.2;

   /* Apply the maths to the CSS. */
   $(this).find('scrolling').width(final); 
});

Here you loop through all your div's with class target and you do the calculations. Within this loop you can simply use $(this) to indicate the currently selected <div> tag.

Allow docker container to connect to a local/host postgres database

The solution posted here does not work for me. Therefore, I am posting this answer to help someone facing similar issue.

OS: Ubuntu 18
PostgreSQL: 9.5 (Hosted on Ubuntu)
Docker: Server Application (which connects to PostgreSQL)

I am using docker-compose.yml to build application.

STEP 1: Please add host.docker.internal:<docker0 IP>

version: '3'
services:
  bank-server:
    ...
    depends_on:
      ....
    restart: on-failure
    ports:
      - 9090:9090
    extra_hosts:
      - "host.docker.internal:172.17.0.1"

To find IP of docker i.e. 172.17.0.1 (in my case) you can use:

$> ifconfig docker0
docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255

OR

$> ip a
1: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever

STEP 2: In postgresql.conf, change listen_addresses to listen_addresses = '*'

STEP 3: In pg_hba.conf, add this line

host    all             all             0.0.0.0/0               md5

STEP 4: Now restart postgresql service using, sudo service postgresql restart

STEP 5: Please use host.docker.internal hostname to connect database from Server Application.
Ex: jdbc:postgresql://host.docker.internal:5432/bankDB

Enjoy!!

Prevent double submission of forms in jQuery

I think Nathan Long's answer is the way to go. For me, I am using client-side validation, so I just added a condition that the form be valid.

EDIT: If this is not added, the user will never be able to submit the form if the client-side validation encounters an error.

        // jQuery plugin to prevent double submission of forms
        jQuery.fn.preventDoubleSubmission = function () {
            $(this).on('submit', function (e) {
                var $form = $(this);

                if ($form.data('submitted') === true) {
                    // Previously submitted - don't submit again
                    alert('Form already submitted. Please wait.');
                    e.preventDefault();
                } else {
                    // Mark it so that the next submit can be ignored
                    // ADDED requirement that form be valid
                    if($form.valid()) {
                        $form.data('submitted', true);
                    }
                }
            });

            // Keep chainability
            return this;
        };

PostgreSQL error: Fatal: role "username" does not exist

Something as simple as changing port from 5432 to 5433 worked for me.

Get last field using awk substr

It should be a comment to the basename answer but I haven't enough point.

If you do not use double quotes, basename will not work with path where there is space character:

$ basename /home/foo/bar foo/bar.png
bar

ok with quotes " "

$ basename "/home/foo/bar foo/bar.png"
bar.png

file example

$ cat a
/home/parent/child 1/child 2/child 3/filename1
/home/parent/child 1/child2/filename2
/home/parent/child1/filename3

$ while read b ; do basename "$b" ; done < a
filename1
filename2
filename3

How to increase font size in the Xcode editor?

  1. Go to XCode > Preferences > Fonts & Color
  2. Double click on a font entry to get the Font inspector window
  3. Select all font entries with sizes you'd like to increase/decrease
  4. In the Font inspector window select the same font (e.g. All Fonts > Menlo > Regular > 14)

Watch out because there's no undo!

Removing trailing newline character from fgets() input

Tim Cas one liner is amazing for strings obtained by a call to fgets, because you know they contain a single newline at the end.

If you are in a different context and want to handle strings that may contain more than one newline, you might be looking for strrspn. It is not POSIX, meaning you will not find it on all Unices. I wrote one for my own needs.

/* Returns the length of the segment leading to the last 
   characters of s in accept. */
size_t strrspn (const char *s, const char *accept)
{
  const char *ch;
  size_t len = strlen(s);

more: 
  if (len > 0) {
    for (ch = accept ; *ch != 0 ; ch++) {
      if (s[len - 1] == *ch) {
        len--;
        goto more;
      }
    }
  }
  return len;
}

For those looking for a Perl chomp equivalent in C, I think this is it (chomp only removes the trailing newline).

line[strrspn(string, "\r\n")] = 0;

The strrcspn function:

/* Returns the length of the segment leading to the last 
   character of reject in s. */
size_t strrcspn (const char *s, const char *reject)
{
  const char *ch;
  size_t len = strlen(s);
  size_t origlen = len;

  while (len > 0) {
    for (ch = reject ; *ch != 0 ; ch++) {
      if (s[len - 1] == *ch) {
        return len;
      }
    }
    len--;
  }
  return origlen;
}

Add Header and Footer for PDF using iTextsharp

For iTextSharp 4.1.6, the last version of iTextSharp that was licensed as LGPL, the solution provided by Alvaro Patiño is both simple and effective.

Because documentation is somewhat scarse I'd like to extend his answer with this code snippet that can be used to change the appearance of the header and footer. By default they have a rather large font-size and a thick border, which many people will want to change.

// Parameters passed on to the function that creates the PDF 
String headerText = "Your header text";
String footerText = "Page";

// Define a font and font-size in points (plus f for float) and pick a color
// This one is for both header and footer but you can also create seperate ones
Font fontHeaderFooter = FontFactory.GetFont("arial", 8f);
fontHeaderFooter.Color = Color.GRAY;

// Apply the font to the headerText and create a Phrase with the result
Chunk chkHeader = new Chunk(headerText, fontHeaderFooter);
Phrase p1 = new Phrase(chkHeader);

// create a HeaderFooter element for the header using the Phrase
// The boolean turns numbering on or off
HeaderFooter header = new HeaderFooter(p1, false);

// Remove the border that is set by default
header.Border = Rectangle.NO_BORDER;
// Align the text: 0 is left, 1 center and 2 right.
header.Alignment = 1;

// add the header to the document
document.Header = header;

// The footer is created in an similar way

// If you want to use numbering like in this example, add a whitespace to the
// text because by default there's no space in between them
if (footerText.Substring(footerText.Length - 1) != " ") footerText += " ";

Chunk chkFooter = new Chunk(footerText, fontHeaderFooter);
Phrase p2 = new Phrase(chkFooter);

// Turn on numbering by setting the boolean to true
HeaderFooter footer = new HeaderFooter(p2, true);
footer.Border = Rectangle.NO_BORDER;
footer.Alignment = 1;

document.Footer = footer;

// Open the Document for writing and continue creating its content
document.Open();

For more info check Creating PDFs with iTextSharp and iTextSharp - Adding Text with Chunks, Phrases and Paragraphs. The source code on GitHub may also be useful.

How to put the legend out of the plot

There are a number of ways to do what you want. To add to what @inalis and @Navi already said, you can use the bbox_to_anchor keyword argument to place the legend partially outside the axes and/or decrease the font size.

Before you consider decreasing the font size (which can make things awfully hard to read), try playing around with placing the legend in different places:

So, let's start with a generic example:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend()

plt.show()

alt text

If we do the same thing, but use the bbox_to_anchor keyword argument we can shift the legend slightly outside the axes boundaries:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)
 
ax.legend(bbox_to_anchor=(1.1, 1.05))

plt.show()

alt text

Similarly, make the legend more horizontal and/or put it at the top of the figure (I'm also turning on rounded corners and a simple drop shadow):

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    line, = ax.plot(x, i * x, label='$y = %ix$'%i)

ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
          ncol=3, fancybox=True, shadow=True)
plt.show()

alt text

Alternatively, shrink the current plot's width, and put the legend entirely outside the axis of the figure (note: if you use tight_layout(), then leave out ax.set_position():

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$'%i)

# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])

# Put a legend to the right of the current axis
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.show()

alt text

And in a similar manner, shrink the plot vertically, and put a horizontal legend at the bottom:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    line, = ax.plot(x, i * x, label='$y = %ix$'%i)

# Shrink current axis's height by 10% on the bottom
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1,
                 box.width, box.height * 0.9])

# Put a legend below current axis
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=5)

plt.show()

alt text

Have a look at the matplotlib legend guide. You might also take a look at plt.figlegend().

Display progress bar while doing some work in C#?

There's a load of information about threading with .NET/C# on Stackoverflow, but the article that cleared up windows forms threading for me was our resident oracle, Jon Skeet's "Threading in Windows Forms".

The whole series is worth reading to brush up on your knowledge or learn from scratch.

I'm impatient, just show me some code

As far as "show me the code" goes, below is how I would do it with C# 3.5. The form contains 4 controls:

  • a textbox
  • a progressbar
  • 2 buttons: "buttonLongTask" and "buttonAnother"

buttonAnother is there purely to demonstrate that the UI isn't blocked while the count-to-100 task is running.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void buttonLongTask_Click(object sender, EventArgs e)
    {
        Thread thread = new Thread(LongTask);
        thread.IsBackground = true;
        thread.Start();
    }

    private void buttonAnother_Click(object sender, EventArgs e)
    {
        textBox1.Text = "Have you seen this?";
    }

    private void LongTask()
    {
        for (int i = 0; i < 100; i++)
        {
            Update1(i);
            Thread.Sleep(500);
        }
    }

    public void Update1(int i)
    {
        if (InvokeRequired)
        {
            this.BeginInvoke(new Action<int>(Update1), new object[] { i });
            return;
        }

        progressBar1.Value = i;
    }
}

Cannot set some HTTP headers when using System.Net.WebRequest

WebRequest being abstract (and since any inheriting class must override the Headers property).. which concrete WebRequest are you using ? In other words, how do you get that WebRequest object to beign with ?

ehr.. mnour answer made me realize that the error message you were getting is actually spot on: it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again. That's probably all you were looking for.

Other classes inheriting from WebRequest might have even better properties wrapping certain headers; See this post for instance.

TypeError: unsupported operand type(s) for /: 'str' and 'str'

The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.

So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.

One way to convert a string to an integer is to use the int function. For example:

percent = (int(pyc) / int(tpy)) * 100

How to limit the number of selected checkboxes?

This is how I made it work:

// Function to check and disable checkbox
function limit_checked( element, size ) {
  var bol = $( element + ':checked').length >= size;
  $(element).not(':checked').attr('disabled',bol);
}

// List of checkbox groups to check
var check_elements = [
  { id: '.group1 input[type=checkbox]', size: 2 },
  { id: '.group2 input[type=checkbox]', size: 3 },
];

// Run function for each group in list
$(check_elements).each( function(index, element) {
  // Limit checked on window load
  $(window).load( function() {
    limit_checked( element.id, element.size );
  })

  // Limit checked on click
  $(element.id).click(function() {
    limit_checked( element.id, element.size );
  });
});

Compiling php with curl, where is curl installed?

php curl lib is just a wrapper of cUrl, so, first of all, you should install cUrl. Download the cUrl source to your linux server. Then, use the follow commands to install:

tar zxvf cUrl_src_taz
cd cUrl_src_taz
./configure --prefix=/curl/install/home
make
make test    (optional)
make install
ln -s  /curl/install/home/bin/curl-config /usr/bin/curl-config

Then, copy the head files in the "/curl/install/home/include/" to "/usr/local/include". After all above steps done, the php curl extension configuration could find the original curl, and you can use the standard php extension method to install php curl.
Hope it helps you, :)

This Row already belongs to another table error when trying to add rows?

yourTable.ImportRow(dataRow);

It's because the row you're copying doesn't have the same TableName:

For example, try:

Table1.TableName = "Table1";
Table2.TableName = "Table2";

Access a function variable outside the function without using "global"

You could do something along these lines (which worked in both Python v2.7.17 and v3.8.1 when I tested it/them):

def hi():
    # other code...
    hi.bye = 42  # Create function attribute.
    sigh = 10

hi()
print(hi.bye)  # -> 42

Functions are objects in Python and can have arbitrary attributes assigned to them.

If you're going to be doing this kind of thing often, you could implement something more generic by creating a function decorator that adds a this argument to each call to the decorated function.

This additional argument will give functions a way to reference themselves without needing to explicitly embed (hardcode) their name into the rest of the definition and is similar to the instance argument that class methods automatically receive as their first argument which is usually named self — I picked something different to avoid confusion, but like the self argument, it can be named whatever you wish.

Here's an example of that approach:

def add_this_arg(func):
    def wrapped(*args, **kwargs):
        return func(wrapped, *args, **kwargs)
    return wrapped

@add_this_arg
def hi(this, that):
    # other code...
    this.bye = 2 * that  # Create function attribute.
    sigh = 10

hi(21)
print(hi.bye)  # -> 42

Note

This doesn't work for class methods. Just use the self argument already passed being passed to instead of the method name. You can reference class-level attributes through type(self). See Function's attributes when in a class.

How to Apply Mask to Image in OpenCV?

Well, this question appears on top of search results, so I believe we need code example here. Here's the Python code:

import cv2

def apply_mask(frame, mask):
    """Apply binary mask to frame, return in-place masked image."""
    return cv2.bitwise_and(frame, frame, mask=mask)

Mask and frame must be the same size, so pixels remain as-is where mask is 1 and are set to zero where mask pixel is 0.

And for C++ it's a little bit different:

cv::Mat inFrame; // Original (non-empty) image
cv::Mat mask; // Original (non-empty) mask

// ...

cv::Mat outFrame;  // Result output
inFrame.copyTo(outFrame, mask);

how can I connect to a remote mongo server from Mac OS terminal

With Mongo 3.2 and higher just use your connection string as is:

mongo mongodb://username:[email protected]:10011/my_database

dplyr mutate with conditional values

It looks like derivedFactor from the mosaic package was designed for this. In this example, it would look something like:

library(mosaic)
myfile <- mutate(myfile, V5 = derivedFactor(
    "1" = (V1==1 & V2!=4),
    "2" = (V2==4 & V3!=1),
    .method = "first",
    .default = 0
    ))

(If you want the outcome to be numeric instead of a factor, wrap the derivedFactor with an as.numeric.)

Note that the .default option combined with .method = "first" sets the "else" condition -- this approach is described in the help file for derivedFactor.

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

I solve this problem by always using the [h] option on floats (such as figures) so that they (mostly) go where I place them. Then when I look at the final draft, I adjust the location of the float by moving it in the LaTeX source. Usually that means moving it around the paragraph where it is referenced. Sometimes I need to add a page break at an appropriate spot.

I've found that the default placement of floats is reasonable in LaTeX, but manual adjustments are almost always needed to get things like this just right. (And sometimes it isn't possible for everything to be perfect when there are lots of floats and footnotes.)

The manual for the memoir class has some good information about how LaTeX places floats and some advice for manipulating the algorithm.

Get selected item value from Bootstrap DropDown with specific ID

The selector would be #demolist.dropdown-menu li a note no space between id and class. However i would suggest a more generic approach:

<div class="input-group">                                            
    <input type="TextBox" Class="form-control datebox"></input>
    <div class="input-group-btn">
    <button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">
        <li><a href="#">A</a></li>
        <li><a href="#">B</a></li>
        <li><a href="#">C</a></li>
    </ul>
</div>


$(document).on('click', '.dropdown-menu li a', function() {
    $(this).parent().parent().parent().find('.datebox').val($(this).html());
}); 

by using a class rather than id, and using parent().find(), you can have as many of these on a page as you like, with no duplicated js

HttpRequest maximum allowable size in tomcat?

The full answer

1. The default (fresh install of tomcat)

When you download tomcat from their official website (of today that's tomcat version 9.0.26), all the apps you installed to tomcat can handle HTTP requests of unlimited size, given that the apps themselves do not have any limits on request size.

However, when you try to upload an app in tomcat's manager app, that app has a default war file limit of 50MB. If you're trying to install Jenkins for example which is 77 MB as ot today, it will fail.

2. Configure tomcat's per port http request size limit

Tomcat itself has size limit for each port, and this is defined in conf\server.xml. This is controlled by maxPostSize attribute of each Connector(port). If this attribute does not exist, which it is by default, there is no limit on the request size.

To add a limit to a specific port, set a byte size for the attribute. For example, the below config for the default 8080 port limits request size to 200 MB. This means that all the apps installed under port 8080 now has the size limit of 200MB

<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443"
           maxPostSize="209715200" />

3. Configure app level size limit

After passing the port level size limit, you can still configure app level limit. This also means that app level limit should be less than port level limit. The limit can be done through annotation within each servlet, or in the web.xml file. Again, if this is not set at all, there is no limit on request size.

To set limit through java annotation

@WebServlet("/uploadFiles")
@MultipartConfig( fileSizeThreshold = 0, maxFileSize = 209715200, maxRequestSize = 209715200)
public class FileUploadServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        // ...
    }
}

To set limit through web.xml

<web-app>
  ...
  <servlet>
    ...
    <multipart-config>
      <file-size-threshold>0</file-size-threshold>
      <max-file-size>209715200</max-file-size>
      <max-request-size>209715200</max-request-size>
    </multipart-config>
    ...
  </servlet>
  ...
</web-app>

4. Appendix - If you see file upload size error when trying to install app through Tomcat's Manager app

Tomcat's Manager app (by default localhost:8080/manager) is nothing but a default web app. By default that app has a web.xml configuration of request limit of 50MB. To install (upload) app with size greater than 50MB through this manager app, you have to change the limit. Open the manager app's web.xml file from webapps\manager\WEB-INF\web.xml and follow the above guide to change the size limit and finally restart tomcat.

What is __main__.py?

What is the __main__.py file for?

When creating a Python module, it is common to make the module execute some functionality (usually contained in a main function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:

if __name__ == '__main__':
    # execute only if run as the entry point into the program
    main()

You can get the same semantics for a Python package with __main__.py, which might have the following structure:

.
+-- demo
    +-- __init__.py
    +-- __main__.py

To see this, paste the below into a Python 3 shell:

from pathlib import Path

demo = Path.cwd() / 'demo'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo/__main__.py executed')

from demo import main

main()
""")

We can treat demo as a package and actually import it, which executes the top-level code in the __init__.py (but not the main function):

>>> import demo
demo/__init__.py executed

When we use the package as the entry point to the program, we perform the code in the __main__.py, which imports the __init__.py first:

$ python -m demo
demo/__init__.py executed
demo/__main__.py executed
main() executed

You can derive this from the documentation. The documentation says:

__main__ — Top-level script environment

'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

if __name__ == '__main__':
     # execute only if run as a script
     main()

For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.

Zipped

You can also zip up this directory, including the __main__.py, into a single file and run it from the command line like this - but note that zipped packages can't execute sub-packages or submodules as the entry point:

from pathlib import Path

demo = Path.cwd() / 'demo2'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo2/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo2/__main__.py executed')

from __init__ import main

main()
""")

Note the subtle change - we are importing main from __init__ instead of demo2 - this zipped directory is not being treated as a package, but as a directory of scripts. So it must be used without the -m flag.

Particularly relevant to the question - zipapp causes the zipped directory to execute the __main__.py by default - and it is executed first, before __init__.py:

$ python -m zipapp demo2 -o demo2zip
$ python demo2zip
demo2/__main__.py executed
demo2/__init__.py executed
main() executed

Note again, this zipped directory is not a package - you cannot import it either.

ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)

In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.

Single TextView with multiple colored text

if (Build.VERSION.SDK_INT >= 24) {
     Html.fromHtml(String, flag) // for 24 API  and more
 } else {
     Html.fromHtml(String) // or for older API 
 }

for 24 API and more (flag)

public static final int FROM_HTML_MODE_COMPACT = 63;
public static final int FROM_HTML_MODE_LEGACY = 0;
public static final int FROM_HTML_OPTION_USE_CSS_COLORS = 256;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_BLOCKQUOTE = 32;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_DIV = 16;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_HEADING = 2;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST = 8;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM = 4;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH = 1;
public static final int TO_HTML_PARAGRAPH_LINES_CONSECUTIVE = 0;
public static final int TO_HTML_PARAGRAPH_LINES_INDIVIDUAL = 1;

More Info

Alternate background colors for list items

If you want to do this purely in CSS then you'd have a class that you'd assign to each alternate list item. E.g.

<ul>
    <li class="alternate"><a href="link">Link 1</a></li>
    <li><a href="link">Link 2</a></li>
    <li class="alternate"><a href="link">Link 3</a></li>
    <li><a href="link">Link 4</a></li>
    <li class="alternate"><a href="link">Link 5</a></li>
</ul>

If your list is dynamically generated, this task would be much easier.

If you don't want to have to manually update this content each time, you could use the jQuery library and apply a style alternately to each <li> item in your list:

<ul id="myList">
    <li><a href="link">Link 1</a></li>
    <li><a href="link">Link 2</a></li>
    <li><a href="link">Link 3</a></li>
    <li><a href="link">Link 4</a></li>
    <li><a href="link">Link 5</a></li>
</ul>

And your jQuery code:

$(document).ready(function(){
  $('#myList li:nth-child(odd)').addClass('alternate');
});

Command to open file with git

I used Atom, to open files this works for me

atom index.html

Hopefully this helps.

OSX -bash: composer: command not found

If you have to run composer with sudo, you should change the directory of composer to

/usr/bin

this was tested on Centos8.

Convert DOS line endings to Linux line endings in Vim

To run directly in a Linux console:

vim file.txt +"set ff=unix" +wq

Android SharedPreferences in Fragment

The method getSharedPreferences is a method of the Context object, so just calling getSharedPreferences from a Fragment will not work...because it is not a Context! (Activity is an extension of Context, so we can call getSharedPreferences from it).

So you have to get your applications Context by

// this = your fragment
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);

Changing image size in Markdown

For all looking for solutions which work in R markdown/ bookdown, these of the previous solutions do/do not work or need slight adaption:

Working

  • Append { width=50% } or { width=50% height=50% }

    • ![foo](foo.png){ width=50% }
    • ![foo](foo.png){ width=50% height=50% }

    • Important: no comma between width and height – i.e. { width=50%, height=30% } won't work!

  • Append { height="36px" width="36px" }

    • ![foo](foo.png){ height="36px" width="36px" }
    • Note: {:height="36px" width="36px"} with colon, as from @sayth, seems not to work with R markdown

Not working:

  • Append =WIDTHxHEIGHT
    • after the URL of the graphic file to resize the image (as from @prosseek)
    • neither =WIDTHxHEIGHT ![foo](foo.png =100x20) nor =WIDTH only ![foo](foo.png =250x) work

How do I get the HTML code of a web page in PHP?

$output = file("http://www.example.com"); didn't work until I enabled: allow_url_fopen, allow_url_include, and file_uploads in php.ini for PHP7

What is an undefined reference/unresolved external symbol error and how do I fix it?

Also if you're using 3rd party libraries make sure you have the correct 32/64 bit binaries

Uninstall / remove a Homebrew package including all its dependencies

Save the following script as brew-purge

#!/bin/bash
#:Usage: brew purge formula
#: 
#:Removes the package and all dependancies.
#: 
#: 
PKG="$1"
if [ -z "$PKG" ];then
   brew purge --help
   exit 1
fi
brew rm $PKG
[ $? -ne 0 ] && exit 1
while brew rm $(join <(brew leaves) <(brew deps $PKG)) 2>/dev/null
  do :
done
echo Package $PKG and its dependancies have been removed.
exit 0

Now install it with the following command

sudo install brew-purge /usr/local/bin

Now run it

brew purge package

Example using gpg

$ brew purge gpg
Uninstalling /usr/local/Cellar/gnupg/2.2.13... (134 files, 11.0MB)
Uninstalling /usr/local/Cellar/adns/1.5.1... (14 files, 597.5KB)
Uninstalling /usr/local/Cellar/gnutls/3.6.6... (1,200 files, 8.9MB)
Uninstalling /usr/local/Cellar/libgcrypt/1.8.4... (21 files, 2.6MB)
Uninstalling /usr/local/Cellar/libksba/1.3.5... (14 files, 344.2KB)
Uninstalling /usr/local/Cellar/libusb/1.0.22... (29 files, 508KB)
Uninstalling /usr/local/Cellar/npth/1.6... (11 files, 71.7KB)
Uninstalling /usr/local/Cellar/pinentry/1.1.0_1... (12 files, 263.9KB)
Uninstalling /usr/local/Cellar/libassuan/2.5.3... (16 files, 444.2KB)
Uninstalling /usr/local/Cellar/libtasn1/4.13... (59 files, 436KB)
Uninstalling /usr/local/Cellar/libunistring/0.9.10... (54 files, 4.4MB)
Uninstalling /usr/local/Cellar/nettle/3.4.1... (85 files, 2MB)
Uninstalling /usr/local/Cellar/p11-kit/0.23.15... (63 files, 2.9MB)
Uninstalling /usr/local/Cellar/gmp/6.1.2_2... (18 files, 3.1MB)
Uninstalling /usr/local/Cellar/libffi/3.2.1... (16 files, 296.8KB)
Uninstalling /usr/local/Cellar/libgpg-error/1.35... (27 files, 854.8KB)
Package gpg and its dependancies have been removed.
$ 

Access denied for root user in MySQL command-line

You mustn't have a space character between -u and the username:

mysql -uroot -p
# or
mysql --user=root --password

Rewrite left outer join involving multiple tables from Informix to Oracle

I'm guessing that you want something like

SELECT tab1.a, tab2.b, tab3.c, tab4.d
  FROM table1 tab1 
       JOIN table2 tab2 ON (tab1.fg = tab2.fg)
       LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
       LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
       LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
                                       tab3.dd = tab5.dd)

how to do "press enter to exit" in batch

Oops... Misunderstood the question...

Pause is the way to go

Old answer:

you can pipe commands into your patch file...

try

build.bat < responsefile.txt

How to get annotations of a member variable?

My way

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

public class ReadAnnotation {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadAnnotation.class);

    public static boolean hasIgnoreAnnotation(String fieldName, Class entity) throws NoSuchFieldException {
        return entity.getDeclaredField(fieldName).isAnnotationPresent(IgnoreAnnotation.class);
    }

    public static boolean isSkip(PropertyDescriptor propertyDescriptor, Class entity) {
        boolean isIgnoreField;
        try {
            isIgnoreField = hasIgnoreAnnotation(propertyDescriptor.getName(), entity);
        } catch (NoSuchFieldException e) {
            LOGGER.error("Can not check IgnoreAnnotation", e);
            isIgnoreField = true;
        }
        return isIgnoreField;
    }

    public void testIsSkip() throws Exception {
        Class<TestClass> entity = TestClass.class;
        BeanInfo beanInfo = Introspector.getBeanInfo(entity);

        for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
            System.out.printf("Field %s, has annotation %b", propertyDescriptor.getName(),  isSkip(propertyDescriptor, entity));
        }
    }

}

Make column fixed position in bootstrap

Use this, works for me and solve problems with small screen.

<div class="row">
    <!-- (fixed content) JUST VISIBLE IN LG SCREEN -->
    <div class="col-lg-3 device-lg visible-lg">
       <div class="affix">
           fixed position 
        </div>
    </div>
    <div class="col-lg-9">
    <!-- (fixed content) JUST VISIBLE IN NO LG SCREEN -->
    <div class="device-sm visible-sm device-xs visible-xs device-md visible-md ">
       <div>
           NO fixed position
        </div>
    </div>
       Normal data enter code here
    </div>
</div>

Number of occurrences of a character in a string

Your string example looks like the query string part of a GET. If so, note that HttpContext has some help for you

int numberOfArgs = HttpContext.Current.QueryString.Count;

For more of what you can do with QueryString, see NameValueCollection

Is there such a thing as min-font-size and max-font-size?

It works well with CSS.

I went through the same issues and fixed it as follow.

Use a fixed "px" size for maximum size at a specific width and above. Then for different smaller widths, use a relative "vw" as a percentage of the screen.

The result below is that it adjusts itself at screens below 960px but keep a fixed size above. Just a reminder, not to forget to add in the html doc in header:

<meta name="viewport" content="width=device-width">

Example in CSS:

@media all and (min-width: 960px) {
h1{
    font-size: 50px;
  }
}

@media all and (max-width: 959px) and (min-width: 600px) {
h1{
    font-size: 5vw;
  }
}

@media all and (max-width: 599px) and (min-width: 50px) {
h1{
    font-size: 6vw;
  }
}

I hope it'll help!

Update all objects in a collection using LINQ

No, LINQ doesn't support a manner of mass updating. The only shorter way would be to use a ForEach extension method - Why there is no ForEach extension method on IEnumerable?

Serialize an object to string

Serialize and Deserialize (XML/JSON):

public static T XmlDeserialize<T>(this string toDeserialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using(StringReader textReader = new StringReader(toDeserialize))
    {      
        return (T)xmlSerializer.Deserialize(textReader);
    }
}

public static string XmlSerialize<T>(this T toSerialize)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using(StringWriter textWriter = new StringWriter())
    {
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

public static T JsonDeserialize<T>(this string toDeserialize)
{
    return JsonConvert.DeserializeObject<T>(toDeserialize);
}

public static string JsonSerialize<T>(this T toSerialize)
{
    return JsonConvert.SerializeObject(toSerialize);
}

cast or convert a float to nvarchar?

Check STR. You need something like SELECT STR([Column_Name],10,0) ** This is SQL Server solution, for other servers check their docs.

Visual Studio Code: How to show line endings

AFAIK there is no way to visually see line endings in the editor space, but in the bottom-right corner of the window there is an indicator that says "CLRF" or "LF" which will let you set the line endings for a particular file. Clicking on the text will allow you to change the line endings as well.

enter image description here

How can INSERT INTO a table 300 times within a loop in SQL?

DECLARE @first AS INT = 1
DECLARE @last AS INT = 300

WHILE(@first <= @last)
BEGIN
    INSERT INTO tblFoo VALUES(@first)
    SET @first += 1
END

Group array items using object

Start by creating a mapping of group names to values. Then transform into your desired format.

_x000D_
_x000D_
var myArray = [_x000D_
    {group: "one", color: "red"},_x000D_
    {group: "two", color: "blue"},_x000D_
    {group: "one", color: "green"},_x000D_
    {group: "one", color: "black"}_x000D_
];_x000D_
_x000D_
var group_to_values = myArray.reduce(function (obj, item) {_x000D_
    obj[item.group] = obj[item.group] || [];_x000D_
    obj[item.group].push(item.color);_x000D_
    return obj;_x000D_
}, {});_x000D_
_x000D_
var groups = Object.keys(group_to_values).map(function (key) {_x000D_
    return {group: key, color: group_to_values[key]};_x000D_
});_x000D_
_x000D_
var pre = document.createElement("pre");_x000D_
pre.innerHTML = "groups:\n\n" + JSON.stringify(groups, null, 4);_x000D_
document.body.appendChild(pre);
_x000D_
_x000D_
_x000D_

Using Array instance methods such as reduce and map gives you powerful higher-level constructs that can save you a lot of the pain of looping manually.

How to parse JSON with VBA without external libraries?

I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):

Sub getData()

    Dim Movie As Object
    Dim scriptControl As Object

    Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
    scriptControl.Language = "JScript"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
        .send
        Set Movie = scriptControl.Eval("(" + .responsetext + ")")
        .abort
        With Sheets(2)
            .Cells(1, 1).Value = Movie.Title
            .Cells(1, 2).Value = Movie.Year
            .Cells(1, 3).Value = Movie.Rated
            .Cells(1, 4).Value = Movie.Released
            .Cells(1, 5).Value = Movie.Runtime
            .Cells(1, 6).Value = Movie.Director
            .Cells(1, 7).Value = Movie.Writer
            .Cells(1, 8).Value = Movie.Actors
            .Cells(1, 9).Value = Movie.Plot
            .Cells(1, 10).Value = Movie.Language
            .Cells(1, 11).Value = Movie.Country
            .Cells(1, 12).Value = Movie.imdbRating
        End With
    End With

End Sub

Generate GUID in MySQL for existing Data?

I faced mostly the same issue. Im my case uuid is stored as BINARY(16) and has NOT NULL UNIQUE constraints. And i faced with the issue when the same UUID was generated for every row, and UNIQUE constraint does not allow this. So this query does not work:

UNHEX(REPLACE(uuid(), '-', ''))

But for me it worked, when i used such a query with nested inner select:

UNHEX(REPLACE((SELECT uuid()), '-', ''))

Then is produced unique result for every entry.

Android Use Done button on Keyboard to click button

Use this class in your layout :

public class ActionEditText extends EditText
{
    public ActionEditText(Context context)
    {
        super(context);
    }

    public ActionEditText(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public ActionEditText(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs)
    {
        InputConnection conn = super.onCreateInputConnection(outAttrs);
        outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
        return conn;
    }

}

In xml:

<com.test.custom.ActionEditText
                android:id="@+id/postED"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@android:color/transparent"
                android:gravity="top|left"
                android:hint="@string/msg_type_message_here"
                android:imeOptions="actionSend"
                android:inputType="textMultiLine"
                android:maxLines="5"
                android:padding="5dip"
                android:scrollbarAlwaysDrawVerticalTrack="true"
                android:textColor="@color/white"
                android:textSize="20sp" />

How to select a value in dropdown javascript?

Using some ES6:

Get the options first, filter the value based on the option and set the selected attribute to true.

_x000D_
_x000D_
window.onload = () => {_x000D_
_x000D_
  Array.from(document.querySelector(`#Mobility`).options)_x000D_
    .filter(x => x.value === "12")[0]_x000D_
    .setAttribute('selected', true);_x000D_
_x000D_
};
_x000D_
<select style="width: 280px" id="Mobility" name="Mobility">_x000D_
  <option selected disabled>Please Select</option>_x000D_
  <option>K</option>_x000D_
  <option>1</option>_x000D_
  <option>2</option>_x000D_
  <option>3</option>_x000D_
  <option>4</option>_x000D_
  <option>5</option>_x000D_
  <option>6</option>_x000D_
  <option>7</option>_x000D_
  <option>8</option>_x000D_
  <option>9</option>_x000D_
  <option>10</option>_x000D_
  <option>11</option>_x000D_
  <option>12</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

What is the easiest way to parse an INI File in C++?

Have you tried libconfig; very JSON-like syntax. I prefer it over XML configuration files.

How to check Elasticsearch cluster health?

If Elasticsearch cluster is not accessible (e.g. behind firewall), but Kibana is:

Kibana => DevTools => Console:

GET /_cluster/health 

enter image description here enter image description here

How to convert interface{} to string?

You need to add type assertion .(string). It is necessary because the map is of type map[string]interface{}:

host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)

Latest version of Docopt returns Opts object that has methods for conversion:

host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port

How to set commands output as a variable in a batch file

Some notes and some tricks.

The 'official' way to assign result to a variable is with FOR /F though in the other answers is shown how a temporary file can be used also.

For command processing FOR command has two forms depending if the usebackq option is used. In the all examples below the whole output is used without splitting it.

FOR /f "tokens=* delims=" %%A in ('whoami') do @set "I-Am=%%A"
FOR /f "usebackq tokens=* delims=" %%A in (`whoami`) do @set "I-Am=%%A"

and if used directly in the console:

FOR /f "tokens=* delims=" %A in ('whoami') do set "I-Am=%A"
FOR /f "usebackq tokens=* delims=" %A in (`whoami`) do set "I-Am=%A"

%%A is a temporary variable available only on the FOR command context and is called token.The two forms can be useful in case when you are dealing with arguments containing specific quotes. It is especially useful with REPL interfaces of other languages or WMIC. Though in both cases the expression can be put in double quotes and it still be processed.

Here's an example with python (it is possible to transition the expression in the brackets on a separate line which is used for easier reading):

@echo off

for /f "tokens=* delims=" %%a in (
  '"python -c ""print("""Message from python""")"""'
) do (
    echo processed message from python: "%%a"
)

To use an assigned variable in the same FOR block check also the DELAYED EXPANSION

And some tricks

To save yourself from writing all the arguments for the FOR command you can use MACRO for assigning the result to variable:

@echo off

::::: ---- defining the assign macro ---- ::::::::
setlocal DisableDelayedExpansion
(set LF=^
%=EMPTY=%
)
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

::set argv=Empty
set assign=for /L %%n in (1 1 2) do ( %\n%
   if %%n==2 (%\n%
      setlocal enableDelayedExpansion%\n%
      for /F "tokens=1,2 delims=," %%A in ("!argv!") do (%\n%
         for /f "tokens=* delims=" %%# in ('%%~A') do endlocal^&set "%%~B=%%#" %\n%
      ) %\n%
   ) %\n%
) ^& set argv=,

::::: -------- ::::::::


:::EXAMPLE
%assign% "WHOAMI /LOGONID",result
echo %result%

the first argument to the macro is the command and the second the name of the variable we want to use and both are separated by , (comma). Though this is suitable only for straight forward scenarios.

If we want a similar macro for the console we can use DOSKEY

doskey assign=for /f "tokens=1,2 delims=," %a in ("$*") do @for /f "tokens=* delims=" %# in ('"%a"') do @set "%b=%#"
rem  -- example --
assign WHOAMI /LOGONID,my-id
echo %my-id%

DOSKEY does accept double quotes as enclosion for arguments so this also is useful for more simple scenarios.

FOR also works well with pipes which can be used for chaining commands (though it is not so good for assigning a variable.

hostname |for /f "tokens=* delims=" %%# in ('more') do @(ping %%#)

Which also can be beautified with macros:

@echo off
:: --- defining chain command macros ---
set "result-as-[arg]:=|for /f "tokens=* delims=" %%# in ('more') do @("
set "[arg]= %%#)"
:::  --------------------------  :::

::Example:
hostname %result-as-[arg]:% ping %[arg]%

And for completnes macros for the temp file approach (no doskey definition ,but it also can be easy done.If you have a SSD this wont be so slow):

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1"
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

chcp %[[%code-page%]]%
echo ~~%code-page%~~

whoami %[[%its-me%]]%
echo ##%its-me%##

For /f with another macro:

::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

Finding and removing non ascii characters from an Oracle Varchar2

The following also works:

select dump(a,1016), a from (
SELECT REGEXP_REPLACE (
          CONVERT (
             '3735844533120%$03  ',
             'US7ASCII',
             'WE8ISO8859P1'),
          '[^!@/\.,;:<>#$%&()_=[:alnum:][:blank:]]') a
  FROM DUAL);

HttpWebRequest using Basic authentication

Following code will solve json response if there Basic Authentication and Proxy implemented.Also IIS 7.5 Hosting Problm will resolve.

public string HttpGetByWebRequ(string uri, string username, string password)
{
//For Basic Authentication
    string authInfo = username + ":" + password;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));

//For Proxy
    WebProxy proxy = new WebProxy("http://10.127.0.1:8080", true);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "GET";
    request.Accept = "application/json; charset=utf-8";
    request.Proxy = proxy;

    request.Headers["Authorization"] = "Basic " + authInfo;

    var response = (HttpWebResponse)request.GetResponse();

    string strResponse = "";
    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        strResponse= sr.ReadToEnd();

    }

    return strResponse;
}