Programs & Examples On #System.configuration

The System.Configuration is a .net framework namespace contains the types that provide the programming model for handling configuration data.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

Yes, ConfigurationManager.AppSettings is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager.

Credits goes to @JeroenMostert for giving me the solution.

Using app.config in .Net Core

  1. You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app. Look into sample provided in the link, that shows how to read configs in the console app.

  2. In most cases, the JSON source (read as .json file) is the most suitable config source.

    Note: don't be confused when someone says that config file should be appsettings.json. You can use any file name, that is suitable for you and file location may be different - there are no specific rules.

    But, as the real world is complicated, there are a lot of different configuration providers:

    • File formats (INI, JSON, and XML)
    • Command-line arguments
    • Environment variables

    and so on. You even could use/write a custom provider.

  3. Actually, app.config configuration file was an XML file. So you can read settings from it using XML configuration provider (source on github, nuget link). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you. Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file.

The type or namespace name 'System' could not be found

Cleaning solution worked for me.

I would also advise to close and relaunch Visual Studio once doing so.

How to read AppSettings values from a .json file in ASP.NET Core

For ASP.NET Core 3.1 you can follow this documentation:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

When you create a new ASP.NET Core 3.1 project you will have the following configuration line in Program.cs:

Host.CreateDefaultBuilder(args)

This enables the following:

  1. ChainedConfigurationProvider : Adds an existing IConfiguration as a source. In the default configuration case, adds the host configuration and setting it as the first source for the app configuration.
  2. appsettings.json using the JSON configuration provider.
  3. appsettings.Environment.json using the JSON configuration provider. For example, appsettings.Production.json and appsettings.Development.json.
  4. App secrets when the app runs in the Development environment.
  5. Environment variables using the Environment Variables configuration provider.
  6. Command-line arguments using the Command-line configuration provider.

This means you can inject IConfiguration and fetch values with a string key, even nested values. Like IConfiguration ["Parent:Child"];

Example:

appsettings.json

{
  "ApplicationInsights":
    {
        "Instrumentationkey":"putrealikeyhere"
    }
}

WeatherForecast.cs

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IConfiguration _configuration;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var key = _configuration["ApplicationInsights:InstrumentationKey"];

        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

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

I had this when build my application with "All cpu" target while it referenced a 3rd party x64-only (managed) dll.

How to refresh or show immediately in datagridview after inserting?

Try below piece of code.

this.dataGridView1.RefreshEdit();

How to use ConfigurationManager

Okay, it took me a while to see this, but there's no way this compiles:

return String.(ConfigurationManager.AppSettings[paramName]);

You're not even calling a method on the String type. Just do this:

return ConfigurationManager.AppSettings[paramName];

The AppSettings KeyValuePair already returns a string. If the name doesn't exist, it will return null.


Based on your edit you have not yet added a Reference to the System.Configuration assembly for the project you're working in.

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

You can enable NuGet packages and update you dlls. so that it work. or you can update the package manually by going through the package manager in your vs if u know which version you require for your solution.

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

This problem would be caused by your application missing a reference to an external dll that you are trying to use code from. Usually Visual Studio should give you an idea about which objects that it doesn't know what to do with so that should be a step in the right direction.

You need to look in the solution explorer and right click on project references and then go to add -> and look up the one you need. It's most likely the System.Configuration assembly as most people have pointed out here while should be under the Framework option in the references window. That should resolve your issue.

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.

Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.

Content Type application/soap+xml; charset=utf-8 was not supported by service

I too had the same error in trace logs. My newly created function in API was throwing the same error but to my surprise, the old functions were performing good. The issue was - My contract data members had few variables of type object. soap-xml was not able to handle it well, however, I can see that array of object types (object[]) were getting passed without any issues. Only a simple object type was not getting parsed by soap. This could be one more reason why the services throw the above error.

SQL update statement in C#

Please, never use this concat form:

String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
        + "WHERE supplier_id = " + textBox1.Text;

use:

command.Parameters.AddWithValue("@attribute", value);

Always work object oriented

Edit: This is because when you parameterize your updates it helps prevent SQL injection.

How to display data from database into textbox, and update it

Wrap your all statements in !IsPostBack condition on page load.

protected void Page_Load(object sender, EventArgs e)
{
   if(!IsPostBack)
   {
      // all statements
   }
}

This will fix your issue.

How to fill DataTable with SQL Table

The SqlDataReader is a valid data source for the DataTable. As such, all you need to do its this:

public DataTable GetData()
{
    SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
    conn.Open();
    string query = "SELECT * FROM [EventOne]";
    SqlCommand cmd = new SqlCommand(query, conn);

    DataTable dt = new DataTable();
    dt.Load(cmd.ExecuteReader());
    conn.Close();
    return dt;
}

App.Config change value

AppSettings.Set does not persist the changes to your configuration file. It just changes it in memory. If you put a breakpoint on System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang);, and add a watch for System.Configuration.ConfigurationManager.AppSettings[0] you will see it change from "English" to "Russian" when that line of code runs.

The following code (used in a console application) will persist the change.

class Program
{
    static void Main(string[] args)
    {
        UpdateSetting("lang", "Russian");
    }

    private static void UpdateSetting(string key, string value)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save();

        ConfigurationManager.RefreshSection("appSettings");
    }
}

From this post: http://vbcity.com/forums/t/152772.aspx

One major point to note with the above is that if you are running this from the debugger (within Visual Studio) then the app.config file will be overwritten each time you build. The best way to test this is to build your application and then navigate to the output directory and launch your executable from there. Within the output directory you will also find a file named YourApplicationName.exe.config which is your configuration file. Open this in Notepad to see that the changes have in fact been saved.

ExecuteNonQuery: Connection property has not been initialized.

A couple of things wrong here.

  1. Do you really want to open and close the connection for every single log entry?

  2. Shouldn't you be using SqlCommand instead of SqlDataAdapter?

  3. The data adapter (or SqlCommand) needs exactly what the error message tells you it's missing: an active connection. Just because you created a connection object does not magically tell C# that it is the one you want to use (especially if you haven't opened the connection).

I highly recommend a C# / SQL Server tutorial.

How do I make calls to a REST API using C#?

The first step is to create the helper class for the HTTP client.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace callApi.Helpers
{
    public class CallApi
    {
        private readonly Uri BaseUrlUri;
        private HttpClient client = new HttpClient();

        public CallApi(string baseUrl)
        {
            BaseUrlUri = new Uri(baseUrl);
            client.BaseAddress = BaseUrlUri;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public HttpClient getClient()
        {
            return client;
        }

        public HttpClient getClientWithBearer(string token)
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            return client;
        }
    }
}

Then you can use this class in your code.

This is an example of how you call the REST API without bearer using the above class.

// GET API/values
[HttpGet]
public async Task<ActionResult<string>> postNoBearerAsync(string email, string password,string baseUrl, string action)
{
    var request = new LoginRequest
    {
        email = email,
        password = password
    };

    var callApi = new CallApi(baseUrl);
    var client = callApi.getClient();
    HttpResponseMessage response = await client.PostAsJsonAsync(action, request);
    if (response.IsSuccessStatusCode)
        return Ok(await response.Content.ReadAsAsync<string>());
    else
        return NotFound();
}

This is an example of how you can call the REST API that require bearer.

// GET API/values
[HttpGet]
public async Task<ActionResult<string>> getUseBearerAsync(string token, string baseUrl, string action)
{
    var callApi = new CallApi(baseUrl);
    var client = callApi.getClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    HttpResponseMessage response = await client.GetAsync(action);
    if (response.IsSuccessStatusCode)
    {
        return Ok(await response.Content.ReadAsStringAsync());
    }
    else
        return NotFound();
}

You can also refer to the below repository if you want to see the working example of how it works.

https://github.com/mokh223/callApi

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

An XSD is included with EntLib 5, and is installed in the Visual Studio schema directory. In my case, it could be found at:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas\EnterpriseLibrary.Configuration.xsd

CONTEXT

  • Visual Studio 2010
  • Enterprise Library 5

STEPS TO REMOVE THE WARNINGS

  1. open app.config in your Visual Studio project
  2. right click in the XML Document editor, select "Properties"
  3. add the fully qualified path to the "EnterpriseLibrary.Configuration.xsd"

ASIDE

It is worth repeating that these "Error List" "Messages" ("Could not find schema information for the element") are only visible when you open the app.config file. If you "Close All Documents" and compile... no messages will be reported.

Reading a key from the Web.Config using ConfigurationManager

There will be two Web.config files. I think you may have confused with those two files.

Check this image:

click this link and check this image

In this image you can see two Web.config files. You should add your constants to the one which is in the project folder not in the views folder

Hope this may help you

How to avoid a System.Runtime.InteropServices.COMException?

I got this exception while coping a object(variable) Matrix Array into Excel sheet. The solution to this is, Matrix array Index(i,j) must start from (0,0) whereas Excel sheet should start with Matrix Array index (i,j) from (1,1) .

I hope you this concept.

The Role Manager feature has not been enabled

You can do this by reading from the boolean property at:

System.Web.Security.Roles.Enabled

This is a direct read from the enabled attribute of the roleManager element in the web.config:

<configuration>
  <system.web>
    <roleManager enabled="true" />
  </system.web>
</configuration>


Update:
For more information, check out this MSDN sample: https://msdn.microsoft.com/en-us/library/aa354509(v=vs.110).aspx

How to get the values of a ConfigurationSection of type NameValueSectionHandler

The only way I can get this to work is to manually instantiate the section handler type, pass the raw XML to it, and cast the resulting object.

Seems pretty inefficient, but there you go.

I wrote an extension method to encapsulate this:

public static class ConfigurationSectionExtensions
{
    public static T GetAs<T>(this ConfigurationSection section)
    {
        var sectionInformation = section.SectionInformation;

        var sectionHandlerType = Type.GetType(sectionInformation.Type);
        if (sectionHandlerType == null)
        {
            throw new InvalidOperationException(string.Format("Unable to find section handler type '{0}'.", sectionInformation.Type));
        }

        IConfigurationSectionHandler sectionHandler;
        try
        {
            sectionHandler = (IConfigurationSectionHandler)Activator.CreateInstance(sectionHandlerType);
        }
        catch (InvalidCastException ex)
        {
            throw new InvalidOperationException(string.Format("Section handler type '{0}' does not implement IConfigurationSectionHandler.", sectionInformation.Type), ex);
        }

        var rawXml = sectionInformation.GetRawXml();
        if (rawXml == null)
        {
            return default(T);
        }

        var xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(rawXml);

        return (T)sectionHandler.Create(null, null, xmlDocument.DocumentElement);
    }
}

The way you would call it in your example is:

var map = new ExeConfigurationFileMap
{
    ExeConfigFilename = @"c:\\foo.config"
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var myParamsSection = configuration.GetSection("MyParams");
var myParamsCollection = myParamsSection.GetAs<NameValueCollection>();

reading from app.config file

Try to rebuild your project - It copies the content of App.config to "<YourProjectName.exe>.config" in the build library.

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

I had this issue, as I had copied a (fairly generic) webpage from one of my ASP.Net applications into a new application.

I changed the relevant namespace commands, to reflect the new location of the file... but... I had forgotten to change the Inherits parameter in the aspx page itself.

<%@ Page MasterPageFile="" StylesheetTheme="" Language="C#"
    AutoEventWireup="true" CodeBehind="MikesReports.aspx.cs" 
    Inherits="MikesCompany.MikesProject.MikesReports" %>

Once I had changed the Inherits parameter, the error went away.

How to get a List<string> collection of values from app.config in WPF?

Thank for the question. But I have found my own solution to this problem. At first, I created a method

    public T GetSettingsWithDictionary<T>() where T:new()
    {
        IConfigurationRoot _configurationRoot = new ConfigurationBuilder()
        .AddXmlFile($"{Assembly.GetExecutingAssembly().Location}.config", false, true).Build();

        var instance = new T();
        foreach (var property in typeof(T).GetProperties())
        {
            if (property.PropertyType == typeof(Dictionary<string, string>))
            {
                property.SetValue(instance, _configurationRoot.GetSection(typeof(T).Name).Get<Dictionary<string, string>>());
                break;
            }

        }
        return instance;
    }

Then I used this method to produce an instance of a class

var connStrs = GetSettingsWithDictionary<AuthMongoConnectionStrings>();

I have the next declaration of class

public class AuthMongoConnectionStrings
{
    public Dictionary<string, string> ConnectionStrings { get; set; }
}

and I store my setting in App.config

<configuration>    
  <AuthMongoConnectionStrings
  First="first"
  Second="second"
  Third="33" />
</configuration> 

The name 'ConfigurationManager' does not exist in the current context

In your project, right-click, Add Reference..., in the .NET tab, find the System.Configuration component name and click OK.

using System.Configuration tells the compiler/IntelliSense to search in that namespace for any classes you use. Otherwise, you would have to use the full name (System.Configuration.ConfigurationManager) every time. But if you don't add the reference, that namespace/class will not be found anywhere.

Note that a DLL can have any namespace, so the file System.Configuration.dll could, in theory, have the namespace Some.Random.Name. For clarity/consistency they're usually the same, but there are exceptions.

Parse JSON in C#

Your data class doesn't match the JSON object. Use this instead:

[DataContract]
public class GoogleSearchResults
{
    [DataMember]
    public ResponseData responseData { get; set; }
}

[DataContract]
public class ResponseData
{
    [DataMember]
    public IEnumerable<Results> results { get; set; }
}

[DataContract]
public class Results
{
    [DataMember]
    public string unescapedUrl { get; set; }

    [DataMember]
    public string url { get; set; }

    [DataMember]
    public string visibleUrl { get; set; }

    [DataMember]
    public string cacheUrl { get; set; }

    [DataMember]
    public string title { get; set; }

    [DataMember]
    public string titleNoFormatting { get; set; }

    [DataMember]
    public string content { get; set; }
}

Also, you don't have to instantiate the class to get its type for deserialization:

public static T Deserialise<T>(string json)
{
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        var serialiser = new DataContractJsonSerializer(typeof(T));
        return (T)serialiser.ReadObject(ms);
    }
}

Reading settings from app.config or web.config in .NET

I always create an IConfig interface with typesafe properties declared for all configuration values. A Config implementation class then wraps the calls to System.Configuration. All your System.Configuration calls are now in one place, and it is so much easier and cleaner to maintain and track which fields are being used and declare their default values. I write a set of private helper methods to read and parse common data types.

Using an IoC framework you can access the IConfig fields anywhere your in application by simply passing the interface to a class constructor. You're also then able to create mock implementations of the IConfig interface in your unit tests so you can now test various configuration values and value combinations without needing to touch your App.config or Web.config file.

Add values to app.config and retrieve them

To Get The Data From the App.config

Keeping in mind you have to:

  1. Added to the References -> System.Configuration
  2. and also added this using statement -> using System.Configuration;

Just Simply do this

string value1 = ConfigurationManager.AppSettings["Value1"];

Alternatively, you can achieve this in one line, if you don't want to add using System.Configuration; explicitly.

string value1 = System.Configuration.ConfigurationManager.AppSettings["Value1"]

Getting return value from stored procedure in C#

When you use

cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

you must then ensure your stored procedure has

return @RETURN_VALUE;

at the end of the stored procedure.

Simplest way to have a configuration file in a Windows Forms C# application

Clarification of previous answers...

  1. Add a new file to your project (AddNew ItemApplication Configuration File)

  2. The new configuration file will appear in Solution Explorer as App.Config.

  3. Add your settings into this file using the following as a template

    <configuration>
      <appSettings>
        <add key="setting1" value="key"/>
      </appSettings>
      <connectionStrings>
        <add name="prod" connectionString="YourConnectionString"/>
      </connectionStrings>
    </configuration>
    
  4. Retrieve them like this:

    private void Form1_Load(object sender, EventArgs e)
    {
        string setting = ConfigurationManager.AppSettings["setting1"];
        string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
    }
    
  5. When built, your output folder will contain a file called <assemblyname>.exe.config. This will be a copy of the App.Config file. No further work should need to be done by the developer to create this file.

How to use '-prune' option of 'find' in sh?

I am no expert at this (and this page was very helpful along with http://mywiki.wooledge.org/UsingFind)

Just noticed -path is for a path that fully matches the string/path that comes just after find (. in theses examples) where as -name matches all basenames.

find . -path ./.git  -prune -o -name file  -print

blocks the .git directory in your current directory ( as your finding in . )

find . -name .git  -prune -o -name file  -print

blocks all .git subdirectories recursively.

Note the ./ is extremely important!! -path must match a path anchored to . or whatever comes just after find if you get matches with out it (from the other side of the or '-o') there probably not being pruned! I was naively unaware of this and it put me of using -path when it is great when you don't want to prune all subdirectory with the same basename :D

Return zero if no record is found

You can also try: (I tried this and it worked for me)

SELECT ISNULL((SELECT SUM(columnA) FROM my_table WHERE columnB = 1),0)) INTO res;

Get model's fields in Django

How about this one.

fields = Model._meta.fields

The model backing the <Database> context has changed since the database was created

I had the same issue - re-adding the migration and updating the database didn't work and none of the answers above seemed right. Then inspiration hit me - I'm using multiple tiers (one web, one data, and one business). The data layer has the context and all the models. The web layer never threw this exception - it was the business layer (which I set as console application for testing and debugging). Turns out the business layer wasn't using the right connection string to get the db and make the context. So I added the connection string to the app config of the business layer (and the data layer) and viola it works. Putting this here for others who may encounter the same issue.

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

First, let gradle set the correct distribution Url

cd projectDirectory
./gradlew wrapper --gradle-version 2.3.0

