Programs & Examples On #Family tree

A family tree, or pedigree chart, is a chart representing family relationships in a conventional tree structure.

Cycles in family tree software

Genealogical data is cyclic and does not fit into an acyclic graph, so if you have assertions against cycles you should remove them.

The way to handle this in a view without creating a custom view is to treat the cyclic parent as a "ghost" parent. In other words, when a person is both a father and a grandfather to the same person, then the grandfather node is shown normally, but the father node is rendered as a "ghost" node that has a simple label like ("see grandfather") and points to the grandfather.

In order to do calculations you may need to improve your logic to handle cyclic graphs so that a node is not visited more than once if there is a cycle.

Scala Doubles, and Precision

I wouldn't use BigDecimal if you care about performance. BigDecimal converts numbers to string and then parses it back again:

  /** Constructs a `BigDecimal` using the decimal text representation of `Double` value `d`, rounding if necessary. */
  def decimal(d: Double, mc: MathContext): BigDecimal = new BigDecimal(new BigDec(java.lang.Double.toString(d), mc), mc)

I'm going to stick to math manipulations as Kaito suggested.

using mailto to send email with an attachment

what about this

<FORM METHOD="post" ACTION="mailto:[email protected]" ENCTYPE="multipart/form-data">
Attachment: <INPUT TYPE="file" NAME="attachedfile" MAXLENGTH=50 ALLOW="text/*" >
 <input type="submit" name="submit" id="submit" value="Email"/>
</FORM>

How to add a 'or' condition in #ifdef

May use this-

#if defined CONDITION1 || defined CONDITION2
//your code here
#endif

This also does the same-

#if defined(CONDITION1) || defined(CONDITION2)
//your code here
#endif

Further-

  • AND: #if defined CONDITION1 && defined CONDITION2
  • XOR: #if defined CONDITION1 ^ defined CONDITION2
  • AND NOT: #if defined CONDITION1 && !defined CONDITION2

How to return JSon object

First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:

I would use an anonymous type filled with your results type:

string json = JsonConvert.SerializeObject(new
{
    results = new List<Result>()
    {
        new Result { id = 1, value = "ABC", info = "ABC" },
        new Result { id = 2, value = "JKL", info = "JKL" }
    }
});

Also, note that the generated JSON has result items with ids of type Number instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id to string in the C#.

I'd also tweak your results type and get rid of the backing fields:

public class Result
{
    public int id { get ;set; }
    public string value { get; set; }
    public string info { get; set; }
}

Furthermore, classes conventionally are PascalCased and not camelCased.

Here's the generated JSON from the code above:

{
  "results": [
    {
      "id": 1,
      "value": "ABC",
      "info": "ABC"
    },
    {
      "id": 2,
      "value": "JKL",
      "info": "JKL"
    }
  ]
}

Select records from today, this week, this month php mysql

I think using NOW() function is incorrect for getting time difference. Because by NOW() function every time your are calculating the past 24 hours. You must use CURDATE() instead.

    function your_function($time, $your_date) {
    if ($time == 'today') {
        $timeSQL = ' Date($your_date)= CURDATE()';
    }
    if ($time == 'week') {
        $timeSQL = ' YEARWEEK($your_date)= YEARWEEK(CURDATE())';
    }
    if ($time == 'month') {
        $timeSQL = ' Year($your_date)=Year(CURDATE()) AND Month(`your_date`)= Month(CURDATE())';
    }

    $Sql = "SELECT * FROM jokes WHERE ".$timeSQL
    return $Result = $this->db->query($Sql)->result_array();
}

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

How to compare pointers?

Yes, that is the definition of raw pointer equality: they both point to the same location (or are pointer aliases); usually in the virtual address space of the process running your application coded in C++ and managed by some operating system (but C++ can also be used for programming embedded devices with micro-controllers having a Harward architecture: on such microcontrollers some pointer casts are forbidden and makes no sense - since read only data could sit in code ROM)

For C++, read a good C++ programming book, see this C++ reference website, read the documentation of your C++ compiler (perhaps GCC or Clang) and consider coding with smart pointers. Maybe read also some draft C++ standard, like n4713 or buy the official standard from your ISO representative.

The concepts and terminology of garbage collection are also relevant when managing pointers and memory zones obtained by dynamic allocation (e.g. ::operator new), so read perhaps the GC handbook.

For pointers on Linux machines, see also this.

SQL Stored Procedure set variables using SELECT

One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.

SELECT @currentTerm = currentterm,
       @termID = termid,
       @endDate = enddate
FROM   table1
WHERE  iscurrent = 1

IF( @@ROWCOUNT <> 1 )
  BEGIN
      RAISERROR ('Unexpected number of matching rows',
                 16,
                 1)

      RETURN
  END  

How to pass multiple parameters to a get method in ASP.NET Core

Why not using just one controller action?

public string Get(int? id, string firstName, string lastName, string address)
{
   if (id.HasValue)
      GetById(id);
   else if (string.IsNullOrEmpty(address))
      GetByName(firstName, lastName);
   else
      GetByNameAddress(firstName, lastName, address);
}

Another option is to use attribute routing, but then you'd need to have a different URL format:

//api/person/byId?id=1
[HttpGet("byId")] 
public string Get(int id)
{
}

//api/person/byName?firstName=a&lastName=b
[HttpGet("byName")]
public string Get(string firstName, string lastName, string address)
{
}

How to select the comparison of two columns as one column in Oracle

If you want to consider null values equality too, try the following

select column1, column2, 
   case
      when column1 is NULL and column2 is NULL then 'true'  
      when column1=column2 then 'true' 
      else 'false' 
   end 
from table;

Inline <style> tags vs. inline css properties

From a maintainability standpoint, it's much simpler to manage one item in one file, than it is to manage multiple items in possibly multiple files.

Separating your styling will help make your life much easier, especially when job duties are distributed amongst different individuals. Reusability and portability will save you plenty of time down the road.

When using an inline style, that will override any external properties that are set.

Concatenate two NumPy arrays vertically

If the actual problem at hand is to concatenate two 1-D arrays vertically, and we are not fixated on using concatenate to perform this operation, I would suggest the use of np.column_stack:

In []: a = np.array([1,2,3])
In []: b = np.array([4,5,6])
In []: np.column_stack((a, b))
array([[1, 4],
       [2, 5],
       [3, 6]])

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

Time in milliseconds in C

The standard C library provides timespec_get. It can tell time up to nanosecond precision, if the system supports. Calling it, however, takes a bit more effort because it involves a struct. Here's a function that just converts the struct to a simple 64-bit integer so you can get time in milliseconds.

#include <stdio.h>
#include <inttypes.h>
#include <time.h>

int64_t millis()
{
    struct timespec now;
    timespec_get(&now, TIME_UTC);
    return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}

int main(void)
{
    printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}

Unlike clock, this function returns a Unix timestamp so it will correctly account for the time spent in blocking functions, such as sleep.

Can I change the viewport meta tag in mobile safari on the fly?

This has been answered for the most part, but I will expand...

Step 1

My goal was to enable zoom at certain times, and disable it at others.

// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');    
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');

// ...later...

// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');

Step 2

The viewport tag would update, but pinch zoom was still active!! I had to find a way to get the page to pick up the changes...

It's a hack solution, but toggling the opacity of body did the trick. I'm sure there are other ways to accomplish this, but here's what worked for me.

// after updating viewport tag, force the page to pick up changes           
document.body.style.opacity = .9999;
setTimeout(function(){
    document.body.style.opacity = 1;
}, 1);

Step 3

My problem was mostly solved at this point, but not quite. I needed to know the current zoom level of the page so I could resize some elements to fit on the page (think of map markers).

// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;

I hope this helps somebody. I spent several hours banging my mouse before finding a solution.

How to get all selected values from <select multiple=multiple>?

$('#select-meal-type :selected') will contain an array of all of the selected items.

$('#select-meal-type option:selected').each(function() {
    alert($(this).val());
});

?

Scroll RecyclerView to show selected item on top

If you want to scroll automatic without show scroll motion then you need to write following code:

mRecyclerView.getLayoutManager().scrollToPosition(position);

If you want to display scroll motion then you need to add following code. =>Step 1: You need to declare SmoothScroller.

RecyclerView.SmoothScroller smoothScroller = new
                LinearSmoothScroller(this.getApplicationContext()) {
                    @Override
                    protected int getVerticalSnapPreference() {
                        return LinearSmoothScroller.SNAP_TO_START;
                    }
                };

=>step 2: You need to add this code any event you want to perform scroll to specific position. =>First you need to set target position to SmoothScroller.

smoothScroller.setTargetPosition(position);

=>Then you need to set SmoothScroller to LayoutManager.

mRecyclerView.getLayoutManager().startSmoothScroll(smoothScroller);

How can I select item with class within a DIV?

Try this

$("#mydiv div.myclass")

Find a private field with Reflection?

Get private variable's value using Reflection:

var _barVariable = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectForFooClass);

Set value for private variable using Reflection:

typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectForFoocClass, "newValue");

Where objectForFooClass is a non null instance for the class type Foo.

How to delete an app from iTunesConnect / App Store Connect

Apps can’t be deleted if they are part of a Game Center group, in an app bundle, or currently displayed on a store. You’ll want to remove the app from sale or from the group if you want to delete it.

Source: iTunes Connect Developer Guide - Transferring and Deleting Apps

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

Non greedy (reluctant) regex matching in sed?

echo "/home/one/two/three/myfile.txt" | sed 's|\(.*\)/.*|\1|'

don bother, i got it on another forum :)

Calculating days between two dates with Java

In Java 8, you could accomplish this by using LocalDate and DateTimeFormatter. From the Javadoc of LocalDate:

LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day.

And the pattern can be constructed using DateTimeFormatter. Here is the Javadoc, and the relevant pattern characters I used:

Symbol - Meaning - Presentation - Examples

y - year-of-era - year - 2004; 04

M/L - month-of-year - number/text - 7; 07; Jul; July; J

d - day-of-month - number - 10

Here is the example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Java8DateExample {
    public static void main(String[] args) throws IOException {
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MM yyyy");
        final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        final String firstInput = reader.readLine();
        final String secondInput = reader.readLine();
        final LocalDate firstDate = LocalDate.parse(firstInput, formatter);
        final LocalDate secondDate = LocalDate.parse(secondInput, formatter);
        final long days = ChronoUnit.DAYS.between(firstDate, secondDate);
        System.out.println("Days between: " + days);
    }
}

Example input/output with more recent last:

23 01 1997
27 04 1997
Days between: 94

With more recent first:

27 04 1997
23 01 1997
Days between: -94

Well, you could do it as a method in a simpler way:

public static long betweenDates(Date firstDate, Date secondDate) throws IOException
{
    return ChronoUnit.DAYS.between(firstDate.toInstant(), secondDate.toInstant());
}

Declaring static constants in ES6 classes?

It is also possible to use Object.freeze on you class(es6)/constructor function(es5) object to make it immutable:

class MyConstants {}
MyConstants.staticValue = 3;
MyConstants.staticMethod = function() {
  return 4;
}
Object.freeze(MyConstants);
// after the freeze, any attempts of altering the MyConstants class will have no result
// (either trying to alter, add or delete a property)
MyConstants.staticValue === 3; // true
MyConstants.staticValue = 55; // will have no effect
MyConstants.staticValue === 3; // true

MyConstants.otherStaticValue = "other" // will have no effect
MyConstants.otherStaticValue === undefined // true

delete MyConstants.staticMethod // false
typeof(MyConstants.staticMethod) === "function" // true

