Programs & Examples On #Cubic

Playing m3u8 Files with HTML Video Tag

<html>
<body>
    <video width="600" height="400" controls>
        <source src="index.m3u8" type="application/x-mpegURL">
    </video>
</body> 

Stream HLS or m3u8 files using above code. it works for desktop: ms edge browser (not working with desktop chrome) and mobile: chrome,opera mini browser.

To play on all browser use flash based media player. media player to support all browser

Resize image with javascript canvas (smoothly)

Based on K3N answer, I rewrite code generally for anyone wants

var oc = document.createElement('canvas'), octx = oc.getContext('2d');
    oc.width = img.width;
    oc.height = img.height;
    octx.drawImage(img, 0, 0);
    while (oc.width * 0.5 > width) {
       oc.width *= 0.5;
       oc.height *= 0.5;
       octx.drawImage(oc, 0, 0, oc.width, oc.height);
    }
    oc.width = width;
    oc.height = oc.width * img.height / img.width;
    octx.drawImage(img, 0, 0, oc.width, oc.height);

UPDATE JSFIDDLE DEMO

Here is my ONLINE DEMO

How to make blinking/flashing text with CSS 3

<style>
    .class1{
        height:100px;
        line-height:100px;
        color:white;
        font-family:Bauhaus 93;
        padding:25px;
        background-color:#2a9fd4;
        border:outset blue;
        border-radius:25px;
        box-shadow:10px 10px green;
        font-size:45px;
    }
     .class2{
        height:100px;
        line-height:100px;
        color:white;
        font-family:Bauhaus 93;
        padding:25px;
        background-color:green;
        border:outset blue;
        border-radius:25px;
        box-shadow:10px 10px green;
        font-size:65px;
    }
</style>
<script src="jquery-3.js"></script>
<script>
    $(document).ready(function () {
        $('#div1').addClass('class1');
        var flag = true;

        function blink() {
            if(flag)
            {
                $("#div1").addClass('class2');
                flag = false;
            }
            else
            { 
                if ($('#div1').hasClass('class2'))
                    $('#div1').removeClass('class2').addClass('class1');
                flag = true;
            }
        }
        window.setInterval(blink, 1000);
    });
</script>

A Generic error occurred in GDI+ in Bitmap.Save method

I encountered this error while trying to convert Tiff images to Jpeg. For me the issue stemmed from the tiff dimensions being too large. Anything up to around 62000 pixels was fine, anything above this size produced the error.

Quadratic and cubic regression in Excel

I know that this question is a little old, but I thought that I would provide an alternative which, in my opinion, might be a little easier. If you're willing to add "temporary" columns to a data set, you can use Excel's Analysis ToolPak?Data Analysis?Regression. The secret to doing a quadratic or a cubic regression analysis is defining the Input X Range:.

If you're doing a simple linear regression, all you need are 2 columns, X & Y. If you're doing a quadratic, you'll need X_1, X_2, & Y where X_1 is the x variable and X_2 is x^2; likewise, if you're doing a cubic, you'll need X_1, X_2, X_3, & Y where X_1 is the x variable, X_2 is x^2 and X_3 is x^3. Notice how the Input X Range is from A1 to B22, spanning 2 columns.

Input for Quadratic Regression Analysis in Excel

The following image the output of the regression analysis. I've highlighted the common outputs, including the R-Squared values and all the coefficients.

Coefficients of Quadratic Regression Analysis in Excel

Image scaling causes poor quality in firefox/internet explorer but not chrome

One way to "normalize" the appearance in the different browsers is using your "server-side" to resize the image. An example using a C# controller:

public ActionResult ResizeImage(string imageUrl, int width)
{
    WebImage wImage = new WebImage(imageUrl);
    wImage = WebImageExtension.Resize(wImage, width);
    return File(wImage.GetBytes(), "image/png");
}

where WebImage is a class in System.Web.Helpers.

WebImageExtension is defined below:

using System.IO;
using System.Web.Helpers;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Collections.Generic;

public static class WebImageExtension
{
    private static readonly IDictionary<string, ImageFormat> TransparencyFormats =
        new Dictionary<string, ImageFormat>(StringComparer.OrdinalIgnoreCase) { { "png", ImageFormat.Png }, { "gif", ImageFormat.Gif } };

    public static WebImage Resize(this WebImage image, int width)
    {
        double aspectRatio = (double)image.Width / image.Height;
        var height = Convert.ToInt32(width / aspectRatio);

        ImageFormat format;

        if (!TransparencyFormats.TryGetValue(image.ImageFormat.ToLower(), out format))
        {
            return image.Resize(width, height);
        }

        using (Image resizedImage = new Bitmap(width, height))
        {
            using (var source = new Bitmap(new MemoryStream(image.GetBytes())))
            {
                using (Graphics g = Graphics.FromImage(resizedImage))
                {
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.DrawImage(source, 0, 0, width, height);
                }
            }

            using (var ms = new MemoryStream())
            {
                resizedImage.Save(ms, format);
                return new WebImage(ms.ToArray());
            }
        }
    }
}

note the option InterpolationMode.HighQualityBicubic. This is the method used by Chrome.

Now you need publish in a web page. Lets going use razor:

<img src="@Url.Action("ResizeImage", "Controller", new { urlImage = "<url_image>", width = 35 })" />

And this worked very fine to me!

Ideally will be better to save the image beforehand in diferent widths, using this resize algorithm, to avoid the controller process in every image load.

(Sorry for my poor english, I'm brazilian...)

Resizing an image in an HTML5 canvas

I just ran a page of side by sides comparisons and unless something has changed recently, I could see no better downsizing (scaling) using canvas vs. simple css. I tested in FF6 Mac OSX 10.7. Still slightly soft vs. the original.

I did however stumble upon something that did make a huge difference and that was using image filters in browsers that support canvas. You can actually manipulate images much like you can in Photoshop with blur, sharpen, saturation, ripple, grayscale, etc.

I then found an awesome jQuery plug-in which makes application of these filters a snap: http://codecanyon.net/item/jsmanipulate-jquery-image-manipulation-plugin/428234

I simply apply the sharpen filter right after resizing the image which should give you the desired effect. I didn't even have to use a canvas element.

c# Image resizing to different size while preserving aspect ratio

I use the following method to calculate the desired image size:

using System.Drawing;
public static Size ResizeKeepAspect(this Size src, int maxWidth, int maxHeight, bool enlarge = false)
{
    maxWidth = enlarge ? maxWidth : Math.Min(maxWidth, src.Width);
    maxHeight = enlarge ? maxHeight : Math.Min(maxHeight, src.Height);

    decimal rnd = Math.Min(maxWidth / (decimal)src.Width, maxHeight / (decimal)src.Height);
    return new Size((int)Math.Round(src.Width * rnd), (int)Math.Round(src.Height * rnd));
}

This puts the problem of aspect ratio and dimensions in a separate method.

Difference between CR LF, LF and CR line break types?

Systems based on ASCII or a compatible character set use either LF (Line feed, 0x0A, 10 in decimal) or CR (Carriage return, 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A); These characters are based on printer commands: The line feed indicated that one line of paper should feed out of the printer, and a carriage return indicated that the printer carriage should return to the beginning of the current line.

Here is the details.

Hive: Filtering Data between Specified Dates when Date is a String

The great thing about yyyy-mm-dd date format is that there is no need to extract month() and year(), you can do comparisons directly on strings:

SELECT *
  FROM your_table
  WHERE your_date_column >= '2010-09-01' AND your_date_column <= '2013-08-31';

What is the equivalent of Java static methods in Kotlin?

For Android using a string from a single activity to all the necessary activity. Just like static in java

public final static String TEA_NAME = "TEA_NAME";

Equivalent approach in Kotlin:

class MainActivity : AppCompatActivity() {
    companion object {
        const val TEA_NAME = "TEA_NAME"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Another activity where value is needed:

val teaName = MainActivity.TEA_NAME

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

I had similar issue with <input type="range" /> and I solved it with

-webkit-tap-highlight-color: transparent;

_x000D_
_x000D_
input[type="range"]{
  -webkit-tap-highlight-color: transparent;
}
_x000D_
 <input type="range" id="volume" name="demo"
         min="0" max="11">
  <label for="volume">Demo</label>
_x000D_
_x000D_
_x000D_

HTTP Status 504

I have had another issue giving me a 504. It's pretty far out but I'll write it up here for googlers and posterity...

I have a client calling an IIS hosted webservice hosted in another domain (Active Directory). There is not full trust between the client domain and the domain where the web services is hosted. One of the many challenges with the selective trust between these two domains is that Kerberos does not work when calling from one to the other.

In my case I was trying to call a service in another domain where I found out that a SPN was registered. Like this : http/myurl.test.local (just an example)

This forces the call to use Kerberos instead of letting it fall back to NTLM and this gave me a 405 back from the calling server.

After removing the spn and allowing the call to fall back to NTLM, it works fine.

As I said ... this is not something you are likely to run into, as most organizations do not venture into having such a selective trusts between two domains ... But it gives a 504 and caused me a few (more) gray hairs.

How to make FileFilter in java?

Here you will find some working examples. This is also a good example of FileFilter used in JFileChooser.

The basics are, you need to override FileFilter class and write your custom code in its accpet method. The accept method in above example is doing filtration based on file types:

public boolean accept(File file) {
    if (file.isDirectory()) {
      return true;
    } else {
      String path = file.getAbsolutePath().toLowerCase();
      for (int i = 0, n = extensions.length; i < n; i++) {
        String extension = extensions[i];
        if ((path.endsWith(extension) && (path.charAt(path.length() 
                  - extension.length() - 1)) == '.')) {
          return true;
        }
      }
    }
    return false;
}

Or more simpler to use is FileNameFilter which has accept method with filename as argument, so you don't need to get it manually.

C# - Substring: index and length must refer to a location within the string

How about something like this :

string url = "http://www.example.com/aaa/bbb.jpg";
Uri uri = new Uri(url);
string path_Query = uri.PathAndQuery;
string extension =  Path.GetExtension(path_Query);

path_Query = path_Query.Replace(extension, string.Empty);// This will remove extension

CSS table column autowidth

If you want to make sure that last row does not wrap and thus size the way you want it, have a look at

td {
 white-space: nowrap;
}

Pause in Python

import pdb
pdb.debug()

This is used to debug the script. Should be useful to break also.

Changing the selected option of an HTML Select element

I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.

Simplest code that worked is below:

var newValue1 = 'Mango'

var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;

Hope that helps someone. Best of luck.
Up vote if this helped you.

Setting up and using Meld as your git difftool and mergetool

While the other answer is correct, here's the fastest way to just go ahead and configure Meld as your visual diff tool. Just copy/paste this:

git config --global diff.tool meld
git config --global difftool.prompt false

Now run git difftool in a directory and Meld will be launched for each different file.

Side note: Meld is surprisingly slow at comparing CSV files, and no Linux diff tool I've found is faster than this Windows tool called Compare It! (last updated in 2010).

How do I compile a .c file on my Mac?

Use the gcc compiler. This assumes that you have the developer tools installed.

What is a StackOverflowError?

Here is an example of a recursive algorithm for reversing a singly linked list. On a laptop with the following spec (4G memory, Intel Core i5 2.3GHz CPU, 64 bit Windows 7), this function will run into StackOverflow error for a linked list of size close to 10,000.

My point is that we should use recursion judiciously, always taking into account of the scale of the system. Often recursion can be converted to iterative program, which scales better. (One iterative version of the same algorithm is given at the bottom of the page, it reverses a singly linked list of size 1 million in 9 milliseconds.)

    private static LinkedListNode doReverseRecursively(LinkedListNode x, LinkedListNode first){

    LinkedListNode second = first.next;

    first.next = x;

    if(second != null){
        return doReverseRecursively(first, second);
    }else{
        return first;
    }
}

public static LinkedListNode reverseRecursively(LinkedListNode head){
    return doReverseRecursively(null, head);
}

Iterative Version of the Same Algorithm:

    public static LinkedListNode reverseIteratively(LinkedListNode head){
    return doReverseIteratively(null, head);
}   

private static LinkedListNode doReverseIteratively(LinkedListNode x, LinkedListNode first) {

    while (first != null) {
        LinkedListNode second = first.next;
        first.next = x;
        x = first;

        if (second == null) {
            break;
        } else {
            first = second;
        }
    }
    return first;
}


public static LinkedListNode reverseIteratively(LinkedListNode head){
    return doReverseIteratively(null, head);
}

Adding an HTTP Header to the request in a servlet filter

as https://stackoverflow.com/users/89391/miku pointed out this would be a complete ServletFilter example that uses the code that also works for Jersey to add the remote_addr header.

package com.bitplan.smartCRM.web;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 
 * @author wf
 * 
 */
public class RemoteAddrFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);
        String remote_addr = request.getRemoteAddr();
        requestWrapper.addHeader("remote_addr", remote_addr);
        chain.doFilter(requestWrapper, response); // Goes to default servlet.
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    // https://stackoverflow.com/questions/2811769/adding-an-http-header-to-the-request-in-a-servlet-filter
    // http://sandeepmore.com/blog/2010/06/12/modifying-http-headers-using-java/
    // http://bijubnair.blogspot.de/2008/12/adding-header-information-to-existing.html
    /**
     * allow adding additional header entries to a request
     * 
     * @author wf
     * 
     */
    public class HeaderMapRequestWrapper extends HttpServletRequestWrapper {
        /**
         * construct a wrapper for this request
         * 
         * @param request
         */
        public HeaderMapRequestWrapper(HttpServletRequest request) {
            super(request);
        }

        private Map<String, String> headerMap = new HashMap<String, String>();

        /**
         * add a header with given name and value
         * 
         * @param name
         * @param value
         */
        public void addHeader(String name, String value) {
            headerMap.put(name, value);
        }

        @Override
        public String getHeader(String name) {
            String headerValue = super.getHeader(name);
            if (headerMap.containsKey(name)) {
                headerValue = headerMap.get(name);
            }
            return headerValue;
        }

        /**
         * get the Header names
         */
        @Override
        public Enumeration<String> getHeaderNames() {
            List<String> names = Collections.list(super.getHeaderNames());
            for (String name : headerMap.keySet()) {
                names.add(name);
            }
            return Collections.enumeration(names);
        }

        @Override
        public Enumeration<String> getHeaders(String name) {
            List<String> values = Collections.list(super.getHeaders(name));
            if (headerMap.containsKey(name)) {
                values.add(headerMap.get(name));
            }
            return Collections.enumeration(values);
        }

    }

}

web.xml snippet:

<!--  first filter adds remote addr header -->
<filter>
    <filter-name>remoteAddrfilter</filter-name>
    <filter-class>com.bitplan.smartCRM.web.RemoteAddrFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>remoteAddrfilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

CALL command vs. START with /WAIT option

There is a useful difference between call and start /wait when calling regsvr32.exe /s for example, also referenced by Gary in in his answer to how-do-i-get-the-application-exit-code-from-a-windows-command-line

call regsvr32.exe /s broken.dll
echo %errorlevel%

will always return 0 but

start /wait regsvr32.exe /s broken.dll
echo %errorlevel%

will return the error level from regsvr32.exe

How to get screen dimensions as pixels in Android

Need to say, that if you are not in Activity, but in View (or have variable of View type in your scope), there is not need to use WINDOW_SERVICE. Then you can use at least two ways.

First:

DisplayMetrics dm = yourView.getContext().getResources().getDisplayMetrics();

Second:

DisplayMetrics dm = new DisplayMetrics();
yourView.getDisplay().getMetrics(dm);

All this methods we call here is not deprecated.

PHP split alternative?

If you want to split a string into words, you can use explode() or str_word_count().

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

I was having the same problem while importing the certificate in local keystore. Whenever i issue the keytool command i got the following error.

Certificate was added to keystore keytool error: java.io.FileNotFoundException: C:\Program Files\Java\jdk1.8.0_151\jre\lib\security (Access is denied)

Following solution work for me.

1) make sure you are running command prompt in Rus as Administrator mode