Then - might not be needed but that's what I did - edit the project's build.gradle to match the version

    dependencies {
    classpath 'com.android.tools.build:gradle:2.3.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

Finally, delete the folders .gradle and gradle and the files gradlew and gradlew.bat. (Original Answer)

Now, rebuild the project.

As the other answers did not suffice for me and the comment pointing out these additional steps is easy to overlook, here as a separate answer

iframe to Only Show a Certain Part of the Page

I needed an iframe that would embed a portion of an external page with a vertical scroll bar, cropping out the navigation menus on the top and left of the page. I was able to do it with some simple HTML and CSS.

HTML

<div id="container">
    <iframe id="embed" src="http://www.example.com"></iframe>
</div>

CSS

div#container
{
    width:840px;
    height:317px;
    overflow:scroll;     /* if you don't want a scrollbar, set to hidden */
    overflow-x:hidden;   /* hides horizontal scrollbar on newer browsers */

    /* resize and min-height are optional, allows user to resize viewable area */
    -webkit-resize:vertical; 
    -moz-resize:vertical;
    resize:vertical;
    min-height:317px;
}

iframe#embed
{
    width:1000px;       /* set this to approximate width of entire page you're embedding */
    height:2000px;      /* determines where the bottom of the page cuts off */
    margin-left:-183px; /* clipping left side of page */
    margin-top:-244px;  /* clipping top of page */
    overflow:hidden;

    /* resize seems to inherit in at least Firefox */
    -webkit-resize:none;
    -moz-resize:none;
    resize:none;
}

What is href="#" and why is it used?

Unordered lists are often created with the intent of using them as a menu, but an li list item is text. Because the list li item is text, the mouse pointer will not be an arrow, but an "I cursor". Users are accustomed to seeing a pointing finger for a mouse pointer when something is clickable. Using an anchor tag a inside of the li tag causes the mouse pointer to change to a pointing finger. The pointing finger is a lot better for using the list as a menu.

<ul id="menu">
   <li><a href="#">Menu Item 1</a></li>
   <li><a href="#">Menu Item 2</a></li>
   <li><a href="#">Menu Item 3</a></li>
   <li><a href="#">Menu Item 4</a></li>
</ul>

If the list is being used for a menu, and doesn't need a link, then a URL doesn't need to be designated. But the problem is that if you leave out the href attribute, text in the <a> tag is seen as text, and therefore the mouse pointer is back to an I-cursor. The I-cursor might make the user think that the menu item is not clickable. Therefore, you still need an href, but you don't need a link to anywhere.

You could use lots of div or p tags for a menu list, but the mouse pointer would be an I-cursor for them also.

You could use lots of buttons stacked on top of each other for a menu list, but the list seems to be preferable. And that's probably why the href="#" that points to nowhere is used in anchor tags inside of list tags.

You can set the pointer style in CSS, so that is another option. The href="#" to nowhere might just be the lazy way to set some styling.

Creating a div element in jQuery

alternatively to append() you can also use appendTo() which has a different syntax:

$("#foo").append("<div>hello world</div>");
$("<div>hello world</div>").appendTo("#foo");    

casting int to char using C++ style casting

You can implicitly convert between numerical types, even when that loses precision:

char c = i;

However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast for the conversion.

Of the other casts:

  • dynamic_cast only works for pointers or references to polymorphic class types;
  • const_cast can't change types, only const or volatile qualifiers;
  • reinterpret_cast is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.
  • C-style and function-style casts do whatever combination of static_cast, const_cast and reinterpret_cast is needed to get the job done.

How to send an email with Gmail as provider using Python?

You down with OOP?

#!/usr/bin/env python


import smtplib

class Gmail(object):
    def __init__(self, email, password):
        self.email = email
        self.password = password
        self.server = 'smtp.gmail.com'
        self.port = 587
        session = smtplib.SMTP(self.server, self.port)        
        session.ehlo()
        session.starttls()
        session.ehlo
        session.login(self.email, self.password)
        self.session = session

    def send_message(self, subject, body):
        ''' This must be removed '''
        headers = [
            "From: " + self.email,
            "Subject: " + subject,
            "To: " + self.email,
            "MIME-Version: 1.0",
           "Content-Type: text/html"]
        headers = "\r\n".join(headers)
        self.session.sendmail(
            self.email,
            self.email,
            headers + "\r\n\r\n" + body)


gm = Gmail('Your Email', 'Password')

gm.send_message('Subject', 'Message')

CSS3 Transition not working

If you have a <script> tag anywhere on your page (even in the HTML, even if it is an empty tag with a src), then a transition must be activated by some event (it won't fire automatically when the page loads).

How to download and save a file from Internet using Java?

It's an old question but here is a concise, readable, JDK-only solution with properly closed resources:

static long download(String sourceUrl, String targetFileName) throws Exception {
    try (InputStream in = URI.create(sourceUrl).toURL().openStream()) {
        return Files.copy(in, Paths.get(targetFileName));
    }
}

Two lines of code and no dependencies.

Here's a complete file downloader example program with output, error checking, and command line argument checks:

package so.downloader;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Application {
    public static void main(String[] args) throws MalformedURLException, IOException {
        if (2 != args.length) {
            System.out.println(String.format("USAGE: java -jar so-downloader.jar <source-URL> <target-filename>"));
            System.exit(1);
        }

        String sourceUrl = args[0];
        String targetFilename = args[1];

        long bytesDownloaded = download(sourceUrl, targetFilename);

        System.out.println(String.format("Downloaded %d bytes from %s to %s.", bytesDownloaded, sourceUrl, targetFilename));
    }

    static long download(String sourceUrl, String targetFileName) throws MalformedURLException, IOException {
        try (InputStream in = URI.create(sourceUrl).toURL().openStream()) {
            return Files.copy(in, Paths.get(targetFileName));
        }
    }

}

As noted in the so-downloader repository README:

To run file download program:

java -jar so-downloader.jar <source-URL> <target-filename>

for example:

java -jar so-downloader.jar https://github.com/JanStureNielsen/so-downloader/archive/main.zip so-downloader-source.zip

print call stack in C or C++

You can use the Boost libraries to print the current callstack.

#include <boost/stacktrace.hpp>

// ... somewhere inside the `bar(int)` function that is called recursively:
std::cout << boost::stacktrace::stacktrace();

Man here: https://www.boost.org/doc/libs/1_65_1/doc/html/stacktrace.html

How to silence output in a Bash script?

Try with:

myprogram &>/dev/null

to get no output

What is the difference between null=True and blank=True in Django?

Simply null=True defines database should accept NULL values, on other hand blank=True defines on form validation this field should accept blank values or not(If blank=True it accept form without a value in that field and blank=False[default value] on form validation it will show This field is required error.

null=True/False related to database

blank=True/False related to form validation

jQuery: how to change title of document during .ready()?

Do not use $('title').text('hi'), because IE doesn't support it.

It is better to use document.title = 'new title';

How to Resize image in Swift?

Swift 4 Solution-

Use this function

func image(with image: UIImage, scaledTo newSize: CGSize) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    drawingImageView.image = newImage
    return newImage ?? UIImage()
}

Calling a function:-

image(with: predictionImage, scaledTo: CGSize(width: 28.0, height: 28.0)

here 28.0 is the pixel size that you want to set

How do I find the number of arguments passed to a Bash script?

#!/bin/bash
echo "The number of arguments is: $#"
a=${@}
echo "The total length of all arguments is: ${#a}: "
count=0
for var in "$@"
do
    echo "The length of argument '$var' is: ${#var}"
    (( count++ ))
    (( accum += ${#var} ))
done
echo "The counted number of arguments is: $count"
echo "The accumulated length of all arguments is: $accum"

Phone: numeric keyboard for text input

<input type="text" inputmode="numeric">

With Inputmode you can give a hint to the browser.

How to use pull to refresh in Swift?

I would like to mention a PRETTY COOL feature that has been included since iOS 10, which is:

For now, UIRefreshControl is directly supported in each of UICollectionView, UITableView and UIScrollView!

Each one of these views have refreshControl instance property, which means that there is no longer a need to add it as a subview in your scroll view, all you have to do is:

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(doSomething), for: .valueChanged)

    // this is the replacement of implementing: "collectionView.addSubview(refreshControl)"
    collectionView.refreshControl = refreshControl
}

func doSomething(refreshControl: UIRefreshControl) {
    print("Hello World!")

    // somewhere in your code you might need to call:
    refreshControl.endRefreshing()
}

Personally, I find it more natural to treat it as a property for scroll view more than add it as a subview, especially because the only appropriate view to be as a superview for a UIRefreshControl is a scrollview, i.e the functionality of using UIRefreshControl is only useful when working with a scroll view; That's why this approach should be more obvious to setup the refresh control view.

However, you still have the option of using the addSubview based on the iOS version:

if #available(iOS 10.0, *) {
  collectionView.refreshControl = refreshControl
} else {
  collectionView.addSubview(refreshControl)
}

How to change a particular element of a C++ STL vector

at and operator[] both return a reference to the indexed element, so you can simply use:

l.at(4) = -1;

or

l[4] = -1;

BeanFactory vs ApplicationContext

To me, the primary difference to choose BeanFactory over ApplicationContext seems to be that ApplicationContext will pre-instantiate all of the beans. From the Spring docs:

Spring sets properties and resolves dependencies as late as possible, when the bean is actually created. This means that a Spring container which has loaded correctly can later generate an exception when you request an object if there is a problem creating that object or one of its dependencies. For example, the bean throws an exception as a result of a missing or invalid property. This potentially delayed visibility of some configuration issues is why ApplicationContext implementations by default pre-instantiate singleton beans. At the cost of some upfront time and memory to create these beans before they are actually needed, you discover configuration issues when the ApplicationContext is created, not later. You can still override this default behavior so that singleton beans will lazy-initialize, rather than be pre-instantiated.

Given this, I initially chose BeanFactory for use in integration/performance tests since I didn't want to load the entire application for testing isolated beans. However -- and somebody correct me if I'm wrong -- BeanFactory doesn't support classpath XML configuration. So BeanFactory and ApplicationContext each provide a crucial feature I wanted, but neither did both.

Near as I can tell, the note in the documentation about overriding default instantiation behavior takes place in the configuration, and it's per-bean, so I can't just set the "lazy-init" attribute in the XML file or I'm stuck maintaining a version of it for test and one for deployment.

What I ended up doing was extending ClassPathXmlApplicationContext to lazily load beans for use in tests like so:

public class LazyLoadingXmlApplicationContext extends ClassPathXmlApplicationContext {

    public LazyLoadingXmlApplicationContext(String[] configLocations) {
        super(configLocations);
    }

    /**
     * Upon loading bean definitions, force beans to be lazy-initialized.
     * @see org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader)
     */

    @Override
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
        super.loadBeanDefinitions(reader);
        for (String name: reader.getBeanFactory().getBeanDefinitionNames()) {
            AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) reader.getBeanFactory().getBeanDefinition(name);
            beanDefinition.setLazyInit(true);
        }
    }

}

Linq on DataTable: select specific column into datatable, not whole table

Your select statement is returning a sequence of anonymous type , not a sequence of DataRows. CopyToDataTable() is only available on IEnumerable<T> where T is or derives from DataRow. You can select r the row object to call CopyToDataTable on it.

var query = from r in matrix.AsEnumerable()
                where r.Field<string>("c_to") == c_to &&
                      r.Field<string>("p_to") == p_to
                 select r;

DataTable conversions = query.CopyToDataTable();

You can also implement CopyToDataTable Where the Generic Type T Is Not a DataRow.

Adding to an ArrayList Java

Well, you have to iterate through your abstract type Foo and that depends on the methods available on that object. You don't have to loop through the ArrayList because this object grows automatically in Java. (Don't confuse it with an array in other programming languages)

Recommended reading. Lists in the Java Tutorial

Java Synchronized list

Yes, Just be careful if you are also iterating over the list, because in this case you will need to synchronize on it. From the Javadoc:

It is imperative that the user manually synchronize on the returned list when iterating over it:

List list = Collections.synchronizedList(new ArrayList());
    ...
synchronized (list) {
    Iterator i = list.iterator(); // Must be in synchronized block
    while (i.hasNext())
        foo(i.next());
}

Or, you can use CopyOnWriteArrayList which is slower for writes but doesn't have this issue.

How should I validate an e-mail address?

Next pattern is used in K-9 mail:

public static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
          "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
          "\\@" +
          "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
          "(" +
          "\\." +
          "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
          ")+"
      );

You can use function

private boolean checkEmail(String email) {
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}

Refresh a page using PHP

I've found two ways to refresh PHP content:

1. Using the HTML meta tag:

echo("<meta http-equiv='refresh' content='1'>"); //Refresh by HTTP 'meta'

2. Using PHP refresh rate:

$delay = 0; // Where 0 is an example of a time delay. You can use 5 for 5 seconds, for example!
header("Refresh: $delay;"); 

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

Differences between arm64 and aarch64

AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.

As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.

So AArch64 and ARM64 refer to the same thing.

How do you perform address validation?

You could also try SAP's Data Quality solutions which are available in both a server platform is processing a large number of requests or as an embeddable SDK if you wanted to run it in process with your application. We use it in our application and it's very robust and scalable.

How do I get the full url of the page I am on in C#

Try the following -

var FullUrl = Request.Url.AbsolutePath.ToString();
var ID = FullUrl.Split('/').Last();

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

Components should start with capital letters. Also remember to change the first letter in the line to export!

How do I alias commands in git?

For those looking to execute shell commands in a git alias, for example:

$ git pof

In my terminal will push force the current branch to my origin repo:

[alias]
    pof = !git push origin -f $(git branch | grep \\* | cut -d ' ' -f2)

Where the

$(git branch | grep \\* | cut -d ' ' -f2)

command returns the current branch.

So this is a shortcut for manually typing the branch name:

git push origin -f <current-branch>

How to create an alert message in jsp page after submit process is complete

You can also create a new jsp file sayng that form is submited and in your main action file just write its file name

Eg. Your form is submited is in a file succes.jsp Then your action file will have

Request.sendRedirect("success.jsp")

How to kill MySQL connections

As above mentioned, there is no special command to do it. However, if all those connection are inactive, using 'flush tables;' is able to release all those connection which are not active.

"find: paths must precede expression:" How do I specify a recursive search that also finds files in the current directory?

I came across this question when I was trying to find multiple filenames that I could not combine into a regular expression as described in @Chris J's answer, here is what worked for me

find . -name one.pdf -o -name two.txt -o -name anotherone.jpg

-o or -or is logical OR. See Finding Files on Gnu.org for more information.

I was running this on CygWin.

Pause Console in C++ program

I always used a couple lines of code which clear the input stream of any characters and then wait for input to ignore.

Something like:

void pause() {
    cin.clear();
    cout << endl << "Press any key to continue...";
    cin.ignore();
}

And then any time I need it in the program I have my own pause(); function, without the overhead of a system pause. This is only really an issue when writing console programs that you want to stay open or stay fixated on a certain point though.

ASP.NET MVC get textbox input value

Another way by using ajax method:

View:

@Html.TextBox("txtValue", null, new { placeholder = "Input value" })
<input type="button" value="Start" id="btnStart"  />

<script>
    $(function () {
        $('#btnStart').unbind('click');
        $('#btnStart').on('click', function () {
            $.ajax({
                url: "/yourControllerName/yourMethod",
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify({
                    txtValue: $("#txtValue").val()
                }),
                async: false
            });
       });
   });
</script>

Controller:

[HttpPost]
public EmptyResult YourMethod(string txtValue)
{
    // do what you want with txtValue
    ...
}

Yes or No confirm box using jQuery

I've used these codes:

HTML:

<a id="delete-button">Delete</a>

jQuery:

<script>
$("#delete-button").click(function(){
    if(confirm("Are you sure you want to delete this?")){
        $("#delete-button").attr("href", "query.php?ACTION=delete&ID='1'");
    }
    else{
        return false;
    }
});
</script>

These codes works for me, but I'm not really sure if this is proper. What do you think?

How to find pg_config path