Trying to alter the class will give you a soft-fail (won't throw any errors, it will simply have no effect).

find files by extension, *.html under a folder in nodejs

I just noticed, you are using sync fs methods, that might block you application, here is a promise-based async way using async and q, you can execute it with START=/myfolder FILTER=".jpg" node myfile.js, assuming you put the following code in a file called myfile.js:

Q = require("q")
async = require("async")
path = require("path")
fs = require("fs")

function findFiles(startPath, filter, files){
    var deferred;
    deferred = Q.defer(); //main deferred

    //read directory
    Q.nfcall(fs.readdir, startPath).then(function(list) {
        var ideferred = Q.defer(); //inner deferred for resolve of async each
        //async crawling through dir
        async.each(list, function(item, done) {

            //stat current item in dirlist
            return Q.nfcall(fs.stat, path.join(startPath, item))
                .then(function(stat) {
                    //check if item is a directory
                    if (stat.isDirectory()) {
                        //recursive!! find files in subdirectory
                        return findFiles(path.join(startPath, item), filter, files)
                            .catch(function(error){
                                console.log("could not read path: " + error.toString());
                            })
                            .finally(function() {
                                //resolve async job after promise of subprocess of finding files has been resolved
                                return done();
                             });
                    //check if item is a file, that matches the filter and add it to files array
                    } else if (item.indexOf(filter) >= 0) {
                        files.push(path.join(startPath, item));
                        return done();
                    //file is no directory and does not match the filefilter -> don't do anything
                    } else {
                        return done();
                    }
                })
                .catch(function(error){
                    ideferred.reject("Could not stat: " + error.toString());
                });
        }, function() {
            return ideferred.resolve(); //async each has finished, so resolve inner deferred
        });
        return ideferred.promise;
    }).then(function() {
        //here you could do anything with the files of this recursion step (otherwise you would only need ONE deferred)
        return deferred.resolve(files); //resolve main deferred
    }).catch(function(error) {
        deferred.reject("Could not read dir: " + error.toString());
        return
    });
    return deferred.promise;
}


findFiles(process.env.START, process.env.FILTER, [])
    .then(function(files){
        console.log(files);
    })
    .catch(function(error){
        console.log("Problem finding files: " + error);
})

Django - iterate number in for loop of a template

{% for days in days_list %}
    <h2># Day {{ forloop.counter }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

or if you want to start from 0

{% for days in days_list %}
        <h2># Day {{ forloop.counter0 }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
    {% endfor %}

What is a simple C or C++ TCP server and client example?

Although many year ago, clsocket seems a really nice small cross-platform (Windows, Linux, Mac OSX): https://github.com/DFHack/clsocket

Undefined reference to 'vtable for xxx'

it suggests that you fail to link the explicitly instantiated basetype public gameCore (whereas the header file forward declares it).

Since we know nothing about your build config/library dependencies, we can't really tell which link flags/source files are missing, but I hope the hint alone helps you fix ti.

How to Query an NTP Server using C#?

I know the topic is quite old, but such tools are always handy. I've used the resources above and created a version of NtpClient which allows asynchronously to acquire accurate time, instead of event based.

 /// <summary>
/// Represents a client which can obtain accurate time via NTP protocol.
/// </summary>
public class NtpClient
{
    private readonly TaskCompletionSource<DateTime> _resultCompletionSource;

    /// <summary>
    /// Creates a new instance of <see cref="NtpClient"/> class.
    /// </summary>
    public NtpClient()
    {
        _resultCompletionSource = new TaskCompletionSource<DateTime>();
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync()
    {
        return await GetNetworkTimeAsync(TimeSpan.FromSeconds(45));
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <param name="timeoutMs">Operation timeout in milliseconds.</param>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync(int timeoutMs)
    {
        return await GetNetworkTimeAsync(TimeSpan.FromMilliseconds(timeoutMs));
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <param name="timeout">Operation timeout.</param>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout)
    {
        using (var socket = new DatagramSocket())
        using (var ct = new CancellationTokenSource(timeout))
        {
            ct.Token.Register(() => _resultCompletionSource.TrySetCanceled());

            socket.MessageReceived += OnSocketMessageReceived;
            //The UDP port number assigned to NTP is 123
            await socket.ConnectAsync(new HostName("pool.ntp.org"), "123");
            using (var writer = new DataWriter(socket.OutputStream))
            {
                // NTP message size is 16 bytes of the digest (RFC 2030)
                var ntpBuffer = new byte[48];

                // Setting the Leap Indicator, 
                // Version Number and Mode values
                // LI = 0 (no warning)
                // VN = 3 (IPv4 only)
                // Mode = 3 (Client Mode)
                ntpBuffer[0] = 0x1B;

                writer.WriteBytes(ntpBuffer);
                await writer.StoreAsync();
                var result = await _resultCompletionSource.Task;
                return result;
            }
        }
    }

    private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
    {
        try
        {
            using (var reader = args.GetDataReader())
            {
                byte[] response = new byte[48];
                reader.ReadBytes(response);
                _resultCompletionSource.TrySetResult(ParseNetworkTime(response));
            }
        }
        catch (Exception ex)
        {
            _resultCompletionSource.TrySetException(ex);
        }
    }

    private static DateTime ParseNetworkTime(byte[] rawData)
    {
        //Offset to get to the "Transmit Timestamp" field (time at which the reply 
        //departed the server for the client, in 64-bit timestamp format."
        const byte serverReplyTime = 40;

        //Get the seconds part
        ulong intPart = BitConverter.ToUInt32(rawData, serverReplyTime);

        //Get the seconds fraction
        ulong fractPart = BitConverter.ToUInt32(rawData, serverReplyTime + 4);

        //Convert From big-endian to little-endian
        intPart = SwapEndianness(intPart);
        fractPart = SwapEndianness(fractPart);

        var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

        //**UTC** time
        DateTime networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
        return networkDateTime;
    }

    // stackoverflow.com/a/3294698/162671
    private static uint SwapEndianness(ulong x)
    {
        return (uint)(((x & 0x000000ff) << 24) +
                       ((x & 0x0000ff00) << 8) +
                       ((x & 0x00ff0000) >> 8) +
                       ((x & 0xff000000) >> 24));
    }
}

Usage:

var ntp = new NtpClient();
var accurateTime = await ntp.GetNetworkTimeAsync(TimeSpan.FromSeconds(10));

How do I keep Python print from adding newlines or spaces?

import sys

sys.stdout.write('h')
sys.stdout.flush()

sys.stdout.write('m')
sys.stdout.flush()

You need to call sys.stdout.flush() because otherwise it will hold the text in a buffer and you won't see it.

How to resolve "Waiting for Debugger" message?

I solved this issue this way:

Go to Run menu ====> click on Edit Configurations ====> Micellaneous and finaly uncheck the option Skip installation if APK has not changed

enter image description here

enter image description here

Reasons for using the set.seed function

You have to set seed every time you want to get a reproducible random result.

set.seed(1)
rnorm(4)
set.seed(1)
rnorm(4)

Could not autowire field:RestTemplate in Spring boot application

Error points directly that RestTemplate bean is not defined in context and it cannot load the beans.

  1. Define a bean for RestTemplate and then use it
  2. Use a new instance of the RestTemplate

If you are sure that the bean is defined for the RestTemplate then use the following to print the beans that are available in the context loaded by spring boot application

ApplicationContext ctx = SpringApplication.run(Application.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
    System.out.println(beanName);
}

If this contains the bean by the name/type given, then all good. Or else define a new bean and then use it.

How to change the output color of echo in Linux

some variables that you can use:

# Reset
Color_Off='\033[0m'       # Text Reset

# Regular Colors
Black='\033[0;30m'        # Black
Red='\033[0;31m'          # Red
Green='\033[0;32m'        # Green
Yellow='\033[0;33m'       # Yellow
Blue='\033[0;34m'         # Blue
Purple='\033[0;35m'       # Purple
Cyan='\033[0;36m'         # Cyan
White='\033[0;37m'        # White

# Bold
BBlack='\033[1;30m'       # Black
BRed='\033[1;31m'         # Red
BGreen='\033[1;32m'       # Green
BYellow='\033[1;33m'      # Yellow
BBlue='\033[1;34m'        # Blue
BPurple='\033[1;35m'      # Purple
BCyan='\033[1;36m'        # Cyan
BWhite='\033[1;37m'       # White

# Underline
UBlack='\033[4;30m'       # Black
URed='\033[4;31m'         # Red
UGreen='\033[4;32m'       # Green
UYellow='\033[4;33m'      # Yellow
UBlue='\033[4;34m'        # Blue
UPurple='\033[4;35m'      # Purple
UCyan='\033[4;36m'        # Cyan
UWhite='\033[4;37m'       # White

# Background
On_Black='\033[40m'       # Black
On_Red='\033[41m'         # Red
On_Green='\033[42m'       # Green
On_Yellow='\033[43m'      # Yellow
On_Blue='\033[44m'        # Blue
On_Purple='\033[45m'      # Purple
On_Cyan='\033[46m'        # Cyan
On_White='\033[47m'       # White

# High Intensity
IBlack='\033[0;90m'       # Black
IRed='\033[0;91m'         # Red
IGreen='\033[0;92m'       # Green
IYellow='\033[0;93m'      # Yellow
IBlue='\033[0;94m'        # Blue
IPurple='\033[0;95m'      # Purple
ICyan='\033[0;96m'        # Cyan
IWhite='\033[0;97m'       # White

# Bold High Intensity
BIBlack='\033[1;90m'      # Black
BIRed='\033[1;91m'        # Red
BIGreen='\033[1;92m'      # Green
BIYellow='\033[1;93m'     # Yellow
BIBlue='\033[1;94m'       # Blue
BIPurple='\033[1;95m'     # Purple
BICyan='\033[1;96m'       # Cyan
BIWhite='\033[1;97m'      # White

# High Intensity backgrounds
On_IBlack='\033[0;100m'   # Black
On_IRed='\033[0;101m'     # Red
On_IGreen='\033[0;102m'   # Green
On_IYellow='\033[0;103m'  # Yellow
On_IBlue='\033[0;104m'    # Blue
On_IPurple='\033[0;105m'  # Purple
On_ICyan='\033[0;106m'    # Cyan
On_IWhite='\033[0;107m'   # White

the escape character in bash, hex and octal respectively:

|       | bash  | hex    | octal   | NOTE                         |
|-------+-------+--------+---------+------------------------------|
| start | \e    | \x1b   | \033    |                              |
| start | \E    | \x1B   | -       | x cannot be capital          |
| end   | \e[0m | \x1m0m | \033[0m |                              |
| end   | \e[m  | \x1b[m | \033[m  | 0 is appended if you omit it |
|       |       |        |         |                              |

short example:

| color       | bash         | hex            | octal          | NOTE                                  |
|-------------+--------------+----------------+----------------+---------------------------------------|
| start green | \e[32m<text> | \x1b[32m<text> | \033[32m<text> | m is NOT optional                     |
| reset       | <text>\e[0m  | <text>\1xb[0m  | <text>\033[om  | o is optional (do it as best practice |
|             |              |                |                |                                       |

bash exception:

If you are going to use these codes in your special bash variables

  • PS0
  • PS1
  • PS2 (= this is for prompting)
  • PS4

you should add extra escape characters so that can interpret them correctly. Without this adding extra escape characters it works but you will face problems when you use Ctrl + r for search in your history.

exception rule for bash

You should add \[ before any starting ANSI code and add \] after any ending ones.
Example:
in regular usage: \033[32mThis is in green\033[0m
for PS0/1/2/4: \[\033[32m\]This is in green\[\033[m\]

\[ is for start of a sequence of non-printable characters
\] is for end of a sequence of non-printable characters

Tip: for memorize it you can first add \[\] and then put your ANSI code between them:

  • \[start-ANSI-code\]
  • \[end-ANSI-code\]

type of color sequence:

  1. 3/4 bit
  2. 8 bit
  3. 24 bit

Before diving into these colors, you should know about 4 modes with these codes:

1. color-mode

It modifies the style of color NOT text. For example make the color bright or darker.

  • 0 reset
  • 1; lighter than normal
  • 2; darker than normal

This mode is not supported widely. It is fully support on Gnome-Terminal.

2. text-mode

This mode is for modifying the style of text NOT color.

  • 3; italic
  • 4; underline
  • 5; blinking (slow)
  • 6; blinking (fast)
  • 7; reverse
  • 8; hide
  • 9; cross-out

and are almost supported.
For example KDE-Konsole supports 5; but Gnome-Terminal does not and Gnome supports 8; but KDE does not.

3. foreground mode

This mode is for colorizing the foreground.

4. background mode

This mode is for colorizing the background.

The below table shows a summary of 3/4 bit version of ANSI-color

|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| color-mode | octal    | hex     | bash  | description      | example (= in octal)         | NOTE                                 |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
|          0 | \033[0m  | \x1b[0m | \e[0m | reset any affect | echo -e "\033[0m"            | 0m equals to m                       |
|          1 | \033[1m  |         |       | light (= bright) | echo -e "\033[1m####\033[m"  | -                                    |
|          2 | \033[2m  |         |       | dark (= fade)    | echo -e "\033[2m####\033[m"  | -                                    |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
|  text-mode | ~        |         |       | ~                | ~                            | ~                                    |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
|          3 | \033[3m  |         |       | italic           | echo -e "\033[3m####\033[m"  |                                      |
|          4 | \033[4m  |         |       | underline        | echo -e "\033[4m####\033[m"  |                                      |
|          5 | \033[5m  |         |       | blink (slow)     | echo -e "\033[3m####\033[m"  |                                      |
|          6 | \033[6m  |         |       | blink (fast)     | ?                            | not wildly support                   |
|          7 | \003[7m  |         |       | reverse          | echo -e "\033[7m####\033[m"  | it affects the background/foreground |
|          8 | \033[8m  |         |       | hide             | echo -e "\033[8m####\033[m"  | it affects the background/foreground |
|          9 | \033[9m  |         |       | cross            | echo -e "\033[9m####\033[m"  |                                      |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| foreground | ~        |         |       | ~                | ~                            | ~                                    |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
|         30 | \033[30m |         |       | black            | echo -e "\033[30m####\033[m" |                                      |
|         31 | \033[31m |         |       | red              | echo -e "\033[31m####\033[m" |                                      |
|         32 | \033[32m |         |       | green            | echo -e "\033[32m####\033[m" |                                      |
|         33 | \033[33m |         |       | yellow           | echo -e "\033[33m####\033[m" |                                      |
|         34 | \033[34m |         |       | blue             | echo -e "\033[34m####\033[m" |                                      |
|         35 | \033[35m |         |       | purple           | echo -e "\033[35m####\033[m" | real name: magenta = reddish-purple  |
|         36 | \033[36m |         |       | cyan             | echo -e "\033[36m####\033[m" |                                      |
|         37 | \033[37m |         |       | white            | echo -e "\033[37m####\033[m" |                                      |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
|         38 | 8/24     |                    This is for special use of 8-bit or 24-bit                                            |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
| background | ~        |         |       | ~                | ~                            | ~                                    |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
|         40 | \033[40m |         |       | black            | echo -e "\033[40m####\033[m" |                                      |
|         41 | \033[41m |         |       | red              | echo -e "\033[41m####\033[m" |                                      |
|         42 | \033[42m |         |       | green            | echo -e "\033[42m####\033[m" |                                      |
|         43 | \033[43m |         |       | yellow           | echo -e "\033[43m####\033[m" |                                      |
|         44 | \033[44m |         |       | blue             | echo -e "\033[44m####\033[m" |                                      |
|         45 | \033[45m |         |       | purple           | echo -e "\033[45m####\033[m" | real name: magenta = reddish-purple  |
|         46 | \033[46m |         |       | cyan             | echo -e "\033[46m####\033[m" |                                      |
|         47 | \033[47m |         |       | white            | echo -e "\033[47m####\033[m" |                                      |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|
|         48 | 8/24     |                    This is for special use of 8-bit or 24-bit                                            |                                                                                       |
|------------+----------+---------+-------+------------------+------------------------------+--------------------------------------|

The below table shows a summary of 8 bit version of ANSI-color

|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
| foreground | octal     | hex       | bash    | description      | example                            | NOTE                    |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
|        0-7 | \033[38;5 | \x1b[38;5 | \e[38;5 | standard. normal | echo -e '\033[38;5;1m####\033[m'   |                         |
|       8-15 |           |           |         | standard. light  | echo -e '\033[38;5;9m####\033[m'   |                         |
|     16-231 |           |           |         | more resolution  | echo -e '\033[38;5;45m####\033[m'  | has no specific pattern |
|    232-255 |           |           |         |                  | echo -e '\033[38;5;242m####\033[m' | from black to white     |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
| foreground | octal     | hex       | bash    | description      | example                            | NOTE                    |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|
|        0-7 |           |           |         | standard. normal | echo -e '\033[48;5;1m####\033[m'   |                         |
|       8-15 |           |           |         | standard. light  | echo -e '\033[48;5;9m####\033[m'   |                         |
|     16-231 |           |           |         | more resolution  | echo -e '\033[48;5;45m####\033[m'  |                         |
|    232-255 |           |           |         |                  | echo -e '\033[48;5;242m####\033[m' | from black to white     |
|------------+-----------+-----------+---------+------------------+------------------------------------+-------------------------|

The 8-bit fast test:
for code in {0..255}; do echo -e "\e[38;05;${code}m $code: Test"; done

The below table shows a summary of 24 bit version of ANSI-color

|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
| foreground | octal     | hex       | bash    | description | example                                  | NOTE            |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
|      0-255 | \033[38;2 | \x1b[38;2 | \e[38;2 | R = red     | echo -e '\033[38;2;255;0;02m####\033[m'  | R=255, G=0, B=0 |
|      0-255 | \033[38;2 | \x1b[38;2 | \e[38;2 | G = green   | echo -e '\033[38;2;;0;255;02m####\033[m' | R=0, G=255, B=0 |
|      0-255 | \033[38;2 | \x1b[38;2 | \e[38;2 | B = blue    | echo -e '\033[38;2;0;0;2552m####\033[m'  | R=0, G=0, B=255 |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
| background | octal     | hex       | bash    | description | example                                  | NOTE            |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|
|      0-255 | \033[48;2 | \x1b[48;2 | \e[48;2 | R = red     | echo -e '\033[48;2;255;0;02m####\033[m'  | R=255, G=0, B=0 |
|      0-255 | \033[48;2 | \x1b[48;2 | \e[48;2 | G = green   | echo -e '\033[48;2;;0;255;02m####\033[m' | R=0, G=255, B=0 |
|      0-255 | \033[48;2 | \x1b[48;2 | \e[48;2 | B = blue    | echo -e '\033[48;2;0;0;2552m####\033[m'  | R=0, G=0, B=255 |
|------------+-----------+-----------+---------+-------------+------------------------------------------+-----------------|

some screen-shots

foreground 8-bit summary in a .gif

foreground.gif

background 8-bit summary in a .gif

background.gif

color summary with their values

enter image description here enter image description here enter image description here enter image description here

blinking on KDE-Terminal

KDE-blinking

a simple `C` code that shows you more

cecho_screenshot

a more advanced tool that I developed to deal with these colors:

bline


color-mode shot

fade-normal-bright

text mode shot

only-text-mode

combining is OK

combine

more shots


Tips and Tricks for Advanced Users and Programmers:

Can we use these codes in a programming language?

Yes, you can. I experienced in , , , ,

Do they slow down the speed of a program?

I think, NO.

Can we use these on Windows?

3/4-bit Yes, if you compile the code with gcc
some screen-shots on Win-7

How to calculate the length of code?

\033[ = 2, other parts 1

Where can we use these codes?

Anywhere that has a tty interpreter
xterm, gnome-terminal, kde-terminal, mysql-client-CLI and so on.
For example if you want to colorize your output with mysql you can use Perl

#!/usr/bin/perl -n
print "\033[1m\033[31m$1\033[36m$2\033[32m$3\033[33m$4\033[m" while /([|+-]+)|([0-9]+)|([a-zA-Z_]+)|([^\w])/g;

store this code in a file name: pcc (= Perl Colorize Character) and then put the file a in valid PATH then use it anywhere you like.

ls | pcc
df | pcc

inside mysql first register it for pager and then try:

[user2:db2] pager pcc
PAGER set to 'pcc'
[user2:db2] select * from table-name;

pcc

It does NOT handle Unicode.

Do these codes only do colorizing?

No, they can do a lot of interesting things. Try:

echo -e '\033[2K'  # clear the screen and do not move the position

or:

echo -e '\033[2J\033[u' # clear the screen and reset the position

There are a lot of beginners that want to clear the screen with system( "clear" ) so you can use this instead of system(3) call

Are they available in Unicode?

Yes. \u001b

Which version of these colors is preferable?

It is easy to use 3/4-bit, but it is much accurate and beautiful to use 24-bit.
If you do not have experience with so here is a quick tutorial:
24 bits means: 00000000 and 00000000 and 00000000. Each 8-bit is for a specific color.
1..8 is for and 9..16 for and 17..24 for
So in #FF0000 means and here it is: 255;0;0
in #00FF00 means which here is: 0;255;0
Does that make sense? what color you want combine it with these three 8-bit values.


reference:
Wikipedia
ANSI escape sequences
tldp.org
tldp.org
misc.flogisoft.com
some blogs/web-pages that I do not remember

Print an integer in binary format in Java

Since no answer is accepted, maybe your question was about how to store an integer in an binary-file. java.io.DataOutputStream might be what you're looking for: https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html

DataOutputStream os = new DataOutputStream(outputStream);
os.writeInt(42);
os.flush();
os.close();

Laravel - display a PDF file in storage without forcing download?

In Laravel 5.5 you can just pass "inline" as the disposition parameter of the download function:

return response()->download('/path/to/file.pdf', 'example.pdf', [], 'inline');

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Search for "SQL mode" if you are using PhpMyAdmin and take off the value: ONLY_FULL_GROUP_BY, just did and it okay.

Java: method to get position of a match in a String?

public int NumberWordsInText(String FullText_, String WordToFind_, int[] positions_)
   {
    int iii1=0;
    int iii2=0;
    int iii3=0;
    while((iii1=(FullText_.indexOf(WordToFind_,iii1)+1))>0){iii2=iii2+1;}
    // iii2 is the number of the occurences
    if(iii2>0) {
        positions_ = new int[iii2];
        while ((iii1 = (FullText_.indexOf(WordToFind_, iii1) + 1)) > 0) {
            positions_[iii3] = iii1-1;
            iii3 = iii3 + 1;
            System.out.println("position=" + positions_[iii3 - 1]);
        }
    }
    return iii2;
}

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

Easiest way is use this way

my_var=`echo 2` echo $my_var output : 2

note that is not simple single quote is back quote ( ` ).

AngularJS : automatically detect change in model

In views with {{}} and/or ng-model, Angular is setting up $watch()es for you behind the scenes.

By default $watch compares by reference. If you set the third parameter to $watch to true, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:

$scope.$watch('myModel', function() { ... }, true);

Update: Angular v1.2 added a new method for this, `$watchCollection():

$scope.$watchCollection('myModel', function() { ... });

Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

How to add "Maven Managed Dependencies" library in build path eclipse?

If you imported an existing maven project and Maven dependencies are not showing in the build path in eclipse then right click on project--> Maven--> 'update Project' will resolve the issue.

Could not create the Java virtual machine

Set the JVM memory:

export _JAVA_OPTIONS=-Xmx512M

Style input element to fill remaining width of its container

Here is a simple and clean solution without using JavaScript or table layout hacks. It is similar to this answer: Input text auto width filling 100% with other elements floating

It is important to wrap the input field with a span which is display:block. Next thing is that the button has to come first and the the input field second.

Then you can float the button to the right and the input field fills the remaining space.

_x000D_
_x000D_
form {_x000D_
    width: 500px;_x000D_
    overflow: hidden;_x000D_
    background-color: yellow;_x000D_
}_x000D_
input {_x000D_
    width: 100%;_x000D_
}_x000D_
span {_x000D_
    display: block;_x000D_
    overflow: hidden;_x000D_
    padding-right:10px;_x000D_
}_x000D_
button {_x000D_
    float: right;_x000D_
}
_x000D_
<form method="post">_x000D_
     <button>Search</button>_x000D_
     <span><input type="text" title="Search" /></span>_x000D_
</form>
_x000D_
_x000D_
_x000D_

A simple fiddle: http://jsfiddle.net/v7YTT/90/

Update 1: If your website is targeted towards modern browsers only, I suggest using flexible boxes. Here you can see the current support.

Update 2: This even works with multiple buttons or other elements that share the full with with the input field. Here is an example.

nvm is not compatible with the npm config "prefix" option:

enter image description hereI had the same problem and it was really annoying each time with the terminal. I run the command to the terminal and it was fixed

For those try to remove nvm from brew

it may not be enough to just brew uninstall nvm

if you see npm prefix is still /usr/local, run this command

sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}

How do I rotate text in css?

You need to use the CSS3 transform property rotate - see here for which browsers support it and the prefix you need to use.

One example for webkit browsers is -webkit-transform: rotate(-90deg);

Edit: The question was changed substantially so I have added a demo that works in Chrome/Safari (as I only included the -webkit- CSS prefixed rules). The problem you have is that you do not want to rotate the title div, but simply the text inside it. If you remove your rotation, the <div>s are in the correct position and all you need to do is wrap the text in an element and rotate that instead.

There already exists a more customisable widget as part of the jQuery UI - see the accordion demo page. I am sure with some CSS cleverness you should be able to make the accordion vertical and also rotate the title text :-)

Edit 2: I had anticipated the text center problem and have already updated my demo. There is a height/width constraint though, so longer text could still break the layout.

Edit 3: It looks like the horizontal version was part of the original plan but I cannot see any way of configuring it on the demo page. I was incorrect… the new accordion is part of the upcoming jQuery UI 1.9! So you could try the development builds if you want the new functionality.

Hope this helps!

How Long Does it Take to Learn Java for a Complete Newbie?

My experience in Java programming for beginner is not difficult to learn; however it is really depended on how your object-oriented programming skills are. As you posed that you had no programming experience , I guess that I recommend a web site, http://www.exampledepot.com/ , and type any java keyword such as Swing, FileInputStream, it provides a lot of practical examples that you can apply into a project.

Please, buy a java book (Sams'java 6 in 24 hours) as reference. It will give you really basic skills for java within a short time. and I sure you will have enough time to learn about the java and J2ME within 10 weeks. Good Luck.

Tiger

How to set opacity in parent div and not affect in child div?

You can't do that, unless you take the child out of the parent and place it via positioning.

The only way I know and it actually works, is to use a translucid image (.png with transparency) for the parent's background. The only disavantage is that you can't control the opacity via CSS, other than that it works!

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

You should not use the viewport meta tag at all if your design is not responsive. Misusing this tag may lead to broken layouts. You may read this article for documentation about why you should'n use this tag unless you know what you're doing. http://blog.javierusobiaga.com/stop-using-the-viewport-tag-until-you-know-ho

"user-scalable=no" also helps to prevent the zoom-in effect on iOS input boxes.

Test method is inconclusive: Test wasn't run. Error?

I was having this problem, and it turned out to be the same as this problem over here. This answer solved the problem for me.

  1. Uncheck "Only build startup projects and dependencies on Run" (Options -> Projects and Solutions -> Build and Run)
  2. In Configuration Manager, make sure both the start-up project and the Test project have "Build" checked.

The second time I hit this issue, it was due to an ampersand in the filepath to the project where the tests reside. It works fine with ReSharper's test runner, but not dotCover's. Remove the ampersand from the filepath.

This is a confirmed bug with dotCover.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

Just putting .encode('utf-8') at the end of object will do the job in recent versions of Python.

How to read file contents into a variable in a batch file?

You can read multiple variables from file like this:

for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H

where param.txt:

PARAM1=value1
PARAM2=value2
...

Should I use past or present tense in git commit messages?

The preference for present-tense, imperative-style commit messages comes from Git itself. From Documentation/SubmittingPatches in the Git repo:

Describe your changes in imperative mood, e.g. "make xyzzy do frotz" instead of "[This patch] makes xyzzy do frotz" or "[I] changed xyzzy to do frotz", as if you are giving orders to the codebase to change its behavior.

So you'll see a lot of Git commit messages written in that style. If you're working on a team or on open source software, it is helpful if everyone sticks to that style for consistency. Even if you're working on a private project, and you're the only one who will ever see your git history, it's helpful to use the imperative mood because it establishes good habits that will be appreciated when you're working with others.

How to use pip with python 3.4 on windows?

Assuming you don't have any other Python installations, you should be able to do python -m pip after a default installation. Something like the following should be in your system path:

C:\Python34\Scripts

This would obviously be different, if you installed Python in a different location.

Android Percentage Layout Height

With introduction of ContraintLayout, it's possible to implement with Guidelines:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.eugene.test1.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#AAA"
        android:text="TextView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/guideline" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

</android.support.constraint.ConstraintLayout>

Result View

You can read more in this article Building interfaces with ConstraintLayout.

n-grams in python, four, five, six grams?

If you want a pure iterator solution for large strings with constant memory usage:

from typing import Iterable  
import itertools

def ngrams_iter(input: str, ngram_size: int, token_regex=r"[^\s]+") -> Iterable[str]:
    input_iters = [ 
        map(lambda m: m.group(0), re.finditer(token_regex, input)) 
        for n in range(ngram_size) 
    ]
    # Skip first words
    for n in range(1, ngram_size): list(map(next, input_iters[n:]))  

    output_iter = itertools.starmap( 
        lambda *args: " ".join(args),  
        zip(*input_iters) 
    ) 
    return output_iter

Test:

input = "If you want a pure iterator solution for large strings with constant memory usage"
list(ngrams_iter(input, 5))

Output:

['If you want a pure',
 'you want a pure iterator',
 'want a pure iterator solution',
 'a pure iterator solution for',
 'pure iterator solution for large',
 'iterator solution for large strings',
 'solution for large strings with',
 'for large strings with constant',
 'large strings with constant memory',
 'strings with constant memory usage']

Find length (size) of an array in jquery

obj={};

$.each(obj, function (key, value) {
    console.log(key+ ' : ' + value); //push the object value
});

for (var i in obj) {
    nameList += "" + obj[i] + "";//display the object value
}

$("id/class").html($(nameList).length);//display the length of object.

Simplest/cleanest way to implement a singleton in JavaScript

This is also a singleton:

function Singleton() {
    var i = 0;
    var self = this;

    this.doStuff = function () {
        i = i + 1;
        console.log('do stuff', i);
    };

    Singleton = function () { return self };
    return this;
}

s = Singleton();
s.doStuff();

How to pass a list from Python, by Jinja2 to JavaScript

I had a similar problem using Flask, but I did not have to resort to JSON. I just passed a list letters = ['a','b','c'] with render_template('show_entries.html', letters=letters), and set

var letters = {{ letters|safe }}

in my javascript code. Jinja2 replaced {{ letters }} with ['a','b','c'], which javascript interpreted as an array of strings.

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

Reverse Contents in Array

Both answers look correct to me.

  1. The first arr[i] = temp; should be removed

  2. You should do a second loop to print all elements, not just half the array. The loop that does the reverse doesn't need to print it.

Laravel 5 Carbon format datetime

just use

Carbon::createFromFormat('Y-m-d H:i:s', $item['created_at'])->format('M d Y');

Increasing the maximum post size

I had been facing similar problem in downloading big files this works fine for me now:

safe_mode = off
max_input_time = 9000
memory_limit = 1073741824
post_max_size = 1073741824
file_uploads = On
upload_max_filesize = 1073741824
max_file_uploads = 100
allow_url_fopen = On

Hope this helps.

I can't find my git.exe file in my Github folder

As of version 2.10.1, here is the path -

C:\Users\usersam\AppData\Local\Programs\Git\cmd\git.exe

PHP Parse error: syntax error, unexpected T_PUBLIC

The public keyword is used only when declaring a class method.

Since you're declaring a simple function and not a class you need to remove public from your code.

How do I create a folder in a GitHub repository?

For the ones using the web browser, you can do the following:

  • Once in the master repository, click on Create new file.
  • In the name of file box at the top, enter the name of your folder
  • Use the / key after the name of the folder. Using this forward slash creates the folder
  • You can see a new box appear next to the folder name wherein you can type the name of your file.
  • In the Commit new file box at the bottom of the page, you can type the description for your file.
  • Select the radio button Commit directly to the master branch.
  • Click on the Commit new file button
  • You will see the new directory will be created.

Using AngularJS date filter with UTC date

After some research I was able to find a good solution for converting UTC to local time, have a a look at the fiddle. Hope it help

https://jsfiddle.net/way2ajay19/2kramzng/20/

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="MyCtrl">
  {{date | date:'yyyy-mm-dd hh:mm:ss' }}
</div>


<script>
function MyCtrl($scope) {
 $scope.d = "2017-07-21 19:47:00";
  $scope.d = $scope.d.replace(" ", 'T') + 'Z';
  $scope.date = new Date($scope.d);
}
</script>

Android + Pair devices via bluetooth programmatically

if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.

Edit

for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action

Returning first x items from array

You can use array_slice function, but do you will use another values? or only the first 5? because if you will use only the first 5 you can use the LIMIT on SQL.

Multipart File upload Spring Boot

@RequestMapping(value="/add/image", method=RequestMethod.POST)
public ResponseEntity upload(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
{   
    try {
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
        Iterator<String> it=multipartRequest.getFileNames();
        MultipartFile multipart=multipartRequest.getFile(it.next());
        String fileName=id+".png";
        String imageName = fileName;

        byte[] bytes=multipart.getBytes();
        BufferedOutputStream stream= new BufferedOutputStream(new FileOutputStream("src/main/resources/static/image/book/"+fileName));;

        stream.write(bytes);
        stream.close();
        return new ResponseEntity("upload success", HttpStatus.OK);

    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity("Upload fialed", HttpStatus.BAD_REQUEST);
    }   
}

String to HtmlDocument

you could get a htmldocument by:

 System.Net.WebClient wc = new System.Net.WebClient();

 System.IO.Stream stream = wc.OpenRead(url);
 System.IO.StreamReader reader = new System.IO.StreamReader(stream);
 string s = reader.ReadToEnd();

 HtmlDocument doc = new HtmlDocument();
 doc.LoadHtml(s);

so you have getbiyid and getbyname ... but any further you'd better of with
HTML Agility Pack as suggested . f.e you can do: doc.DocumentNode.SelectNodes(xpathselector) or regex to parse the doc ..

btw: why not regex ? . its soo cool if you can use it right... but xpath is also very mighty ... so "choose your poison"

cu

How can I write to the console in PHP?

For Ajax calls or XML / JSON responses, where you don't want to mess with the body, you need to send logs via HTTP headers, then add them to the console with a web extension. This is how FirePHP (no longer available) and QuantumPHP (a fork of ChromePHP) do it in Firefox.

If you have the patience, x-debug is a better option - you get deeper insight into PHP, with the ability to pause your script, see what is going on, then resume the script.

Disabling Log4J Output in Java

In addition, it is also possible to turn logging off programmatically:

Logger.getRootLogger().setLevel(Level.OFF);

Or

Logger.getRootLogger().removeAllAppenders();
Logger.getRootLogger().addAppender(new NullAppender());

These use imports:

import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.NullAppender;

How to format column to number format in Excel sheet?

Sorry to bump an old question but the answer is to count the character length of the cell and not its value.

CellCount = Cells(Row, 10).Value
If Len(CellCount) <= "13" Then
'do something
End If

hope that helps. Cheers

Calling onclick on a radiobutton list using javascript

How are you generating the radio button list? If you're just using HTML:

<input type="radio" onclick="alert('hello');"/>

If you're generating these via something like ASP.NET, you can add that as an attribute to each element in the list. You can run this after you populate your list, or inline it if you build up your list one-by-one:

foreach(ListItem RadioButton in RadioButtons){
    RadioButton.Attributes.Add("onclick", "alert('hello');");
}

More info: http://www.w3schools.com/jsref/event_onclick.asp

"Actual or formal argument lists differs in length"

Say you have defined your class like this:

    @Data
    @AllArgsConstructor(staticName = "of")
    private class Pair<P,Q> {

        public P first;
        public Q second;
    }

So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.

Pair<Integer, String> pair = Pair.of(menuItemId, category);

If you define it like this, you will get the error asked for.

Pair<Integer, String> pair = new Pair(menuItemId, category);

how to create a login page when username and password is equal in html

Doing password checks on client side is unsafe especially when the password is hard coded.

The safest way is password checking on server side, but even then the password should not be transmitted plain text.

Checking the password client side is possible in a "secure way":

  • The password needs to be hashed
  • The hashed password is used as part of a new url

Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).

Python: Find index of minimum item in list of floats

You're effectively scanning the list once to find the min value, then scanning it again to find the index, you can do both in one go:

from operator import itemgetter
min(enumerate(a), key=itemgetter(1))[0] 

Write HTML to string

You could use some third party open-source libraries to generated strong typed verified (X)HTML, such as CityLizard Framework or Sharp DOM.

Update For example

html
    [head
        [title["Title of the page"]]
        [meta_(
            content: "text/html;charset=UTF-8",
            http_equiv: "Content-Type")
        ]
        [link_(href: "css/style.css", rel: "stylesheet", type: "text/css")]
        [script_(type: "text/javascript", src: "/JavaScript/jquery-1.4.2.min.js")]
    ]
    [body
        [div
            [h1["Test Form to Test"]]
            [form_(action: "post", id: "Form1")
                [div
                    [label["Parameter"]]
                    [input_(type: "text", value: "Enter value")]
                    [input_(type: "submit", value: "Submit!")]
                ]
            ]
            [div
                [p["Textual description of the footer"]]
                [a_(href: "http://google.com/")
                    [span["You can find us here"]]
                ]
                [div["Another nested container"]]
            ]
        ]
    ];

How to create roles in ASP.NET Core and assign them to users?

In Configure method declare your role manager (Startup)

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RoleManager<IdentityRole> roleManager)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        Task.Run(()=>this.CreateRoles(roleManager)).Wait();
    }


    private async Task CreateRoles(RoleManager<IdentityRole> roleManager)
    {
        foreach (string rol in this.Configuration.GetSection("Roles").Get<List<string>>())
        {
            if (!await roleManager.RoleExistsAsync(rol))
            {
                await roleManager.CreateAsync(new IdentityRole(rol));
            }
        }
    }

OPTIONAL - In appsettings.JSON (it depends on you where you wanna get roles from)

{
"Roles": [
"SuperAdmin",
"Admin",
"Employee",
"Customer"
  ]
}

What does the C++ standard state the size of int, long type to be?

On a 64-bit machine:

int: 4
long: 8
long long: 8
void*: 8
size_t: 8

How to prevent page scrolling when scrolling a DIV element?

Update 2: My solution is based on disabling the browser's native scrolling altogether (when cursor is inside the DIV) and then manually scrolling the DIV with JavaScript (by setting its .scrollTop property). An alternative and IMO better approach would be to only selectively disable the browser's scrolling in order to prevent the page scroll, but not the DIV scroll. Check out Rudie's answer below which demonstrates this solution.


Here you go:

$( '.scrollable' ).on( 'mousewheel DOMMouseScroll', function ( e ) {
    var e0 = e.originalEvent,
        delta = e0.wheelDelta || -e0.detail;

    this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
    e.preventDefault();
});

Live demo: https://jsbin.com/howojuq/edit?js,output

So you manually set the scroll position and then just prevent the default behavior (which would be to scroll the DIV or whole web-page).

Update 1: As Chris noted in the comments below, in newer versions of jQuery, the delta information is nested within the .originalEvent object, i.e. jQuery does not expose it in its custom Event object anymore and we have to retrieve it from the native Event object instead.

Good MapReduce examples

From time to time I present MR concepts to people. I find processing tasks familiar to people and then map them to the MR paradigm.

Usually I take two things:

  1. Group By / Aggregations. Here the advantage of the shuffling stage is clear. An explanation that shuffling is also distributed sort + an explanation of distributed sort algorithm also helps.

  2. Join of two tables. People working with DB are familiar with the concept and its scalability problem. Show how it can be done in MR.

How do I clone a subdirectory only of a Git repository?

I wrote a .gitconfig [alias] for performing a "sparse checkout". Check it out (no pun intended):

On Windows run in cmd.exe

git config --global alias.sparse-checkout "!f(){ [ $# -eq 2 ] && L=${1##*/} L=${L%.git} || L=$2; mkdir -p \"$L/.git/info\" && cd \"$L\" && git init --template= && git remote add origin \"$1\" && git config core.sparseCheckout 1; [ $# -eq 2 ] && echo \"$2\" >> .git/info/sparse-checkout || { shift 2; for i; do echo $i >> .git/info/sparse-checkout; done }; git pull --depth 1 origin master;};f"

Otherwise:

git config --global alias.sparse-checkout '!f(){ [ $# -eq 2 ] && L=${1##*/} L=${L%.git} || L=$2; mkdir -p "$L/.git/info" && cd "$L" && git init --template= && git remote add origin "$1" && git config core.sparseCheckout 1; [ $# -eq 2 ] && echo "$2" >> .git/info/sparse-checkout || { shift 2; for i; do echo $i >> .git/info/sparse-checkout; done }; git pull --depth 1 origin master;};f'

Usage:

# Makes a directory ForStackExchange with Plug checked out
git sparse-checkout https://github.com/YenForYang/ForStackExchange Plug

# To do more than 1 directory, you have to specify the local directory:
git sparse-checkout https://github.com/YenForYang/ForStackExchange ForStackExchange Plug Folder

The git config commands are 'minified' for convenience and storage, but here is the alias expanded:

# Note the --template= is for disabling templates.
# Feel free to remove it if you don't have issues with them (like I did)
# `mkdir` makes the .git/info directory ahead of time, as I've found it missing sometimes for some reason
f(){
    [ "$#" -eq 2 ] && L="${1##*/}" L=${L%.git} || L=$2;
    mkdir -p "$L/.git/info"
        && cd "$L"
        && git init --template=
        && git remote add origin "$1"
        && git config core.sparseCheckout 1;
    [ "$#" -eq 2 ]
        && echo "$2" >> .git/info/sparse-checkout
        || {
            shift 2;
            for i; do
                echo $i >> .git/info/sparse-checkout;
            done
        };
    git pull --depth 1 origin master;
};
f

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

Why not just set the left two columns to a fixed with in your own css and then make a new grid layout of the full 12 columns for the rest of the content?

<div class="row">
    <div class="fixed-1">Left 1</div>
    <div class="fixed-2">Left 2</div>
    <div class="row">
        <div class="col-md-1"></div>
        <div class="col-md-11"></div>
    </div>
</div>

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

I just figured. You need to add a shared folder using VirtualBox before you access it with the guest.

Click "Device" in the menu bar--->Shared File--->add a directory and name it

then in the guest terminal, use:

sudo mount -t vboxsf myFileName ~/destination

Dont directly refer to the host directory

PostgreSQL: how to convert from Unix epoch to date?

select to_timestamp(cast(epoch_ms/1000 as bigint))::date

worked for me

How to import csv file in PHP?

Here is the version to extract the specific columns by name (modified from @coreyward):

$row = 0;
$headers = [];
$filepath = "input.csv";
if (($handle = fopen($filepath, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if (++$row == 1) {
          $headers = array_flip($data); // Get the column names from the header.
          continue;
        } else {
          $col1 = $data[$headers['Col1Name']]; // Read row by the column name.
          $col2 = $data[$headers['Col2Name']];
          print "Row $row: $col1, $col2\n";
        }
    }
    fclose($handle);
}

PHP str_replace replace spaces with underscores

I'll suggest that you use this as it will check for both single and multiple occurrence of white space (as suggested by Lucas Green).

$journalName = preg_replace('/\s+/', '_', $journalName);

instead of:

$journalName = str_replace(' ', '_', $journalName);

Correct way to find max in an Array in Swift

Given:

let numbers = [1, 2, 3, 4, 5]

Swift 3:

numbers.min() // equals 1
numbers.max() // equals 5

Swift 2:

numbers.minElement() // equals 1
numbers.maxElement() // equals 5

Java rounding up to an int using Math.ceil

In Java adding a .0 will make it a double...

int total = (int) Math.ceil(157.0 / 32.0);

Why is "throws Exception" necessary when calling a function?

The throws Exception declaration is an automated way of keeping track of methods that might throw an exception for anticipated but unavoidable reasons. The declaration is typically specific about the type or types of exceptions that may be thrown such as throws IOException or throws IOException, MyException.

We all have or will eventually write code that stops unexpectedly and reports an exception due to something we did not anticipate before running the program, like division by zero or index out of bounds. Since the errors were not expected by the method, they could not be "caught" and handled with a try catch clause. Any unsuspecting users of the method would also not know of this possibility and their programs would also stop.

When the programmer knows certain types of errors may occur but would like to handle these exceptions outside of the method, the method can "throw" one or more types of exceptions to the calling method instead of handling them. If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw. Since programs can have many layers of methods written by many different programs, it becomes difficult (impossible) to keep track of which methods might throw exceptions.

Even though Java has the ability to declare exceptions, you can still write a new method with unhandled and undeclared exceptions, and Java will compile it and you can run it and hope for the best. What Java won't let you do is compile your new method if it uses a method that has been declared as throwing exception(s), unless you either handle the declared exception(s) in your method or declare your method as throwing the same exception(s) or if there are multiple exceptions, you can handle some and throw the rest.

When a programmer declares that the method throws a specific type of exception, it is just an automated way of warning other programmers using the method that an exception is possible. The programmer can then decide to handled the exception or pass on the warning by declaring the calling method as also throwing the same exception. Since the compiler has been warned the exception is possible in this new method, it can automatically check if future callers of the new method handle the exception or declare it and enforcing one or the other to happen.

The nice thing about this type of solution is that when the compiler reports Error: Unhandled exception type java.io.IOException it gives the file and line number of the method that was declared to throw the exception. You can then choose to simply pass the buck and declare your method also "throws IOException". This can be done all the way up to main method where it would then cause the program to stop and report the exception to the user. However, it is better to catch the exception and deal with it in a nice way such as explaining to the user what has happened and how to fix it. When a method does catch and handle the exception, it no longer has to declare the exception. The buck stops there so to speak.

How to debug stored procedures with print statements?

try using:

RAISERROR('your message here!!!',0,1) WITH NOWAIT

you could also try switching to "Results to Text" it is just a few icons to the right of "Execute" on the default tool bar.

With both of the above in place, and you still you do not see the messages, make sure you are running the same server/database/owner version of the procedure that you are editing. Make sure you are hitting the RAISERROR command, make it the first command inside the procedure.

If all else fails, you could create a table:

create table temp_log (RowID int identity(1,1) primary key not null
                      , MessageValue varchar(255))

then:

INSERT INTO temp_log VALUES ('Your message here')

then after running the procedure (provided no rollbacks) just select the table.

How Do I Uninstall Yarn

I couldn't uninstall yarn on windows and I tried every single answer here, but every time I ran yarn -v, the command worked. But then I realized that there is another thing that can affect this.

If you on windows (not sure if this also happens in mac) and using nvm, one problem that can happen is that you have installed nvm without uninstalling npm, and the working yarn command is from your old yarn version from the old npm.

So what you need to do is follow this step from the nvm docs

You should also delete the existing npm install location (e.g. "C:\Users<user>\AppData\Roaming\npm"), so that the nvm install location will be correctly used instead. Backup the global npmrc config (e.g. C:\Users&lt;user>\AppData\Roaming\npm\etc\npmrc), if you have some important settings there, or copy the settings to the user config C:\Users&lt;user>.npmrc.

And to confirm that you problem is with the old npm, you will probably see the yarn.cmd file inside the C:\Users\<user>\AppData\Roaming\npm folder.

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

Java - How to find the redirected url of a url?

You need to cast the URLConnection to HttpURLConnection and instruct it to not follow the redirects by setting HttpURLConnection#setInstanceFollowRedirects() to false. You can also set it globally by HttpURLConnection#setFollowRedirects().

You only need to handle redirects yourself then. Check the response code by HttpURLConnection#getResponseCode(), grab the Location header by URLConnection#getHeaderField() and then fire a new HTTP request on it.

sed edit file in place

Very good examples. I had the challenge to edit in place many files and the -i option seems to be the only reasonable solution using it within the find command. Here the script to add "version:" in front of the first line of each file:

find . -name pkg.json -print -exec sed -i '.bak' '1 s/^/version /' {} \;

How to ignore ansible SSH authenticity checking?

Ignoring checking is a bad idea as it makes you susceptible to Man-in-the-middle attacks.

I took the freedom to improve nikobelia's answer by only adding each machine's key once and actually setting ok/changed status in Ansible:

- name: Accept EC2 SSH host keys
  connection: local
  become: false
  shell: |
    ssh-keygen -F {{ inventory_hostname }} || 
      ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts
  register: known_hosts_script
  changed_when: "'found' not in known_hosts_script.stdout"

However, Ansible starts gathering facts before the script runs, which requires an SSH connection, so we have to either disable this task or manually move it to later:

- name: Example play
  hosts: all
  gather_facts: no  # gather facts AFTER the host key has been accepted instead

  tasks:

  # https://stackoverflow.com/questions/32297456/
  - name: Accept EC2 SSH host keys
    connection: local
    become: false
    shell: |
      ssh-keygen -F {{ inventory_hostname }} ||
        ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts
    register: known_hosts_script
    changed_when: "'found' not in known_hosts_script.stdout"
  
  - name: Gathering Facts
    setup:

One kink I haven't been able to work out is that it marks all as changed even if it only adds a single key. If anyone could contribute a fix that would be great!

How to parse a CSV file in Bash?

We can parse csv files with quoted strings and delimited by say | with following code

while read -r line
do
    field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
    field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')

    echo "$field1 $field2"
done < "$csvFile"

awk parses the string fields to variables and tr removes the quote.

Slightly slower as awk is executed for each field.

Using switch statement with a range of value in each case?

Try this if you must use switch.

public static int range(int num){ 
    if ( 10 < num && num < 20)
        return 1;
    if ( 20 <= num && num < 30)
        return 2;
    return 3;
}

public static final int TEN_TWENTY = 1;
public static final int TWENTY_THIRTY = 2;

public static void main(String[]args){
    int a = 110;
    switch (range(a)){
        case TEN_TWENTY: 
            System.out.println("10-20"); 
            break;
        case TWENTY_THIRTY: 
            System.out.println("20-30"); 
            break;
        default: break;
    }
}

How to get folder path from file path with CMD

I had same problem in my loop where i wanted to extract zip files in the same directory and then delete the zip file. The problem was that 7z requires the output folder, so i had to obtain the folder path of each file. Here is my solution:

FOR /F "usebackq tokens=1" %%i IN (`DIR /S/B *.zip` ) DO (
  7z.exe x %%i -aoa -o%%i\..
) 

%%i was a full filename path and %ii\.. simply returns the parent folder.

hope it helps.

How can I resolve the error: "The command [...] exited with code 1"?

For me, in VS 2013, I had to get rid of missing references under References in the UI project (MVC). Turns out, the ones missing were not referenced.

How to create JSON post to api using C#

Try using Web API HttpClient

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://domain.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            // HTTP POST
            var obj = new MyObject() { Str = "MyString"};
            response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
            if (response.IsSuccessStatusCode)
            {
                response.//.. Contains the returned content.
            }
        }
    }

You can find more details here Web API Clients

Minimal web server using netcat

I had the same need/problem but nothing here worked for me (or I didn't understand everything), so this is my solution.

I post my minimal_http_server.sh (working with my /bin/bash (4.3.11) but not /bin/sh because of the redirection):

rm -f out
mkfifo out
trap "rm -f out" EXIT
while true
do
  cat out | nc -l 1500 > >( # parse the netcat output, to build the answer redirected to the pipe "out".
    export REQUEST=
    while read -r line
    do
      line=$(echo "$line" | tr -d '\r\n')

      if echo "$line" | grep -qE '^GET /' # if line starts with "GET /"
      then
        REQUEST=$(echo "$line" | cut -d ' ' -f2) # extract the request
      elif [ -z "$line" ] # empty line / end of request
      then
        # call a script here
        # Note: REQUEST is exported, so the script can parse it (to answer 200/403/404 status code + content)
        ./a_script.sh > out
      fi
    done
  )
done

And my a_script.sh (with your need):

#!/bin/bash

echo -e "HTTP/1.1 200 OK\r"
echo "Content-type: text/html"
echo

date

How can I symlink a file in Linux?

ln -s TARGET LINK_NAME

Where the -s makes it symbolic.

How to read a file in other directory in python

For windows you can either use the full path with '\\' ('/' for Linux and Mac) as separator of you can use os.getcwd to get the current working directory and give path in reference to the current working directory

data_dir = os.getcwd()+'\\child_directory'
file = open(data_dir+'\\filename.txt', 'r')

When I tried to give the path of child_diectory entirely it resulted in error. For e.g. in this case:

file = open('child_directory\\filename.txt', 'r')

Resulted in error. But I think it must work or I am doing it somewhat wrong way but it doesn't work for me. The about way always works.

Removing an item from a select box

Just to augment this for anyone looking, you are also able to just:

$("#selectBox option[value='option1']").hide();

and

$("#selectBox option[value='option1']").show();

Get hostname of current request in node.js Express

If you need a fully qualified domain name and have no HTTP request, on Linux, you could use:

var child_process = require("child_process");

child_process.exec("hostname -f", function(err, stdout, stderr) {
  var hostname = stdout.trim();
});

How do I put hint in a asp:textbox

The placeholder attribute

You're looking for the placeholder attribute. Use it like any other attribute inside your ASP.net control:

<asp:textbox id="txtWithHint" placeholder="hint" runat="server"/>

Don't bother about your IDE (i.e. Visual Studio) maybe not knowing the attribute. Attributes which are not registered with ASP.net are passed through and rendered as is. So the above code (basically) renders to:

<input type="text" placeholder="hint"/>

Using placeholder in resources

A fine way of applying the hint to the control is using resources. This way you may have localized hints. Let's say you have an index.aspx file, your App_LocalResources/index.aspx.resx file contains

<data name="WithHint.placeholder">
    <value>hint</value>
</data>

and your control looks like

<asp:textbox id="txtWithHint" meta:resourcekey="WithHint" runat="server"/>

the rendered result will look the same as the one in the chapter above.

Add attribute in code behind

Like any other attribute you can add the placeholder to the AttributeCollection:

txtWithHint.Attributes.Add("placeholder", "hint");

Enable/Disable a dropdownbox in jquery

$("#chkdwn2").change(function() { 
    if (this.checked) $("#dropdown").prop("disabled",'disabled');
}) 

move div with CSS transition

I added the vendor prefixes, and changed the animation to all, so you have both opacity and width that are animated.

Is this what you're looking for ? http://jsfiddle.net/u2FKM/3/

ALTER DATABASE failed because a lock could not be placed on database

I managed to reproduce this error by doing the following.

Connection 1 (leave running for a couple of minutes)

CREATE DATABASE TESTING123
GO

USE TESTING123;

SELECT NEWID() AS X INTO FOO
FROM sys.objects s1,sys.objects s2,sys.objects s3,sys.objects s4 ,sys.objects s5 ,sys.objects s6

Connections 2 and 3

set lock_timeout 5;

ALTER DATABASE TESTING123 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

What are the differences between C, C# and C++ in terms of real-world applications?

My opinion is C# and ASP.NET would be the best of the three for development that is web biased.

I doubt anyone writes new web apps in C or C++ anymore. It was done 10 years ago, and there's likely a lot of legacy code still in use, but they're not particularly well suited, there doesn't appear to be as much (ongoing) tool support, and they probably have a small active community that does web development (except perhaps for web server development). I wrote many website C++ COM objects back in the day, but C# is far more productive that there's no compelling reason to code C or C++ (in this context) unless you need to.

I do still write C++ if necessary, but it's typically for a small problem domain. e.g. communicating from C# via P/Invoke to old C-style dll's - doing some things that are downright clumsy in C# were a breeze to create a C++ COM object as a bridge.

The nice thing with C# is that you can also easily transfer into writing Windows and Console apps and stay in C#. With Mono you're also not limited to Windows (although you may be limited to which libraries you use).

Anyways this is all from a web-biased perspective. If you asked about embedded devices I'd say C or C++. You could argue none of these are suited for web development, but C#/ASP.NET is pretty slick, it works well, there are heaps of online resources, a huge community, and free dev tools.

So from a real-world perspective, picking only one of C#, C++ and C as requested, as a general rule, you're better to stick with C#.

How do you get assembler output from C/C++ source in gcc?

Use the -S switch

g++ -S main.cpp

or also with gcc

gcc -S main.c

Also see this

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

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

How do you create a toggle button?

I would be inclined to use a class in your css that alters the border style or border width when the button is depressed, so it gives the appearance of a toggle button.

JVM property -Dfile.encoding=UTF8 or UTF-8?

If, running an Oracle HotSpot JDK 1.7.x, on a Linux platform where your locale suggests UTF-8 (e.g. LANG=en_US.utf8), if you don't set it on the command-line with -Dfile.encoding, the JDK will default file.encoding and the default Charset like this:

System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));

... yields:

file.encoding: UTF-8
defaultCharset: UTF-8

... suggesting the default is UTF-8 on such a platform.

Additionally, if java.nio.charset.Charset.defaultCharset() finds file.encoding not-set, it looks for java.nio.charset.Charset.forName("UTF-8"), suggesting it prefers that string, although it is well-aliased, so "UTF8" will also work fine.

If you run the same program on the same platform with java -Dfile.encoding=UTF8, without the hypen, it yields:

file.encoding: UTF8
defaultCharset: UTF-8

... noting that the default charset has been canonicalized from UTF8 to UTF-8.

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

You can use filter like this

angular.module('app').filter('trustAs', ['$sce', 
    function($sce) {
        return function (input, type) {
            if (typeof input === "string") {
                return $sce.trustAs(type || 'html', input);
            }
            console.log("trustAs filter. Error. input isn't a string");
            return "";
        };
    }
]);

usage

<div ng-bind-html="myData | trustAs"></div>

it can be used for other resource types, for example source link for iframes and other types declared here

How to restrict user to type 10 digit numbers in input element?

You can use maxlength to limit the length. Normally for numeric input you'd use type="number", however this adds a spinny box thing to scroll through numbers, which is completely useless for phone numbers. You can, however, use the pattern attribute to limit input to numbers (and require 10 numbers too, if you want):

<input type="text" maxlength="10" pattern="\d{10}" title="Please enter exactly 10 digits" />

How to check file MIME type with javascript before upload?

As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.

get list of pandas dataframe columns based on data type

If after 6 years you still have the issue, this should solve it :)

cols = [c for c in df.columns if df[c].dtype in ['object', 'datetime64[ns]']]

Best way to repeat a character in C#

string.Concat(Enumerable.Repeat("ab", 2));

Returns

"abab"

And

string.Concat(Enumerable.Repeat("a", 2));

Returns

"aa"

from...

Is there a built-in function to repeat string or char in .net?

Check if a specific value exists at a specific key in any subarray of a multidimensional array

I came upon this post looking to do the same and came up with my own solution I wanted to offer for future visitors of this page (and to see if doing this way presents any problems I had not forseen).

If you want to get a simple true or false output and want to do this with one line of code without a function or a loop you could serialize the array and then use stripos to search for the value:

stripos(serialize($my_array),$needle)

It seems to work for me.

Get counts of all tables in a schema

If you want simple SQL for Oracle (e.g. have XE with no XmlGen) go for a simple 2-step:

select ('(SELECT ''' || table_name || ''' as Tablename,COUNT(*) FROM "' || table_name || '") UNION') from USER_TABLES;

Copy the entire result and replace the last UNION with a semi-colon (';'). Then as the 2nd step execute the resulting SQL.

How to clear text area with a button in html using javascript?

You need to attach a click event handler and clear the contents of the textarea from that handler.

HTML

<input type="button" value="Clear" id="clear"> 
<textarea id='output' rows=20 cols=90></textarea>

JS

var input = document.querySelector('#clear');
var textarea = document.querySelector('#output');

input.addEventListener('click', function () {
    textarea.value = '';
}, false);

and here's the working demo.

Windows equivalent of $export

There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.

How to get Map data using JDBCTemplate.queryForMap

queryForMap is appropriate if you want to get a single row. You are selecting without a where clause, so you probably want to queryForList. The error is probably indicative of the fact that queryForMap wants one row, but you query is retrieving many rows.

Check out the docs. There is a queryForList that takes just sql; the return type is a

List<Map<String,Object>>.

So once you have the results, you can do what you are doing. I would do something like

List results = template.queryForList(sql);

for (Map m : results){
   m.get('userid');
   m.get('username');
} 

I'll let you fill in the details, but I would not iterate over keys in this case. I like to explicit about what I am expecting.

If you have a User object, and you actually want to load User instances, you can use the queryForList that takes sql and a class type

queryForList(String sql, Class<T> elementType)

(wow Spring has changed a lot since I left Javaland.)

Capitalize the first letter of both words in a two word string

This gives capital Letters to all major words

library(lettercase)
xString = str_title_case(xString)

CXF: No message body writer found for class - automatically mapping non-simple resources

If you are using "cxf-rt-rs-client" version 3.03. or above make sure the xml name space and schemaLocation are declared as below

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:jaxrs="http://cxf.apache.org/jaxrs" 
    xmlns:jaxrs-client="http://cxf.apache.org/jaxrs-client"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/jaxrs-client http://cxf.apache.org/schemas/jaxrs-client.xsd">

And make sure the client have JacksonJsonProvider or your custom JsonProvider

<jaxrs-client:client id="serviceClient" address="${cxf.endpoint.service.address}" serviceClass="serviceClass">
        <jaxrs-client:headers>
            <entry key="Accept" value="application/json"></entry>
        </jaxrs-client:headers>
        <jaxrs-client:providers>
            <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider">
            <property name="mapper" ref="jacksonMapper" />
        </bean>
        </jaxrs-client:providers>
</jaxrs-client:client>

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

Just telling my resolution: in my case, the libraries and projects weren't being added automatically to the classpath (i don't know why), even clicking at the "add to build path" option. So I went on run -> run configurations -> classpath and added everything I needed through there.

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.querySelector('attributeValue').value='new value'");

What is the meaning of "int(a[::-1])" in Python?

The notation that is used in

a[::-1]

means that for a given string/list/tuple, you can slice the said object using the format

<object_name>[<start_index>, <stop_index>, <step>]

This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.

In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.

So,

a = '1234'
print a[::2]

would print

13

Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example

a = '1234'
print a[3:0:-1]

This would return

432

Note, that it doesn't return 4321 because, the stop index is not included.

Now in your case,

str(int(a[::-1]))

would just reverse a given integer, that is stored in a string, and then convert it back to a string

i.e "1234" -> "4321" -> 4321 -> "4321"

If what you are trying to do is just reverse the given string, then simply a[::-1] would work .

Is it possible to convert char[] to char* in C?

You don't need to declare them as arrays if you want to use use them as pointers. You can simply reference pointers as if they were multi-dimensional arrays. Just create it as a pointer to a pointer and use malloc:

int i;
int M=30, N=25;
int ** buf;
buf = (int**) malloc(M * sizeof(int*));
for(i=0;i<M;i++)
    buf[i] = (int*) malloc(N * sizeof(int));

and then you can reference buf[3][5] or whatever.

Convert Python dict into a dataframe

This is how it worked for me :

df= pd.DataFrame([d.keys(), d.values()]).T
df.columns= ['keys', 'values']  # call them whatever you like

I hope this helps

Centering a button vertically in table cell, using Twitter Bootstrap

So why is td default set to vertical-align: top;? I really don't know that yet. I would not dare to touch it. Instead add this to your stylesheet. It alters the buttons in the tables.

table .btn{
  vertical-align: top;
}

jQuery: set selected value of dropdown list?

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

What is the difference between json.dump() and json.dumps() in python?

One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

(emphasis mine). Note that it may still be a str instance as well.

Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

NSCameraUsageDescription in iOS 10.0 runtime crash?

You have to add this below key in info.plist.

NSCameraUsageDescription Or Privacy - Camera usage description

And add description of usage.

Detailed screenshots are available in this link

Error message Strict standards: Non-static method should not be called statically in php

Your methods are missing the static keyword. Change

function getInstanceByName($name=''){

to

public static function getInstanceByName($name=''){

if you want to call them statically.

Note that static methods (and Singletons) are death to testability.

Also note that you are doing way too much work in the constructor, especially all that querying shouldn't be in there. All your constructor is supposed to do is set the object into a valid state. If you have to have data from outside the class to do that consider injecting it instead of pulling it. Also note that constructors cannot return anything. They will always return void so all these return false statements do nothing but end the construction.

Disable double-tap "zoom" option in browser on touch devices

Note (as of 2020-08-04): this solution does not appear to work in iOS Safari v12+. I will update this answer and delete this note once I find a clear solution that covers iOS Safari.

CSS-only solution

Add touch-action: manipulation to any element on which you want to disable double tap zoom, like with the following disable-dbl-tap-zoom class:

.disable-dbl-tap-zoom {
  touch-action: manipulation;
}

From the touch-action docs (emphasis mine):

manipulation

Enable panning and pinch zoom gestures, but disable additional non-standard gestures such as double-tap to zoom.

This value works on Android and on iOS.

ReactJS - Call One Component Method From Another Component

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true

How to delete a character from a string using Python

from random import randint


def shuffle_word(word):
    newWord=""
    for i in range(0,len(word)):
        pos=randint(0,len(word)-1)
        newWord += word[pos]
        word = word[:pos]+word[pos+1:]
    return newWord

word = "Sarajevo"
print(shuffle_word(word))

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

List<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList();

This one works.

Why does Date.parse give incorrect results?

According to http://blog.dygraphs.com/2012/03/javascript-and-dates-what-mess.html the format "yyyy/mm/dd" solves the usual problems. He says: "Stick to "YYYY/MM/DD" for your date strings whenever possible. It's universally supported and unambiguous. With this format, all times are local." I've set tests: http://jsfiddle.net/jlanus/ND2Qg/432/ This format: + avoids the day and month order ambiguity by using y m d ordering and a 4-digit year + avoids the UTC vs. local issue not complying with ISO format by using slashes + danvk, the dygraphs guy, says that this format is good in all browsers.

How to send POST request?

If you don't want to use a module you have to install like requests, and your use case is very basic, then you can use urllib2

urllib2.urlopen(url, body)

See the documentation for urllib2 here: https://docs.python.org/2/library/urllib2.html.

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

Changing upload_max_filesize on PHP

I've faced the same problem , but I found out that not all the configuration settings could be set using ini_set() function , check this Where a configuration setting may be set

git - Your branch is ahead of 'origin/master' by 1 commit

If you just want to throw away the changes and revert to the last commit (the one you wanted to share):

git reset --hard HEAD~

You may want to check to make absolutely sure you want this (git log), because you'll loose all changes.

A safer alternative is to run

git reset --soft HEAD~ # reset to the last commit
git stash              # stash all the changes in the working tree 
git push               # push changes 
git stash pop          # get your changes back 

java : convert float to String and String to float

You can try this sample of code:

public class StringToFloat
{

  public static void main (String[] args)
  {

    // String s = "fred";    // do this if you want an exception

    String s = "100.00";

    try
    {
      float f = Float.valueOf(s.trim()).floatValue();
      System.out.println("float f = " + f);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }
  }
}

found here

The Android emulator is not starting, showing "invalid command-line parameter"

  • If your SDK location path in Eclipse is in C:\Program Files (x86)\ change to C:\PROGRA~2\.
  • If you are running 32-bit Windows, C:\Program Files\, change the path to C:\PROGRA~1\.

enter image description here

iOS: Multi-line UILabel in Auto Layout

I have a UITableViewCell which has a text wrap label. I worked text wrapping as follows.

1) Set UILabel constraints as follows.

enter image description here

2) Set no. of lines to 0.

3) Added UILabel height constraint to UITableViewCell.

@IBOutlet weak var priorityLabelWidth: NSLayoutConstraint!

4) On UITableViewCell:

priorityLabel.sizeToFit()
priorityLabelWidth.constant = priorityLabel.intrinsicContentSize().width+5

Passing parameter to controller from route in laravel

You don't need anything special for adding paramaters. Just like you had it.

Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups@show'));


class Groups_Controller extends Base_Controller {

    public $restful = true;    

    public function get_show($groupID) {
        return 'I am group id ' . $groupID;
    }  


}

Check if a file exists with wildcard in shell script

You can also cut other files out

if [ -e $( echo $1 | cut -d" " -f1 ) ] ; then
   ...
fi

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Had to add the service in the calling App.config file to have it work. Make sure that you but it after all . This seemed to work for me.

Java "lambda expressions not supported at this language level"

As Stephen C pointed out, Eclipse Kepler (4.3) has Java 8 support when the patch is installed (installation instructions here)

Once installed, you’ll need to tell your projects to use java 8. First add the JDK to eclipse:

  • Go to Window -> Preferences
  • Go to Java -> Installed JREs
  • Add Standard VM, and point to the location of the JRE
  • Then go to Compiler
  • Set Compiler compliance level to 1.8

Then tell the project to use JDK 1.8:

  • Go to Project -> preferences
  • Go to Java Compiler
  • Enable project specific settings
  • Set Compiler compliance level to 1.8

Plotting of 1-dimensional Gaussian distribution function

you can read this tutorial for how to use functions of statistical distributions in python. http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html

from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np 

#initialize a normal distribution with frozen in mean=-1, std. dev.= 1
rv = norm(loc = -1., scale = 1.0)
rv1 = norm(loc = 0., scale = 2.0)
rv2 = norm(loc = 2., scale = 3.0)

x = np.arange(-10, 10, .1)

#plot the pdfs of these normal distributions 
plt.plot(x, rv.pdf(x), x, rv1.pdf(x), x, rv2.pdf(x))

How to compile a static library in Linux?

Generate the object files with gcc, then use ar to bundle them into a static library.

JSON string to JS object

You can use this library from JSON.org to translate your string into a JSON object.

var var1_obj = JSON.parse(var1);

Or you can use the jquery-json library as well.

var var1_obj = $.toJSON(var1);

Converting XDocument to XmlDocument and vice versa

You can use the built in xDocument.CreateReader() and an XmlNodeReader to convert back and forth.

Putting that into an Extension method to make it easier to work with.

using System;
using System.Xml;
using System.Xml.Linq;

namespace MyTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {

            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");

            var xDocument = xmlDocument.ToXDocument();
            var newXmlDocument = xDocument.ToXmlDocument();
            Console.ReadLine();
        }
    }

    public static class DocumentExtensions
    {
        public static XmlDocument ToXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new XmlDocument();
            using(var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }
            return xmlDocument;
        }

        public static XDocument ToXDocument(this XmlDocument xmlDocument)
        {
            using (var nodeReader = new XmlNodeReader(xmlDocument))
            {
                nodeReader.MoveToContent();
                return XDocument.Load(nodeReader);
            }
        }
    }
}

Sources:

How to update a single pod without touching other dependencies

I'm using cocoapods version 1.0.1 and using pod update name-of-pod works perfectly. No other pods are updated, just the specific one you enter.

Mongoose's find method with $or condition does not work properly

According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."

So add indexes for your other fields and it will work. I had a similar problem and this solved it.

You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/

C/C++ macro string concatenation

If they're both strings you can just do:

#define STR3 STR1 STR2

This then expands to:

#define STR3 "s" "1"

and in the C language, separating two strings with space as in "s" "1" is exactly equivalent to having a single string "s1".

cannot load such file -- bundler/setup (LoadError)

NOTE: My hosting company is Site5.com and I have a Managed VPS.

I added env variables for both GEM_HOME and GEM_PATH to the .htaccess file in my public_html directory (an alias to the public directory in the rails app)

They were not needed before so something must have changed on the hosts side. It got this error after touching the restart.txt file to restart the passenger server.

Got GEM_PATH by:

echo $GEM_PATH

Got the GEM_HOME by:

gem env

 RubyGems Environment:
   - RUBYGEMS VERSION: 2.0.14
   - RUBY VERSION: 2.0.0 (2013-11-22 patchlevel 353) [x86_64-linux]
   - INSTALLATION DIRECTORY: /home/username/ruby/gems
   - RUBY EXECUTABLE: /usr/local/ruby20/bin/ruby
   - EXECUTABLE DIRECTORY: /home/username/ruby/gems/bin
   - RUBYGEMS PLATFORMS:
     - ruby
     - x86_64-linux
   - GEM PATHS:
      - /home/username/ruby/gems
      - /usr/local/ruby2.0/lib64/ruby/gems/
   - GEM CONFIGURATION:
      - :update_sources => true
      - :verbose => true
      - :backtrace => false
      - :bulk_threshold => 1000
      - "gem" => "--remote --gen-rdoc --run-tests"
      **- "gemhome" => "/home/username/ruby/gems"**
      - "gempath" => ["/home/username/ruby/gems", "/usr/local/ruby2.0/lib64/ruby/gems/"]
      - "rdoc" => "--inline-source --line-numbers"
   - REMOTE SOURCES:
      - https://rubygems.org/

Updated .htaccess file with the following lines:

SetEnv GEM_HOME /usr/local/ruby2.0/lib64/ruby/gems/
SetEnv GEM_PATH /home/username/ruby/gems:/usr/local/ruby20/lib64/ruby/gems/:/home/username/ruby/gems:/usr/

html table cell width for different rows

One solution would be to divide your table into 20 columns of 5% width each, then use colspan on each real column to get the desired width, like this:

_x000D_
_x000D_
<html>_x000D_
<body bgcolor="#14B3D9">_x000D_
<table width="100%" border="1" bgcolor="#ffffff">_x000D_
    <colgroup>_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
        <col width="5%"><col width="5%">_x000D_
    </colgroup>_x000D_
    <tr>_x000D_
        <td colspan=5>25</td>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=5>25</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan=10>50</td>_x000D_
        <td colspan=6>30</td>_x000D_
        <td colspan=4>20</td>_x000D_
    </tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

JSFIDDLE

How to find Google's IP address?

The following IP address ranges belong to Google:

64.233.160.0 - 64.233.191.255
66.102.0.0 - 66.102.15.255
66.249.64.0 - 66.249.95.255
72.14.192.0 - 72.14.255.255
74.125.0.0 - 74.125.255.255
209.85.128.0 - 209.85.255.255
216.239.32.0 - 216.239.63.255

Like many popular Web sites, Google utilizes multiple Internet servers to handle incoming requests to its Web site. Instead of entering http://www.google.com/ into the browser, a person can enter http:// followed by one of the above addresses, for example:

http://74.125.224.72/

SOURCE

Why call git branch --unset-upstream to fixup?

Issue: Your branch is based on 'origin/master', but the upstream is gone.

Solution: git branch --unset-upstream

How do you remove columns from a data.frame?

I use data.table's := operator to delete columns instantly regardless of the size of the table.

DT[, coltodelete := NULL]

or

DT[, c("col1","col20") := NULL]

or

DT[, (125:135) := NULL]

or

DT[, (variableHoldingNamesOrNumbers) := NULL]

Any solution using <- or subset will copy the whole table. data.table's := operator merely modifies the internal vector of pointers to the columns, in place. That operation is therefore (almost) instant.

Correct way to initialize HashMap and can HashMap hold different value types?

A HashMap can hold any object as a value, even if it is another HashMap. Eclipse is suggesting that you declare the types because that is the recommended practice for Collections. under Java 5. You are free to ignore Eclipse's suggestions.

Under Java 5, an int (or any primitive type) will be autoboxed into an Integer (or other corresponding type) when you add it to a collection. Be careful with this though, as there are some catches to using autoboxing.

Android Studio: Where is the Compiler Error Output Window?

In android studio 2.2.3 you can find output in the gradle console as shown below gradle console

Convert MySql DateTime stamp into JavaScript's Date format

var a=dateString.split(" ");
var b=a[0].split("-");
var c=a[1].split(":");
var date = new Date(b[0],(b[1]-1),b[2],b[0],c[1],c[2]);

What is the most elegant way to check if all values in a boolean array are true?

That line should be sufficient:

BooleanUtils.and(boolean... array)

but to calm the link-only purists:

Performs an and on a set of booleans.

How can I get the number of days between 2 dates in Oracle 11g?

This will work i have tested myself.
It gives difference between sysdate and date fetched from column admitdate

  TABLE SCHEMA:
    CREATE TABLE "ADMIN"."DUESTESTING" 
    (   
  "TOTAL" NUMBER(*,0), 
"DUES" NUMBER(*,0), 
"ADMITDATE" TIMESTAMP (6), 
"DISCHARGEDATE" TIMESTAMP (6)
    )

EXAMPLE:
select TO_NUMBER(trunc(sysdate) - to_date(to_char(admitdate, 'yyyy-mm-dd'),'yyyy-mm-dd')) from admin.duestesting where total=300

How to enter command with password for git pull?

Doesn't answer the question directly, but I found this question when searching for a way to, basically, not re-enter the password every single time I pull on a remote server.

Well, git allows you to cache your credentials for a finite amount of time. It's customizable in git config and this page explains it very well:

https://help.github.com/articles/caching-your-github-password-in-git/#platform-linux

In a terminal, run:

$ git config --global credential.helper cache
# Set git to use the credential memory cache

To customize the cache timeout, you can do:

$ git config --global credential.helper 'cache --timeout=3600'
# Set the cache to timeout after 1 hour (setting is in seconds)

Your credentials will then be stored in-memory for the requested amount of time.

How do I convert an existing callback API to promises?

I don't think the window.onload suggestion by @Benjamin will work all the time, as it doesn't detect whether it is called after the load. I have been bitten by that many times. Here is a version which should always work:

function promiseDOMready() {
    return new Promise(function(resolve) {
        if (document.readyState === "complete") return resolve();
        document.addEventListener("DOMContentLoaded", resolve);
    });
}
promiseDOMready().then(initOnLoad);

Get records with max value for each group of grouped SQL results

I would not use Group as column name since it is reserved word. However following SQL would work.

SELECT a.Person, a.Group, a.Age FROM [TABLE_NAME] a
INNER JOIN 
(
  SELECT `Group`, MAX(Age) AS oldest FROM [TABLE_NAME] 
  GROUP BY `Group`
) b ON a.Group = b.Group AND a.Age = b.oldest

Bootstrap: change background color

You could hard code it.

<div class="col-md-6" style="background-color:blue;">
</div>

<div class="col-md-6" style="background-color:white;">
</div>

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

There is actually a default pattern that you can employ to achieve this result without having to implement IDesignTimeDbContextFactory and do any config file copying.

It is detailed in this doc, which also discusses the other ways in which the framework will attempt to instantiate your DbContext at design time.

Specifically, you leverage a new hook, in this case a static method of the form public static IWebHost BuildWebHost(string[] args). The documentation implies otherwise, but this method can live in whichever class houses your entry point (see src). Implementing this is part of the guidance in the 1.x to 2.x migration document and what's not completely obvious looking at the code is that the call to WebHost.CreateDefaultBuilder(args) is, among other things, connecting your configuration in the default pattern that new projects start with. That's all you need to get the configuration to be used by the design time services like migrations.

Here's more detail on what's going on deep down in there:

While adding a migration, when the framework attempts to create your DbContext, it first adds any IDesignTimeDbContextFactory implementations it finds to a collection of factory methods that can be used to create your context, then it gets your configured services via the static hook discussed earlier and looks for any context types registered with a DbContextOptions (which happens in your Startup.ConfigureServices when you use AddDbContext or AddDbContextPool) and adds those factories. Finally, it looks through the assembly for any DbContext derived classes and creates a factory method that just calls Activator.CreateInstance as a final hail mary.

The order of precedence that the framework uses is the same as above. Thus, if you have IDesignTimeDbContextFactory implemented, it will override the hook mentioned above. For most common scenarios though, you won't need IDesignTimeDbContextFactory.

"Sources directory is already netbeans project" error when opening a project from existing sources

Thank you!

I was having the same problem:
Sources directory is already NetBeans project (maybe only in memory).

Netbeans creates a folder in your project named "nbproject". Once you delete that, restart the IDE and you're good to go.

How to use terminal commands with Github?

git add myfile.h
git commit -m "your commit message"
git push -u origin master

if you don't remember all the files you need to update, use

git status

The 'json' native gem requires installed build tools

I believe those installers make changes to the path. Did you try closing and re-opening the CMD window after running them and before the last attempt to install the gem that wants devkit present?

Also, be sure you are using the right devkit installer for your version of Ruby. The documentation at devkit wiki page has a requirements note saying:

For RubyInstaller versions 1.8.7, 1.9.2, and 1.9.3 use the DevKit 4.5.2

Handle spring security authentication exceptions with @ExceptionHandler

In ResourceServerConfigurerAdapter class, below code snipped worked for me. http.exceptionHandling().authenticationEntryPoint(new AuthFailureHandler()).and.csrf().. did not work. That's why I wrote it as separate call.

public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.exceptionHandling().authenticationEntryPoint(new AuthFailureHandler());

        http.csrf().disable()
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers("/subscribers/**").authenticated()
                .antMatchers("/requests/**").authenticated();
    }

Implementation of AuthenticationEntryPoint for catching token expiry and missing authorization header.


public class AuthFailureHandler implements AuthenticationEntryPoint {

  @Override
  public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)
      throws IOException, ServletException {
    httpServletResponse.setContentType("application/json");
    httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    if( e instanceof InsufficientAuthenticationException) {

      if( e.getCause() instanceof InvalidTokenException ){
        httpServletResponse.getOutputStream().println(
            "{ "
                + "\"message\": \"Token has expired\","
                + "\"type\": \"Unauthorized\","
                + "\"status\": 401"
                + "}");
      }
    }
    if( e instanceof AuthenticationCredentialsNotFoundException) {

      httpServletResponse.getOutputStream().println(
          "{ "
              + "\"message\": \"Missing Authorization Header\","
              + "\"type\": \"Unauthorized\","
              + "\"status\": 401"
              + "}");
    }

  }
}

How to prevent colliders from passing through each other?

Collision with fast-moving objects is always a problem. A good way to ensure that you detect all collision is to use Raycasting instead of relying on the physics simulation. This works well for bullets or small objects, but will not produce good results for large objects. http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html

Pseudo-codeish (I don't have code-completion here and a poor memory):

void FixedUpdate()
{
    Vector3 direction = new Vector3(transform.position - lastPosition);
    Ray ray = new Ray(lastPosition, direction);
    RaycastHit hit;
    if (Physics.Raycast(ray, hit, direction.magnitude))
    {
        // Do something if hit
    }

    this.lastPosition = transform.position;
}

AngularJS - Animate ng-view transitions

1.Install angular-animate

2.Add the animation effect to the class ng-enter for page entering animation and the class ng-leave for page exiting animation

for reference: this page has a free resource on angular view transition https://e21code.herokuapp.com/angularjs-page-transition/

How to prevent custom views from losing state across screen orientation changes

I found that this answer was causing some crashes on Android versions 9 and 10. I think it's a good approach but when I was looking at some Android code I found out it was missing a constructor. The answer is quite old so at the time there probably was no need for it. When I added the missing constructor and called it from the creator the crash was fixed.

So here is the edited code:

public class CustomView extends LinearLayout {

    private int stateToSave;

    ...

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);

        // your custom state
        ss.stateToSave = this.stateToSave;

        return ss;
    }

    @Override
    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container)
    {
        dispatchFreezeSelfOnly(container);
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());

        // your custom state
        this.stateToSave = ss.stateToSave;
    }

    @Override
    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container)
    {
        dispatchThawSelfOnly(container);
    }

    static class SavedState extends BaseSavedState {
        int stateToSave;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            this.stateToSave = in.readInt();
        }

        // This was the missing constructor
        @RequiresApi(Build.VERSION_CODES.N)
        SavedState(Parcel in, ClassLoader loader)
        {
            super(in, loader);
            this.stateToSave = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(this.stateToSave);
        }    
        
        public static final Creator<SavedState> CREATOR =
            new ClassLoaderCreator<SavedState>() {
          
            // This was also missing
            @Override
            public SavedState createFromParcel(Parcel in, ClassLoader loader)
            {
                return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new SavedState(in, loader) : new SavedState(in);
            }

            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in, null);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
}

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

If you use module with c++ code and have the same issue you could try

Build -> Refresh Linked C++ Projects

Also, you should open some file from this module and do

Build -> Make module "YourNativeLibModuleName"

Pip error: Microsoft Visual C++ 14.0 is required

Try doing this:

py -m pip install pipwin
py -m pipwin install PyAudio

JFrame in full screen Java

you can simply do like this -

public void FullScreen() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            final View v = this.activity.getWindow().getDecorView();
            v.setSystemUiVisibility(8);
        }
        else if (Build.VERSION.SDK_INT >= 19) {
            final View decorView = this.activity.getWindow().getDecorView();
            final int uiOptions = 4102;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

Display exact matches only with grep

Recently I came across an issue in grep. I was trying to match the pattern x.y.z and grep returned x.y-z.Using some regular expression we may can overcome this, but with grep whole word matching did not help. Since the script I was writing is a generic one, I cannot restrict search for a specific way as in like x.y.z or x.y-z ..

Quick way I figured is to run a grep and then a condition check var="x.y.z" var1=grep -o x.y.z file.txt if [ $var1 == $var ] echo "Pattern match exact" else echo "Pattern does not match exact" fi

https://linuxacatalyst.blogspot.com/2019/12/grep-pattern-matching-issues.html

How do I import material design library to Android Studio?

If you are using Android Studio:

  • You can import the project as a module and change the following in the build.gradle file of the imported module.

  • Change apply plugin: com.android.application to apply plugin: com.android.library remove applicationId and set minSdkVersion to match your project minSdkVersion.

  • And in your project build.gradle file compile project(':MaterialDesignLibrary'), where MaterialDesignLibrary is the name of your library project or you can import the module by File -> Project Structure -> Select your project under Modules -> Dependencies -> Click on + to add a module.

Service vs IntentService in the Android platform

IntentService

IntentService runs on its own thread. It will stop itself when it's done. More like fire and forget. Subsequent calls will be queued. Good for queuing calls. You can also spin multiple threads within IntentServiceif you need to- You can achieve this using ThreadPoolExecutor. I say this because many people asked me "why use IntentService since it doesn't support parallel execution". IntentService is just a thread. You can do whatever you need inside it- Even spinning multiple threads. The only caveat is that IntentService finishes as soon as you spin those multiple threads. It doesn't wait for those threads to come back. You need to take care of this. So I recommend using ThreadPoolExecutor in those scenarios.

  • Good for Syncing, uploading etc …

Service

By Default Service runs on the main thread. You need to spin a worker thread to do your job. You need to stop service explicitly. I used it for a situation when you need to run stuff in the background even when you move away from your app and come back more for a Headless service.

  • Again you can run multiple threads if you need to.
  • Can be used for apps like music players.

You can always communicate back to your activity using BroadcastReceivers if you need to.

Why does Java have transient fields?

My small contribution :

What is a transient field?
Basically, any field modified with the transient keyword is a transient field.

Why are transient fields needed in Java?
The transient keyword gives you some control over the serialization process and allows you to exclude some object properties from this process. The serialization process is used to persist Java objects, mostly so that their states can be preserved while they are transferred or inactive. Sometimes, it makes sense not to serialize certain attributes of an object.

Which fields should you mark transient?
Now we know the purpose of the transient keyword and transient fields, it's important to know which fields to mark transient. Static fields aren't serialized either, so the corresponding keyword would also do the trick. But this might ruin your class design; this is where the transient keyword comes to the rescue. I try not to allow fields whose values can be derived from others to be serialized, so I mark them transient. If you have a field called interest whose value can be calculated from other fields (principal, rate & time), there is no need to serialize it.

Another good example is with article word counts. If you are saving an entire article, there's really no need to save the word count, because it can be computed when article gets "deserialized." Or think about loggers; Logger instances almost never need to be serialized, so they can be made transient.

Unable to show a Git tree in terminal

git log --oneline --decorate --all --graph

A visual tree with branch names included.

Use this to add it as an alias

git config --global alias.tree "log --oneline --decorate --all --graph"

You call it with

git tree

Git Tree

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

it should vary with the architecture because it represents the size of any object. So on a 32-bit system size_t will likely be at least 32-bits wide. On a 64-bit system it will likely be at least 64-bit wide.

QLabel: set color of text and background

This one is working perfect

QColorDialog *dialog = new QColorDialog(this);
QColor color=  dialog->getColor();
QVariant variant= color;
QString colcode = variant.toString();
ui->label->setStyleSheet("QLabel { background-color :"+colcode+" ; color : blue; }");

getColor() method returns the selected color. You can change label color using stylesheet

Saving a text file on server using JavaScript

You must have a server-side script to handle your request, it can't be done using javascript.

To send raw data without URIencoding or escaping special characters to the php and save it as new txt file you can send ajax request using post method and FormData like:

JS:

var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);

PHP:

if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name

$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}

Edit:

As Florian mentioned below, the XHR fallback is not required since FormData is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:

var xhr = new XMLHttpRequest();

Also please note that this works only for browsers that support FormData such as IE +10.

How to set the locale inside a Debian/Ubuntu Docker container?

Rather than resetting the locale after the installation of the locales package you can answer the questions you would normally get asked (which is disabled by noninteractive) before installing the package so that the package scripts setup the locale correctly, this example sets the locale to english (British, UTF-8):

RUN echo locales locales/default_environment_locale select en_GB.UTF-8 | debconf-set-selections
RUN echo locales locales/locales_to_be_generated select "en_GB.UTF-8 UTF-8" | debconf-set-selections

RUN \
  apt-get update && \
  DEBIAN_FRONTEND=noninteractive apt-get install -y locales && \
  rm -rf /var/lib/apt/lists/*

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()