2) Change your current directory to %JAVA_HOME%\jre\lib\security

3) then Issue the below command

keytool -import -alias "mycertificatedemo" -file "C:\Users\name\Downloads\abc.crt" -keystore cacerts

3) give the password changeit

4) enter y

5) you will see the following message on successful "Certificate was added to keystore"

Make sure you are giving the "cacerts" only in -keystore param value , as i was giving the full path like "C**:\Program Files\Java\jdk1.8.0_151\jre\lib\security**".

Hope this will work

How to store a dataframe using Pandas

You can use feather format file. It is extremely fast.

df.to_feather('filename.ft')

How do you run a crontab in Cygwin on Windows?

Just wanted to add that the options to cron seem to have changed. Need to pass -n rather than -D.

cygrunsrv -I cron -p /usr/sbin/cron -a -n

combining results of two select statements

Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:

WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
    SELECT tableA.Id, COUNT(tableC.Id)
    FROM tableC
        RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
    GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
                     CompanyImageUrl,NumberOfUsers) AS (
    SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
        tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
    FROM tableA
        INNER JOIN tableB ON tableB.Id = tableA.Owner
        RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
    GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
    ,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
    INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id

After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

You should just install python 3.6. I tried it and it worked. Just install that version of python and just do the normal download process (pip install pyaudio).

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

There are multiple ways how to present a timespan in the database.

time

This datatype is supported since SQL Server 2008 and is the prefered way to store a TimeSpan. There is no mapping needed. It also works well with SQL code.

public TimeSpan ValidityPeriod { get; set; }

However, as stated in the original question, this datatype is limited to 24 hours.

datetimeoffset

The datetimeoffset datatype maps directly to System.DateTimeOffset. It's used to express the offset between a datetime/datetime2 to UTC, but you can also use it for TimeSpan.

However, since the datatype suggests a very specific semantic, so you should also consider other options.

datetime / datetime2

One approach might be to use the datetime or datetime2 types. This is best in scenarios where you need to process the values in the database directly, ie. for views, stored procedures, or reports. The drawback is that you need to substract the value DateTime(1900,01,01,00,00,00) from the date to get back the timespan in your business logic.

public DateTime ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return ValidityPeriod - DateTime(1900,01,01,00,00,00); }
    set { ValidityPeriod = DateTime(1900,01,01,00,00,00) + value; }
}

bigint

Another approach might be to convert the TimeSpan into ticks and use the bigint datatype. However, this approach has the drawback that it's cumbersome to use in SQL queries.

public long ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return TimeSpan.FromTicks(ValidityPeriod); }
    set { ValidityPeriod = value.Ticks; }
}

varchar(N)

This is best for cases where the value should be readable by humans. You might also use this format in SQL queries by utilizing the CONVERT(datetime, ValidityPeriod) function. Dependent on the required precision, you will need between 8 and 25 characters.

public string ValidityPeriod { get; set; }

[NotMapped]
public TimeSpan ValidityPeriodTimeSpan
{
    get { return TimeSpan.Parse(ValidityPeriod); }
    set { ValidityPeriod = value.ToString("HH:mm:ss"); }
}

Bonus: Period and Duration

Using a string, you can also store NodaTime datatypes, especially Duration and Period. The first is basically the same as a TimeSpan, while the later respects that some days and months are longer or shorter than others (ie. January has 31 days and February has 28 or 29; some days are longer or shorter because of daylight saving time). In such cases, using a TimeSpan is the wrong choice.

You can use this code to convert Periods:

using NodaTime;
using NodaTime.Serialization.JsonNet;

internal static class PeriodExtensions
{
    public static Period ToPeriod(this string input)
    {
        var js = JsonSerializer.Create(new JsonSerializerSettings());
        js.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
        var quoted = string.Concat(@"""", input, @"""");
        return js.Deserialize<Period>(new JsonTextReader(new StringReader(quoted)));
    }
}

And then use it like

public string ValidityPeriod { get; set; }

[NotMapped]
public Period ValidityPeriodPeriod
{
    get => ValidityPeriod.ToPeriod();
    set => ValidityPeriod = value.ToString();
}

I really like NodaTime and it often saves me from tricky bugs and lots of headache. The drawback here is that you really can't use it in SQL queries and need to do calculations in-memory.

CLR User-Defined Type

You also have the option to use a custom datatype and support a custom TimeSpan class directly. See CLR User-Defined Types for details.

The drawback here is that the datatype might not behave well with SQL Reports. Also, some versions of SQL Server (Azure, Linux, Data Warehouse) are not supported.

Value Conversions

Starting with EntityFramework Core 2.1, you have the option to use Value Conversions.

However, when using this, EF will not be able to convert many queries into SQL, causing queries to run in-memory; potentially transfering lots and lots of data to your application.

So at least for now, it might be better not to use it, and just map the query result with Automapper.

Making a triangle shape using xml definitions?

Using vector drawable:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
   android:width="24dp"
   android:height="24dp"
   android:viewportWidth="24.0"
   android:viewportHeight="24.0">
   <path
        android:pathData="M0,0 L24,0 L0,24 z"
        android:strokeColor="@color/color"
        android:fillColor="@color/color"/>
</vector>

enter image description here

ZIP Code (US Postal Code) validation

Javascript Regex Literal:

US Zip Codes: /(^\d{5}$)|(^\d{5}-\d{4}$)/

var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210");

Some countries use Postal Codes, which would fail this pattern.

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

Eclipse - Failed to create the java virtual machine

It works for me after removing -XX:+UseParallelOldGC option from file.

Android dependency has different version for the compile and runtime

I resolved it by following what Eddi mentioned above,

 resolutionStrategy.eachDependency { details ->
            if (details.requested.group == 'com.android.support'
                    && !details.requested.name.contains('multidex') ) {
                details.useVersion "26.1.0"
            }
        }

How can I find out the current route in Rails?

You can see all routes via rake:routes (this might help you).

Flask-SQLalchemy update a row's information

Retrieve an object using the tutorial shown in the Flask-SQLAlchemy documentation. Once you have the entity that you want to change, change the entity itself. Then, db.session.commit().

For example:

admin = User.query.filter_by(username='admin').first()
admin.email = '[email protected]'
db.session.commit()

user = User.query.get(5)
user.name = 'New Name'
db.session.commit()

Flask-SQLAlchemy is based on SQLAlchemy, so be sure to check out the SQLAlchemy Docs as well.

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

It happen if there are two more ContextLoaderListener exist in your project.

For ex: in my case 2 ContextLoaderListener was exist using

  1. java configuration
  2. web.xml

So, remove any one ContextLoaderListener from your project and run your application.

How to find all positions of the maximum value in a list?

Just one line:

idx = max(range(len(a)), key = lambda i: a[i])

Regex pattern to match at least 1 number and 1 character in a string

If you need the digit to be at the end of any word, this worked for me:

/\b([a-zA-Z]+[0-9]+)\b/g
  • \b word boundary
  • [a-zA-Z] any letter
  • [0-9] any number
  • "+" unlimited search (show all results)

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

Convert object to JSON in Android

Most people are using gson : check this

Gson gson = new Gson();
String json = gson.toJson(myObj);

how to check if a form is valid programmatically using jQuery Validation Plugin

For a group of inputs you can use an improved version based in @mikemaccana's answer

$.fn.isValid = function(){
    var validate = true;
    this.each(function(){
        if(this.checkValidity()==false){
            validate = false;
        }
    });
};

now you can use this to verify if the form is valid:

if(!$(".form-control").isValid){
    return;
}

You could use the same technique to get all the error messages:

$.fn.getVelidationMessage = function(){
    var message = "";
    var name = "";
    this.each(function(){
        if(this.checkValidity()==false){
            name = ($( "label[for=" + this.id + "] ").html() || this.placeholder || this.name || this.id);
            message = message + name +":"+ (this.validationMessage || 'Invalid value.')+"\n<br>";
        }
    })
    return message;
}

"Cannot instantiate the type..."

You are trying to instantiate an interface, you need to give the concrete class that you want to use i.e. Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();.

Why does Lua have no "continue" statement?

Lua is lightweight scripting language which want to smaller as possible. For example, many unary operation such as pre/post increment is not available

Instead of continue, you can use goto like

arr = {1,2,3,45,6,7,8}
for key,val in ipairs(arr) do
  if val > 6 then
     goto skip_to_next
  end
     # perform some calculation
  ::skip_to_next::
end

C# - How to convert string to char?

char[] myChar = theString.ToCharArray();

Set environment variables from file of key/value pairs

I came across this thread when I was trying reuse Docker --env-files in a shell. Their format is not bash compatible but it is simple: name=value, no quoting, no substitution. They also ignore blank lines and # comments.

I couldn't quite get it posix compatible, but here's one that should work in bash-like shells (tested in zsh on OSX 10.12.5 and bash on Ubuntu 14.04):

while read -r l; do export "$(sed 's/=.*$//' <<<$l)"="$(sed -E 's/^[^=]+=//' <<<$l)"; done < <(grep -E -v '^\s*(#|$)' your-env-file)

It will not handle three cases in the example from the docs linked above:

  • bash: export: `123qwe=bar': not a valid identifier
  • bash: export: `org.spring.config=something': not a valid identifier
  • and it will not handle the passthrough syntax (a bare FOO)

Java code To convert byte to Hexadecimal

The fastest way i've yet found to do this is the following:

private static final String    HEXES    = "0123456789ABCDEF";

static String getHex(byte[] raw) {
    final StringBuilder hex = new StringBuilder(2 * raw.length);
    for (final byte b : raw) {
        hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
    }
    return hex.toString();
}

It's ~ 50x faster than String.format. if you want to test it:

public class MyTest{
    private static final String    HEXES        = "0123456789ABCDEF";