I recommend that you try to use Postgres.app. (http://postgresapp.com) This way you can easily turn Postgres on and off on your Mac. Once you do, add the path to Postgres to your .profile file by appending the following:

PATH="/Applications/Postgres.app/Contents/Versions/latest/bin:$PATH"

Only after you added Postgres to your path you can try to install psycopg2 either within a virtual environment (using pip) or into your global site packages.

How to export html table to excel using javascript

Check https://github.com/linways/table-to-excel. Its a wrapper for exceljs/exceljs to export html tables to xlsx.

_x000D_
_x000D_
TableToExcel.convert(document.getElementById("simpleTable1"));
_x000D_
<script src="https://cdn.jsdelivr.net/gh/linways/[email protected]/dist/tableToExcel.js"></script>_x000D_
<table id="simpleTable1" data-cols-width="70,15,10">_x000D_
<tbody>_x000D_
    <tr>_x000D_
        <td class="header" colspan="5" data-f-sz="25" data-f-color="FFFFAA00" data-a-h="center" data-a-v="middle" data-f-underline="true">_x000D_
            Sample Excel_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="5" data-f-italic="true" data-a-h="center" data-f-name="Arial" data-a-v="top">_x000D_
            Italic and horizontal center in Arial_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <th data-a-text-rotation="90">Col 1 (number)</th>_x000D_
        <th data-a-text-rotation="vertical">Col 2</th>_x000D_
        <th data-a-wrap="true">Wrapped Text</th>_x000D_
        <th data-a-text-rotation="-45">Col 4 (date)</th>_x000D_
        <th data-a-text-rotation="-90">Col 5</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td rowspan="1" data-t="n">1</td>_x000D_
        <td rowspan="1" data-b-b-s="thick" data-b-l-s="thick" data-b-r-s="thick">_x000D_
            ABC1_x000D_
        </td>_x000D_
        <td rowspan="1" data-f-strike="true">Striked Text</td>_x000D_
        <td data-t="d">05-20-2018</td>_x000D_
        <td data-t="n" data-num-fmt="$ 0.00">2210.00</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
        <td rowspan="2" data-t="n">2</td>_x000D_
        <td rowspan="2" data-fill-color="FFFF0000" data-f-color="FFFFFFFF">_x000D_
            ABC 2_x000D_
        </td>_x000D_
        <td rowspan="2" data-a-indent="3">Merged cell</td>_x000D_
        <td data-t="d">05-21-2018</td>_x000D_
        <td data-t="n" data-b-a-s="dashed" data-num-fmt="$ 0.00">230.00</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-t="d">05-22-2018</td>_x000D_
_x000D_
        <td data-t="n" data-num-fmt="$ 0.00">2493.00</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
        <td colspan="4" align="right" data-f-bold="true" data-a-h="right" data-hyperlink="https://google.com">_x000D_
            <b><a href="https://google.com">Hyperlink</a></b>_x000D_
        </td>_x000D_
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
            <b>4933.00</b>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="4" align="right" data-f-bold="true" data-a-rtl="true">_x000D_
            ?????_x000D_
        </td>_x000D_
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
            <b>2009.00</b>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-b-a-s="dashed" data-b-a-c="FFFF0000">All borders</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-t="b">true</td>_x000D_
        <td data-t="b">false</td>_x000D_
        <td data-t="b">1</td>_x000D_
        <td data-t="b">0</td>_x000D_
        <td data-error="#VALUE!">Value Error</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-b-t-s="thick" data-b-l-s="thick" data-b-b-s="thick" data-b-r-s="thick" data-b-t-c="FF00FF00" data-b-l-c="FF00FF00" data-b-b-c="FF00FF00" data-b-r-c="FF00FF00">_x000D_
            All borders separately_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr data-exclude="true">_x000D_
        <td>Excluded row</td>_x000D_
        <td>Something</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Included Cell</td>_x000D_
        <td data-exclude="true">Excluded Cell</td>_x000D_
        <td>Included Cell</td>_x000D_
    </tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This creates valid xlsx on the client side. Also supports some basic styling. Check https://codepen.io/rohithb/pen/YdjVbb for a working example.

What version of MongoDB is installed on Ubuntu

In the terminal just write : $ mongod --version

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

Here it goes an example:

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

Hope it helps.

How to present a modal atop the current view in Swift

First, remove all explicit setting of modal presentation style in code and do the following:

  1. In the storyboard set the ModalViewController's modalPresentation style to Over Current context

img1

  1. Check the checkboxes in the Root/Presenting ViewController - Provide Context and Define Context. They seem to be working even unchecked.

Finding the layers and layer sizes for each Docker image

You can first find the image ID using:

$ docker images -a

Then find the image's layers and their sizes:

$ docker history --no-trunc <Image ID>

Note: I'm using Docker version 1.13.1

$ docker -v
Docker version 1.13.1, build 092cba3

What's the difference between Cache-Control: max-age=0 and no-cache?

One thing that (surprisingly) hasn't been mentioned is that a request can explicitly indicate that it will accept stale data, using the max-stale directive. In that case, if the server responded with max-age=0, the cache would merely consider the response stale, and would be free to use it to satisfy the client's request [which asked for potentially-stale data]. By contrast, if the server sends no-cache that really does trump any request by the client (with max-stale) for stale data, as the cache MUST revalidate.

How to word wrap text in HTML?

The only one that works across IE, Firefox, chrome, safari and opera if there are no spaces in the word (such as a long URL) is:

div{
    width: 200px;  
    word-break: break-all;
}

I found this to be bullet-proof.

array_push() with key value pair

For Example:

$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');

For changing key value:

$data['firstKey'] = 'changedValue'; 
//this will change value of firstKey because firstkey is available in array

output:

Array ( [firstKey] => changedValue [secondKey] => secondValue )

For adding new key value pair:

$data['newKey'] = 'newValue'; 
//this will add new key and value because newKey is not available in array

output:

Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue )

How to save LogCat contents to file?

If you are in the console window for the device and if you use Teraterm, then from the Menu do a File | Log and it will automatically save to file.

How can I do DNS lookups in Python, including referring to /etc/hosts?

This code works well for returning all of the IP addresses that might belong to a particular URI. Since many systems are now in a hosted environment (AWS/Akamai/etc.), systems may return several IP addresses. The lambda was "borrowed" from @Peter Silva.

def get_ips_by_dns_lookup(target, port=None):
    '''
        this function takes the passed target and optional port and does a dns
        lookup. it returns the ips that it finds to the caller.

        :param target:  the URI that you'd like to get the ip address(es) for
        :type target:   string
        :param port:    which port do you want to do the lookup against?
        :type port:     integer
        :returns ips:   all of the discovered ips for the target
        :rtype ips:     list of strings

    '''
    import socket

    if not port:
        port = 443

    return list(map(lambda x: x[4][0], socket.getaddrinfo('{}.'.format(target),port,type=socket.SOCK_STREAM)))

ips = get_ips_by_dns_lookup(target='google.com')

How do I disable fail_on_empty_beans in Jackson?

In my case, I missed to write @JsonProperty annotation in one of the fields which was causing this error.

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

there might be a problem at your web hosting company from where you are testing the secure communication for gateway, that they might not allow you to do that.

also there might be a username, password that must be provided before connecting to remote host.

or your IP might need to be in the list of approved IP for the remote server for communication to initiate.

What is cardinality in Databases?

Cardinality of a set is the namber of the elements in set for we have a set a > a,b,c < so ths set contain 3 elements 3 is the cardinality of that set

Find the line number where a specific word appears with "grep"

You can call tail +[line number] [file] and pipe it to grep -n which shows the line number:

tail +[line number] [file] | grep -n /regex/

The only problem with this method is the line numbers reported by grep -n will be [line number] - 1 less than the actual line number in [file].

Convert xlsx to csv in Linux with command line

If .xlsx file has many sheets, -s flag can be used to get the sheet you want. For example:

xlsx2csv "my_file.xlsx" -s 2 second_sheet.csv

second_sheet.csv would contain data of 2nd sheet in my_file.xlsx.

How to check syslog in Bash on Linux?

tail -f /var/log/syslog | grep process_name where process_name is the name of the process we are interested in

Spin or rotate an image on hover

if you want to rotate inline elements, you should set the inline element to inline-block first.

i {
  display: inline-block;
}

i:hover {
  animation: rotate-btn .5s linear 3;
  -webkit-animation: rotate-btn .5s linear 3;
}

@keyframes rotate-btn {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(-360deg);
  }
}

MySQL JOIN ON vs USING?

For those experimenting with this in phpMyAdmin, just a word:

phpMyAdmin appears to have a few problems with USING. For the record this is phpMyAdmin run on Linux Mint, version: "4.5.4.1deb2ubuntu2", Database server: "10.2.14-MariaDB-10.2.14+maria~xenial - mariadb.org binary distribution".

I have run SELECT commands using JOIN and USING in both phpMyAdmin and in Terminal (command line), and the ones in phpMyAdmin produce some baffling responses:

1) a LIMIT clause at the end appears to be ignored.
2) the supposed number of rows as reported at the top of the page with the results is sometimes wrong: for example 4 are returned, but at the top it says "Showing rows 0 - 24 (2503 total, Query took 0.0018 seconds.)"

Logging on to mysql normally and running the same queries does not produce these errors. Nor do these errors occur when running the same query in phpMyAdmin using JOIN ... ON .... Presumably a phpMyAdmin bug.

Share cookie between subdomain and domain

Simple solution

setcookie("NAME", "VALUE", time()+3600, '/', EXAMPLE.COM);

Setcookie's 5th parameter determines the (sub)domains that the cookie is available to. Setting it to (EXAMPLE.COM) makes it available to any subdomain (eg: SUBDOMAIN.EXAMPLE.COM )

Reference: http://php.net/manual/en/function.setcookie.php

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

How can moment.js be imported with typescript?

via typings

Moment.js now supports TypeScript in v2.14.1.

See: https://github.com/moment/moment/pull/3280


Directly

Might not be the best answer, but this is the brute force way, and it works for me.

  1. Just download the actual moment.js file and include it in your project.
  2. For example, my project looks like this:

$ tree . +-- main.js +-- main.js.map +-- main.ts +-- moment.js

  1. And here's a sample source code:

```

import * as moment from 'moment';

class HelloWorld {
    public hello(input:string):string {
        if (input === '') {
            return "Hello, World!";
        }
        else {
            return "Hello, " + input + "!";
        }
    }
}

let h = new HelloWorld();
console.log(moment().format('YYYY-MM-DD HH:mm:ss'));
  1. Just use node to run main.js.

where does MySQL store database files?

WAMP stores the db data under WAMP\bin\mysql\mysql(version)\data. Where the WAMP folder itself is depends on where you installed it to (on xp, I believe it is directly in the main drive, for example c:\WAMP\...

If you deleted that folder, or if the uninstall deleted that folder, if you did not do a DB backup before the uninstall, you may be out of luck.

If you did do a backup though phpmyadmin, then login, and click the import tab, and browse to the backup file.

What is managed or unmanaged code in programming?

In as few words as possible:

  • managed code = .NET programs
  • unmanaged code = "normal" programs

How to check if a variable is both null and /or undefined in JavaScript

A variable cannot be both null and undefined at the same time. However, the direct answer to your question is:

if (variable != null)

One =, not two.

There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null and the other being undefined, and the result is true for == and false for !=. Thus if the value of the variable is undefined, it's not != null, and if it's not null, it's obviously not != null.

Now, the case of an identifier not being defined at all, either as a var or let, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:

var isDefined = false;
try {
  (variable);
  isDefined = true;
}
catch (x) {}

I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window property (in browser JavaScript):

var isJqueryAvailable = window.jQuery != null;

or

var isJqueryAvailable = "jQuery" in window;

Automatically set appsettings.json for dev and release environments in asp.net core?

You may use conditional compilation:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
#if SOME_BUILD_FLAG_A
    .AddJsonFile($"appsettings.flag_a.json", optional: true)
#else
    .AddJsonFile($"appsettings.no_flag_a.json", optional: true)
#endif
    .AddEnvironmentVariables();
    this.configuration = builder.Build();
}

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Git Push Error: insufficient permission for adding an object to repository database

A good way to debug this is the next time it happens, SSH into the remote repo, cd into the objects folder and do an ls -al.

If you see 2-3 files with different user:group ownership than this is the problem.

It's happened to me in the past with some legacy scripts access our git repo and usually means a different (unix) user pushed / modified files last and your user doesn't have permissions to overwrite those files. You should create a shared git group that all git-enabled users are in and then recursively chgrp the objects folder and it's contents so that it's group ownership is the shared git group.

You should also add a sticky bit on the folder so that all the files created in the folder will always have the group of git.

chmod g+s directory-name

Update: I didn't know about core.sharedRepository. Good to know, though it probably just does the above.

Make Adobe fonts work with CSS3 @font-face in IE9

The issue might be to do with your server configuration - it may not be sending the right headers for the font files. Take a look at the answer given for the question IE9 blocks download of cross-origin web font.

EricLaw suggests adding the following to your Apache config

<FilesMatch "\.(ttf|otf|eot|woff)$">
    <IfModule mod_headers.c>
        Header set Access-Control-Allow-Origin "http://mydomain.com"
    </IfModule>
</FilesMatch>

Python pandas: fill a dataframe row by row

My approach was, but I can't guarantee that this is the fastest solution.

df = pd.DataFrame(columns=["firstname", "lastname"])
df = df.append({
     "firstname": "John",
     "lastname":  "Johny"
      }, ignore_index=True)

Creation timestamp and last update timestamp with Hibernate and MySQL

For those whose want created or modified user detail along with the time using JPA and Spring Data can follow this. You can add @CreatedDate,@LastModifiedDate,@CreatedBy and @LastModifiedBy in the base domain. Mark the base domain with @MappedSuperclass and @EntityListeners(AuditingEntityListener.class) like shown below:

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseDomain implements Serializable {

    @CreatedDate
    private Date createdOn;

    @LastModifiedDate
    private Date modifiedOn;

    @CreatedBy
    private String createdBy;

    @LastModifiedBy
    private String modifiedBy;

}

Since we marked the base domain with AuditingEntityListener we can tell JPA about currently logged in user. So we need to provide an implementation of AuditorAware and override getCurrentAuditor() method. And inside getCurrentAuditor() we need to return the currently authorized user Id.

public class AuditorAwareImpl implements AuditorAware<String> {
    @Override
    public Optional<String> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication == null ? Optional.empty() : Optional.ofNullable(authentication.getName());
    }
}

In the above code if Optional is not working you may using older spring data. In that case try changing Optional with String.

Now for enabling the above Audtior implementation use the code below

@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class JpaConfig {
    @Bean
    public AuditorAware<String> auditorAware() {
        return new AuditorAwareImpl();
    }
}

Now you can extend the BaseDomain class to all of your entity class where you want the created and modified date & time along with user Id

How do you change the server header returned by nginx?

Nginx-extra package is deprecated now.

The following therefore did now work for me as i tried installing various packages more_set_headers 'Server: My Very Own Server';

You can just do the following and no server or version information will be sent back

    server_tokens '';

if you just want to remove the version number this works

   server_tokens off;

How to use cURL in Java?

Using standard java libs, I suggest looking at the HttpUrlConnection class http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html

It can handle most of what curl can do with setting up the connection. What you do with the stream is up to you.

How to generate a random integer number from within a range

Will return a floating point number in the range [0,1]:

#define rand01() (((double)random())/((double)(RAND_MAX)))

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

Below code may help you to achieve session attribution inside java script:

var name = '<%= session.getAttribute("username") %>';

Eclipse does not highlight matching variables

maybe because it not supports code highlights inside scriplets. not sure though.

You can try using one of the eclipse plugin like 'glance search' which works great. Here's a link for that- http://code.google.com/p/eclipse-glance/

With ng-bind-html-unsafe removed, how do I inject HTML?

You do not need to use {{ }} inside of ng-bind-html-unsafe:

<div ng-bind-html-unsafe="preview_data.preview.embed.html"></div>

Here's an example: http://plnkr.co/edit/R7JmGIo4xcJoBc1v4iki?p=preview

The {{ }} operator is essentially just a shorthand for ng-bind, so what you were trying amounts to a binding inside a binding, which doesn't work.

error: request for member '..' in '..' which is of non-class type

@MykolaGolubyev has already given wonderful explanation. I was looking for a solution to do somthing like this MyClass obj ( MyAnotherClass() ) but the compiler was interpreting it as a function declaration.

C++11 has braced-init-list. Using this we can do something like this

Temp t{String()};

However, this:

Temp t(String());

throws compilation error as it considers t as of type Temp(String (*)()).

#include <iostream>

class String {
public:
    String(const char* str): ptr(str)
    {
        std::cout << "Constructor: " << str << std::endl;
    }
    String(void): ptr(nullptr)
    {
        std::cout << "Constructor" << std::endl;
    }
    virtual ~String(void)
    {
        std::cout << "Destructor" << std::endl;
    }

private:
    const char *ptr;
};

class Temp {
public:
    Temp(String in): str(in)
    {
        std::cout << "Temp Constructor" << std::endl;
    }

    Temp(): str(String("hello"))
    {
        std::cout << "Temp Constructor: 2" << std::endl;
    }
    virtual ~Temp(void)
    {
        std::cout << "Temp Destructor" << std::endl;
    }

    virtual String get_str()
    {
        return str;
    }

private:
    String str;
};

int main(void)
{
    Temp t{String()}; // Compiles Success!
    // Temp t(String()); // Doesn't compile. Considers "t" as of type: Temp(String (*)())
    t.get_str(); // dummy statement just to check if we are able to access the member
    return 0;
}

List<Map<String, String>> vs List<? extends Map<String, String>>

Today, I have used this feature, so here's my very fresh real-life example. (I have changed class and method names to generic ones so they won't distract from the actual point.)

I have a method that's meant to accept a Set of A objects that I originally wrote with this signature:

void myMethod(Set<A> set)

But it want to actually call it with Sets of subclasses of A. But this is not allowed! (The reason for that is, myMethod could add objects to set that are of type A, but not of the subtype that set's objects are declared to be at the caller's site. So this could break the type system if it were possible.)

Now here come generics to the rescue, because it works as intended if I use this method signature instead:

<T extends A> void myMethod(Set<T> set)

or shorter, if you don't need to use the actual type in the method body:

void myMethod(Set<? extends A> set)

This way, set's type becomes a collection of objects of the actual subtype of A, so it becomes possible to use this with subclasses without endangering the type system.

Read from file or stdin

First, ask the program to tell you what is wrong by checking the errno, which is set on failure, such as during fseek or ftell.

Others (tonio & LatinSuD) have explained the mistake with handling stdin versus checking for a filename. Namely, first check argc (argument count) to see if there are any command line parameters specified if (argc > 1), treating - as a special case meaning stdin.

If no parameters are specified, then assume input is (going) to come from stdin, which is a stream not file, and the fseek function fails on it.

In the case of a stream, where you cannot use file-on-disk oriented library functions (i.e. fseek and ftell), you simply have to count the number of bytes read (including trailing newline characters) until receiving EOF (end-of-file).

For usage with large files you could speed it up by using fgets to a char array for more efficient reading of the bytes in a (text) file. For a binary file you need to use fopen(const char* filename, "rb") and use fread instead of fgetc/fgets.

You could also check the for feof(stdin) / ferror(stdin) when using the byte-counting method to detect any errors when reading from a stream.

The sample below should be C99 compliant and portable.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

long getSizeOfInput(FILE *input){
   long retvalue = 0;
   int c;

   if (input != stdin) {
      if (-1 == fseek(input, 0L, SEEK_END)) {
         fprintf(stderr, "Error seek end: %s\n", strerror(errno));
         exit(EXIT_FAILURE);
      }
      if (-1 == (retvalue = ftell(input))) {
         fprintf(stderr, "ftell failed: %s\n", strerror(errno));
         exit(EXIT_FAILURE);
      }
      if (-1 == fseek(input, 0L, SEEK_SET)) {
         fprintf(stderr, "Error seek start: %s\n", strerror(errno));
         exit(EXIT_FAILURE);
      }
   } else {
      /* for stdin, we need to read in the entire stream until EOF */
      while (EOF != (c = fgetc(input))) {
         retvalue++;
      }
   }

   return retvalue;
}

int main(int argc, char **argv) {
   FILE *input;

   if (argc > 1) {
      if(!strcmp(argv[1],"-")) {
         input = stdin;
      } else {
         input = fopen(argv[1],"r");
         if (NULL == input) {
            fprintf(stderr, "Unable to open '%s': %s\n",
                  argv[1], strerror(errno));
            exit(EXIT_FAILURE);
         }
      }
   } else {
      input = stdin;
   }

   printf("Size of file: %ld\n", getSizeOfInput(input));

   return EXIT_SUCCESS;
}

Web-scraping JavaScript page with Python

As mentioned, Selenium is a good choice for rendering the results of the JavaScript:

from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True
browser = Firefox(executable_path="/usr/local/bin/geckodriver", options=options)

url = "https://www.example.com"
browser.get(url)

And gazpacho is a really easy library to parse over the rendered html:

from gazpacho import Soup

soup = Soup(browser.page_source)
soup.find("a").attrs['href']

How do I declare an array variable in VBA?

The Array index only accepts a long value.

You declared iCounter as an integer. You should declare it as a long.

How to exit an Android app programmatically?

ghost activity called with singletop and finish() on onCreate should do the trick

Reading string from input with space character?

"%s" will read the input until whitespace is reached.

gets might be a good place to start if you want to read a line (i.e. all characters including whitespace until a newline character is reached).

Where is the list of predefined Maven properties

This link shows how to list all the active properties: http://skillshared.blogspot.co.uk/2012/11/how-to-list-down-all-maven-available.html

In summary, add the following plugin definition to your POM, then run mvn install:

<plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.7</version>
    <executions>
        <execution>
            <phase>install</phase>
            <configuration>
                <target>
                    <echoproperties />
                </target>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
    </executions>
</plugin>

CSS media query to target only iOS devices

I don't know about targeting iOS as a whole, but to target iOS Safari specifically:

@supports (-webkit-touch-callout: none) {
   /* CSS specific to iOS devices */ 
}

@supports not (-webkit-touch-callout: none) {
   /* CSS for other than iOS devices */ 
}

Apparently as of iOS 13 -webkit-overflow-scrolling no longer responds to @supports, but -webkit-touch-callout still does. Of course that could change in the future...

Casting a number to a string in TypeScript

"Casting" is different than conversion. In this case, window.location.hash will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:

window.location.hash = ""+page_number; 
window.location.hash = String(page_number); 

These conversions are ideal if you don't want an error to be thrown when page_number is null or undefined. Whereas page_number.toString() and page_number.toLocaleString() will throw when page_number is null or undefined.

When you only need to cast, not convert, this is how to cast to a string in TypeScript:

window.location.hash = <string>page_number; 
// or 
window.location.hash = page_number as string;

The <string> or as string cast annotations tell the TypeScript compiler to treat page_number as a string at compile time; it doesn't convert at run time.

However, the compiler will complain that you can't assign a number to a string. You would have to first cast to <any>, then to <string>:

window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;

So it's easier to just convert, which handles the type at run time and compile time:

window.location.hash = String(page_number); 

(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)

How does Task<int> become an int?

Does an implicit conversion occur between Task<> and int?

Nope. This is just part of how async/await works.

Any method declared as async has to have a return type of:

  • void (avoid if possible)
  • Task (no result beyond notification of completion/failure)
  • Task<T> (for a logical result of type T in an async manner)

The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length - you can't make the method just return int, as the actual method will return when it hits the first await expression which hasn't already completed. So instead, it returns a Task<int> which will complete when the async method itself completes.

Note that await does the opposite - it unwraps a Task<T> to a T value, which is how this line works:

string urlContents = await getStringTask;

... but of course it unwraps it asynchronously, whereas just using Result would block until the task had completed. (await can unwrap other types which implement the awaitable pattern, but Task<T> is the one you're likely to use most often.)

This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:

public async Task<int> AccessTheWebAndDoubleAsync()
{
    var task = AccessTheWebAsync();
    int result = await task;
    return result * 2;
}

(Or simply return await AccessTheWebAsync() * 2; of course.)

How to change the icon of .bat file programmatically?

Assuming you're referring to MS-DOS batch files: as it is simply a text file with a special extension, a .bat file doesn't store an icon of its own.

You can, however, create a shortcut in the .lnk format that stores an icon.

How to pass a function as a parameter in Java?

Java 8 and above

Using Java 8+ lambda expressions, if you have a class or interface with only a single abstract method (sometimes called a SAM type), for example:

public interface MyInterface {
    String doSomething(int param1, String param2);
}

then anywhere where MyInterface is used, you can substitute a lambda expression:

class MyClass {
    public MyInterface myInterface = (p1, p2) -> { return p2 + p1; };
}

For example, you can create a new thread very quickly:

new Thread(() -> someMethod()).start();

And use the method reference syntax to make it even cleaner:

new Thread(this::someMethod).start();

Without lambda expressions, these last two examples would look like:

new Thread(new Runnable() { someMethod(); }).start();

Before Java 8

A common pattern would be to 'wrap' it within an interface, like Callable, for example, then you pass in a Callable:

public T myMethod(Callable<T> func) {
    return func.call();
}

This pattern is known as the Command Pattern.

Keep in mind you would be best off creating an interface for your particular usage. If you chose to go with callable, then you'd replace T above with whatever type of return value you expect, such as String.

In response to your comment below you could say:

public int methodToPass() { 
        // do something
}

public void dansMethod(int i, Callable<Integer> myFunc) {
       // do something
}

then call it, perhaps using an anonymous inner class:

dansMethod(100, new Callable<Integer>() {
   public Integer call() {
        return methodToPass();
   }
});

Keep in mind this is not a 'trick'. It's just java's basic conceptual equivalent to function pointers.

How to remove the bottom border of a box with CSS

You seem to misunderstand the box model - in CSS you provide points for the top and left and then width and height - these are all that are needed for a box to be placed with exact measurements.

The width property is what your C-D is, but it is also what A-B is. If you omit it, the div will not have a defined width and the width will be defined by its contents.


Update (following the comments on the question:

Add a border-bottom-style: none; to your CSS to remove this style from the bottom only.

Wait until page is loaded with Selenium WebDriver for Python

Find below 3 methods:

readyState

Checking page readyState (not reliable):

def page_has_loaded(self):
    self.log.info("Checking if {} page is loaded.".format(self.driver.current_url))
    page_state = self.driver.execute_script('return document.readyState;')
    return page_state == 'complete'

The wait_for helper function is good, but unfortunately click_through_to_new_page is open to the race condition where we manage to execute the script in the old page, before the browser has started processing the click, and page_has_loaded just returns true straight away.

id

Comparing new page ids with the old one:

def page_has_loaded_id(self):
    self.log.info("Checking if {} page is loaded.".format(self.driver.current_url))
    try:
        new_page = browser.find_element_by_tag_name('html')
        return new_page.id != old_page.id
    except NoSuchElementException:
        return False

It's possible that comparing ids is not as effective as waiting for stale reference exceptions.

staleness_of

Using staleness_of method:

@contextlib.contextmanager
def wait_for_page_load(self, timeout=10):
    self.log.debug("Waiting for page to load at {}.".format(self.driver.current_url))
    old_page = self.find_element_by_tag_name('html')
    yield
    WebDriverWait(self, timeout).until(staleness_of(old_page))

For more details, check Harry's blog.

What's the source of Error: getaddrinfo EAI_AGAIN?

If you are not get that at localhost either production, that means you must upgrade your plan due to the limitations of the free tier

The remote certificate is invalid according to the validation procedure

Even shorter version of the solution from Dominic Zukiewicz:

ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

But this means that you will trust all certificates. For a service that isn't just run locally, something a bit smarter will be needed. In the first instance you could use this code to just test whether it solves your problem.

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

before going for the step "compile -DIPLIB=NONE filename.cxx" take the path of VIsual Studio installation upto the vcvarsall batch file and change the configuration as shown below.

*C:\apps\MVS9\VC\vcvarsall.bat x86_amd64*

now next step should be

compile -64bit -DIPLIB=none filename.cxx

this solved the problem for me

Disable/turn off inherited CSS3 transitions

You could also disinherit all transitions inside a containing element:

CSS:

.noTrans *{
-moz-transition: none;
-webkit-transition: none;
-o-transition: color 0 ease-in;
transition: none;
}

HTML:

<a href="#">Content</a>
<a href="#">Content</a>
<div class="noTrans">
<a href="#">Content</a>
</div>
<a href="#">Content</a>

Does Index of Array Exist

The answers here are straightforward but only apply to a 1 dimensional array. For multi-dimensional arrays, checking for null is a straightforward way to tell if the element exists. Example code here checks for null. Note the try/catch block is [probably] overkill but it makes the block bomb-proof.

public ItemContext GetThisElement(int row,
    int col)
{
    ItemContext ctx = null;
    if (rgItemCtx[row, col] != null)
    {
        try
        {
          ctx = rgItemCtx[row, col];
        }
        catch (SystemException sex)
        {
          ctx = null;
          // perhaps do something with sex properties
        }
    }

    return (ctx);
}

ES6 class variable alternatives

If its only the cluttering what gives the problem in the constructor why not implement a initialize method that intializes the variables. This is a normal thing to do when the constructor gets to full with unnecessary stuff. Even in typed program languages like C# its normal convention to add an Initialize method to handle that.

How to use SearchView in Toolbar Android

If you want to add it directly in the toolbar.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:iconifiedByDefault="false"
            android:queryHint="Search"
            android:layout_centerHorizontal="true" />

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

Programmatic equivalent of default(Type)

  • In case of a value type use Activator.CreateInstance and it should work fine.
  • When using reference type just return null
public static object GetDefault(Type type)
{
   if(type.IsValueType)
   {
      return Activator.CreateInstance(type);
   }
   return null;
}

In the newer version of .net such as .net standard, type.IsValueType needs to be written as type.GetTypeInfo().IsValueType

Counting duplicates in Excel

Say A:A contains the post codes, you could add a B column and put a 1 in each cell. In C1, put =SUMIF(A:A, A1, B:B) and Drag it down your sheet. That would give you the first desired result listed in your question.

EDIT: As Corey pointed out, you can just use COUNTIF(A:A, A1). As I mentioned in the comments you can copy paste special the row with formulas to hard code the counts, the select column A and click remove duplicates (entire row) to get your ideal result.

SQL Server Error : String or binary data would be truncated

You're trying to write more data than a specific column can store. Check the sizes of the data you're trying to insert against the sizes of each of the fields.

In this case transaction_status is a varchar(10) and you're trying to store 19 characters to it.

How to install OpenSSL in windows 10?

I also wanted to create OPEN SSL for Windows 10. An easy way of getting it done without running into a risk of installing unknown software from 3rd party websites and risking entries of viruses, is by using the openssl.exe that comes inside your Git for Windows installation. In my case, I found the open SSL in the following location of Git for Windows Installation.

C:\Program Files\Git\usr\bin\openssl.exe

If you also want instructions on how to use OPENSSL to generate and use Certificates. Here is a write-up on my blog. The step by step instructions first explains how to use Microsoft Windows Default Tool and also OPEN SSL and explains the difference between them.

http://kaushikghosh12.blogspot.com/2016/08/self-signed-certificates-with-microsoft.html

Find the directory part (minus the filename) of a full path in access 97

If you are confident in your input parameters, you can use this single line of code which uses the native Split and Join functions and Excel native Application.pathSeparator.

Split(Join(Split(strPath, "."), Application.pathSeparator), Application.pathSeparator)

If you want a more extensive function, the code below is tested in Windows and should also work on Mac (though not tested). Be sure to also copy the supporting function GetPathSeparator, or modify the code to use Application.pathSeparator. Note, this is a first draft; I should really refactor it to be more concise.

Private Sub ParsePath2Test()
    'ParsePath2(DrivePathFileExt, -2) returns a multi-line string for debugging.
    Dim p As String, n As Integer

    Debug.Print String(2, vbCrLf)

    If True Then
        Debug.Print String(2, vbCrLf)
        Debug.Print ParsePath2("", -2)
        Debug.Print ParsePath2("C:", -2)
        Debug.Print ParsePath2("C:\", -2)
        Debug.Print ParsePath2("C:\Windows", -2)
        Debug.Print ParsePath2("C:\Windows\notepad.exe", -2)
        Debug.Print ParsePath2("C:\Windows\SysWOW64", -2)
        Debug.Print ParsePath2("C:\Windows\SysWOW64\", -2)
        Debug.Print ParsePath2("C:\Windows\SysWOW64\AcLayers.dll", -2)
        Debug.Print ParsePath2("C:\Windows\SysWOW64\.fakedir", -2)
        Debug.Print ParsePath2("C:\Windows\SysWOW64\fakefile.ext", -2)
    End If

    If True Then
        Debug.Print String(1, vbCrLf)
        Debug.Print ParsePath2("\Windows", -2)
        Debug.Print ParsePath2("\Windows\notepad.exe", -2)
        Debug.Print ParsePath2("\Windows\SysWOW64", -2)
        Debug.Print ParsePath2("\Windows\SysWOW64\", -2)
        Debug.Print ParsePath2("\Windows\SysWOW64\AcLayers.dll", -2)
        Debug.Print ParsePath2("\Windows\SysWOW64\.fakedir", -2)
        Debug.Print ParsePath2("\Windows\SysWOW64\fakefile.ext", -2)
    End If

    If True Then
        Debug.Print String(1, vbCrLf)
        Debug.Print ParsePath2("Windows\notepad.exe", -2)
        Debug.Print ParsePath2("Windows\SysWOW64", -2)
        Debug.Print ParsePath2("Windows\SysWOW64\", -2)
        Debug.Print ParsePath2("Windows\SysWOW64\AcLayers.dll", -2)
        Debug.Print ParsePath2("Windows\SysWOW64\.fakedir", -2)
        Debug.Print ParsePath2("Windows\SysWOW64\fakefile.ext", -2)
        Debug.Print ParsePath2(".fakedir", -2)
        Debug.Print ParsePath2("fakefile.txt", -2)
        Debug.Print ParsePath2("fakefile.onenote", -2)
        Debug.Print ParsePath2("C:\Personal\Workspace\Code\PythonVenvs\xlwings_test\.idea", -2)
        Debug.Print ParsePath2("Windows", -2)   ' Expected to raise error 52
    End If

    If True Then
        Debug.Print String(2, vbCrLf)
        Debug.Print "ParsePath2 ""\Windows\SysWOW64\fakefile.ext"" with different ReturnType values"
        Debug.Print , "{empty}", "D", ParsePath2("Windows\SysWOW64\fakefile.ext")(1)
        Debug.Print , "0", "D", ParsePath2("Windows\SysWOW64\fakefile.ext", 0)(1)
        Debug.Print , "1", "ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 1)
        Debug.Print , "10", "file", ParsePath2("Windows\SysWOW64\fakefile.ext", 10)
        Debug.Print , "11", "file.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 11)
        Debug.Print , "100", "path", ParsePath2("Windows\SysWOW64\fakefile.ext", 100)
        Debug.Print , "110", "path\file", ParsePath2("Windows\SysWOW64\fakefile.ext", 110)
        Debug.Print , "111", "path\file.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 111)
        Debug.Print , "1000", "D", ParsePath2("Windows\SysWOW64\fakefile.ext", 1000)
        Debug.Print , "1100", "D:\path", ParsePath2("Windows\SysWOW64\fakefile.ext", 1100)
        Debug.Print , "1110", "D:\p\file", ParsePath2("Windows\SysWOW64\fakefile.ext", 1110)
        Debug.Print , "1111", "D:\p\f.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 1111)
        On Error GoTo EH:
        ' This is expected to presetn an error:
        p = "Windows\SysWOW64\fakefile.ext"
        n = 1010
        Debug.Print "1010", "D:\p\file.ext", ParsePath2("Windows\SysWOW64\fakefile.ext", 1010)
        On Error GoTo 0
    End If
Exit Sub
EH:
    Debug.Print , CStr(n), "Error: "; Err.Number, Err.Description
    Resume Next
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function ParsePath2(ByVal DrivePathFileExt As String _
                         , Optional ReturnType As Integer = 0)
' Writen by Chris Advena.  You may modify and use this code provided you leave
' this credit in the code.
' Parses the input DrivePathFileExt string into individual components (drive
' letter, folders, filename and extension) and returns the portions you wish
' based on ReturnType.
' Returns either an array of strings (ReturnType = 0) or an individual string
' (all other defined ReturnType values).
'
' Parameters:
'   DrivePathFileExt: The full drive letter, path, filename and extension
'   ReturnType: -2 or a string up of to 4 ones with leading or lagging zeros
'              (e.g., 0001)
'      -2: special code for debugging use in ParsePath2Test().
'          Results in printing verbose information to the Immediate window.
'       0: default: Array(driveStr, pathStr, fileStr, extStr)
'       1: extension
'      10: filename stripped of extension
'      11: filename.extension, excluding drive and folders
'     100: folders, excluding drive letter filename and extension
'     111: folders\filename.extension, excluding drive letter
'    1000: drive leter only
'    1100: drive:\folders,  excluding filename and extension
'    1110: drive:\folders\filename, excluding extension
'    1010, 0101, 1001: invalid ReturnTypes.  Will result raise error 380, Value
'          is not valid.

    Dim driveStr As String, pathStr As String
    Dim fileStr As String, extStr As String
    Dim drivePathStr As String
    Dim pathFileExtStr As String, fileExtStr As String
    Dim s As String, cnt As Integer
    Dim i As Integer, slashStr As String
    Dim dotLoc As Integer, slashLoc As Integer, colonLoc As Integer
    Dim extLen As Integer, fileLen As Integer, pathLen As Integer
    Dim errStr As String

    DrivePathFileExt = Trim(DrivePathFileExt)

    If DrivePathFileExt = "" Then
        fileStr = ""
        extStr = ""
        fileExtStr = ""
        pathStr = ""
        pathFileExtStr = ""
        drivePathStr = ""
        GoTo ReturnResults
    End If

    ' Determine if Dos(/) or UNIX(\) slash is used
    slashStr = GetPathSeparator(DrivePathFileExt)

' Find location of colon, rightmost slash and dot.
    ' COLON: colonLoc and driveStr
    colonLoc = 0
    driveStr = ""
    If Mid(DrivePathFileExt, 2, 1) = ":" Then
        colonLoc = 2
        driveStr = Left(DrivePathFileExt, 1)
    End If
    #If Mac Then
        pathFileExtStr = DrivePathFileExt
    #Else ' Windows
        pathFileExtStr = ""
        If Len(DrivePathFileExt) > colonLoc _
        Then pathFileExtStr = Mid(DrivePathFileExt, colonLoc + 1)
    #End If

    ' SLASH: slashLoc, fileExtStr and fileStr
    ' Find the rightmost path separator (Win backslash or Mac Fwdslash).
    slashLoc = InStrRev(DrivePathFileExt, slashStr, -1, vbBinaryCompare)

    ' DOT: dotLoc and extStr
    ' Find rightmost dot.  If that dot is not part of a relative reference,
    ' then set dotLoc.  dotLoc is meant to apply to the dot before an extension,
    ' NOT relative path reference dots.  REl ref dots appear as "." or ".." at
    ' the very leftmost of the path string.
    dotLoc = InStrRev(DrivePathFileExt, ".", -1, vbTextCompare)
    If Left(DrivePathFileExt, 1) = "." And dotLoc <= 2 Then dotLoc = 0
    If slashLoc + 1 = dotLoc Then
        dotLoc = 0
        If Len(extStr) = 0 And Right(pathFileExtStr, 1) <> slashStr _
        Then pathFileExtStr = pathFileExtStr & slashStr
    End If
    #If Not Mac Then
        ' In windows, filenames cannot end with a dot (".").
        If dotLoc = Len(DrivePathFileExt) Then
            s = "Error in FileManagementMod.ParsePath2 function.  " _
                & "DrivePathFileExt " & DrivePathFileExt _
                & " cannot end iwth a dot ('.')."
            Err.Raise 52, "FileManagementMod.ParsePath2", s
        End If
    #End If

    ' extStr
    extStr = ""
    If dotLoc > 0 And (dotLoc < Len(DrivePathFileExt)) _
    Then extStr = Mid(DrivePathFileExt, dotLoc + 1)

    ' fileExtStr
    fileExtStr = ""
    If slashLoc > 0 _
    And slashLoc < Len(DrivePathFileExt) _
    And dotLoc > slashLoc Then
        fileExtStr = Mid(DrivePathFileExt, slashLoc + 1)
    End If


' Validate the input: DrivePathFileExt
    s = ""
    #If Mac Then
        If InStr(1, DrivePathFileExt, ":") > 0 Then
            s = "DrivePathFileExt ('" & DrivePathFileExt _
                & "')has invalid format.  " _
                & "UNIX/Mac filenames cannot contain a colon ('.')."
        End If
    #End If
    If Not colonLoc = 0 And slashLoc = 0 And dotLoc = 0 _
    And Left(DrivePathFileExt, 1) <> slashStr _
    And Left(DrivePathFileExt, 1) <> "." Then
        s = "DrivePathFileExt ('" & DrivePathFileExt _
            & "') has invalid format.  " _
            & "Good example: 'C:\folder\file.txt'"
    ElseIf colonLoc <> 0 And colonLoc <> 2 Then
        ' We are on Windows and there is a colon; it can only be
        ' in position 2.
        s = "DrivePathFileExt ('" & DrivePathFileExt _
            & "') has invalid format.  " _
            & "In the  Windows operating system, " _
            & "a colon (':') can only be the second character '" _
            & "of a valid file path. "
    ElseIf Left(DrivePathFileExt, 1) = ":" _
    Or InStr(3, DrivePathFileExt, ":", vbTextCompare) > 0 Then
        'If path contains a drive letter, it must contain at least one slash.
        s = "DrivePathFileExt ('" & DrivePathFileExt _
            & "') has invalid format.  " _
            & "Colon can only appear in the second character position." _
            & slashStr & "')."
    ElseIf colonLoc > 0 And slashLoc = 0 _
    And Len(DrivePathFileExt) > 2 Then
        'If path contains a drive letter, it must contain at least one slash.
        s = "DrivePathFileExt ('" & DrivePathFileExt _
            & "') has invalid format.  " _
            & "The last dot ('.') cannot be before the last file separator '" _
            & slashStr & "')."
    ElseIf colonLoc = 2 _
    And InStr(1, DrivePathFileExt, slashStr, vbTextCompare) = 0 _
    And Len(DrivePathFileExt) > 2 Then
        ' There is a colon, but no file separator (slash).  This is invalid.
        s = "DrivePathFileExt ('" & DrivePathFileExt _
            & "') has invalid format.  " _
            & "If a drive letter is included, then there must be at " _
            & "least one file separator character ('" & slashStr & "')."
    ElseIf Len(driveStr) > 0 And Len(DrivePathFileExt) > 2 And slashLoc = 0 Then
        ' If path contains a drive letter and is more than 2 character long
        ' (e.g., 'C:'), it must contain at least one slash.
        s = "DrivePathFileExt cannot contain a drive letter but no path separator."
    End If
    If Len(s) > 0 Then
    End If



' Determine if DrivePathFileExt = DrivePath
' or  = Path (with no fileStr or extStr components).
    If Right(DrivePathFileExt, 1) = slashStr _
    Or slashLoc = 0 _
    Or dotLoc = 0 _
    Or (dotLoc > 0 And dotLoc <= slashLoc + 1) Then
        ' If rightmost character is the slashStr, then no fileExt exists, just drivePath
        ' If no dot found, then no extension.  Assume a folder is after the last slashstr,
        ' not a filename.
        ' If a dot is found (extension exists),
        ' If a rightmost dot appears one-char to the right of the rightmost slash
        '    or anywhere before (left) of that, it is not a file/ext separator. Exmaple:
        '    'C:\folder1\.folder2' Then
        ' If no slashes, then no fileExt exists.  It must just be a driveletter.
        ' DrivePathFileExt contains no file or ext name.
        fileStr = ""
        extStr = ""
        fileExtStr = ""
        pathStr = pathFileExtStr
        drivePathStr = DrivePathFileExt
        GoTo ReturnResults
    Else
        ' fileStr
        fileStr = ""
        If slashLoc > 0 Then
            If Len(extStr) = 0 Then
                fileStr = fileExtStr
            Else
                ' length of filename excluding dot and extension.
                i = Len(fileExtStr) - Len(extStr) - 1
                fileStr = Left(fileExtStr, i)
            End If
        Else
                s = "Error in FileManagementMod.ParsePath2 function. " _
                    & "*** Unhandled scenario: find fileStr when slashLoc = 0. *** "
                Err.Raise 52, "FileManagementMod.ParsePath2", s
        End If

        ' pathStr
        pathStr = ""
        ' length of pathFileExtStr excluding fileExt.
        i = Len(pathFileExtStr) - Len(fileExtStr)
        pathStr = Left(pathFileExtStr, i)

        ' drivePathStr
        drivePathStr = ""
        ' length of DrivePathFileExt excluding dot and extension.
        i = Len(DrivePathFileExt) - Len(fileExtStr)
        drivePathStr = Left(DrivePathFileExt, i)
    End If

ReturnResults:
    ' ReturnType uses a 4-digit binary code: dpfe = drive path file extension,
    ' where 1 = return in array and 0 = do not return in array
    ' -2, and 0 are special cases that do not follow the code.

    ' Note: pathstr is determined with the tailing slashstr
    If Len(drivePathStr) > 0 And Right(drivePathStr, 1) <> slashStr _
    Then drivePathStr = drivePathStr & slashStr
    If Len(pathStr) > 0 And Right(pathStr, 1) <> slashStr _
    Then pathStr = pathStr & slashStr
    #If Not Mac Then
        ' Including this code add a slash to the beginnning where missing.
        ' the downside is that it would create an absolute path where a
        ' sub-path of the current folder is intended.
        'If colonLoc = 0 Then
        '    If Len(drivePathStr) > 0 And Not IsIn(Left(drivePathStr, 1), slashStr, ".") _
             Then drivePathStr = slashStr & drivePathStr
        '    If Len(pathStr) > 0 And Not IsIn(Left(pathStr, 1), slashStr, ".") _
             Then pathStr = slashStr & pathStr
        '    If Len(pathFileExtStr) > 0 And Not IsIn(Left(pathFileExtStr, 1), slashStr, ".") _
             Then pathFileExtStr = slashStr & pathFileExtStr
        'End If
    #End If
    Select Case ReturnType
        Case -2  ' used for ParsePath2Test() only.
            ParsePath2 = "DrivePathFileExt          " _
                        & CStr(Nz(DrivePathFileExt, "{empty string}")) _
                        & vbCrLf & "        " _
                        & "--------------    -----------------------------------------" _
                        & vbCrLf & "        " & "D:\Path\          " & drivePathStr _
                        & vbCrLf & "        " & "\path[\file.ext]  " & pathFileExtStr _
                        & vbCrLf & "        " & "\path\            " & pathStr _
                        & vbCrLf & "        " & "file.ext          " & fileExtStr _
                        & vbCrLf & "        " & "file              " & fileStr _
                        & vbCrLf & "        " & "ext               " & extStr _
                        & vbCrLf & "        " & "D                 " & driveStr _
                        & vbCrLf & vbCrLf
            ' My custom debug printer prints to Immediate winodw and log file.
            ' Dbg.Prnt 2, ParsePath2
            Debug.Print ParsePath2
        Case 1      '0001: ext
            ParsePath2 = extStr
        Case 10     '0010: file
            ParsePath2 = fileStr
        Case 11     '0011: file.ext
            ParsePath2 = fileExtStr
        Case 100    '0100: path
            ParsePath2 = pathStr
        Case 110    '0110: (path, file)
            ParsePath2 = pathStr & fileStr
        Case 111    '0111:
            ParsePath2 = pathFileExtStr
        Case 1000
            ParsePath2 = driveStr
        Case 1100
            ParsePath2 = drivePathStr
        Case 1110
            ParsePath2 = drivePathStr & fileStr
        Case 1111
            ParsePath2 = DrivePathFileExt
        Case 1010, 101, 1001
            s = "Error in FileManagementMod.ParsePath2 function.  " _
                & "Value of Paramter (ReturnType = " _
                & CStr(ReturnType) & ") is not valid."
            Err.Raise 380, "FileManagementMod.ParsePath2", s
        Case Else   '   default: 0
            ParsePath2 = Array(driveStr, pathStr, fileStr, extStr)
    End Select

End Function

Supporting function GetPathSeparatorTest extends the native Application.pathSeparator (or bypasses when needed) to work on Mac and Win. It can also takes an optional path string and will try to determine the path separator used in the string (favoring the OS native path separator).

Private Sub GetPathSeparatorTest()
    Dim s As String
    Debug.Print "GetPathSeparator(s):"
    Debug.Print "s not provided: ", GetPathSeparator
    s = "C:\folder1\folder2\file.ext"
    Debug.Print "s = "; s, GetPathSeparator(DrivePathFileExt:=s)
    s = "C:/folder1/folder2/file.ext"
    Debug.Print "s = "; s, GetPathSeparator(DrivePathFileExt:=s)
End Sub
Function GetPathSeparator(Optional DrivePathFileExt As String = "") As String
' by Chris Advena
' Finds the path separator from a string, DrivePathFileExt.
' If DrivePathFileExt is not provided, return the operating system path separator
' (Windows = backslash, Mac = forwardslash).
' Mac/Win compatible.

    ' Initialize
    Dim retStr As String: retStr = ""
    Dim OSSlash As String: OSSlash = ""
    Dim OSOppositeSlash As String: OSOppositeSlash = ""
        Dim PathFileExtSlash As String

    GetPathSeparator = ""
    retStr = ""

    ' Determine if OS expects fwd or back slash ("/" or "\").
    On Error GoTo EH
    OSSlash = Application.pathSeparator

    If DrivePathFileExt = "" Then
    ' Input parameter DrivePathFileExt is empty, so use OS file separator.
        retStr = OSSlash
    Else
    ' Input parameter DrivePathFileExt provided.  See if it contains / or \.
        ' Set OSOppositeSlash to the opposite slash the OS expects.
        OSOppositeSlash = "\"
        If OSSlash = "\" Then OSOppositeSlash = "/"

        ' If DrivePathFileExt does NOT contain OSSlash
        ' and DOES contain OSOppositeSlash, return OSOppositeSlash.
        ' Otherwise, assume OSSlash is correct.
        retStr = OSSlash
        If InStr(1, DrivePathFileExt, OSSlash, vbTextCompare) = 0 _
        And InStr(1, DrivePathFileExt, OSOppositeSlash, vbTextCompare) > 0 Then
            retStr = OSOppositeSlash
        End If
    End If

    GetPathSeparator = retStr
Exit Function
EH:
    ' Application.PathSeparator property does not exist in Access,
    ' so get it the slightly less easy way.
    #If Mac Then ' Application.PathSeparator doesn't seem to exist in Access...
        OSSlash = "/"
    #Else
        OSSlash = "\"
    #End If
    Resume Next
End Function

Supporting function (actually commented out, so you can skip this if you don't plan to use it).

Sub IsInTest()
' IsIn2 is case insensitive
    Dim StrToFind As String, arr As Variant
    arr = Array("Me", "You", "Dog", "Boo")

    StrToFind = "doG"
    Debug.Print "Is '" & CStr(StrToFind) & "' in list (expect True): " _
                , IsIn(StrToFind, "Me", "You", "Dog", "Boo")

    StrToFind = "Porcupine"
    Debug.Print "Is '" & CStr(StrToFind) & "' in list (expect False): " _
                , IsIn(StrToFind, "Me", "You", "Dog", "Boo")
End Sub
Function IsIn(ByVal StrToFind, ParamArray StringArgs() As Variant) As Boolean
' StrToFind: the string to find in the list of StringArgs()
' StringArgs: 1-dimensional array containing string values.
' Built for Strings, but actually works with other data types.
    Dim arr As Variant
    arr = StringArgs
    IsIn = Not IsError(Application.Match(StrToFind, arr, False))
End Function

GitLab git user password

To add yet another reason to the list ... in my case I found this problem was being caused by an SELinux permissions problem on the server. This is worth checking if your server is running Fedora / CentOS / Red Hat. To test this scenario you can run:

Client: ssh -vT git@<gitlab-server> -- asks for password
Server: sudo setenforce 0
Client: ssh -vT git@<gitlab-server> -- succeeds
Server: sudo setenforce 1

In my case the gitlab/git user's authorized_keys file had the wrong SELinux file context, and the ssh service was being denied permission to read it. I fixed this on the server side as follows:

sudo semanage fcontext -a -t ssh_home_t /gitlab/.ssh/
sudo semanage fcontext -a -t ssh_home_t /gitlab/.ssh/authorized_keys
sudo restorecon -F -Rv /gitlab/.ssh/

And I was then able to git clone on the client side as expected.

Configure hibernate to connect to database via JNDI Datasource

Tomcat-7 JNDI configuration:

Steps:

  1. Open the server.xml in the tomcat-dir/conf
  2. Add below <Resource> tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
          global="jdbc/mydb"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/test"
          username="root"
          password=""
          maxActive="10"
          maxIdle="10"
          minIdle="5"
          maxWait="10000"/>
  1. Save the server.xml file
  2. Open the context.xml in the tomcat-dir/conf
  3. Add the below <ResourceLink> inside the <Context> tag.
<ResourceLink name="jdbc/mydb" 
              global="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource" />
  1. Save the context.xml
  2. Open the hibernate-cfg.xml file and add and remove below properties.
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>

Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
  1. Save the file and put latest .WAR file in tomcat.
  2. Restart the tomcat. the DB connection will work.

console.log timestamps in Chrome?

extended the very nice solution "with format string" from JSmyth to also support

  • all the other console.log variations (log,debug,info,warn,error)
  • including timestamp string flexibility param (e.g. 09:05:11.518 vs. 2018-06-13T09:05:11.518Z)
  • including fallback in case console or its functions do not exist in browsers

.

var Utl = {

consoleFallback : function() {

    if (console == undefined) {
        console = {
            log : function() {},
            debug : function() {},
            info : function() {},
            warn : function() {},
            error : function() {}
        };
    }
    if (console.debug == undefined) { // IE workaround
        console.debug = function() {
            console.info( 'DEBUG: ', arguments );
        }
    }
},


/** based on timestamp logging: from: https://stackoverflow.com/a/13278323/1915920 */
consoleWithTimestamps : function( getDateFunc = function(){ return new Date().toJSON() } ) {

    console.logCopy = console.log.bind(console)
    console.log = function() {
        var timestamp = getDateFunc()
        if (arguments.length) {
            var args = Array.prototype.slice.call(arguments, 0)
            if (typeof arguments[0] === "string") {
                args[0] = "%o: " + arguments[0]
                args.splice(1, 0, timestamp)
                this.logCopy.apply(this, args)
            } else this.logCopy(timestamp, args)
        }
    }
    console.debugCopy = console.debug.bind(console)
    console.debug = function() {
        var timestamp = getDateFunc()
        if (arguments.length) {
            var args = Array.prototype.slice.call(arguments, 0)
            if (typeof arguments[0] === "string") {
                args[0] = "%o: " + arguments[0]
                args.splice(1, 0, timestamp)
                this.debugCopy.apply(this, args)
            } else this.debugCopy(timestamp, args)
        }
    }
    console.infoCopy = console.info.bind(console)
    console.info = function() {
        var timestamp = getDateFunc()
        if (arguments.length) {
            var args = Array.prototype.slice.call(arguments, 0)
            if (typeof arguments[0] === "string") {
                args[0] = "%o: " + arguments[0]
                args.splice(1, 0, timestamp)
                this.infoCopy.apply(this, args)
            } else this.infoCopy(timestamp, args)
        }
    }
    console.warnCopy = console.warn.bind(console)
    console.warn = function() {
        var timestamp = getDateFunc()
        if (arguments.length) {
            var args = Array.prototype.slice.call(arguments, 0)
            if (typeof arguments[0] === "string") {
                args[0] = "%o: " + arguments[0]
                args.splice(1, 0, timestamp)
                this.warnCopy.apply(this, args)
            } else this.warnCopy(timestamp, args)
        }
    }
    console.errorCopy = console.error.bind(console)
    console.error = function() {
        var timestamp = getDateFunc()
        if (arguments.length) {
            var args = Array.prototype.slice.call(arguments, 0)
            if (typeof arguments[0] === "string") {
                args[0] = "%o: " + arguments[0]
                args.splice(1, 0, timestamp)
                this.errorCopy.apply(this, args)
            } else this.errorCopy(timestamp, args)
        }
    }
}
}  // Utl

Utl.consoleFallback()
//Utl.consoleWithTimestamps()  // defaults to e.g. '2018-06-13T09:05:11.518Z'
Utl.consoleWithTimestamps( function(){ return new Date().toJSON().replace( /^.+T(.+)Z.*$/, '$1' ) } )  // e.g. '09:05:11.518'

Encoding as Base64 in Java

public String convertImageToBase64(String filePath) {
    byte[] fileContent = new byte[0];
    String base64encoded = null;
    try {
        fileContent = FileUtils.readFileToByteArray(new File(filePath));
    } catch (IOException e) {
        log.error("Error reading file: {}", filePath);
    }
    try {
        base64encoded = Base64.getEncoder().encodeToString(fileContent);
    } catch (Exception e) {
        log.error("Error encoding the image to base64", e);
    }
    return base64encoded;
}

HTML - how can I show tooltip ONLY when ellipsis is activated

I created a jQuery plugin that uses Bootstrap's tooltip instead of the browser's build-in tooltip. Please note that this has not been tested with older browser.

JSFiddle: https://jsfiddle.net/0bhsoavy/4/

$.fn.tooltipOnOverflow = function(options) {
    $(this).on("mouseenter", function() {
    if (this.offsetWidth < this.scrollWidth) {
        options = options || { placement: "auto"}
        options.title = $(this).text();
      $(this).tooltip(options);
      $(this).tooltip("show");
    } else {
      if ($(this).data("bs.tooltip")) {
        $tooltip.tooltip("hide");
        $tooltip.removeData("bs.tooltip");
      }
    }
  });
};

Fully change package name including company domain

I found another solution for renaming a package in the entire project:

Open a file in the package. IntelliJ displays the breadcrumbs of the file, above the opened file. On the package you want renamed: Right click > Refactor > Rename. This renames the package/directory throughout the entire project.

Return multiple fields as a record in PostgreSQL with PL/pgSQL

If you have a table with this exact record layout, use its name as a type, otherwise you will have to declare the type explicitly:

CREATE OR REPLACE FUNCTION get_object_fields
        (
        name text
        )
RETURNS mytable
AS
$$
        DECLARE f1 INT;
        DECLARE f2 INT;
        …
        DECLARE f8 INT;
        DECLARE retval mytable;
        BEGIN
        -- fetch fields f1, f2 and f3 from table t1
        -- fetch fields f4, f5 from table t2
        -- fetch fields f6, f7 and f8 from table t3
                retval := (f1, f2, …, f8);
                RETURN retval;
        END
$$ language plpgsql; 

MyISAM versus InnoDB

myisam is a NOGO for that type of workload (high concurrency writes), i dont have that much experience with innodb (tested it 3 times and found in each case that the performance sucked, but it's been a while since the last test) if you're not forced to run mysql, consider giving postgres a try as it handles concurrent writes MUCH better

Setting Oracle 11g Session Timeout

This is likely caused by your application's connection pool; not an Oracle DBMS issue. Most connection pools have a validate statement that can execute before giving you the connection. In oracle you would want "Select 1 from dual".

The reason it started occurring after you restarted the server is that the connection pool was probably added without a restart and you are just now experiencing the use of the connection pool for the first time. What is the modification dates on your resource files that deal with database connections?

Validate Query example:

 <Resource name="jdbc/EmployeeDB" auth="Container" 
            validationQuery="Select 1 from dual" type="javax.sql.DataSource" username="dbusername" password="dbpassword"
            driverClassName="org.hsql.jdbcDriver" url="jdbc:HypersonicSQL:database"
            maxActive="8" maxIdle="4"/>

EDIT: In the case of Grails, there are similar configuration options for the grails pool. Example for Grails 1.2 (see release notes for Grails 1.2)

dataSource {
    pooled = true
    dbCreate = "update"
    url = "jdbc:mysql://localhost/yourDB"
    driverClassName = "com.mysql.jdbc.Driver"
    username = "yourUser"
    password = "yourPassword"
    properties {
        maxActive = 50
        maxIdle = 25
        minIdle = 5
        initialSize = 5
        minEvictableIdleTimeMillis = 60000
        timeBetweenEvictionRunsMillis = 60000
        maxWait = 10000     
    }   
}

jQuery Button.click() event is triggered twice

in my case, i was using the change command like this way

$(document).on('change', '.select-brand', function () {...my codes...});

and then i changed the way to

$('.select-brand').on('change', function () {...my codes...});

and it solved my problem.

Calculating the distance between 2 points

Given points (X1,Y1) and (X2,Y2) then:

dX = X1 - X2;
dY = Y1 - Y2;

if (dX*dX + dY*dY > (5*5))
{
    //your code
}

Selectors in Objective-C?

You have to be very careful about the method names. In this case, the method name is just "lowercaseString", not "lowercaseString:" (note the absence of the colon). That's why you're getting NO returned, because NSString objects respond to the lowercaseString message but not the lowercaseString: message.

How do you know when to add a colon? You add a colon to the message name if you would add a colon when calling it, which happens if it takes one argument. If it takes zero arguments (as is the case with lowercaseString), then there is no colon. If it takes more than one argument, you have to add the extra argument names along with their colons, as in compare:options:range:locale:.

You can also look at the documentation and note the presence or absence of a trailing colon.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &. That also requires using parentheses so that & wouldn't take precedence.

It would go something like this:

mask = ((50  < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...

In order to avoid that, you can build series for lower and upper limits:

low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)

Now you can slice it as follows:

mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out: 
     dyastolic blood pressure  heart rate  pulse oximetry  respiratory rate  \
17                        136          62              97                15   
69                        110          85              96                18   
72                        105          85              97                16   
161                       126          57              99                16   
286                       127          84              99                12   
435                        92          67              96                13   
499                       110          66              97                15   

     systolic blood pressure  temperature  
17                       141           37  
69                       155           38  
72                       154           36  
161                      153           36  
286                      156           37  
435                      155           36  
499                      149           36  

And for assignment you can use np.where:

df['class'] = np.where(mask, 'excellent', 'critical')

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

There are 3 ways to allow cross domain origin (excluding jsonp):

1) Set the header in the page directly using a templating language like PHP. Keep in mind there can be no HTML before your header or it will fail.

 <?php header("Access-Control-Allow-Origin: http://example.com"); ?>

2) Modify the server configuration file (apache.conf) and add this line. Note that "*" represents allow all. Some systems might also need the credential set. In general allow all access is a security risk and should be avoided:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Credentials true

3) To allow multiple domains on Apache web servers add the following to your config file

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(example.org|example.com)$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Credentials true
</IfModule>

4) For development use only hack your browser and allow unlimited CORS using the Chrome Allow-Control-Allow-Origin extension

5) Disable CORS in Chrome: Quit Chrome completely. Open a terminal and execute the following. Just be cautious you are disabling web security:

open -a Google\ Chrome --args --disable-web-security --user-data-dir

assign multiple variables to the same value in Javascript

The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let, const, and var can all be used for this type of assignment.

let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false);

How to check whether a int is not null or empty?

I think you are asking about code like this.

int  count = (request.getParameter("counter") == null) ? 0 : Integer.parseInt(request.getParameter("counter"));

How to remove all duplicate items from a list

This should do it for you:

new_list = list(set(old_list))

set will automatically remove duplicates. list will cast it back to a list.

Create an ArrayList of unique values

Just Override the boolean equals() method of custom object. Say you have an ArrayList with custom field f1, f2, ... override

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof CustomObject)) return false;

    CustomObject object = (CustomObject) o;

    if (!f1.equals(object.dob)) return false;
    if (!f2.equals(object.fullName)) return false;
    ...
    return true;
}

and check using ArrayList instance's contains() method. That's it.

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

While trace flag 272 may work for many, it definitely won't work for hosted Sql Server Express installations. So, I created an identity table, and use this through an INSTEAD OF trigger. I'm hoping this helps someone else, and/or gives others an opportunity to improve my solution. The last line allows returning the last identity column added. Since I typically use this to add a single row, this works to return the identity of a single inserted row.

The identity table:

CREATE TABLE [dbo].[tblsysIdentities](
[intTableId] [int] NOT NULL,
[intIdentityLast] [int] NOT NULL,
[strTable] [varchar](100) NOT NULL,
[tsConcurrency] [timestamp] NULL,
CONSTRAINT [PK_tblsysIdentities] PRIMARY KEY CLUSTERED 
(
    [intTableId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

and the insert trigger:

-- INSERT --
IF OBJECT_ID ('dbo.trgtblsysTrackerMessagesIdentity', 'TR') IS NOT NULL
   DROP TRIGGER dbo.trgtblsysTrackerMessagesIdentity;
GO
CREATE TRIGGER trgtblsysTrackerMessagesIdentity
ON dbo.tblsysTrackerMessages
INSTEAD OF INSERT AS 
BEGIN
    DECLARE @intTrackerMessageId INT
    DECLARE @intRowCount INT

    SET @intRowCount = (SELECT COUNT(*) FROM INSERTED)

    SET @intTrackerMessageId = (SELECT intIdentityLast FROM tblsysIdentities WHERE intTableId=1)
    UPDATE tblsysIdentities SET intIdentityLast = @intTrackerMessageId + @intRowCount WHERE intTableId=1

    INSERT INTO tblsysTrackerMessages( 
    [intTrackerMessageId],
    [intTrackerId],
    [strMessage],
    [intTrackerMessageTypeId],
    [datCreated],
    [strCreatedBy])
    SELECT @intTrackerMessageId + ROW_NUMBER() OVER (ORDER BY [datCreated]) AS [intTrackerMessageId], 
    [intTrackerId],
   [strMessage],
   [intTrackerMessageTypeId],
   [datCreated],
   [strCreatedBy] FROM INSERTED;

   SELECT TOP 1 @intTrackerMessageId + @intRowCount FROM INSERTED;
END

Opacity CSS not working in IE8

CSS

I used to use the following from CSS-Tricks:

.transparent_class {
  /* IE 8 */
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";

  /* IE 5-7 */
  filter: alpha(opacity=50);

  /* Netscape */
  -moz-opacity: 0.5;

  /* Safari 1.x */
  -khtml-opacity: 0.5;

  /* Good browsers */
  opacity: 0.5;
}

Compass

However, a better solution is to use the Opacity Compass mixin, all you need to do is to @include opacity(0.1); and it will take care of any cross-browser issues for you. You can find an example here.

Invalid use side-effecting operator Insert within a function

Disclaimer: This is not a solution, it is more of a hack to test out something. User-defined functions cannot be used to perform actions that modify the database state.

I found one way to make insert or update using sqlcmd.exe so you need just to replace the code inside @sql variable.

CREATE FUNCTION [dbo].[_tmp_func](@orderID NVARCHAR(50))
RETURNS INT
AS
BEGIN
DECLARE @sql varchar(4000), @cmd varchar(4000)
SELECT @sql = 'INSERT INTO _ord (ord_Code) VALUES (''' + @orderID + ''') '
SELECT @cmd = 'sqlcmd -S ' + @@servername +
              ' -d ' + db_name() + ' -Q "' + @sql + '"'
EXEC master..xp_cmdshell @cmd, 'no_output'
RETURN 1
END

How to get docker-compose to always re-create containers from fresh images?

By current official documentation there is a short cut that stops and removes containers, networks, volumes, and images created by up, if they are already stopped or partially removed and so on, then it will do the trick too:

docker-compose down

Then if you have new changes on your images or Dockerfiles use:

docker-compose build --no-cache

Finally:docker-compose up

In one command: docker-compose down && docker-compose build --no-cache && docker-compose up

Freeing up a TCP/IP port?

The "netstat --programs" command will give you the process information, assuming you're the root user. Then you will have to kill the "offending" process which may well start up again just to annoy you.

Depending on what you're actually trying to achieve, solutions to that problem will vary based on the processes holding those ports. For example, you may need to disable services (assuming they're unneeded) or configure them to use a different port (if you do need them but you need that port more).

jQuery Find and List all LI elements within a UL within a specific DIV

var column1RelArray = [];
$('#column1 li').each(function(){
    column1RelArray.push($(this).attr('rel'));
});

or fp style

var column1RelArray = $('#column1 li').map(function(){ 
    return $(this).attr('rel'); 
});

Caching a jquery ajax response in javascript/browser

Old question, but my solution is a bit different.

I was writing a single page web app that was constantly making ajax calls triggered by the user, and to make it even more difficult it required libraries that used methods other than jquery (like dojo, native xhr, etc). I wrote a plugin for one of my own libraries to cache ajax requests as efficiently as possible in a way that would work in all major browsers, regardless of which libraries were being used to make the ajax call.

The solution uses jSQL (written by me - a client-side persistent SQL implementation written in javascript which uses indexeddb and other dom storage methods), and is bundled with another library called XHRCreep (written by me) which is a complete re-write of the native XHR object.

To implement all you need to do is include the plugin in your page, which is here.

There are two options:

jSQL.xhrCache.max_time = 60;

Set the maximum age in minutes. any cached responses that are older than this are re-requested. Default is 1 hour.

jSQL.xhrCache.logging = true;

When set to true, mock XHR calls will be shown in the console for debugging.

You can clear the cache on any given page via

jSQL.tables = {}; jSQL.persist();

How do I make a batch file terminate upon encountering an error?

Here is a polyglot program for BASH and Windows CMD that runs a series of commands and quits out if any of them fail:

#!/bin/bash 2> nul

:; set -o errexit
:; function goto() { return $?; }

command 1 || goto :error

command 2 || goto :error

command 3 || goto :error

:; exit 0
exit /b 0

:error
exit /b %errorlevel%

I have used this type of thing in the past for a multiple platform continuous integration script.

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

I bet the problem is being shown in this line

SqlDataReader dr3 = com2.ExecuteReader();

I suggest that you execute the first reader and do a dr.Close(); and the iterate historicos, with another loop, performing the com2.ExecuteReader().

public List<string[]> get_dados_historico_verificacao_email_WEB(string email)
    {

        List<string[]> historicos = new List<string[]>();
        conecta();
        sql = "SELECT * FROM historico_verificacao_email WHERE nm_email = '" + email + "' ORDER BY  dt_verificacao_email DESC, hr_verificacao_email DESC"; 
        com = new SqlCommand(sql, conexao);
        SqlDataReader dr = com.ExecuteReader();

        if (dr.HasRows)
        {
            while (dr.Read())
            {
                string[] dados_historico = new string[6];
                dados_historico[0] = dr["nm_email"].ToString();
                dados_historico[1] = dr["dt_verificacao_email"].ToString();
                dados_historico[1] = dados_historico[1].Substring(0, 10);
                //System.Windows.Forms.MessageBox.Show(dados_historico[1]);
                dados_historico[2] = dr["hr_verificacao_email"].ToString();
                dados_historico[3] = dr["ds_tipo_verificacao"].ToString();
                dados_historico[5] = dr["cd_login_usuario"].ToString();
                historicos.Add(dados_historico);
            }

            dr.Close();

            sql = "SELECT COUNT(e.cd_historico_verificacao_email) QT FROM emails_lidos e WHERE e.cd_historico_verificacao_email = '" + dr["cd_historico_verificacao_email"].ToString() + "'";
            tipo_sql = "seleção";
            com2 = new SqlCommand(sql, conexao);

            for(int i = 0 ; i < historicos.Count() ; i++)
            {
                SqlDataReader dr3 = com2.ExecuteReader();
                while (dr3.Read())
                {
                    historicos[i][4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
                }
                dr3.Close();
            }

        }

        return historicos;

What is the use of "using namespace std"?

  • using: You are going to use it.
  • namespace: To use what? A namespace.
  • std: The std namespace (where features of the C++ Standard Library, such as string or vector, are declared).

After you write this instruction, if the compiler sees string it will know that you may be referring to std::string, and if it sees vector, it will know that you may be referring to std::vector. (Provided that you have included in your compilation unit the header files where they are defined, of course.)

If you don't write it, when the compiler sees string or vector it will not know what you are refering to. You will need to explicitly tell it std::string or std::vector, and if you don't, you will get a compile error.

Adding Git-Bash to the new Windows Terminal

Overview

  1. Open settings with ctrl + ,
  2. You'll want to append one of the profiles options below (depending on what version of git you have installed) to the "list": portion of the settings.json file
{
    "$schema": "https://aka.ms/terminal-profiles-schema",

    "defaultProfile": "{00000000-0000-0000-ba54-000000000001}",

    "profiles":
    {
        "defaults":
        {
            // Put settings here that you want to apply to all profiles
        },
        "list":
        [
            <put one of the configuration below right here>
        ]
    }
}

Profile options

Uncomment correct paths for commandline and icon if you are using:

  • Git for Windows in %PROGRAMFILE%
  • Git for Windows in %USERPROFILE%
  • If you're using scoop
{
    "guid": "{00000000-0000-0000-ba54-000000000002}",
    "commandline": "%PROGRAMFILES%/git/usr/bin/bash.exe -i -l",
    // "commandline": "%USERPROFILE%/AppData/Local/Programs/Git/bin/bash.exe -l -i",
    // "commandline": "%USERPROFILE%/scoop/apps/git/current/usr/bin/bash.exe -l -i",
    "icon": "%PROGRAMFILES%/Git/mingw64/share/git/git-for-windows.ico",
    // "icon": "%USERPROFILE%/AppData/Local/Programs/Git/mingw64/share/git/git-for-windows.ico",
    // "icon": "%USERPROFILE%/apps/git/current/usr/share/git/git-for-windows.ico",
    "name" : "Bash",
    "startingDirectory" : "%USERPROFILE%",

},

You can also add other options like:

{
    "guid": "{00000000-0000-0000-ba54-000000000002}",
    // ...
    "acrylicOpacity" : 0.75,
    "closeOnExit" : true,
    "colorScheme" : "Campbell",
    "cursorColor" : "#FFFFFF",
    "cursorShape" : "bar",
    "fontFace" : "Consolas",
    "fontSize" : 10,
    "historySize" : 9001,
    "padding" : "0, 0, 0, 0",
    "snapOnInput" : true,
    "useAcrylic" : true
}

Notes

  • make your own guid as of https://github.com/microsoft/terminal/pull/2475 this is no longer generated.
  • the guid can be used in in the globals > defaultProfile so you can press you can press CtrlShiftT or start a Windows terminal and it will start up bash by default
"defaultProfile" : "{00000000-0000-0000-ba54-000000000001}",
  • -l -i to make sure that .bash_profile gets loaded
  • use environment variables so they can map to different systems correctly.
  • target git/bin/bash.exe to avoid spawning off additional processes which saves about 10MB per process according to Process Explorer compared to using bin/bash or git-bash

I have my configuration that uses Scoop in https://gist.github.com/trajano/24f4edccd9a997fad8b4de29ea252cc8

YAML Multi-Line Arrays

Following Works for me and its good from readability point of view when array element values are small:

key: [string1, string2, string3, string4, string5, string6]

Note:snakeyaml implementation used

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

I had the same problem with numpy arrays and the solution is to flatten them:

data = {
    'b': array1.flatten(),
    'a': array2.flatten(),
}

df = pd.DataFrame(data)

Set JavaScript variable = null, or leave undefined?

It depends on the context.

  • "undefined" means this value does not exist. typeof returns "undefined"

  • "null" means this value exists with an empty value. When you use typeof to test for "null", you will see that it's an object. Other case when you serialize "null" value to backend server like asp.net mvc, the server will receive "null", but when you serialize "undefined", the server is unlikely to receive a value.

How to get the process ID to kill a nohup process?

You could try

kill -9 `pgrep [command name]`

How to install python-dateutil on Windows?

Install from the "Unofficial Windows Binaries for Python Extension Packages"

http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-dateutil

Pretty much has every package you would need.

How do I get a list of locked users in an Oracle database?

Found it!

SELECT username, 
       account_status
  FROM dba_users;

Javascript array search and remove string?

Loop through the list in reverse order, and use the .splice method.

var array = ['A', 'B', 'C']; // Test
var search_term = 'B';

for (var i=array.length-1; i>=0; i--) {
    if (array[i] === search_term) {
        array.splice(i, 1);
        // break;       //<-- Uncomment  if only the first term has to be removed
    }
}

The reverse order is important when all occurrences of the search term has to be removed. Otherwise, the counter will increase, and you will skip elements.

When only the first occurrence has to be removed, the following will also work:

var index = array.indexOf(search_term);    // <-- Not supported in <IE9
if (index !== -1) {
    array.splice(index, 1);
}

How do I implement charts in Bootstrap?

Github did this using the HTML canvas element.

This specification defines the 2D Context for the HTML canvas element. The 2D Context provides objects, methods, and properties to draw and manipulate graphics on a canvas drawing surface.

If you use a browser inspector, you see inside every list element a div with a canvas element.

<div class="participation-graph">
   <canvas class="bars" data-color-all="#F5F5F5" data-color-owner="#F5F5F5" data-source="/mxcl/homebrew/graphs/owner_participation" height="80" width="640"></canvas>
</div>

With CSS (z-index, position...) you can put that canvas in the background of a li element or table, in your case.

Do a search about jquery pluggins that fit your requirement.

Hope this pointers help you to achieve that.

Get input type="file" value when it has multiple files selected

The files selected are stored in an array: [input].files

For example, you can access the items

// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

For jQuery-comfortable people, it's similarly easy

// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

How to undo a successful "git cherry-pick"?

To undo your last commit, simply do git reset --hard HEAD~.

Edit: this answer applied to an earlier version of the question that did not mention preserving local changes; the accepted answer from Tim is indeed the correct one. Thanks to qwertzguy for the heads up.

Simple timeout in java

The example 1 will not compile. This version of it compiles and runs. It uses lambda features to abbreviate it.

/*
 * [RollYourOwnTimeouts.java]
 *
 * Summary: How to roll your own timeouts.
 *
 * Copyright: (c) 2016 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2016-06-28 initial version
 */
package com.mindprod.example;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static java.lang.System.*;

/**
 * How to roll your own timeouts.
 * Based on code at http://stackoverflow.com/questions/19456313/simple-timeout-in-java
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2016-06-28 initial version
 * @since 2016-06-28
 */

public class RollYourOwnTimeout
    {

    private static final long MILLIS_TO_WAIT = 10 * 1000L;

    public static void main( final String[] args )
        {
        final ExecutorService executor = Executors.newSingleThreadExecutor();

        // schedule the work
        final Future<String> future = executor.submit( RollYourOwnTimeout::requestDataFromWebsite );

        try
            {
            // where we wait for task to complete
            final String result = future.get( MILLIS_TO_WAIT, TimeUnit.MILLISECONDS );
            out.println( "result: " + result );
            }

        catch ( TimeoutException e )
            {
            err.println( "task timed out" );
            future.cancel( true /* mayInterruptIfRunning */ );
            }

        catch ( InterruptedException e )
            {
            err.println( "task interrupted" );
            }

        catch ( ExecutionException e )
            {
            err.println( "task aborted" );
            }

        executor.shutdownNow();

        }
/**
 * dummy method to read some data from a website
 */
private static String requestDataFromWebsite()
    {
    try
        {
        // force timeout to expire
        Thread.sleep( 14_000L );
        }
    catch ( InterruptedException e )
        {
        }
    return "dummy";
    }

}

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

Docker how to change repository name or rename image?

The accepted answer is great for single renames, but here is a way to rename multiple images that have the same repository all at once (and remove the old images).

If you have old images of the form:

$ docker images
REPOSITORY               TAG                 IMAGE ID            CREATED             SIZE
old_name/image_name_1    latest              abcdefghijk1        5 minutes ago      1.00GB
old_name/image_name_2    latest              abcdefghijk2        5 minutes ago      1.00GB

And you want:

new_name/image_name_1
new_name/image_name_2

Then you can use this (subbing in OLD_REPONAME, NEW_REPONAME, and TAG as appropriate):

OLD_REPONAME='old_name'
NEW_REPONAME='new_name'
TAG='latest'

# extract image name, e.g. "old_name/image_name_1"
for image in $(docker images | awk '{ if( FNR>1 ) { print $1 } }' | grep $OLD_REPONAME)
do \
  OLD_NAME="${image}:${TAG}" && \
  NEW_NAME="${NEW_REPONAME}${image:${#OLD_REPONAME}:${#image}}:${TAG}" && \
  docker image tag $OLD_NAME $NEW_NAME && \
  docker rmi $image:${TAG}  # omit this line if you want to keep the old image
done

What size should apple-touch-icon.png be for iPad and iPhone?

I think this question is about web icons. I've tried giving an icon at 512x512, and on the iPhone 4 simulator it looks great (in the preview) however, when added to the home-screen it's badly pixelated.

On the good side, if you use a larger icon on the iPad (still with my 512x512 test) it does seem to come out in better quality on the iPad. Hopefully the iPhone 4 rendering is a bug.

I've opened a bug about this on radar.

EDIT:

I'm currently using a 114x114 icon in hopes that it'll look good on the iPhone 4 when it is released. If the iPhone 4 still has a bug when it comes out, I'm going to optimize the icon for the iPad (crisp and no resize at 72x72), and then let it scale down for old iPhones.

Print Currency Number Format in PHP

try

echo "$".money_format('%i',$price);

output will be

$1.06

Using bootstrap with bower

The css and js files are located within the package: bootstrap/docs/assets/

UPDATE:

since v3 there is a dist folder in the package that contains all css, js and fonts.


Another option (if you just want to fetch single files) might be: pulldown. Configuration is extremely simple and you can easily add your own files/urls to the list.

Get the Query Executed in Laravel 3/4

Last query print

$queries = \DB::getQueryLog();
$last_query = end($queries);

// Add binding to query
foreach ($last_query['bindings'] as $val) {
        $last_query['query'] = preg_replace('/\?/', "'{$val}'", $last_query['query'], 1);
}
dd($last_query);

How to get the screen width and height in iOS?

The modern answer:

if your app support split view on iPad, this problem becomes a little complicated. You need window's size, not the screen's, which may contain 2 apps. Window's size may also vary while running.

Use app's main window's size:

UIApplication.shared.delegate?.window??.bounds.size ?? .zero

Note: The method above may get wrong value before window becoming key window when starting up. if you only need width, method below is very recommended:

UIApplication.shared.statusBarFrame.width

The old solution using UIScreen.main.bounds will return the device's bounds. If your app running in split view mode, it get the wrong dimensions.

self.view.window in the hottest answer may get wrong size when app contains 2 or more windows and the window have small size.

How to detect when an @Input() value changes in Angular?

Here ngOnChanges will trigger always when your input property changes:

ngOnChanges(changes: SimpleChanges): void {
 console.log(changes.categoryId.currentValue)
}

Can PHP cURL retrieve response headers AND body in a single request?

Curl has a built in option for this, called CURLOPT_HEADERFUNCTION. The value of this option must be the name of a callback function. Curl will pass the header (and the header only!) to this callback function, line-by-line (so the function will be called for each header line, starting from the top of the header section). Your callback function then can do anything with it (and must return the number of bytes of the given line). Here is a tested working code:

function HandleHeaderLine( $curl, $header_line ) {
    echo "<br>YEAH: ".$header_line; // or do whatever
    return strlen($header_line);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "HandleHeaderLine");
$body = curl_exec($ch); 

The above works with everything, different protocols and proxies too, and you dont need to worry about the header size, or set lots of different curl options.

P.S.: To handle the header lines with an object method, do this:

curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$object, 'methodName'))

The default for KeyValuePair

You can create a general (and generic) extension method, like this one:

public static class Extensions
{
    public static bool IsDefault<T>(this T value) where T : struct
    {
        bool isDefault = value.Equals(default(T));

        return isDefault;
    }
}

Usage:

// We have to set explicit default value '0' to avoid build error:
// Use of unassigned local variable 'intValue'
int intValue = 0;
long longValue = 12;
KeyValuePair<String, int> kvp1 = new KeyValuePair<String, int>("string", 11);
KeyValuePair<String, int> kvp2 = new KeyValuePair<String, int>();
List<KeyValuePair<String, int>> kvps = new List<KeyValuePair<String, int>> { kvp1, kvp2 };
KeyValuePair<String, int> kvp3 = kvps.FirstOrDefault(kvp => kvp.Value == 11);
KeyValuePair<String, int> kvp4 = kvps.FirstOrDefault(kvp => kvp.Value == 15);

Console.WriteLine(intValue.IsDefault()); // results 'True'
Console.WriteLine(longValue.IsDefault()); // results 'False'
Console.WriteLine(kvp1.IsDefault()); // results 'False'
Console.WriteLine(kvp2.IsDefault()); // results 'True'
Console.WriteLine(kvp3.IsDefault()); // results 'False'
Console.WriteLine(kvp4.IsDefault()); // results 'True'

How should I have explained the difference between an Interface and an Abstract class?

When I am trying to share behavior between 2 closely related classes, I create an abstract class that holds the common behavior and serves as a parent to both classes.

When I am trying to define a Type, a list of methods that a user of my object can reliably call upon, then I create an interface.

For example, I would never create an abstract class with 1 concrete subclass because abstract classes are about sharing behavior. But I might very well create an interface with only one implementation. The user of my code won't know that there is only one implementation. Indeed, in a future release there may be several implementations, all of which are subclasses of some new abstract class that didn't even exist when I created the interface.

That might have seemed a bit too bookish too (though I have never seen it put that way anywhere that I recall). If the interviewer (or the OP) really wanted more of my personal experience on that, I would have been ready with anecdotes of an interface has evolved out of necessity and visa versa.

One more thing. Java 8 now allows you to put default code into an interface, further blurring the line between interfaces and abstract classes. But from what I have seen, that feature is overused even by the makers of the Java core libraries. That feature was added, and rightly so, to make it possible to extend an interface without creating binary incompatibility. But if you are making a brand new Type by defining an interface, then the interface should be JUST an interface. If you want to also provide common code, then by all means make a helper class (abstract or concrete). Don't be cluttering your interface from the start with functionality that you may want to change.

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

I was looking for the same behavior using jdbi's BindBeanList and found the syntax is exactly the same as Peter Lang's answer above. In case anybody is running into this question, here's my code:

  @SqlUpdate("INSERT INTO table_one (col_one, col_two) VALUES <beans> ON DUPLICATE KEY UPDATE col_one=VALUES(col_one), col_two=VALUES(col_two)")
void insertBeans(@BindBeanList(value = "beans", propertyNames = {"colOne", "colTwo"}) List<Beans> beans);

One key detail to note is that the propertyName you specify within @BindBeanList annotation is not same as the column name you pass into the VALUES() call on update.

Is there a way to specify which pytest tests to run from a file?

Maybe using pytest_collect_file() hook you can parse the content of a .txt o .yaml file where the tests are specify as you want, and return them to the pytest core.

A nice example is shown in the pytest documentation. I think what you are looking for.

404 Not Found The requested URL was not found on this server

change this

Include conf/extra/httpd-vhosts.conf

to

#Include conf/extra/httpd-vhosts.conf

and restart all services

How to stop tracking and ignore changes to a file in Git?

Apply .gitignore to the present/future

This method applies the standard .gitignore behavior, and does not require manually specifying the files that need to be ignored.

Can't use --exclude-from=.gitignore anymore :/ - Here's the updated method:

General advice: start with a clean repo - everything committed, nothing pending in working directory or index, and make a backup!

#commit up-to-date .gitignore (if not already existing)
#this command must be run on each branch
git add .gitignore
git commit -m "Create .gitignore"

#apply standard git ignore behavior only to current index, not working directory (--cached)
#if this command returns nothing, ensure /.git/info/exclude AND/OR .gitignore exist
#this command must be run on each branch
git ls-files -z --ignored --exclude-standard | xargs -0 git rm --cached

#optionally add anything to the index that was previously ignored but now shouldn't be:
git add *

#commit again
#optionally use the --amend flag to merge this commit with the previous one instead of creating 2 commits.

git commit -m "re-applied modified .gitignore"

#other devs who pull after this commit is pushed will see the  newly-.gitignored files DELETED

If you also need to purge the newly-ignored files from the branch's commit history or if you don't want the newly-ignored files to be deleted from future pulls, see this answer.

In .NET, which loop runs faster, 'for' or 'foreach'?

Patrick Smacchia blogged about this last month, with the following conclusions:

  • for loops on List are a bit more than 2 times cheaper than foreach loops on List.
  • Looping on array is around 2 times cheaper than looping on List.
  • As a consequence, looping on array using for is 5 times cheaper than looping on List using foreach (which I believe, is what we all do).

Capture screenshot of active window?

Rectangle bounds = Screen.GetBounds(Point.Empty);
using(Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
    using(Graphics g = Graphics.FromImage(bitmap))
    {
         g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
    }
    bitmap.Save("test.jpg", ImageFormat.Jpeg);
}

for capturing current window use

 Rectangle bounds = this.Bounds;
 using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
 {
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.CopyFromScreen(new Point(bounds.Left,bounds.Top), Point.Empty, bounds.Size);
    }
    bitmap.Save("C://test.jpg", ImageFormat.Jpeg);
 }

Can the Android layout folder contain subfolders?

I just wanted to add onto eskis' fantastic answer for people having trouble. (Note: This will only work and look like separate directories inside the 'project' view, not the 'android' view unfortunately.)

Tested with the following. BuildToolsVersion = 23.0.0 gradle 1.2.3 & 1.3.0

This is how I got mine to work with an already built project.

  1. Copy all of the XML files out of your layout directory, and put them into a directory on the desktop or something for backup.
  2. Delete the entire layout directory (Make sure you backed everything up from step 1!!!)
  3. Right click the res directory and select new > directory.
  4. Name this new directory "layouts". (This can be whatever you want, but it will not be a 'fragment' directory or 'activity' directory, that comes later).
  5. Right click the new "layouts" directory and select new > directory. (This will be the name of the type of XML files you will have in it, for example, 'fragments' and 'activities').
  6. Right click the 'fragment' or 'activities' directory (Note: this doesn't have to be 'fragment' or 'activities' that's just what i'm using as an example) and select new > directory once again and name this directory "layout". (Note: This MUST be named 'layout'!!! very important).
  7. Put the XML files you want inside the new 'layout' directory from the backup you made on your desktop.
  8. Repeat steps 5 - 7 for as many custom directories as you desire.
  9. Once this is complete, go into your modules gradle.build file and create a sourceSets definition like this...(Make sure 'src/main/res/layouts' & 'src/main/res' are always the bottom two!!!! Like I am showing below).

    sourceSets {
        main {
            res.srcDirs =
                    [
                            'src/main/res/layouts/activities',
                            'src/main/res/layouts/fragments',
                            'src/main/res/layouts/content',
                            'src/main/res/layouts',
                            'src/main/res'
                    ]
        }
    }
    
  10. Profit $$$$

But seriously.. this is how I got it to work. Let me know if anyone has any questions.. I can try to help.

Pictures are worth more than words.

Directory Structure

Datatables: Cannot read property 'mData' of undefined

I had a dynamically generated, but badly formed table with a typo. I copied a <td> tag inside another <td> by mistake. My column count matched. I had <thead> and <tbody> tags. Everything matched, except for this little mistake I didn't notice for a while, because my column had a lot of link and image tags in it.

How to use CMAKE_INSTALL_PREFIX

There are two ways to use this variable:

  • passing it as a command line argument just like Job mentioned:

    cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..

  • assigning value to it in CMakeLists.txt:

    SET(CMAKE_INSTALL_PREFIX < install_path >)

    But do remember to place it BEFORE PROJECT(< project_name>) command, otherwise it will not work!

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

Regular expression to detect semi-colon terminated C++ for & while loops

I wouldn't even pay attention to the contents of the parens.

Just match any line that starts with for and ends with semi-colon:

^\t*for.+;$

Unless you've got for statements split over multiple lines, that will work fine?

What range of values can integer types store in C++

The minimum ranges you can rely on are:

  • short int and int: -32,767 to 32,767
  • unsigned short int and unsigned int: 0 to 65,535
  • long int: -2,147,483,647 to 2,147,483,647
  • unsigned long int: 0 to 4,294,967,295

This means that no, long int cannot be relied upon to store any 10 digit number. However, a larger type long long int was introduced to C in C99 and C++ in C++11 (this type is also often supported as an extension by compilers built for older standards that did not include it). The minimum range for this type, if your compiler supports it, is:

  • long long int: -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807
  • unsigned long long int: 0 to 18,446,744,073,709,551,615

So that type will be big enough (again, if you have it available).


A note for those who believe I've made a mistake with these lower bounds - I haven't. The C requirements for the ranges are written to allow for ones' complement or sign-magnitude integer representations, where the lowest representable value and the highest representable value differ only in sign. It is also allowed to have a two's complement representation where the value with sign bit 1 and all value bits 0 is a trap representation rather than a legal value. In other words, int is not required to be able to represent the value -32,768.

How to set default value for form field in Symfony2?

You can set the default for related field in your model class (in mapping definition or set the value yourself).

Furthermore, FormBuilder gives you a chance to set initial values with setData() method. Form builder is passed to the createForm() method of your form class.

Also, check this link: http://symfony.com/doc/current/book/forms.html#using-a-form-without-a-class

How to increase buffer size in Oracle SQL Developer to view all records?

If you are running a script, instead of a statement, you can increase this by selecting Tools/Preferences/Worksheet and increasing "Max Rows to print in a script". The default is 5000, you can change it to any size.

What is the technology behind wechat, whatsapp and other messenger apps?

To my knowledge, Ejabberd (http://www.ejabberd.im/) is the parent, this is XMPP server which provide quite good features of open source, Whatsapp uses some modified version of this, facebook messaging also uses a modified version of this. Some more chat applications likes Samsung's ChatOn, Nimbuzz messenger all use ejabberd based ones and Erlang solutions also have modified version of this ejabberd which they claim to be highly scalable and well tested with more performance improvements and renamed as MongooseIM.

Ejabberd is the server which has most of the featured implemented when compared to other. Since it is build in Erlang it is highly scalable horizontally.

Sublime text 3. How to edit multiple lines?

Use CTRL+D at each line and it will find the matching words and select them then you can use multiple cursors.

You can also use find to find all the occurrences and then it would be multiple cursors too.

How to check if a Docker image with a specific tag exist locally?

Using test

if test ! -z "$(docker images -q <name:tag>)"; then
  echo "Exist"
fi

or in one line

test ! -z "$(docker images -q <name:tag>)" &&  echo exist

Print JSON parsed object?

to Print JSON parsed object just type

console.log( JSON.stringify(data, null, " ") );

and you will get output very clear

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Validate phone number using javascript

^(\(?[0-9]{3}\)?)((\s|\-){1})?[0-9]{3}((\s|\-){1})?[0-9]{4}$

Assuming you are validating US phone numbers, this will do the trick.

First, we allow 0 or 1 open parentheses to start \(?

Then, we allow 3 consecutive digits between 0-9 [0-9]{3}

After, we repeat the first step and allow 0 or 1 closing parentheses \)?

For the second grouping, we start by allowing a space or a hyphen 0 or 1 times ((\s|\-){1})?

This is repeated between the second and third grouping of numbers, and we check for 3 consecutive digits then four consecutive digits to end it. For US phone numbers I think this covers the bases for a lot of different ways that people might format the number, but is restrictive enough that they can't pass an unreasonable string.

How do I install imagemagick with homebrew?

Answering old thread here (and a bit off-topic) because it's what I found when I was searching how to install Image Magick on Mac OS to run on the local webserver. It's not enough to brew install Imagemagick. You have to also PECL install it so the PHP module is loaded.

From this SO answer:

brew install php
brew install imagemagick
brew install pkg-config
pecl install imagick

And you may need to sudo apachectl restart. Then check your phpinfo() within a simple php script running on your web server.

If it's still not there, you probably have an issue with running multiple versions of PHP on the same Mac (one through the command line, one through your web server). It's beyond the scope of this answer to resolve that issue, but there are some good options out there.

Compare string with all values in list

for word in d:
    if d in paid[j]:
         do_something()

will try all the words in the list d and check if they can be found in the string paid[j].

This is not very efficient since paid[j] has to be scanned again for each word in d. You could also use two sets, one composed of the words in the sentence, one of your list, and then look at the intersection of the sets.

sentence = "words don't come easy"
d = ["come", "together", "easy", "does", "it"]

s1 = set(sentence.split())
s2 = set(d)

print (s1.intersection(s2))

Output:

{'come', 'easy'}

Vue - Deep watching an array of objects and calculating the change?

Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.

The best way is to create a person-component and watch every person separately inside its own component, as shown below:

<person-component :person="person" v-for="person in people"></person-component>

Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit to send an event upwards, containing the id of modified person.

_x000D_
_x000D_
Vue.component('person-component', {_x000D_
    props: ["person"],_x000D_
    template: `_x000D_
        <div class="person">_x000D_
            {{person.name}}_x000D_
            <input type='text' v-model='person.age'/>_x000D_
        </div>`,_x000D_
    watch: {_x000D_
        person: {_x000D_
            handler: function(newValue) {_x000D_
                console.log("Person with ID:" + newValue.id + " modified")_x000D_
                console.log("New age: " + newValue.age)_x000D_
            },_x000D_
            deep: true_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
    el: '#app',_x000D_
    data: {_x000D_
        people: [_x000D_
          {id: 0, name: 'Bob', age: 27},_x000D_
          {id: 1, name: 'Frank', age: 32},_x000D_
          {id: 2, name: 'Joe', age: 38}_x000D_
        ]_x000D_
    }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<body>_x000D_
    <div id="app">_x000D_
        <p>List of people:</p>_x000D_
        <person-component :person="person" v-for="person in people"></person-component>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Handling exceptions from Java ExecutorService tasks

This works

  • It is derived from SingleThreadExecutor, but you can adapt it easily
  • Java 8 lamdas code, but easy to fix

It will create a Executor with a single thread, that can get a lot of tasks; and will wait for the current one to end execution to begin with the next

In case of uncaugth error or exception the uncaughtExceptionHandler will catch it

public final class SingleThreadExecutorWithExceptions {

    public static ExecutorService newSingleThreadExecutorWithExceptions(final Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {

        ThreadFactory factory = (Runnable runnable)  -> {
            final Thread newThread = new Thread(runnable, "SingleThreadExecutorWithExceptions");
            newThread.setUncaughtExceptionHandler( (final Thread caugthThread,final Throwable throwable) -> {
                uncaughtExceptionHandler.uncaughtException(caugthThread, throwable);
            });
            return newThread;
        };
        return new FinalizableDelegatedExecutorService
                (new ThreadPoolExecutor(1, 1,
                        0L, TimeUnit.MILLISECONDS,
                        new LinkedBlockingQueue(),
                        factory){


                    protected void afterExecute(Runnable runnable, Throwable throwable) {
                        super.afterExecute(runnable, throwable);
                        if (throwable == null && runnable instanceof Future) {
                            try {
                                Future future = (Future) runnable;
                                if (future.isDone()) {
                                    future.get();
                                }
                            } catch (CancellationException ce) {
                                throwable = ce;
                            } catch (ExecutionException ee) {
                                throwable = ee.getCause();
                            } catch (InterruptedException ie) {
                                Thread.currentThread().interrupt(); // ignore/reset
                            }
                        }
                        if (throwable != null) {
                            uncaughtExceptionHandler.uncaughtException(Thread.currentThread(),throwable);
                        }
                    }
                });
    }



    private static class FinalizableDelegatedExecutorService
            extends DelegatedExecutorService {
        FinalizableDelegatedExecutorService(ExecutorService executor) {
            super(executor);
        }
        protected void finalize() {
            super.shutdown();
        }
    }

    /**
     * A wrapper class that exposes only the ExecutorService methods
     * of an ExecutorService implementation.
     */
    private static class DelegatedExecutorService extends AbstractExecutorService {
        private final ExecutorService e;
        DelegatedExecutorService(ExecutorService executor) { e = executor; }
        public void execute(Runnable command) { e.execute(command); }
        public void shutdown() { e.shutdown(); }
        public List shutdownNow() { return e.shutdownNow(); }
        public boolean isShutdown() { return e.isShutdown(); }
        public boolean isTerminated() { return e.isTerminated(); }
        public boolean awaitTermination(long timeout, TimeUnit unit)
                throws InterruptedException {
            return e.awaitTermination(timeout, unit);
        }
        public Future submit(Runnable task) {
            return e.submit(task);
        }
        public  Future submit(Callable task) {
            return e.submit(task);
        }
        public  Future submit(Runnable task, T result) {
            return e.submit(task, result);
        }
        public  List> invokeAll(Collection> tasks)
                throws InterruptedException {
            return e.invokeAll(tasks);
        }
        public  List> invokeAll(Collection> tasks,
                                             long timeout, TimeUnit unit)
                throws InterruptedException {
            return e.invokeAll(tasks, timeout, unit);
        }
        public  T invokeAny(Collection> tasks)
                throws InterruptedException, ExecutionException {
            return e.invokeAny(tasks);
        }
        public  T invokeAny(Collection> tasks,
                               long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return e.invokeAny(tasks, timeout, unit);
        }
    }



    private SingleThreadExecutorWithExceptions() {}
}

is vs typeof

This should answer that question, and then some.

The second line, if (obj.GetType() == typeof(ClassA)) {}, is faster, for those that don't want to read the article.

(Be aware that they don't do the same thing)

Google Maps API warning: NoApiKeys

Creating and using the key is the way to go. The usage is free until your application reaches 25.000 calls per day on 90 consecutive days.

BTW.: In the google Developer documentation it says you shall add the api key as option {key:yourKey} when calling the API to create new instances. This however doesn't shush the console warning. You have to add the key as a parameter when including the api.

<script src="https://maps.googleapis.com/maps/api/js?key=yourKEYhere"></script>

Get the key here: GoogleApiKey Generation site

Install psycopg2 on Ubuntu

Use

sudo apt-get install python3-psycopg2

for Python3 )

Store query result in a variable using in PL/pgSQL

As long as you are assigning a single variable, you can also use plain assignment in a plpgsql function:

name := (SELECT t.name from test_table t where t.id = x);

Or use SELECT INTO like @mu already provided.

This works, too:

name := t.name from test_table t where t.id = x;

But better use one of the first two, clearer methods, as @Pavel commented.

I shortened the syntax with a table alias additionally.
Update: I removed my code example and suggest to use IF EXISTS() instead like provided by @Pavel.

NVIDIA NVML Driver/library version mismatch

First I installed the Nvidia driver.

Next I installed cuda.

Ater that I got the "Driver/library version mismatch" ERROR but I could see the cuda version so I purged the Nvidia driver and reinstall it.

Then it worked correctly.

How to format a string as a telephone number in C#

If you can get i["MyPhone"] as a long, you can use the long.ToString() method to format it:

Convert.ToLong(i["MyPhone"]).ToString("###-###-####");

See the MSDN page on Numeric Format Strings.

Be careful to use long rather than int: int could overflow.

How to remove decimal part from a number in C#

Because the numbers after point is only zero, the best solution is to use the Math.Round(MyNumber)

How to delete multiple files at once in Bash on Linux?

Bash supports all sorts of wildcards and expansions.

Your exact case would be handled by brace expansion, like so:

$ rm -rf abc.log.2012-03-{14,27,28}

The above would expand to a single command with all three arguments, and be equivalent to typing:

$ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28

It's important to note that this expansion is done by the shell, before rm is even loaded.

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

You can skip the Performance counter check in the setup altogether:

setup.exe /ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck

How to compress a String in Java?

You don't see any compression happening for your String, As you atleast require couple of hundred bytes to have real compression using GZIPOutputStream or ZIPOutputStream. Your String is too small.(I don't understand why you require compression for same)

Check Conclusion from this article:

The article also shows how to compress and decompress data on the fly in order to reduce network traffic and improve the performance of your client/server applications. Compressing data on the fly, however, improves the performance of client/server applications only when the objects being compressed are more than a couple of hundred bytes. You would not be able to observe improvement in performance if the objects being compressed and transferred are simple String objects, for example.

JavaScript: Object Rename Key

I'd do something like this:

function renameKeys(dict, keyMap) {
  return _.reduce(dict, function(newDict, val, oldKey) {
    var newKey = keyMap[oldKey] || oldKey
    newDict[newKey] = val 
    return newDict
  }, {})
}

Toggle visibility property of div

To clean this up a little bit and maintain a single line of code (like you would with a toggle()), you can use a ternary operator so your code winds up looking like this (also using jQuery):

$('#video-over').css('visibility', $('#video-over').css('visibility') == 'hidden' ? 'visible' : 'hidden');

How should you diagnose the error SEHException - External component has thrown an exception

Yes. This error is a structured exception that wasn't mapped into a .NET error. It's probably your DataGrid mapping throwing a native exception that was uncaught.

You can tell what exception is occurring by looking at the ExternalException.ErrorCode property. I'd check your stack trace, and if it's tied to the DevExpress grid, report the problem to them.

Getting "Cannot call a class as a function" in my React Project

Two things you can check is,

class Slider extends React.Component {
    // Your React Code
}

Slider.propTypes = {
    // accessibility: PropTypes.bool,
}
  • Make sure that you extends React.Component
  • Use propTypes instead of prototype (as per IDE intellisense)

What is the functionality of setSoTimeout and how it works?

This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketTest extends Thread {
  private ServerSocket serverSocket;

  public SocketTest() throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);
  }

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        client.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String[] args) {
    try {
      Thread t = new SocketTest();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Android: Background Image Size (in Pixel) which Support All Devices

I looked around the internet for correct dimensions for these densities for square images, but couldn't find anything reliable.

If it's any consolation, referring to Veerababu Medisetti's answer I used these dimensions for SQUARES :)

xxxhdpi: 1280x1280 px
xxhdpi: 960x960 px
xhdpi: 640x640 px
hdpi: 480x480 px
mdpi: 320x320 px
ldpi: 240x240 px

CASE WHEN statement for ORDER BY clause

declare @OrderByCmd  nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'    
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd 

Filtering JSON array using jQuery grep()

_x000D_
_x000D_
var data = {_x000D_
  "items": [{_x000D_
    "id": 1,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 2,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 3,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 4,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 5,_x000D_
    "category": "cat1"_x000D_
  }]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
_x000D_
_x000D_

The $.grep() method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.