    @Test
    public void test_get_hex() {
        byte[] raw = {
            (byte) 0xd0, (byte) 0x0b, (byte) 0x01, (byte) 0x2a, (byte) 0x63,
            (byte) 0x78, (byte) 0x01, (byte) 0x2e, (byte) 0xe3, (byte) 0x6c,
            (byte) 0xd2, (byte) 0xb0, (byte) 0x78, (byte) 0x51, (byte) 0x73,
            (byte) 0x34, (byte) 0xaf, (byte) 0xbb, (byte) 0xa0, (byte) 0x9f,
            (byte) 0xc3, (byte) 0xa9, (byte) 0x00, (byte) 0x1e, (byte) 0xd5,
            (byte) 0x4b, (byte) 0x89, (byte) 0xa3, (byte) 0x45, (byte) 0x35,
            (byte) 0xd6, (byte) 0x10,
        };

        int N = 77777;
        long t;

        {
            t = System.currentTimeMillis();
            for (int i = 0; i < N; i++) {
                final StringBuilder hex = new StringBuilder(2 * raw.length);
                for (final byte b : raw) {
                    hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
                }
                hex.toString();
            }
            System.out.println(System.currentTimeMillis() - t); // 50
        }

        {
            t = System.currentTimeMillis();
            for (int i = 0; i < N; i++) {
                StringBuilder hex = new StringBuilder(2 * raw.length);
                for (byte b : raw) {
                    hex.append(String.format("%02X", b));
                }
                hex.toString();
            }
            System.out.println(System.currentTimeMillis() - t); // 2535
        }

    }
}

Edit: Just found something just a lil faster and that holds on one line but is not compatible with JRE 9. Use at your own risks

import javax.xml.bind.DatatypeConverter;

DatatypeConverter.printHexBinary(raw);

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

If the above solutions don't work on ubuntu/linux then you can try this

sudo fuser -k -n tcp port

Run it several times to kill processes on your port of choosing. port could be 3000 for example. You would have killed all the processes if you see no output after running the command

CSS: Control space between bullet and <li>

It seems you can (somewhat) control the spacing using padding on the <li> tag.

<style type="text/css">
    li { padding-left: 10px; }
</style>

The catch is that it doesn't seem to allow you to scrunch it way-snug like your final example.

For that you could try turning off list-style-type and using &bull;

<ul style="list-style-type: none;">
    <li>&bull;Some list text goes here.</li>
</ul>

What are the aspect ratios for all Android phone and tablet devices?

the best way to calculate the equation is simplified. That is, find the maximum divisor between two numbers and divide:

ex.

1920:1080 maximum common divisor 120 = 16:9
1024:768  maximum common divisor 256 = 4:3
1280:768  maximum common divisor 256 = 5:3

may happen also some approaches

JSONDecodeError: Expecting value: line 1 column 1

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

getDate with Jquery Datepicker

I think you would want to add an 'onSelect' event handler to the initialization of your datepicker so your code gets triggered when the user selects a date. Try it out on jsFiddle

$(document).ready(function(){
    // Datepicker
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        inline: true,
        minDate: new Date(2010, 1 - 1, 1),
        maxDate:new Date(2010, 12 - 1, 31),
        altField: '#datepicker_value',
        onSelect: function(){
            var day1 = $("#datepicker").datepicker('getDate').getDate();                 
            var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;             
            var year1 = $("#datepicker").datepicker('getDate').getFullYear();
            var fullDate = year1 + "-" + month1 + "-" + day1;
            var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
            $('#page_output').html(str_output);
        }
    });
});

Reverse a string without using reversed() or [::-1]?

Today I was asked this same exercise on pen&paper, so I come up with this function for lists:

def rev(s):
  l = len(s)
  for i,j in zip(range(l-1, 0, -1), range(l//2)):
    s[i], s[j] = s[j], s[i]
  return s

which can be used with strings with "".join(rev(list("hello")))

get list of pandas dataframe columns based on data type

I came up with this three liner.

Essentially, here's what it does:

  1. Fetch the column names and their respective data types.
  2. I am optionally outputting it to a csv.

inp = pd.read_csv('filename.csv') # read input. Add read_csv arguments as needed
columns = pd.DataFrame({'column_names': inp.columns, 'datatypes': inp.dtypes})
columns.to_csv(inp+'columns_list.csv', encoding='utf-8') # encoding is optional

This made my life much easier in trying to generate schemas on the fly. Hope this helps

Simple excel find and replace for formulas

If the formulas are identical you can use Find and Replace with Match entire cell contents checked and Look in: Formulas. Select the range, go into Find and Replace, make your entries and `Replace All.

enter image description here

Or do you mean that there are several formulas with this same form, but different cell references? If so, then one way to go is a regular expression match and replace. Regular expressions are not built into Excel (or VBA), but can be accessed via Microsoft's VBScript Regular Expressions library.

The following function provides the necessary match and replace capability. It can be used in a subroutine that would identify cells with formulas in the specified range and use the formulas as inputs to the function. For formulas strings that match the pattern you are looking for, the function will produce the replacement formula, which could then be written back to the worksheet.

Function RegexFormulaReplace(formula As String)
    Dim regex As New RegExp
    regex.Pattern = "=\(\(([A-Z]+\d+)-([A-Z]+\d+)\)/([A-Z]+\d+)\)"
'   Test if a match is found
    If regex.Test(formula) = True Then
        RegexFormulaReplace = regex.Replace(formula, "=(EXP((LN($1/$2)/14.32))-1")
    Else
        RegexFormulaReplace = CVErr(xlErrValue)
    End If
    Set regex = Nothing
End Function

In order for the function to work, you would need to add a reference to the Microsoft VBScript Regular Expressions 5.5 library. From the Developer tab of the main ribbon, select VBA and then References from the main toolbar. Scroll down to find the reference to the library and check the box next to it.

Android ADB stop application command like "force-stop" for non rooted device

If you want to kill the Sticky Service,the following command NOT WORKING:

adb shell am force-stop <PACKAGE>
adb shell kill <PID>

The following command is WORKING:

adb shell pm disable <PACKAGE>

If you want to restart the app,you must run command below first:

adb shell pm enable <PACKAGE>

Why does multiplication repeats the number several times?

You cannot multiply an integer by a string. To be sure, you could try using the int (short for integer which means whole number) command, like this for example -

firstNumber = int(9)
secondNumber = int(1)
answer = (firstNumber*secondNumber)

Hope that helped :)

Why has it failed to load main-class manifest attribute from a JAR file?

The easiest way to be sure that you have created the runnable JAR file correctly, with the appropriate manifest file, is to use Eclipse to build it for you. In your Eclipse project, you basically just select File/Export from the menu, and follow the prompts.

That way, you can be sure that your JAR file is correct and will know to look elsewhere if there is still an issue. The process is described in full in FAQ How do I create an executable JAR file for a stand-alone SWT program?.

Iterate through a C array

It depends. If it's a dynamically allocated array, that is, you created it calling malloc, then as others suggest you must either save the size of the array/number of elements somewhere or have a sentinel (a struct with a special value, that will be the last one).

If it's a static array, you can sizeof it's size/the size of one element. For example:

int array[10], array_size;
...
array_size = sizeof(array)/sizeof(int);

Note that, unless it's global, this only works in the scope where you initialized the array, because if you past it to another function it gets decayed to a pointer.

Hope it helps.

Android Location Providers - GPS or Network Provider?

GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.

A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.

http://developer.android.com/guide/topics/location/obtaining-user-location.html

What is syntax for selector in CSS for next element?

Not exactly. The h1.hc-reform > p means "any p exactly one level underneath h1.hc-reform".

What you want is h1.hc-reform + p. Of course, that might cause some issues in older versions of Internet Explorer; if you want to make the page compatible with older IEs, you'll be stuck with either adding a class manually to the paragraphs or using some JavaScript (in jQuery, for example, you could do something like $('h1.hc-reform').next('p').addClass('first-paragraph')).

More info: http://www.w3.org/TR/CSS2/selector.html or http://css-tricks.com/child-and-sibling-selectors/

React - Preventing Form Submission

function onTestClick(evt) {
  evt.stopPropagation();
}

How do you make an anchor link non-clickable or disabled?

Use pointer-events CSS style. (as Jason MacDonald suggested)

See MDN https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events. Its supported in most browsers.

Simple adding "disabled" attribute to anchor will do the job if you have global CSS rule like following:

a[disabled], a[disabled]:hover {
   pointer-events: none;
   color: #e1e1e1;
}

No server in Eclipse; trying to install Tomcat

You have probably installed Eclipse for Java Developers instead of Eclipse IDE for Enterprise Java Developers, server tab and some other are not available.

You don't have to uninstall. Just rerun eclipse-inst-win64.exe and choose Java EE IDE

JAVA EE IDE Installation

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

Changing 'java.library.path' variable at runtime is not enough because it is read only once by JVM. You have to reset it like:

System.setProperty("java.library.path", path);
//set sys_paths to null
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);

Please, take a loot at: Changing Java Library Path at Runtime.

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

Is there any way to show a countdown on the lockscreen of iphone?

A today extension would be the most fitting solution.

Also you could do something on the lock screen with local notifications queued up to fire at regular intervals showing the latest countdown value.

Better way to get type of a Javascript variable?

typeof condition is used to check variable type, if you are check variable type in if-else condition e.g.

if(typeof Varaible_Name "undefined")
{

}

What does $@ mean in a shell script?

From the manual:

@

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" .... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

react-native :app:installDebug FAILED

Just lock and unlock the android solved my issue then

adb reverse tcp:8081 tcp:8081

How to stop text from taking up more than 1 line?

You can use CSS white-space Property to achieve this.

white-space: nowrap

Date validation with ASP.NET validator

A CustomValidator would also work here:

<asp:CustomValidator runat="server"
    ID="valDateRange" 
    ControlToValidate="txtDatecompleted"
    onservervalidate="valDateRange_ServerValidate" 
    ErrorMessage="enter valid date" />

Code-behind:

protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
    DateTime minDate = DateTime.Parse("1000/12/28");
    DateTime maxDate = DateTime.Parse("9999/12/28");
    DateTime dt;

    args.IsValid = (DateTime.TryParse(args.Value, out dt) 
                    && dt <= maxDate 
                    && dt >= minDate);
}

When do I have to use interfaces instead of abstract classes?

With support of default methods in interface since launch of Java 8, the gap between interface and abstract classes has been reduced but still they have major differences.

  1. Variables in interface are public static final. But abstract class can have other type of variables like private, protected etc

  2. Methods in interface are public or public static but methods in abstract class can be private and protected too

  3. Use abstract class to establish relation between interrelated objects. Use interface to establish relation between unrelated classes.

Have a look at this article for special properties of interface in java 8. static modifier for default methods in interface causes compile time error in derived error if you want to use @override.

This article explains why default methods have been introduced in java 8 : To enhance the Collections API in Java 8 to support lambda expressions.

Have a look at oracle documentation too to understand the differences in better way.

Have a look at this related SE questions with code example to understand things in better way:

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

Check whether user has a Chrome extension installed

Another method is to expose a web-accessible resource, though this will allow any website to test if your extension is installed.

Suppose your extension's ID is aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and you add a file (say, a transparent pixel image) as test.png in your extension's files.

Then, you expose this file to the web pages with web_accessible_resources manifest key:

  "web_accessible_resources": [
    "test.png"
  ],

In your web page, you can try to load this file by its full URL (in an <img> tag, via XHR, or in any other way):

chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/test.png

If the file loads, then the extension is installed. If there's an error while loading this file, then the extension is not installed.

// Code from https://groups.google.com/a/chromium.org/d/msg/chromium-extensions/8ArcsWMBaM4/2GKwVOZm1qMJ
function detectExtension(extensionId, callback) { 
  var img; 
  img = new Image(); 
  img.src = "chrome-extension://" + extensionId + "/test.png"; 
  img.onload = function() { 
    callback(true); 
  }; 
  img.onerror = function() { 
    callback(false); 
  };
}

Of note: if there is an error while loading this file, said network stack error will appear in the console with no possibility to silence it. When Chromecast used this method, it caused quite a bit of controversy because of this; with the eventual very ugly solution of simply blacklisting very specific errors from Dev Tools altogether by the Chrome team.


Important note: this method will not work in Firefox WebExtensions. Web-accessible resources inherently expose the extension to fingerprinting, since the URL is predictable by knowing the ID. Firefox decided to close that hole by assigning an instance-specific random URL to web accessible resources:

The files will then be available using a URL like:

moz-extension://<random-UUID>/<path/to/resource>

This UUID is randomly generated for every browser instance and is not your extension's ID. This prevents websites from fingerprinting the extensions a user has installed.

However, while the extension can use runtime.getURL() to obtain this address, you can't hard-code it in your website.

Where is the application.properties file in a Spring Boot project?

You will need to add the application.properties file in your classpath.

If you are using Maven or Gradle, you can just put the file under src/main/resources.
If you are not using Maven or any other build tools, put that under your src folder and you should be fine.

Then you can just add an entry server.port = xxxx in the properties file.

Redis: Show database size/size for keys

Take a look at this project it outputs some interesting stats about keyspaces based on regexs and prefixes. It uses the DEBUG OBJECT command and scans the db, identifying groups of keys and estimating the percentage of space they're taking up.

https://github.com/snmaynard/redis-audit

Output looks like this:

Summary  

---------------------------------------------------+--------------+-------------------+---------------------------------------------------  
Key                                                | Memory Usage | Expiry Proportion | Last Access Time                                    
---------------------------------------------------+--------------+-------------------+---------------------------------------------------  
notification_3109439                               | 88.14%       | 0.0%              | 2 minutes                               
user_profile_3897016                               | 11.86%       | 99.98%            | 20 seconds  
---------------------------------------------------+--------------+-------------------+---------------------------------------------------  

Or this this one: https://github.com/sripathikrishnan/redis-rdb-tools which does a full analysis on the entire keyspace by analyzing a dump.rdb file offline. This one works well also. It can give you the avg/min/max size for the entries in your db, and will even do it based on a prefix.

Connection pooling options with JDBC: DBCP vs C3P0

Just got done wasting a day and a half with DBCP. Even though I'm using the latest DBCP release, I ran into exactly the same problems as j pimmel did. I would not recommend DBCP at all, especially it's knack of throwing connections out of the pool when the DB goes away, its inability to reconnect when the DB comes back and its inability to dynamically add connection objects back into the pool (it hangs forever on a post JDBCconnect I/O socket read)

I'm switching over to C3P0 now. I've used that in previous projects and it worked and performed like a charm.

Installing Python library from WHL file

First open a console then cd to where you've downloaded your file like some-package.whl and use

pip install some-package.whl

Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. I have multiple Python installations, and needed to use the pip associated with Python 3 to install a version 3 wheel.

If pip is not installed, and you are using Windows: How to install pip on Windows?

Browser detection

I would not advise hacking browser-specific things manually with JS. Either use a javascript library like "prototype" or "jquery", which will handle all the specific issues transparently.

Or use these libs to determine the browser type if you really must.

Also see Browser & version in prototype library?

socket.error: [Errno 48] Address already in use

You can allow the server to reuse an address with allow_reuse_address.

Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.

import SimpleHTTPServer, SocketServer
PORT = 8000
httpd = SocketServer.TCPServer(("", PORT), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.allow_reuse_address = True
print "Serving at port", PORT
httpd.serve_forever()

How to split long commands over multiple lines in PowerShell

Splat Method with Calculations

If you choose splat method, beware calculations that are made using other parameters. In practice, sometimes I have to set variables first then create the hash table. Also, the format doesn't require single quotes around the key value or the semi-colon (as mentioned above).

Example of a call to a function that creates an Excel spreadsheet

$title = "Cut-off File Processing on $start_date_long_str"
$title_row = 1
$header_row = 2
$data_row_start = 3
$data_row_end = $($data_row_start + $($file_info_array.Count) - 1)

# use parameter hash table to make code more readable
$params = @{
    title = $title
    title_row = $title_row
    header_row = $header_row
    data_row_start = $data_row_start
    data_row_end = $data_row_end
}
$xl_wksht = Create-Excel-Spreadsheet @params

Note: The file array contains information that will affect how the spreadsheet is populated.

How do you redirect to a page using the POST verb?

I would like to expand the answer of Jason Bunting

like this

ActionResult action = new SampelController().Index(2, "text");
return action;

And Eli will be here for something idea on how to make it generic variable

Can get all types of controller

How can I git stash a specific file?

To add to svick's answer, the -m option simply adds a message to your stash, and is entirely optional. Thus, the command

git stash push [paths you wish to stash]

is perfectly valid. So for instance, if I want to only stash changes in the src/ directory, I can just run

git stash push src/

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

For those interested, this is code for creating SHA-256 hash using sjcl:

import sjcl from 'sjcl'

const myString = 'Hello'
const myBitArray = sjcl.hash.sha256.hash(myString)
const myHash = sjcl.codec.hex.fromBits(myBitArray)

PHP "pretty print" json_encode

Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);

But if you really want to prettify your json... Check this out

How to fix "containing working copy admin area is missing" in SVN?

I added a directory to svn, then I accidentally deleted the .svn folder within.

I used

svn delete --keep-local folderName

to fix my problem.

How do I keep CSS floats in one line?

When user reduces window size horizontally and this causes floats to stack vertically, remove the floats and on the second div (that was a float) use margin-top: -123px (your value) and margin-left: 444px (your value) to position the divs as they appeared with floats. When done this way, when the window narrows, the right-side div stays in place and disappears when page is too narrow to include it. ... which (to me) is better than having the right-side div "jump" down below the left-side div when the browser window is narrowed by the user.

Restart pods when configmap updates in Kubernetes?

Signalling a pod on config map update is a feature in the works (https://github.com/kubernetes/kubernetes/issues/22368).

You can always write a custom pid1 that notices the confimap has changed and restarts your app.

You can also eg: mount the same config map in 2 containers, expose a http health check in the second container that fails if the hash of config map contents changes, and shove that as the liveness probe of the first container (because containers in a pod share the same network namespace). The kubelet will restart your first container for you when the probe fails.

Of course if you don't care about which nodes the pods are on, you can simply delete them and the replication controller will "restart" them for you.

Toggle button using two image on different state

You can try something like this. Here on click of image button I toggle the imageview.

holder.imgitem.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!onclick){
            mSparseBooleanArray.put((Integer) view.getTag(), true);
            holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_delete_overlay_com);
            onclick=true;}
            else if(onclick)
            {
                 mSparseBooleanArray.put((Integer) view.getTag(), false);
                  holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_selection_com);

            onclick=false;
            }
        }
    });

Detect enter press in JTextField

Do you want to do something like this ?

JTextField mTextField = new JTextField();
    mTextField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
                // something like...
               //mTextField.getText();
               // or...
               //mButton.doClick();
            }
        }

    });

caching JavaScript files

In your Apache .htaccess file:

#Create filter to match files you want to cache 
<Files *.js>
Header add "Cache-Control" "max-age=604800"
</Files>

I wrote about it here also:

http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/

How to getElementByClass instead of GetElementById with JavaScript?

adding to CMS's answer, this is a more generic approach of toggle_visibility I've just used myself:

function toggle_visibility(className,display) {
   var elements = getElementsByClassName(document, className),
       n = elements.length;
   for (var i = 0; i < n; i++) {
     var e = elements[i];

     if(display.length > 0) {
       e.style.display = display;
     } else {
       if(e.style.display == 'block') {
         e.style.display = 'none';
       } else {
         e.style.display = 'block';
       }
     }
  }
}

Manually map column names with class properties

For some time, the following should work:

Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

How can I get a list of Git branches, ordered by most recent commit?

git 2.7 (Q4 2015) will introduce branch sorting using directly git branch:
See commit aa3bc55, commit aedcb7d, commit 1511b22, commit f65f139, ... (23 Sep 2015), commit aedcb7d, commit 1511b22, commit ca41799 (24 Sep 2015), and commit f65f139, ... (23 Sep 2015) by Karthik Nayak (KarthikNayak).
(Merged by Junio C Hamano -- gitster -- in commit 7f11b48, 15 Oct 2015)

In particular, commit aedcb7d:

branch.c: use 'ref-filter' APIs

Make 'branch.c' use 'ref-filter' APIs for iterating through refs sorting. This removes most of the code used in 'branch.c' replacing it with calls to the 'ref-filter' library.

It adds the option --sort=<key>:

Sort based on the key given.
Prefix - to sort in descending order of the value.

You may use the --sort=<key> option multiple times, in which case the last key becomes the primary key.

The keys supported are the same as those in git for-each-ref.
Sort order defaults to sorting based on the full refname (including refs/... prefix). This lists detached HEAD (if present) first, then local branches and finally remote-tracking branches.

Here:

git branch --sort=-committerdate 

Or (see below with Git 2.19)

# if you are sure to /always/ want to see branches ordered by commits:
git config --global branch.sort -committerdate
git branch

See also commit 9e46833 (30 Oct 2015) by Karthik Nayak (KarthikNayak).
Helped-by: Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 415095f, 03 Nov 2015)

When sorting as per numerical values (e.g. --sort=objectsize) there is no fallback comparison when both refs hold the same value. This can cause unexpected results (i.e. the order of listing refs with equal values cannot be pre-determined) as pointed out by Johannes Sixt ($gmane/280117).

Hence, fallback to alphabetical comparison based on the refname whenever the other criterion is equal.

$ git branch --sort=objectsize

*  (HEAD detached from fromtag)
      branch-two
      branch-one
      master

With Git 2.19, the sort order can be set by default.
git branch supports a config branch.sort, like git tag, which already had a config tag.sort.
See commit 560ae1c (16 Aug 2018) by Samuel Maftoul (``).
(Merged by Junio C Hamano -- gitster -- in commit d89db6f, 27 Aug 2018)

branch.sort:

This variable controls the sort ordering of branches when displayed by git-branch.
Without the "--sort=<value>" option provided, the value of this variable will be used as the default.


To list remote branches, use git branch -r --sort=objectsize. The -r flag causes it to list remote branches instead of local branches.


With Git 2.27 (Q2 2020), "git branch" and other "for-each-ref" variants accepted multiple --sort=<key> options in the increasing order of precedence, but it had a few breakages around "--ignore-case" handling, and tie-breaking with the refname, which have been fixed.

See commit 7c5045f, commit 76f9e56 (03 May 2020) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 6de1630, 08 May 2020)

ref-filter: apply fallback refname sort only after all user sorts

Signed-off-by: Jeff King

Commit 9e468334b4 ("ref-filter: fallback on alphabetical comparison", 2015-10-30, Git v2.7.0-rc0 -- merge listed in batch #10) taught ref-filter's sort to fallback to comparing refnames.
But it did it at the wrong level, overriding the comparison result for a single "--sort" key from the user, rather than after all sort keys have been exhausted.

This worked correctly for a single "--sort" option, but not for multiple ones.
We'd break any ties in the first key with the refname and never evaluate the second key at all.

To make matters even more interesting, we only applied this fallback sometimes!
For a field like "taggeremail" which requires a string comparison, we'd truly return the result of strcmp(), even if it was 0.
But for numerical "value" fields like "taggerdate", we did apply the fallback. And that's why our multiple-sort test missed this: it uses taggeremail as the main comparison.

So let's start by adding a much more rigorous test. We'll have a set of commits expressing every combination of two tagger emails, dates, and refnames. Then we can confirm that our sort is applied with the correct precedence, and we'll be hitting both the string and value comparators.

That does show the bug, and the fix is simple: moving the fallback to the outer compare_refs() function, after all ref_sorting keys have been exhausted.

Note that in the outer function we don't have an "ignore_case" flag, as it's part of each individual ref_sorting element. It's debatable what such a fallback should do, since we didn't use the user's keys to match.
But until now we have been trying to respect that flag, so the least-invasive thing is to try to continue to do so.
Since all callers in the current code either set the flag for all keys or for none, we can just pull the flag from the first key. In a hypothetical world where the user really can flip the case-insensitivity of keys separately, we may want to extend the code to distinguish that case from a blanket "--ignore-case".


The implementation of "git branch --sort"(man) wrt the detached HEAD display has always been hacky, which has been cleaned up with Git 2.31 (Q1 2021).

See commit 4045f65, commit 2708ce6, commit 7c269a7, commit d094748, commit 75c50e5 (07 Jan 2021), and commit 08bf6a8, commit ffdd02a (06 Jan 2021) by Ævar Arnfjörð Bjarmason (avar).
(Merged by Junio C Hamano -- gitster -- in commit 9e409d7, 25 Jan 2021)

branch: show "HEAD detached" first under reverse sort

Signed-off-by: Ævar Arnfjörð Bjarmason

Change the output of the likes of "git branch -l --sort=-objectsize"(man) to show the "(HEAD detached at <hash>)" message at the start of the output.
Before the compare_detached_head() function added in a preceding commit we'd emit this output as an emergent effect.

It doesn't make any sense to consider the objectsize, type or other non-attribute of the "(HEAD detached at <hash>)" message for the purposes of sorting.
Let's always emit it at the top instead.
The only reason it was sorted in the first place is because we're injecting it into the ref-filter machinery so builtin/branch.c doesn't need to do its own "am I detached?" detection.

How do I divide in the Linux console?

I assume that by Linux console you mean Bash.

If X and Y are your variables, $(($X / $Y)) returns what you ask for.

How to add a reference programmatically

There are two ways to add references using VBA. .AddFromGuid(Guid, Major, Minor) and .AddFromFile(Filename). Which one is best depends on what you are trying to add a reference to. I almost always use .AddFromFile because the things I am referencing are other Excel VBA Projects and they aren't in the Windows Registry.

The example code you are showing will add a reference to the workbook the code is in. I generally don't see any point in doing that because 90% of the time, before you can add the reference, the code has already failed to compile because the reference is missing. (And if it didn't fail-to-compile, you are probably using late binding and you don't need to add a reference.)

If you are having problems getting the code to run, there are two possible issues.

  1. In order to easily use the VBE's object model, you need to add a reference to Microsoft Visual Basic for Application Extensibility. (VBIDE)
  2. In order to run Excel VBA code that changes anything in a VBProject, you need to Trust access to the VBA Project Object Model. (In Excel 2010, it is located in the Trust Center - Macro Settings.)

Aside from that, if you can be a little more clear on what your question is or what you are trying to do that isn't working, I could give a more specific answer.

Connecting to smtp.gmail.com via command line

Check this post in lifehacker : Geek to Live: Back up Gmail with fetchmail . It uses a command line program. Check and see if it helps. BTW why are you using command line when there are many other nice alternatives?

git command to move a folder inside another

I had similar problem, but in folder which I wanted to move I had files which I was not tracking.

let's say I had files

a/file1
a/untracked1
b/file2
b/untracked2

And I wanted to move only tracked files to subfolder subdir, so the goal was:

subdir/a/file1
subdir/a/untracked1
subdir/b/file2
subdir/b/untracked2

what I had done was:

  • I created new folder and moved all files that I was interested in moving: mkdir tmpdir && mv a b tmpdir
  • checked out old files git checkout a b
  • created new dir and moved clean folders (without untracked files) to new subdir: mkdir subdir && mv a b subdir
  • added all files from subdir (so Git could add only tracked previously files - it was somekind of git add --update with directory change trick): git add subdir (normally this would add even untracked files - this would require creating .gitignore file)
  • git status shows now only moved files
  • moved rest of files from tmpdir to subdir: mv tmpdir/* subdir
  • git status looks like we executed git mv :)

Escaping regex string

You can use re.escape():

re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'

If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.

If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_).

Why is list initialization (using curly braces) better than the alternatives?

There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:

  • If the object I'm creating conceptually holds the values I'm passing in the constructor (e.g. containers, POD structs, atomics, smart pointers etc.), then I'm using the braces.
  • If the constructor resembles a normal function call (it performs some more or less complex operations that are parametrized by the arguments) then I'm using the normal function call syntax.
  • For default initialization I always use curly braces.
    For one, that way I'm always sure that the object gets initialized irrespective of whether it e.g. is a "real" class with a default constructor that would get called anyway or a builtin / POD type. Second it is - in most cases - consistent with the first rule, as a default initialized object often represents an "empty" object.

In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).

It e.g. fits nicely with standard library-types like std::vector:

vector<int> a{10,20};   //Curly braces -> fills the vector with the arguments

vector<int> b(10,20);   //Parentheses -> uses arguments to parametrize some functionality,                          
vector<int> c(it1,it2); //like filling the vector with 10 integers or copying a range.

vector<int> d{};      //empty braces -> default constructs vector, which is equivalent
                      //to a vector that is filled with zero elements

XPath to fetch SQL XML value

I always go back to this article SQL Server 2005 XQuery and XML-DML - Part 1 to know how to use the XML features in SQL Server 2005.

For basic XPath know-how, I'd recommend the W3Schools tutorial.

What datatype should be used for storing phone numbers in SQL Server 2005?

It is fairly common to use an "x" or "ext" to indicate extensions, so allow 15 characters (for full international support) plus 3 (for "ext") plus 4 (for the extension itself) giving a total of 22 characters. That should keep you safe.

Alternatively, normalise on input so any "ext" gets translated to "x", giving a maximum of 20.

What is ":-!!" in C code?

It's creating a size 0 bitfield if the condition is false, but a size -1 (-!!1) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1 bitfield is created, of course).

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

Remove a folder from git tracking

This works for me:

git rm -r --cached --ignore-unmatch folder_name

--ignore-unmatch is important here, without that option git will exit with error on the first file not in the index.

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

This is actually a bit of a perpetuated falsehood. While it is true that C programs are frequently faster, this is not always the case, especially if the C programmer isn't very good at it.

One big glaring hole that people tend to forget about is when the program has to block for some sort of IO, such as user input in any GUI program. In these cases, it doesn't really matter what language you use since you are limited by the rate at which data can come in rather than how fast you can process it. In this case, it doesn't matter much if you are using C, Java, C# or even Perl; you just cannot go any faster than the data can come in.

The other major thing is that using garbage collection and not using proper pointers allows the virtual machine to make a number of optimizations not available in other languages. For instance, the JVM is capable of moving objects around on the heap to defragment it. This makes future allocations much faster since the next index can simply be used rather than looking it up in a table. Modern JVMs also don't have to actually deallocate memory; instead, they just move the live objects around when they GC and the spent memory from the dead objects is recovered essentially for free.

This also brings up an interesting point about C and even more so in C++. There is something of a design philosophy of "If you don't need it, you don't pay for it." The problem is that if you do want it, you end up paying through the nose for it. For instance, the vtable implementation in Java tends to be a lot better than C++ implementations, so virtual function calls are a lot faster. On the other hand, you have no choice but to use virtual functions in Java and they still cost something, but in programs that use a lot of virtual functions, the reduced cost adds up.

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

You can add the following JS script

<script>
    function myfunction(event) {
        alert('Checked radio with ID = ' + event.target.id);
    }
    document.querySelectorAll("input[name='gun']").forEach((input) => {
        input.addEventListener('change', myfunction);
    });
</script>

How to use mongoimport to import csv

you will most likely need to authenticate if you're working in production sort of environments. You can use something like this to authenticate against the correct database with appropriate credentials.

mongoimport -d db_name -c collection_name --type csv --file filename.csv --headerline --host hostname:portnumber --authenticationDatabase admin --username 'iamauser' --password 'pwd123'

Resize command prompt through commands

mode con:cols=[whatever you want] lines=[whatever you want].

The unit is the number of characters that fit in the command prompt, eg.

mode con:cols=80 lines=100

will make the command prompt 80 ASCII chars of width and 100 of height

Defining a HTML template to append using JQuery

In order to solve this problem, I recognize two solutions:

  • The first one goes with AJAX, with which you'll have to load the template from another file and just add everytime you want with .clone().

    $.get('url/to/template', function(data) {
        temp = data
        $('.search').keyup(function() {
            $('.list-items').html(null);
    
            $.each(items, function(index) {
                 $(this).append(temp.clone())
            });
    
        });
    });
    

    Take into account that the event should be added once the ajax has completed to be sure the data is available!

  • The second one would be to directly add it anywhere in the original html, select it and hide it in jQuery:

    temp = $('.list_group_item').hide()
    

    You can after add a new instance of the template with

    $('.search').keyup(function() {
        $('.list-items').html(null);
    
        $.each(items, function(index) {
            $(this).append(temp.clone())
        });
    });
    
  • Same as the previous one, but if you don't want the template to remain there, but just in the javascript, I think you can use (have not tested it!) .detach() instead of hide.

    temp = $('.list_group_item').detach()
    

    .detach() removes elements from the DOM while keeping the data and events alive (.remove() does not!).

How to convert HH:mm:ss.SSS to milliseconds?

If you want to use SimpleDateFormat, you could write:

private final SimpleDateFormat sdf =
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    { sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }

private long parseTimeToMillis(final String time) throws ParseException
    { return sdf.parse("1970-01-01 " + time).getTime(); }

But a custom method would be much more efficient. SimpleDateFormat, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)

Also, SimpleDateFormat is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)

Personally, I'd probably write a custom method.

Getting Index of an item in an arraylist;

for (int i = 0; i < list.length; i++) {
   if (list.get(i) .getName().equalsIgnoreCase("myName")) {
    System.out.println(i);
    break;
  }
}

Submit form and stay on same page?

When you hit on the submit button, the page is sent to the server. If you want to send it async, you can do it with ajax.

Generating UML from C++ code?

UML Studio does this quite well in my experience, and will run in "freeware mode" for small projects.

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

For MAMP

ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock

From https://coderwall.com/p/w5kwzw/solved-can-t-connect-to-local-mysql-server-through-socket-tmp-mysql-sock

UPDATE: Every time my computer restarts I have to enter this command, so I created a shortcut.

Do the following in terminal type:

~: vi ~/.profile

Add

alias ...='source ~/.profile'
alias sockit='sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock'

Save.

In terminal type:

~: ... to source the .profile config.

Now in terminal you can just type

~: sockit

How to turn off gcc compiler optimization to enable buffer overflow

I won't quote the entire page but the whole manual on optimisation is available here: http://gcc.gnu.org/onlinedocs/gcc-4.4.3/gcc/Optimize-Options.html#Optimize-Options

From the sounds of it you want at least -O0, the default, and:

-fmudflap -fmudflapth -fmudflapir

For front-ends that support it (C and C++), instrument all risky pointer/array dereferencing operations, some standard library string/heap functions, and some other associated constructs with range/validity tests. Modules so instrumented should be immune to buffer overflows, invalid heap use, and some other classes of C/C++ programming errors. The instrumentation relies on a separate runtime library (libmudflap), which will be linked into a program if -fmudflap is given at link time. Run-time behavior of the instrumented program is controlled by the MUDFLAP_OPTIONS environment variable. See env MUDFLAP_OPTIONS=-help a.out for its options.

Assembly code vs Machine code vs Object code?

The source files of your programs are compiled into object files, and then the linker links those object files together, producing an executable file including your architecture's machine codes.

Both object file and executable file involves architecture's machine code in the form of printable and non-printable characters when it's opened by a text editor.

Nonetheless, the dichotomy between the files is that the object file(s) may contain unresolved external references (such as printf, for instance). So, it may need to be linked against other object files.. That is to say, the unresolved external references are needed to be resolved in order to get the decent runnable executable file by linking with other object files such as C/C++ runtime library's.

How to change Tkinter Button state from disabled to normal?

You simply have to set the state of the your button self.x to normal:

self.x['state'] = 'normal'

or

self.x.config(state="normal")

This code would go in the callback for the event that will cause the Button to be enabled.


Also, the right code should be:

self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download)
self.x.pack(side=LEFT)

The method pack in Button(...).pack() returns None, and you are assigning it to self.x. You actually want to assign the return value of Button(...) to self.x, and then, in the following line, use self.x.pack().

How to import multiple csv files in a single load?

Use wildcard, e.g. replace 2008 with *:

df = sqlContext.read
       .format("com.databricks.spark.csv")
       .option("header", "true")
       .load("../Downloads/*.csv") // <-- note the star (*)

Spark 2.0

// these lines are equivalent in Spark 2.0
spark.read.format("csv").option("header", "true").load("../Downloads/*.csv")
spark.read.option("header", "true").csv("../Downloads/*.csv")

Notes:

  1. Replace format("com.databricks.spark.csv") by using format("csv") or csv method instead. com.databricks.spark.csv format has been integrated to 2.0.

  2. Use spark not sqlContext

Get rid of "The value for annotation attribute must be a constant expression" message

This is what a constant expression in Java looks like:

package com.mycompany.mypackage;

public class MyLinks {
  // constant expression
  public static final String GUESTBOOK_URL = "/guestbook";
}

You can use it with annotations as following:

import com.mycompany.mypackage.MyLinks;

@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
  // ...
}

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.

int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();

Hope this answers the question.

Cannot set content-type to 'application/json' in jQuery.ajax

I had the same issue. I'm running a java rest app on a jboss server. But I think the solution is similar on an ASP .NET webapp.

Firefox makes a pre call to your server / rest url to check which options are allowed. That is the "OPTIONS" request which your server doesn't reply to accordingly. If this OPTIONS call is replied correct a second call is performed which is the actual "POST" request with json content.

This only happens when performing a cross-domain call. In your case calling 'http://localhost:16329/Hello' instead of calling a url path under the same domain '/Hello'

If you intend to make a cross domain call you have to enhance your rest service class with an annotated method the supports a "OPTIONS" http request. This is the according java implementation:

@Path("/rest")
public class RestfulService {

    @POST
    @Path("/Hello")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public string HelloWorld(string name)
    {
        return "hello, " + name;
    }

//THIS NEEDS TO BE ADDED ADDITIONALLY IF MAKING CROSS-DOMAIN CALLS

    @OPTIONS
    @Path("/Hello")
    @Produces(MediaType.TEXT_PLAIN+ ";charset=utf-8")
    public Response checkOptions(){
        return Response.status(200)
        .header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Headers", "Content-Type")
        .header("Access-Control-Allow-Methods", "POST, OPTIONS") //CAN BE ENHANCED WITH OTHER HTTP CALL METHODS 
        .build();
    }
}

So I guess in .NET you have to add an additional method annotated with

[WebInvoke(
        Method = "OPTIONS",
        UriTemplate = "Hello",
        ResponseFormat = WebMessageFormat.)]

where the following headers are set

.header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Headers", "Content-Type")
        .header("Access-Control-Allow-Methods", "POST, OPTIONS")

vba pass a group of cells as range to function

As written, your function accepts only two ranges as arguments.

To allow for a variable number of ranges to be used in the function, you need to declare a ParamArray variant array in your argument list. Then, you can process each of the ranges in the array in turn.

For example,

Function myAdd(Arg1 As Range, ParamArray Args2() As Variant) As Double
    Dim elem As Variant
    Dim i As Long
    For Each elem In Arg1
        myAdd = myAdd + elem.Value
    Next elem
    For i = LBound(Args2) To UBound(Args2)
        For Each elem In Args2(i)
            myAdd = myAdd + elem.Value
        Next elem
    Next i
End Function

This function could then be used in the worksheet to add multiple ranges.

myAdd usage

For your function, there is the question of which of the ranges (or cells) that can passed to the function are 'Sessions' and which are 'Customers'.

The easiest case to deal with would be if you decided that the first range is Sessions and any subsequent ranges are Customers.

Function calculateIt(Sessions As Range, ParamArray Customers() As Variant) As Double
    'This function accepts a single Sessions range and one or more Customers
    'ranges
    Dim i As Long
    Dim sessElem As Variant
    Dim custElem As Variant
    For Each sessElem In Sessions
        'do something with sessElem.Value, the value of each
        'cell in the single range Sessions
        Debug.Print "sessElem: " & sessElem.Value
    Next sessElem
    'loop through each of the one or more ranges in Customers()
    For i = LBound(Customers) To UBound(Customers)
        'loop through the cells in the range Customers(i)
        For Each custElem In Customers(i)
            'do something with custElem.Value, the value of
            'each cell in the range Customers(i)
            Debug.Print "custElem: " & custElem.Value
         Next custElem
    Next i
End Function

If you want to include any number of Sessions ranges and any number of Customers range, then you will have to include an argument that will tell the function so that it can separate the Sessions ranges from the Customers range.

This argument could be set up as the first, numeric, argument to the function that would identify how many of the following arguments are Sessions ranges, with the remaining arguments implicitly being Customers ranges. The function's signature would then be:

Function calculateIt(numOfSessionRanges, ParamAray Args() As Variant)

Or it could be a "guard" argument that separates the Sessions ranges from the Customers ranges. Then, your code would have to test each argument to see if it was the guard. The function would look like:

Function calculateIt(ParamArray Args() As Variant)

Perhaps with a call something like:

calculateIt(sessRange1,sessRange2,...,"|",custRange1,custRange2,...)

The program logic might then be along the lines of:

Function calculateIt(ParamArray Args() As Variant) As Double
   ...
   'loop through Args
   IsSessionArg = True
   For i = lbound(Args) to UBound(Args)
       'only need to check for the type of the argument
       If TypeName(Args(i)) = "String" Then
          IsSessionArg = False
       ElseIf IsSessionArg Then
          'process Args(i) as Session range
       Else
          'process Args(i) as Customer range
       End if
   Next i
   calculateIt = <somevalue>
End Function

Quickest way to convert a base 10 number to any base in .NET?

FAST "FROM" AND "TO" METHODS

I am late to the party, but I compounded previous answers and improved over them. I think these two methods are faster than any others posted so far. I was able to convert 1,000,000 numbers from and to base 36 in under 400ms in a single core machine.

Example below is for base 62. Change the BaseChars array to convert from and to any other base.

private static readonly char[] BaseChars = 
         "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
private static readonly Dictionary<char, int> CharValues = BaseChars
           .Select((c,i)=>new {Char=c, Index=i})
           .ToDictionary(c=>c.Char,c=>c.Index);

public static string LongToBase(long value)
{
   long targetBase = BaseChars.Length;
   // Determine exact number of characters to use.
   char[] buffer = new char[Math.Max( 
              (int) Math.Ceiling(Math.Log(value + 1, targetBase)), 1)];

   var i = buffer.Length;
   do
   {
       buffer[--i] = BaseChars[value % targetBase];
       value = value / targetBase;
   }
   while (value > 0);

   return new string(buffer, i, buffer.Length - i);
}

public static long BaseToLong(string number) 
{ 
    char[] chrs = number.ToCharArray(); 
    int m = chrs.Length - 1; 
    int n = BaseChars.Length, x;
    long result = 0; 
    for (int i = 0; i < chrs.Length; i++)
    {
        x = CharValues[ chrs[i] ];
        result += x * (long)Math.Pow(n, m--);
    }
    return result;  
} 

EDIT (2018-07-12)

Fixed to address the corner case found by @AdrianBotor (see comments) converting 46655 to base 36. This is caused by a small floating-point error calculating Math.Log(46656, 36) which is exactly 3, but .NET returns 3 + 4.44e-16, which causes an extra character in the output buffer.

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

Time stamp in the C programming language

Also making aware of interactions between clock() and usleep(). usleep() suspends the program, and clock() only measures the time the program is running.

If might be better off to use gettimeofday() as mentioned here

How can I read large text files in Python, line by line, without loading it into memory?

All you need to do is use the file object as an iterator.

for line in open("log.txt"):
    do_something_with(line)

Even better is using context manager in recent Python versions.

with open("log.txt") as fileobject:
    for line in fileobject:
        do_something_with(line)

This will automatically close the file as well.

Giving height to table and row in Bootstrap

CSS:

tr {
width: 100%;
display: inline-table;
height:60px;                // <-- the rows height 
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // For firefox bad effect
}
tbody{
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl

Jenkins: Failed to connect to repository

I had the exact same problem. The way I solved it on Mac is this:

  1. Switch to jenkins user (sudo -iu jenkins)
  2. Run: ssh-keygen (Note - You are creating ssh key pairs for jenkins user now. You should see something like this : Enter file in which to save the key (/Users/Shared/Jenkins/.ssh/id_rsa):
  3. Keep pressing Enter for default value till end
  4. Run the command showing in the Jenkins error message, on your teminal (eg : "git ls-remote -h [email protected]:adolfosrs/jenkins-test.git HEAD")
  5. You will be asked if you want to continue. Say yes
  6. The Github repo will be added to your known_hosts file in : /Users/Shared/Jenkins/.ssh/
  7. Go back to Jenkins portal and try your Github SSH url
  8. It should work. Good Luck

SVG drop shadow using css3

You can easily add a drop-shadow effect to an svg-element using the drop-shadow() CSS function and rgba color values. By using rgba color values you can change the opacity of your shadow.

_x000D_
_x000D_
img.light-shadow{_x000D_
  filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 0.4));_x000D_
}_x000D_
_x000D_
img.dark-shadow{_x000D_
  filter: drop-shadow(0px 3px 3px rgba(0, 0, 0, 1));_x000D_
}
_x000D_
<img class="light-shadow" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg" />_x000D_
<img class="dark-shadow" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg" />
_x000D_
_x000D_
_x000D_

Error in Swift class: Property not initialized at super.init call

Sorry for ugly formatting. Just put a question character after declaration and everything will be ok. A question tells the compiler that the value is optional.

class Square: Shape {
    var sideLength: Double?   // <=== like this ..

    init(sideLength:Double, name:String) {
        super.init(name:name) // Error here
        self.sideLength = sideLength
        numberOfSides = 4
    }
    func area () -> Double {
        return sideLength * sideLength
    }
}

Edit1:

There is a better way to skip this error. According to jmaschad's comment there is no reason to use optional in your case cause optionals are not comfortable in use and You always have to check if optional is not nil before accessing it. So all you have to do is to initialize member after declaration:

class Square: Shape {
    var sideLength: Double=Double()   

    init(sideLength:Double, name:String) {
        super.init(name:name)
        self.sideLength = sideLength
        numberOfSides = 4
    }
    func area () -> Double {
        return sideLength * sideLength
    }
}

Edit2:

After two minuses got on this answer I found even better way. If you want class member to be initialized in your constructor you must assign initial value to it inside contructor and before super.init() call. Like this:

class Square: Shape {
    var sideLength: Double  

    init(sideLength:Double, name:String) {
        self.sideLength = sideLength   // <= before super.init call..
        super.init(name:name)
        numberOfSides = 4
    }
    func area () -> Double {
        return sideLength * sideLength
    }
}

Good luck in learning Swift.

How to build jars from IntelliJ properly?

Some of the other answers are useless because as soon as you re-import the IntelliJ IDEA project from the maven project, all changes will be lost.

The building of the jar needs to be triggered by a run/debug configuration, not by the project settings.

Jetbrains has a nice description of how you can accomplish this here:

https://www.jetbrains.com/help/idea/maven.html

Scroll down to the section called "Configuring triggers for Maven goals".

(The only disadvantage of their description is that their screenshots are in the default black-on-white color scheme instead of the super-awesome darcula theme. Ugh!)

So, basically, what you do is that you open the "Maven Projects" panel, you find the project of interest, (in your case, the project that builds your jar,) underneath it you find the maven goal that you want to execute, (usually the "package" goal creates jars,) you open up the context menu on it, (right-click on a Windows machine,) and there will be an "Execute before Run/Debug..." option that you can select and it will take you by the hand from there. Really easy.

convert strtotime to date time format in php

<?php
  echo date('d - m - Y',strtotime('2013-01-19 01:23:42'));
 ?>       
Out put : 19 - 01 - 2013

angularjs: allows only numbers to be typed into a text box

Use ng-only-number to allow only numbers, for example:

<input type="text" ng-only-number data-max-length=5>

How do I list loaded plugins in Vim?

:help local-additions

Lists local plugins added.

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

When I find myself thinking about using Manager or Helper in a class name, I consider it a code smell that means I haven't found the right abstraction yet and/or I'm violating the single responsibility principle, so refactoring and putting more effort into design often makes naming much easier.

But even well-designed classes don't (always) name themselves, and your choices partly depend on whether you're creating business model classes or technical infrastructure classes.

Business model classes can be hard, because they're different for every domain. There are some terms I use a lot, like Policy for strategy classes within a domain (e.g., LateRentalPolicy), but these usually flow from trying to create a "ubiquitous language" that you can share with business users, designing and naming classes so they model real-world ideas, objects, actions, and events.

Technical infrastructure classes are a bit easier, because they describe domains we know really well. I prefer to incorporate design pattern names into the class names, like InsertUserCommand, CustomerRepository, or SapAdapter. I understand the concern about communicating implementation instead of intent, but design patterns marry these two aspects of class design - at least when you're dealing with infrastructure, where you want the implementation design to be transparent even while you're hiding the details.

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

Excel 2010: how to use autocomplete in validation list

Here's another option. It works by putting an ActiveX ComboBox on top of the cell with validation enabled, and then providing autocomplete in the ComboBox instead.

Option Explicit

' Autocomplete - replacing validation lists with ActiveX ComboBox
'
' Usage:
'   1. Copy this code into a module named m_autocomplete
'   2. Go to Tools / References and make sure "Microsoft Forms 2.0 Object Library" is checked
'   3. Copy and paste the following code to the worksheet where you want autocomplete
'      ------------------------------------------------------------------------------------------------------
'      - autocomplete
'      Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'          m_autocomplete.SelectionChangeHandler Target
'      End Sub
'      Private Sub AutoComplete_Combo_KeyDown(ByVal KeyCode As msforms.ReturnInteger, ByVal Shift As Integer)
'          m_autocomplete.KeyDownHandler KeyCode, Shift
'      End Sub
'      Private Sub AutoComplete_Combo_Click()
'          m_autocomplete.AutoComplete_Combo_Click
'      End Sub
'      ------------------------------------------------------------------------------------------------------

' When the combobox is clicked, it should dropdown (expand)
Public Sub AutoComplete_Combo_Click()
    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim cbo As OLEObject: Set cbo = GetComboBoxObject(ws)
    Dim cb As ComboBox: Set cb = cbo.Object
    If cbo.Visible Then cb.DropDown
End Sub

' Make it easier to navigate between cells
Public Sub KeyDownHandler(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Const UP As Integer = -1
    Const DOWN As Integer = 1

    Const K_TAB_______ As Integer = 9
    Const K_ENTER_____ As Integer = 13
    Const K_ARROW_UP__ As Integer = 38
    Const K_ARROW_DOWN As Integer = 40

    Dim direction As Integer: direction = 0

    If Shift = 0 And KeyCode = K_TAB_______ Then direction = DOWN
    If Shift = 0 And KeyCode = K_ENTER_____ Then direction = DOWN
    If Shift = 1 And KeyCode = K_TAB_______ Then direction = UP
    If Shift = 1 And KeyCode = K_ENTER_____ Then direction = UP
    If Shift = 1 And KeyCode = K_ARROW_UP__ Then direction = UP
    If Shift = 1 And KeyCode = K_ARROW_DOWN Then direction = DOWN

    If direction <> 0 Then ActiveCell.Offset(direction, 0).Activate

    AutoComplete_Combo_Click
End Sub

Public Sub SelectionChangeHandler(ByVal Target As Range)
    On Error GoTo errHandler

    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim cbo As OLEObject: Set cbo = GetComboBoxObject(ws)
    Dim cb As ComboBox: Set cb = cbo.Object

    ' Try to hide the ComboBox. This might be buggy...
    If cbo.Visible Then
        cbo.Left = 10
        cbo.Top = 10
        cbo.ListFillRange = ""
        cbo.LinkedCell = ""
        cbo.Visible = False
        Application.ScreenUpdating = True
        ActiveSheet.Calculate
        ActiveWindow.SmallScroll
        Application.WindowState = Application.WindowState
        DoEvents
    End If

    If Not HasValidationList(Target) Then GoTo ex

    Application.EnableEvents = False

    ' TODO: the code below is a little fragile
    Dim lfr As String
    lfr = Mid(Target.Validation.Formula1, 2)
    lfr = Replace(lfr, "INDIREKTE", "") ' norwegian
    lfr = Replace(lfr, "INDIRECT", "") ' english
    lfr = Replace(lfr, """", "")
    lfr = Application.Range(lfr).Address(External:=True)

    cbo.ListFillRange = lfr
    cbo.Visible = True
    cbo.Left = Target.Left
    cbo.Top = Target.Top
    cbo.Height = Target.Height + 5
    cbo.Width = Target.Width + 15
    cbo.LinkedCell = Target.Address(External:=True)
    cbo.Activate
    cb.SelStart = 0
    cb.SelLength = cb.TextLength
    cb.DropDown

    GoTo ex

errHandler:
    Debug.Print "Error"
    Debug.Print Err.Number
    Debug.Print Err.Description
ex:
    Application.EnableEvents = True
End Sub

' Does the cell have a validation list?
Function HasValidationList(Cell As Range) As Boolean
    HasValidationList = False
    On Error GoTo ex
    If Cell.Validation.Type = xlValidateList Then HasValidationList = True
ex:
End Function

' Retrieve or create the ComboBox
Function GetComboBoxObject(ws As Worksheet) As OLEObject
    Dim cbo As OLEObject
    On Error Resume Next
    Set cbo = ws.OLEObjects("AutoComplete_Combo")
    On Error GoTo 0
    If cbo Is Nothing Then
        'Dim EnableSelection As Integer: EnableSelection = ws.EnableSelection
        Dim ProtectContents As Boolean: ProtectContents = ws.ProtectContents

        Debug.Print "Lager AutoComplete_Combo"
        If ProtectContents Then ws.Unprotect
        Set cbo = ws.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, _
                            Left:=50, Top:=18.75, Width:=129, Height:=18.75)
        cbo.name = "AutoComplete_Combo"
        cbo.Object.MatchRequired = True
        cbo.Object.ListRows = 12
        If ProtectContents Then ws.Protect
    End If
    Set GetComboBoxObject = cbo
End Function

React Router with optional path parameter

Working syntax for multiple optional params:

<Route path="/section/(page)?/:page?/(sort)?/:sort?" component={Section} />

Now, url can be:

  1. /section
  2. /section/page/1
  3. /section/page/1/sort/asc

CSS text-align: center; is not centering things

I don't Know you use any Bootstrap version but the useful helper class for centering and block an element in center it is .center-block because this class contain margin and display CSS properties but the .text-center class only contain the text-align property

Bootstrap Helper Class center-block

EOL conversion in notepad ++

Depending on your project, you might want to consider using EditorConfig (https://editorconfig.org/). There's a Notepad++ plugin which will load an .editorconfig where you can specify "lf" as the mandatory line ending.

I've only started using it, but it's nice so far, and open source projects I've worked on have included .editorconfig files for years. The "EOL Conversion" setting isn't changed, so it can be a bit confusing, but if you "View > Show Symbol > Show End of Line", you can see that it's adding LF instead of CRLF, even when "EOL Conversion" and the lower bottom corner shows something else (e.g. Windows (CR LF)).

assign function return value to some variable using javascript

The only way to retrieve the correct value in your context is to run $.ajax() function synchronously (what actually contradicts to main AJAX idea). There is the special configuration attribute async you should set to false. In that case the main scope which actually contains $.ajax() function call is paused until the synchronous function is done, so, the return is called only after $.ajax().

function doSomething() {
    var status = 0;
    $.ajax({
        url: 'action.php',
        type: 'POST',
        data: dataString,
        async: false,
        success: function (txtBack) {
            if (txtBack == 1)
                status = 1;
        }
    });

    return status;
}

var response = doSomething();

json call with C#

If your function resides in an mvc controller u can use the below code with a dictionary object of what you want to convert to json

Json(someDictionaryObj, JsonRequestBehavior.AllowGet);

Also try and look at system.web.script.serialization.javascriptserializer if you are using .net 3.5

as for your web request...it seems ok at first glance..

I would use something like this..

public void WebRequestinJson(string url, string postData)
    {
    StreamWriter requestWriter;

    var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.ServicePoint.Expect100Continue = false;
        webRequest.Timeout = 20000;

        webRequest.ContentType = "application/json";
        //POST the data.
        using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
        {
            requestWriter.Write(postData);
        }
    }
}

May be you can make the post and json string a parameter and use this as a generic webrequest method for all calls.

Reading values from DataTable

You can do it using the foreach loop

DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];

  foreach(DataRow row in dr_art_line_2.Rows)
  {
     QuantityInIssueUnit_value = Convert.ToInt32(row["columnname"]);
  }

How to update an object in a List<> in C#

Can also try.

 _lstProductDetail.Where(S => S.ProductID == "")
        .Select(S => { S.ProductPcs = "Update Value" ; return S; }).ToList();

how to save canvas as png image?

To accomodate all three points:

  • button
  • save the image as a png file
  • open up the save, open, close dialog box

The file dialog is a setting in the browser.

For the button/save part assign the following function, boiled down from other answers, to your buttons onclick:

function DownloadCanvasAsImage(){
    let downloadLink = document.createElement('a');
    downloadLink.setAttribute('download', 'CanvasAsImage.png');
    let canvas = document.getElementById('myCanvas');
    let dataURL = canvas.toDataURL('image/png');
    let url = dataURL.replace(/^data:image\/png/,'data:application/octet-stream');
    downloadLink.setAttribute('href', url);
    downloadLink.click();
}

Example on Codepen

Another, somewhat cleaner, approach is using Canvas.toBlob():

function DownloadCanvasAsImage(){
    let downloadLink = document.createElement('a');
    downloadLink.setAttribute('download', 'CanvasAsImage.png');
    let canvas = document.getElementById('myCanvas');
    canvas.toBlob(function(blob) {
      let url = URL.createObjectURL(blob);
      downloadLink.setAttribute('href', url);
      downloadLink.click();
    });
}

Example on Codepen

Neither solution is 100% cross browser compatible, so check the client

How to pass parameters or arguments into a gradle task

task mathOnProperties << {
    println Integer.parseInt(a)+Integer.parseInt(b)
    println new Integer(a) * new Integer(b)
}

$ gradle -Pa=3 -Pb=4 mathOnProperties
:mathOnProperties
7
12

BUILD SUCCESSFUL

Check if certain value is contained in a dataframe column in pandas

I think you need str.contains, if you need rows where values of column date contains string 07311954:

print df[df['date'].astype(str).str.contains('07311954')]

Or if type of date column is string:

print df[df['date'].str.contains('07311954')]

If you want check last 4 digits for string 1954 in column date:

print df[df['date'].astype(str).str[-4:].str.contains('1954')]

Sample:

print df['date']
0    8152007
1    9262007
2    7311954
3    2252011
4    2012011
5    2012011
6    2222011
7    2282011
Name: date, dtype: int64

print df['date'].astype(str).str[-4:].str.contains('1954')
0    False
1    False
2     True
3    False
4    False
5    False
6    False
7    False
Name: date, dtype: bool

print df[df['date'].astype(str).str[-4:].str.contains('1954')]
     cmte_id trans_typ entity_typ state  employer  occupation     date  \
2  C00119040       24K        CCM    MD       NaN         NaN  7311954   

   amount     fec_id    cand_id  
2    1000  C00140715  H2MD05155  

Remove property for all objects in array

I will suggest to use Object.assign within a forEach() loop so that the objects are copied and does not affect the original array of objects

var res = [];
array.forEach(function(item) { 
    var tempItem = Object.assign({}, item);
    delete tempItem.bad; 
    res.push(tempItem);
});
console.log(res);

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

Thanks to Don Branson,I solve my problem.I think next time i should use this code when i build my repo on server:

root@localhost:~#mkdir foldername
root@localhost:~#cd foldername
root@localhost:~#git init --bare
root@localhost:~#cd ../
root@localhost:~#chown -R usergroup:username foldername

And on client,i user this

$ git remote add origin git@servername:/var/git/foldername
$ git push origin master

batch/bat to copy folder and content at once

if you have xcopy, you can use the /E param, which will copy directories and subdirectories and the files within them, including maintaining the directory structure for empty directories

xcopy [source] [destination] /E

How do I make an HTML text box show a hint when empty?

$('input[value="text"]').focus(function(){ 
if ($(this).attr('class')=='hint') 
{ 
   $(this).removeClass('hint'); 
   $(this).val(''); 
}
});

$('input[value="text"]').blur(function(){
  if($(this).val() == '')
  {
    $(this).addClass('hint');
    $(this).val($(this).attr('title'));
  } 
});

<input type="text" value="" title="Default Watermark Text">

Select rows which are not present in other table

SELECT * FROM testcases1 t WHERE NOT EXISTS ( SELECT 1
FROM executions1 i WHERE t.tc_id = i.tc_id and t.pro_id=i.pro_id and pro_id=7 and version_id=5 ) and pro_id=7 ;

Here testcases1 table contains all datas and executions1 table contains some data among testcases1 table. I am retrieving only the datas which are not present in exections1 table. ( and even I am giving some conditions inside that you can also give.) specify condition which should not be there in retrieving data should be inside brackets.

Pandas split column of lists into multiple columns

You can use DataFrame constructor with lists created by to_list:

import pandas as pd

d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
                ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
print (df2)
       teams
0  [SF, NYG]
1  [SF, NYG]
2  [SF, NYG]
3  [SF, NYG]
4  [SF, NYG]
5  [SF, NYG]
6  [SF, NYG]

df2[['team1','team2']] = pd.DataFrame(df2.teams.tolist(), index= df2.index)
print (df2)
       teams team1 team2
0  [SF, NYG]    SF   NYG
1  [SF, NYG]    SF   NYG
2  [SF, NYG]    SF   NYG
3  [SF, NYG]    SF   NYG
4  [SF, NYG]    SF   NYG
5  [SF, NYG]    SF   NYG
6  [SF, NYG]    SF   NYG

And for new DataFrame:

df3 = pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2'])
print (df3)
  team1 team2
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG

Solution with apply(pd.Series) is very slow:

#7k rows
df2 = pd.concat([df2]*1000).reset_index(drop=True)

In [121]: %timeit df2['teams'].apply(pd.Series)
1.79 s ± 52.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [122]: %timeit pd.DataFrame(df2['teams'].to_list(), columns=['team1','team2'])
1.63 ms ± 54.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

jQuery preventDefault() not triggered

i just had the same problems - have been testing a lot of different stuff. but it just wouldn't work. then i checked the tutorial examples on jQuery.com again and found out:

your jQuery script needs to be after the elements you are referring to !

so your script needs to be after the html-code you want to access!

seems like jQuery can't access it otherwise.

How to get the index of a maximum element in a NumPy array along one axis

argmax() will only return the first occurrence for each row. http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html

If you ever need to do this for a shaped array, this works better than unravel:

import numpy as np
a = np.array([[1,2,3], [4,3,1]])  # Can be of any shape
indices = np.where(a == a.max())

You can also change your conditions:

indices = np.where(a >= 1.5)

The above gives you results in the form that you asked for. Alternatively, you can convert to a list of x,y coordinates by:

x_y_coords =  zip(indices[0], indices[1])

How To Launch Git Bash from DOS Command Line?

If you want to launch from a batch file:

  • for x86

    start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login
    
  • for x64

    start "" "%PROGRAMFILES%\Git\bin\sh.exe" --login
    

Postgres: How to convert a json string to text?

->> works for me.

postgres version:

<postgres.version>11.6</postgres.version>

Query:

select object_details->'valuationDate' as asofJson, object_details->>'valuationDate' as asofText from MyJsonbTable;

Output:

  asofJson       asofText
"2020-06-26"    2020-06-26
"2020-06-25"    2020-06-25
"2020-06-25"    2020-06-25
"2020-06-25"    2020-06-25

Creating a procedure in mySql with parameters

Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.

DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;

In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.

How to call procedure? Well! its very easy, simply you can call procedure by hitting this command

$mysql> CAll getStudentInfo('pass_required_name');

enter image description here

What are all codecs and formats supported by FFmpeg?

ffmpeg -codecs

should give you all the info about the codecs available.

You will see some letters next to the codecs:

Codecs:
 D..... = Decoding supported
 .E.... = Encoding supported
 ..V... = Video codec
 ..A... = Audio codec
 ..S... = Subtitle codec
 ...I.. = Intra frame-only codec
 ....L. = Lossy compression
 .....S = Lossless compression

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

Avoid converting the table object directly. If relations are set between other tables, it might throw this error. Rather, you can create a model class, assign values to the class object and then serialize it.

How to run Pip commands from CMD

Little side note for anyone new to Python who didn't figure it out by theirself: this should be automatic when installing Python, but just in case, note that to run Python using the python command in Windows' CMD you must first add it to the PATH environment variable, as explained here.


To execute Pip, first of all make sure you have it installed, so type in your CMD:

> python
>>> import pip
>>>

And it should proceed with no error. Otherwise, if this fails, you can look here to see how to install it. Now that you are sure you've got Pip, you can run it from CMD with Python using the -m (module) parameter, like this:

> python -m pip <command> <args>

Where <command> is any Pip command you want to run, and <args> are its relative arguments, separated by spaces.

For example, to install a package:

> python -m pip install <package-name>

How to get current working directory using vba?

Your code: path = ActiveWorkbook.Path

returns blank because you haven't saved your workbook yet.

To overcome your problem, go back to the Excel sheet, save your sheet, and run your code again.

This time it will not show blank, but will show you the path where it is located (current folder)

I hope that helped.

Toggle visibility property of div

There is another way of doing this with just JavaScript. All you have to do is toggle the visibility based on the current state of the DIV's visibility in CSS.

Example:

function toggleVideo() {
     var e = document.getElementById('video-over');

     if(e.style.visibility == 'visible') {
          e.style.visibility = 'hidden';
     } else if(e.style.visibility == 'hidden') {
          e.style.visibility = 'visible';
     }
}

The character encoding of the HTML document was not declared

Your initial page is a complete HTML page containing a form, the contents of which are posted to insert.php when the submit button is clicked, but insert.php needs to process the form's contents and do something with them, like add them to a database, or output them to a new page. Your current insert.php just outputs the contents of the title field, so your browser tries to interpret that as an HTML page, and fails, obviously, because it isn't valid HTML (i.e. it isn't contained in an 'HTML' tag, etc.).

Your insert.php needs to output the necessary HTML, and insert the form data in there somewhere.

For example:

<?php 

   $title = $_POST["title"];
   $price = $_POST["price"];

  echo '<html xmlns="http://www.w3.org/1999/xhtml">';
  echo '<head>';
  echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
  echo '<title>';
  echo $title;
  echo '</title>';
  echo '</head>';
  echo '<body>';
  echo 'Hello, world.';
  echo '</body>';

 ?>

Programmatically find the number of cores on a machine

On Linux, you can read the /proc/cpuinfo file and count the cores.

How to implement the ReLU function in Numpy

I'm completely revising my original answer because of points raised in the other questions and comments. Here is the new benchmark script:

import time
import numpy as np


def fancy_index_relu(m):
    m[m < 0] = 0


relus = {
    "max": lambda x: np.maximum(x, 0),
    "in-place max": lambda x: np.maximum(x, 0, x),
    "mul": lambda x: x * (x > 0),
    "abs": lambda x: (abs(x) + x) / 2,
    "fancy index": fancy_index_relu,
}

for name, relu in relus.items():
    n_iter = 20
    x = np.random.random((n_iter, 5000, 5000)) - 0.5

    t1 = time.time()
    for i in range(n_iter):
        relu(x[i])
    t2 = time.time()

    print("{:>12s}  {:3.0f} ms".format(name, (t2 - t1) / n_iter * 1000))

It takes care to use a different ndarray for each implementation and iteration. Here are the results:

         max  126 ms
in-place max  107 ms
         mul  136 ms
         abs   86 ms
 fancy index  132 ms

How do I check if an index exists on a table field in MySQL?

SHOW KEYS FROM  tablename WHERE Key_name='unique key name'

you can find if there exists an unique key in the table

pip installs packages successfully, but executables not found from command line

On macOS with the default python installation you need to add /Users/<you>/Library/Python/2.7/bin/ to your $PATH.

Add this to your .bash_profile:

export PATH="/Users/<you>/Library/Python/2.7/bin:$PATH"

That's where pip installs the executables.

Tip: For non-default python version which python to find the location of your python installation and replace that portion in the path above. (Thanks for the hint Sanket_Diwale)

Top 5 time-consuming SQL queries in Oracle

You could find disk intensive full table scans with something like this:

SELECT Disk_Reads DiskReads, Executions, SQL_ID, SQL_Text SQLText, 
   SQL_FullText SQLFullText 
FROM
(
   SELECT Disk_Reads, Executions, SQL_ID, LTRIM(SQL_Text) SQL_Text, 
      SQL_FullText, Operation, Options, 
      Row_Number() OVER 
         (Partition By sql_text ORDER BY Disk_Reads * Executions DESC) 
         KeepHighSQL
   FROM
   (
       SELECT Avg(Disk_Reads) OVER (Partition By sql_text) Disk_Reads, 
          Max(Executions) OVER (Partition By sql_text) Executions, 
          t.SQL_ID, sql_text, sql_fulltext, p.operation,p.options
       FROM v$sql t, v$sql_plan p
       WHERE t.hash_value=p.hash_value AND p.operation='TABLE ACCESS' 
       AND p.options='FULL' AND p.object_owner NOT IN ('SYS','SYSTEM')
       AND t.Executions > 1
   ) 
   ORDER BY DISK_READS * EXECUTIONS DESC
)
WHERE KeepHighSQL = 1
AND rownum <=5;

How does Git handle symbolic links?

"Editor's" note: This post may contain outdated information. Please see comments and this question regarding changes in Git since 1.6.1.

Symlinked directories:

It's important to note what happens when there is a directory which is a soft link. Any Git pull with an update removes the link and makes it a normal directory. This is what I learnt hard way. Some insights here and here.

Example

Before

 ls -l
 lrwxrwxrwx 1 admin adm   29 Sep 30 15:28 src/somedir -> /mnt/somedir

git add/commit/push

It remains the same

After git pull AND some updates found

 drwxrwsr-x 2 admin adm 4096 Oct  2 05:54 src/somedir

How to uncheck a radio button?

Try

$(this).removeAttr('checked')

Since a lot of browsers will interpret 'checked=anything' as true. This will remove the checked attribute altogether.

Hope this helps.

How to render an ASP.NET MVC view as a string?

Quick tip

For a strongly typed Model just add it to the ViewData.Model property before passing to RenderViewToString. e.g

this.ViewData.Model = new OrderResultEmailViewModel(order);
string myString = RenderViewToString(this.ControllerContext, "~/Views/Order/OrderResultEmail.aspx", "~/Views/Shared/Site.Master", this.ViewData, this.TempData);

How to declare strings in C

Strings in C are represented as arrays of characters.

char *p = "String";

You are declaring a pointer that points to a string stored some where in your program (modifying this string is undefined behavior) according to the C programming language 2 ed.

char p2[] = "String";

You are declaring an array of char initialized with the string "String" leaving to the compiler the job to count the size of the array.

char p3[5] = "String";

You are declaring an array of size 5 and initializing it with "String". This is an error be cause "String" don't fit in 5 elements.

char p3[7] = "String"; is the correct declaration ('\0' is the terminating character in c strings).

http://c-faq.com/~scs/cclass/notes/sx8.html

jQuery on window resize

Move your javascript into a function and then bind that function to window resize.

$(document).ready(function () {
    updateContainer();
    $(window).resize(function() {
        updateContainer();
    });
});
function updateContainer() {
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    if ($containerHeight > 819) {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    }
}

How can I check for NaN values?

here is an answer working with:

  • NaN implementations respecting IEEE 754 standard
    • ie: python's NaN: float('nan'), numpy.nan...
  • any other objects: string or whatever (does not raise exceptions if encountered)

A NaN implemented following the standard, is the only value for which the inequality comparison with itself should return True:

def is_nan(x):
    return (x != x)

And some examples:

import numpy as np
values = [float('nan'), np.nan, 55, "string", lambda x : x]
for value in values:
    print(f"{repr(value):<8} : {is_nan(value)}")

Output:

nan      : True
nan      : True
55       : False
'string' : False
<function <lambda> at 0x000000000927BF28> : False

Postgres: SQL to list table foreign keys

One another way:

WITH foreign_keys AS (
    SELECT
      conname,
      conrelid,
      confrelid,
      unnest(conkey)  AS conkey,
      unnest(confkey) AS confkey
    FROM pg_constraint
    WHERE contype = 'f' -- AND confrelid::regclass = 'your_table'::regclass
)
-- if confrelid, conname pair shows up more than once then it is multicolumn foreign key
SELECT fk.conname as constraint_name,
       fk.confrelid::regclass as referenced_table, af.attname as pkcol,
       fk.conrelid::regclass as referencing_table, a.attname as fkcol
FROM foreign_keys fk
JOIN pg_attribute af ON af.attnum = fk.confkey AND af.attrelid = fk.confrelid
JOIN pg_attribute a ON a.attnum = conkey AND a.attrelid = fk.conrelid
ORDER BY fk.confrelid, fk.conname
;

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Activity class is the basic class. (The original) It supports Fragment management (Since API 11). Is not recommended anymore its pure use because its specializations are far better.

ActionBarActivity was in a moment the replacement to the Activity class because it made easy to handle the ActionBar in an app.

AppCompatActivity is the new way to go because the ActionBar is not encouraged anymore and you should use Toolbar instead (that's currently the ActionBar replacement). AppCompatActivity inherits from FragmentActivity so if you need to handle Fragments you can (via the Fragment Manager). AppCompatActivity is for ANY API, not only 16+ (who said that?). You can use it by adding compile 'com.android.support:appcompat-v7:24:2.0' in your Gradle file. I use it in API 10 and it works perfect.

Cache an HTTP 'Get' service response in AngularJS?

Check out the library angular-cache if you like $http's built-in caching but want more control. You can use it to seamlessly augment $http cache with time-to-live, periodic purges, and the option of persisting the cache to localStorage so that it's available across sessions.

FWIW, it also provides tools and patterns for making your cache into a more dynamic sort of data-store that you can interact with as POJO's, rather than just the default JSON strings. Can't comment on the utility of that option as yet.

(Then, on top of that, related library angular-data is sort of a replacement for $resource and/or Restangular, and is dependent upon angular-cache.)

Creating a blocking Queue<T> in .NET?

Use .net 4 BlockingCollection, to enqueue use Add(), to dequeue use Take(). It internally uses non-blocking ConcurrentQueue. More info here Fast and Best Producer/consumer queue technique BlockingCollection vs concurrent Queue

How to set a Postgresql default value datestamp like 'YYYYMM'?

It's a common misconception that you can denormalise like this for performance. Use date_trunc('month', date) for your queries and add an index expression for this if you find it running slow.

JOIN queries vs multiple queries

Construct both separate queries and joins, then time each of them -- nothing helps more than real-world numbers.

Then even better -- add "EXPLAIN" to the beginning of each query. This will tell you how many subqueries MySQL is using to answer your request for data, and how many rows scanned for each query.

Using GregorianCalendar with SimpleDateFormat

SimpleDateFormat.format() method takes a Date as a parameter. You can get a Date from a Calendar by calling its getTime() method:

public static String format(GregorianCalendar calendar) {
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    fmt.setCalendar(calendar);
    String dateFormatted = fmt.format(calendar.getTime());

    return dateFormatted;
}

Also note that the months start at 0, so you probably meant:

int month = Integer.parseInt(splitDate[1]) - 1;

"You have mail" message in terminal, os X

If you don't want the hassle of using mail, you can read the mail with

cat /var/mail/<username>

and delete the mail with

sudo rm /var/mail/<username>

How to disable Paste (Ctrl+V) with jQuery?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
   $('input').on("cut copy paste",function(e) {_x000D_
      e.preventDefault();_x000D_
   });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" />
_x000D_
_x000D_
_x000D_

Apply formula to the entire column

Found another solution:

  • Apply the formula to the first 3 or 4 cells of the column
  • Ctrl + C the formula in one of the last rows (if you copy the first line it won't work)
  • Click on the column header to select the whole column
  • Press Ctrl + V to paste it in all cells bellow

Formatting MM/DD/YYYY dates in textbox in VBA

For a quick solution, I usually do like this.

This approach will allow the user to enter date in any format they like in the textbox, and finally format in mm/dd/yyyy format when he is done editing. So it is quite flexible:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If TextBox1.Text <> "" Then
        If IsDate(TextBox1.Text) Then
            TextBox1.Text = Format(TextBox1.Text, "mm/dd/yyyy")
        Else
            MsgBox "Please enter a valid date!"
            Cancel = True
        End If
    End If
End Sub

However, I think what Sid developed is a much better approach - a full fledged date picker control.

Can’t delete docker image with dependent child images

What worked to me was to use the REPOSITORY:TAG combination rather than IMAGE ID.

When I tried to delete a docker image with the command docker rmi <IMAGE ID> with no containers associated with this image I had the message:

$ docker rmi 3f66bec2c6bf
Error response from daemon: conflict: unable to delete 3f66bec2c6bf (cannot be forced) - image has dependent child images

I could delete with success when I used the command docker rmi RPOSITORY:TAG

$ docker rmi ubuntu:18.04v1
Untagged: ubuntu:18.04v1

Update a table using JOIN in SQL Server?

Aaron's approach above worked perfectly for me. My update statement was slightly different because I needed to join based on two fields concatenated in one table to match a field in another table.

 --update clients table cell field from custom table containing mobile numbers

update clients
set cell = m.Phone
from clients as c
inner join [dbo].[COSStaffMobileNumbers] as m 
on c.Last_Name + c.First_Name = m.Name

How do I parse JSON with Objective-C?

JSON parsing using NSJSONSerialization

   NSString* path  = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
   
    //Here you can take JSON string from your URL ,I am using json file
    NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *jsonError;
    NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
  
    NSLog(@"jsonDataArray: %@",jsonDataArray);

    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];
if(jsonObject !=nil){
   // NSString *errorCode=[NSMutableString stringWithFormat:@"%@",[jsonObject objectForKey:@"response"]];
   
        
        if(![[jsonObject objectForKey:@"#data"] isEqual:@""]){
            
            NSMutableArray *array=[jsonObject objectForKey:@"#data"];
             // NSLog(@"array: %@",array);
            NSLog(@"array: %d",array.count);  
            
            int k = 0;
            for(int z = 0; z<array.count;z++){
                
                NSString *strfd = [NSString stringWithFormat:@"%d",k];
                NSDictionary *dicr = jsonObject[@"#data"][strfd];
                k=k+1;
                // NSLog(@"dicr: %@",dicr);
                 NSLog(@"Firstname - Lastname   : %@ - %@",
                     [NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_first_name"]],
                     [NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_last_name"]]);
            }
            
          }

     }

You can see the Console output as below :

Firstname - Lastname : Chandra Bhusan - Pandey

Firstname - Lastname : Kalaiyarasan - Balu

Firstname - Lastname : (null) - (null)

Firstname - Lastname : Girija - S

Firstname - Lastname : Girija - S

Firstname - Lastname : (null) - (null)

install apt-get on linux Red Hat server

wget http://dag.wieers.com/packages/apt/apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

rpm -ivh apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

wget http://dag.wieers.com/packages/rpmforge-release/rpmforge-release-0.3.4-1.el4.rf.i386.rpm

rpm -Uvh rpmforge-release-0.3.4-1.el4.rf.i386.rpm

maybe some URL is broken,please research it. Enjoy~~

Using variables inside a bash heredoc

As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.

Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE

Demo: https://ideone.com/rMF2XA

Note that any of the quoting mechanisms -- \____HERE or "____HERE" or '____HERE' -- will disable all variable interpolation, and turn the here-document into a piece of literal text.

A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.

local=$(uname)
ssh -t remote <<:
    echo "$local is the value from the host which ran the ssh command"
    # Prevent here doc from expanding locally; remote won't see backslash
    remote=\$(uname)
    # Same here
    echo "\$remote is the value from the host we ssh:ed to"
:

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

used ast, example

In [15]: a = "[{'start_city': '1', 'end_city': 'aaa', 'number': 1},\
...:      {'start_city': '2', 'end_city': 'bbb', 'number': 1},\
...:      {'start_city': '3', 'end_city': 'ccc', 'number': 1}]"
In [16]: import ast
In [17]: ast.literal_eval(a)
Out[17]:
[{'end_city': 'aaa', 'number': 1, 'start_city': '1'},
 {'end_city': 'bbb', 'number': 1, 'start_city': '2'},
 {'end_city': 'ccc', 'number': 1, 'start_city': '3'}]

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

how to configure apache server to talk to HTTPS backend server?

In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service to https://my-service helped.

AngularJS directive does not update on scope variable changes

You should keep a watch on your scope.

Here is how you can do it:

<layout layoutId="myScope"></layout>

Your directive should look like

app.directive('layout', function($http, $compile){
    return {
        restrict: 'E',
        scope: {
            layoutId: "=layoutId"
        },
        link: function(scope, element, attributes) {
            var layoutName = (angular.isDefined(attributes.name)) ? attributes.name : 'Default';
            $http.get(scope.constants.pathLayouts + layoutName + '.html')
                .success(function(layout){
                    var regexp = /^([\s\S]*?){{content}}([\s\S]*)$/g;
                    var result = regexp.exec(layout);

                    var templateWithLayout = result[1] + element.html() + result[2];
                    element.html($compile(templateWithLayout)(scope));
        });
    }
}

$scope.$watch('myScope',function(){
        //Do Whatever you want
    },true)

Similarly you can models in your directive, so if model updates automatically your watch method will update your directive.

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

For me, this used to work, but upgrading libraries caused this issue to appear. Problem was having a class like this:

package example.counter;

import javax.validation.constraints.NotNull;

import lombok.Data;

@Data
public class CounterRequest {
    @NotNull
    private final Integer int1;

    @NotNull
    private final Integer int2;
}

Using lombok:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.0</version>
</dependency>

Falling back to

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.10</version>
</dependency>

Fixed the issue. Not sure why, but wanted to document it for future.

Can I set an opacity only to the background image of a div?

I implemented Marcus Ekwall's solution but was able to remove a few things to make it simpler and it still works. Maybe 2017 version of html/css?

html:

<div id="content">
  <div id='bg'></div>
  <h2>What is Lorem Ipsum?</h2>
  <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
    book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
    desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

css:

#content {
  text-align: left;
  width: 75%;
  margin: auto;
  position: relative;
}

#bg {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url('https://static.pexels.com/photos/6644/sea-water-ocean-waves.jpg') center center;
  opacity: .4;
  width: 100%;
  height: 100%;
}

https://jsfiddle.net/abalter/3te9fjL5/

How can I set the default value for an HTML <select> element?

value attribute of tag is missing, so it doesn't show as u desired selected. By default first option show on dropdown page load, if value attribute is set on tag.... I got solved my problem this way