Programs & Examples On #Vob

How to set width of mat-table column in angular?

As i have implemented, and it is working fine. you just need to add column width using matColumnDef="description"

for example :

<mat-table #table [dataSource]="dataSource" matSortDisableClear>
    <ng-container matColumnDef="productId">
        <mat-header-cell *matHeaderCellDef>product ID</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.id}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="productName">
        <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.name}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="actions">
        <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
        <mat-cell *matCellDef="let product">
            <button (click)="view(product)">
                <mat-icon>visibility</mat-icon>
            </button>
        </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

here matColumnDef is productId, productName and action

now we apply width by matColumnDef

styling

.mat-column-productId {
    flex: 0 0 10%;
}
.mat-column-productName {
    flex: 0 0 50%;
}

and remaining width is equally allocated to other columns

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.

Example python implementation:

import sys

inner_loop = 0

def collatz_sequence(N, cache):
    global inner_loop

    l = [ ]
    stop = False
    n = N

    tails = [ ]

    while not stop:
        inner_loop += 1
        tmp = n
        l.append(n)
        if n <= 1:
            stop = True  
        elif n in cache:
            stop = True
        elif n % 2:
            n = 3*n + 1
        else:
            n = n // 2
        tails.append((tmp, len(l)))

    for key, offset in tails:
        if not key in cache:
            cache[key] = l[offset:]

    return l

def gen_sequence(l, cache):
    for elem in l:
        yield elem
        if elem in cache:
            yield from gen_sequence(cache[elem], cache)
            raise StopIteration

if __name__ == "__main__":
    le_cache = {}

    for n in range(1, 4711, 5):
        l = collatz_sequence(n, le_cache)
        print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))

    print("inner_loop = {}".format(inner_loop))

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Another approach(Inside of $function to asure that the each is executed on document ready):

var ids = [1,2];
$(function(){
  $('.checkbox-wrapper>input[type="checkbox"]').each(function(i,item){
    if(ids.indexOf($(item).data('id')) > -1){
       $(item).prop("checked", "checked");
    }
  });
});

Working fiddle: https://jsfiddle.net/robertrozas/w5uda72v/

What is the n.fn.init[0], and why it is returned? Why are my two seemingly identical JQuery functions returning different things?

Answer: It seems that your elements are not in the DOM yet, when you are trying to find them. As @Rory McCrossan pointed out, the length:0 means that it doesn't find any element based on your search criteria.

About n.fn.init[0], lets look at the core of the Jquery Library:

var jQuery = function( selector, context ) {
   return new jQuery.fn.init( selector, context );
};

Looks familiar, right?, now in a minified version of jquery, this should looks like:

var n = function( selector, context ) {
   return new n.fn.init( selector, context );
};

So when you use a selector you are creating an instance of the jquery function; when found an element based on the selector criteria it returns the matched elements; when the criteria does not match anything it returns the prototype object of the function.

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

Loop over html table and get checked checkboxes (JQuery)

use .filter(':has(:checkbox:checked)' ie:

$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
 $('#out').append(this.id);
});

CSV new-line character seen in unquoted field error

I realize this is an old post, but I ran into the same problem and don't see the correct answer so I will give it a try

Python Error:

_csv.Error: new-line character seen in unquoted field

Caused by trying to read Macintosh (pre OS X formatted) CSV files. These are text files that use CR for end of line. If using MS Office make sure you select either plain CSV format or CSV (MS-DOS). Do not use CSV (Macintosh) as save-as type.

My preferred EOL version would be LF (Unix/Linux/Apple), but I don't think MS Office provides the option to save in this format.

jQuery get values of checked checkboxes into array

DEMO: http://jsfiddle.net/PBhHK/

$(document).ready(function(){

    var searchIDs = $('input:checked').map(function(){

      return $(this).val();

    });
    console.log(searchIDs.get());

});

Just call get() and you'll have your array as it is written in the specs: http://api.jquery.com/map/

$(':checkbox').map(function() {
      return this.id;
    }).get().join();

Error Message : Cannot find or open the PDB file

I'm also a newbie to CUDA/Visual studio and encountered the same problem with a couple of the samples. If you run DEBUG-> Start Debugging, then repeatedly step over (F10) you'll see the output window appear and get populated. Normal execution returns nomal completion status 0x0 (as you observed) and the output window is closed.

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

How to simulate a click with JavaScript?

Have you considered using jQuery to avoid all the browser detection? With jQuery, it would be as simple as:

$("#mytest1").click();

How to get the background color of an HTML element?

Simple solution

myDivObj = document.getElementById("myDivID")
let myDivObjBgColor = window.getComputedStyle(myDivObj).backgroundColor;

Now the background color is stored in the new variable.

https://jsfiddle.net/7q1dpeo9/1/

Ball to Ball Collision - Detection and Handling

One thing I see here to optimize.

While I do agree that the balls hit when the distance is the sum of their radii one should never actually calculate this distance! Rather, calculate it's square and work with it that way. There's no reason for that expensive square root operation.

Also, once you have found a collision you have to continue to evaluate collisions until no more remain. The problem is that the first one might cause others that have to be resolved before you get an accurate picture. Consider what happens if the ball hits a ball at the edge? The second ball hits the edge and immediately rebounds into the first ball. If you bang into a pile of balls in the corner you could have quite a few collisions that have to be resolved before you can iterate the next cycle.

As for the O(n^2), all you can do is minimize the cost of rejecting ones that miss:

1) A ball that is not moving can't hit anything. If there are a reasonable number of balls lying around on the floor this could save a lot of tests. (Note that you must still check if something hit the stationary ball.)

2) Something that might be worth doing: Divide the screen into a number of zones but the lines should be fuzzy--balls at the edge of a zone are listed as being in all the relevant (could be 4) zones. I would use a 4x4 grid, store the zones as bits. If an AND of the zones of two balls zones returns zero, end of test.

3) As I mentioned, don't do the square root.

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

How to get multiple selected values from select box in JSP?

Since I don't find a simple answer just adding more this will be JSP page. save this content to a jsp file once you run you can see the values of the selected displayed.

Update: save the file as test.jsp and run it on any web/app server

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<% String[] a = request.getParameterValues("multiple");
if(a!=null)
{
for(int i=0;i<a.length;i++){
//out.println(Integer.parseInt(a[i])); //If integer
out.println(a[i]);
}}
%>
<html>
<body>
<form action="test.jsp" method="get">
<select name="multiple" multiple="multiple"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>
<input type="submit">
</form>
</body>
</html>

Open directory dialog

Ookii folder dialog can be found at Nuget.

PM> Install-Package Ookii.Dialogs.Wpf

And, example code is as below.

var dialog = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog();
if (dialog.ShowDialog(this).GetValueOrDefault())
{
    textBoxFolderPath.Text = dialog.SelectedPath;
}

More information on how to use it: https://github.com/augustoproiete/ookii-dialogs-wpf

Iterating over a numpy array

I think you're looking for the ndenumerate.

>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
...  print x,y
... 
0 0
0 1
1 0
1 1
2 0
2 1

Regarding the performance. It is a bit slower than a list comprehension.

X = np.zeros((100, 100, 100))

%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop

%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop

If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords attribute of the flat iterator.

a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop

Converting dictionary to JSON

No need to convert it in a string by using json.dumps()

r = {'is_claimed': 'True', 'rating': 3.5}
file.write(r['is_claimed'])
file.write(str(r['rating']))

You can get the values directly from the dict object.

Problem with converting int to string in Linq to entities

Can you try:

var items = from c in contacts
        select new ListItem
        {
            Value = Convert.ToString(c.ContactId), 
            Text = c.Name
        };

Number of days between past date and current date in Google spreadsheet

DAYS360 does not calculate what you want, i.e. the number of days passed between the two dates. Use simple subtraction (-) or MINUS(). I made an updated copy of @DrCord’s sample spreadsheet to illustrate this.

Are you SURE you want DAYS360? That is a specialized function used in the financial sector to simplify calculations for bonds. It assumes a 360 day year, with 12 months of 30 days each. If you really want actual days, you'll lose 6 days each year. [source]

Regex to replace everything except numbers and a decimal point

Use this:

document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');

How to pass multiple values to single parameter in stored procedure

This can not be done easily. There's no way to make an NVARCHAR parameter take "more than one value". What I've done before is - as you do already - make the parameter value like a list with comma-separated values. Then, split this string up into its parts in the stored procedure.

Splitting up can be done using string functions. Add every part to a temporary table. Pseudo-code for this could be:

CREATE TABLE #TempTable (ID INT)
WHILE LEN(@PortfolioID) > 0
BEGIN
    IF NOT <@PortfolioID contains Comma>
    BEGIN
        INSERT INTO #TempTable VALUES CAST(@PortfolioID as INT)
        SET @PortfolioID = ''
    END ELSE
    BEGIN
         INSERT INTO #Temptable VALUES CAST(<Part until next comma> AS INT)
         SET @PortfolioID = <Everything after the next comma>
    END
END

Then, change your condition to

WHERE PortfolioId IN (SELECT ID FROM #TempTable)

EDIT
You may be interested in the documentation for multi value parameters in SSRS, which states:

You can define a multivalue parameter for any report parameter that you create. However, if you want to pass multiple parameter values back to a data source by using the query, the following requirements must be satisfied:

The data source must be SQL Server, Oracle, Analysis Services, SAP BI NetWeaver, or Hyperion Essbase.

The data source cannot be a stored procedure. Reporting Services does not support passing a multivalue parameter array to a stored procedure.

The query must use an IN clause to specify the parameter.

This I found here.

How to add white spaces in HTML paragraph

If you really need then you can use i.e. &nbsp; entity to do that, but remember that fonts used to render your page are usually proportional, so "aligning" with spaces does not really work and looks ugly.

How to get div height to auto-adjust to background size?

There is a very nice and cool way to make a background image work like an img element so it adjust its height automatically. You need to know the image width and height ratio. Set the height of the container to 0 and set the padding-top as percentage based upon the image ratio.

It will look like the following:

div {
    background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
    background-size: contain;
    background-repeat: no-repeat;
    width: 100%;
    height: 0;
    padding-top: 66.64%; /* (img-height / img-width * container-width) */
                /* (853 / 1280 * 100) */
}

You just got a background image with auto height which will work just like an img element. Here is a working prototype (you can resize and check the div height): http://jsfiddle.net/TPEFn/2/

How to flush output of print function?

How to flush output of Python print?

I suggest five ways of doing this:

  • In Python 3, call print(..., flush=True) (the flush argument is not available in Python 2's print function, and there is no analogue for the print statement).
  • Call file.flush() on the output file (we can wrap python 2's print function to do this), for example, sys.stdout
  • apply this to every print function call in the module with a partial function,
    print = partial(print, flush=True) applied to the module global.
  • apply this to the process with a flag (-u) passed to the interpreter command
  • apply this to every python process in your environment with PYTHONUNBUFFERED=TRUE (and unset the variable to undo this).

Python 3.3+

Using Python 3.3 or higher, you can just provide flush=True as a keyword argument to the print function:

print('foo', flush=True) 

Python 2 (or < 3.3)

They did not backport the flush argument to Python 2.7 So if you're using Python 2 (or less than 3.3), and want code that's compatible with both 2 and 3, may I suggest the following compatibility code. (Note the __future__ import must be at/very "near the top of your module"):

from __future__ import print_function
import sys

if sys.version_info[:2] < (3, 3):
    old_print = print
    def print(*args, **kwargs):
        flush = kwargs.pop('flush', False)
        old_print(*args, **kwargs)
        if flush:
            file = kwargs.get('file', sys.stdout)
            # Why might file=None? IDK, but it works for print(i, file=None)
            file.flush() if file is not None else sys.stdout.flush()

The above compatibility code will cover most uses, but for a much more thorough treatment, see the six module.

Alternatively, you can just call file.flush() after printing, for example, with the print statement in Python 2:

import sys
print 'delayed output'
sys.stdout.flush()

Changing the default in one module to flush=True

You can change the default for the print function by using functools.partial on the global scope of a module:

import functools
print = functools.partial(print, flush=True)

if you look at our new partial function, at least in Python 3:

>>> print = functools.partial(print, flush=True)
>>> print
functools.partial(<built-in function print>, flush=True)

We can see it works just like normal:

>>> print('foo')
foo

And we can actually override the new default:

>>> print('foo', flush=False)
foo

Note again, this only changes the current global scope, because the print name on the current global scope will overshadow the builtin print function (or unreference the compatibility function, if using one in Python 2, in that current global scope).

If you want to do this inside a function instead of on a module's global scope, you should give it a different name, e.g.:

def foo():
    printf = functools.partial(print, flush=True)
    printf('print stuff like this')

If you declare it a global in a function, you're changing it on the module's global namespace, so you should just put it in the global namespace, unless that specific behavior is exactly what you want.

Changing the default for the process

I think the best option here is to use the -u flag to get unbuffered output.

$ python -u script.py

or

$ python -um package.module

From the docs:

Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.

Note that there is internal buffering in file.readlines() and File Objects (for line in sys.stdin) which is not influenced by this option. To work around this, you will want to use file.readline() inside a while 1: loop.

Changing the default for the shell operating environment

You can get this behavior for all python processes in the environment or environments that inherit from the environment if you set the environment variable to a nonempty string:

e.g., in Linux or OSX:

$ export PYTHONUNBUFFERED=TRUE

or Windows:

C:\SET PYTHONUNBUFFERED=TRUE

from the docs:

PYTHONUNBUFFERED

If this is set to a non-empty string it is equivalent to specifying the -u option.


Addendum

Here's the help on the print function from Python 2.7.12 - note that there is no flush argument:

>>> from __future__ import print_function
>>> help(print)
print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

Getting value from appsettings.json in .net core

This tends to happen particularly with as I'd assume because of how one configures the launch.json.

Based on this answer I had to reconfigure the base path the configuration is being searched for to that of DLL's path, and since the default setting was optional it was hard to track this down on a .net core 3.1 & net 5.0 app. Here's how I've reconfigured

Program.cs:

using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace API
{
    public class Program
    {
        public static int Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
            return 0;
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(c =>
            {
                var codeBase = Assembly.GetExecutingAssembly().Location;
                var uri = new UriBuilder(codeBase);
                var path = Uri.UnescapeDataString(uri.Path);
                var assembyDirectory = Path.GetDirectoryName(path);
                c.SetBasePath(assembyDirectory);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            ;
        }
    }
}

I could access the configuration fine in Startup.cs:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Model;

namespace API
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var myOptions = Configuration.To<ApiConfig>();
            services.AddAuthentication(myOptions.Secret);
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}

Is the size of C "int" 2 bytes or 4 bytes?

Is the size of C “int” 2 bytes or 4 bytes?

Does an Integer variable in C occupy 2 bytes or 4 bytes?

C allows "bytes" to be something other than 8 bits per "byte".

CHAR_BIT number of bits for smallest object that is not a bit-field (byte) C11dr §5.2.4.2.1 1

A value of something than 8 is increasingly uncommon. For maximum portability, use CHAR_BIT rather than 8. The size of an int in bits in C is sizeof(int) * CHAR_BIT.

#include <limits.h>
printf("(int) Bit size %zu\n", sizeof(int) * CHAR_BIT);

What are the factors that it depends on?

The int bit size is commonly 32 or 16 bits. C specified minimum ranges:

minimum value for an object of type int INT_MIN -32767
maximum value for an object of type int INT_MAX +32767
C11dr §5.2.4.2.1 1

The minimum range for int forces the bit size to be at least 16 - even if the processor was "8-bit". A size like 64 bits is seen in specialized processors. Other values like 18, 24, 36, etc. have occurred on historic platforms or are at least theoretically possible. Modern coding rarely worries about non-power-of-2 int bit sizes.

The computer's processor and architecture drive the int bit size selection.

Yet even with 64-bit processors, the compiler's int size may be 32-bit for compatibility reasons as large code bases depend on int being 32-bit (or 32/16).

Oracle Sql get only month and year in date datatype

SELECT to_char(to_date(month,'yyyy-mm'),'Mon yyyy'), nos
FROM (SELECT to_char(credit_date,'yyyy-mm') MONTH,count(*) nos
      FROM HCN
      WHERE   TRUNC(CREDIT_dATE) BEtween '01-jul-2014' AND '30-JUN-2015'
      AND CATEGORYCODECFR=22
      --AND CREDIT_NOTE_NO IS NOT  NULL
      AND CANCELDATE IS NULL
GROUP BY to_char(credit_date,'yyyy-mm')
ORDER BY to_char(credit_date,'yyyy-mm') ) mm

Output:

Jul 2014        49
Aug 2014        35
Sep 2014        57
Oct 2014        50
Nov 2014        45
Dec 2014        88
Jan 2015       131
Feb 2015       112
Mar 2015        76
Apr 2015        45
May 2015        49
Jun 2015        40

How can I make a list of installed packages in a certain virtualenv?

In Python3

pip list

Empty venv is

Package    Version
---------- ------- 
pip        19.2.3 
setuptools 41.2.0

To start a new environment

python3 -m venv your_foldername_here

Activate

cd your_foldername_here
source bin/activate

Deactivate

deactivate

You can also stand in the folder and give the virtual environment a name/folder (python3 -m venv name_of_venv).

Venv is a subset of virtualenv that is shipped with Python after 3.3.

What is the connection string for localdb for version 11

I had the same problem for a bit. I noticed that I had:

Data Source= (localdb)\v11.0"

Simply by adding one back-slash it solved the problem for me:

Data Source= (localdb)\\v11.0"

Selenium Finding elements by class name in python

Use nth-child, for example: http://www.w3schools.com/cssref/sel_nth-child.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:nth-child(1)')

or http://www.w3schools.com/cssref/sel_firstchild.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:first-child')

Traversing text in Insert mode

I believe Home and End (and PageUp/PageDn) also work normally while in insert mode, but aside from that, I don't believe there are any other standard keys defined for text traversal.

How to dismiss a Twitter Bootstrap popover by clicking outside?

I came up with this: My scenario included more popovers on the same page, and hiding them just made them invisible and because of that, clicking on items behind the popover was not possible. The idea is to mark the specific popover-link as 'active' and then you can simply 'toggle' the active popover. Doing so will close the popover completely $('.popover-link').popover({ html : true, container: 'body' })

$('.popover-link').popover().on 'shown.bs.popover', ->
  $(this).addClass('toggled')

$('.popover-link').popover().on 'hidden.bs.popover', ->
  $(this).removeClass('toggled')

$("body").on "click", (e) ->
  $openedPopoverLink = $(".popover-link.toggled")
  if $openedPopoverLink.has(e.target).length == 0
    $openedPopoverLink.popover "toggle"
    $openedPopoverLink.removeClass "toggled"

How to build a query string for a URL in C#?

The code below is taken off the HttpValueCollection implementation of ToString, via ILSpy, which gives you a name=value querystring.

Unfortunately HttpValueCollection is an internal class which you only ever get back if you use HttpUtility.ParseQueryString(). I removed all the viewstate parts to it, and it encodes by default:

public static class HttpExtensions
{
    public static string ToQueryString(this NameValueCollection collection)
    {
        // This is based off the NameValueCollection.ToString() implementation
        int count = collection.Count;
        if (count == 0)
            return string.Empty;

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < count; i++)
        {
            string text = collection.GetKey(i);
            text = HttpUtility.UrlEncodeUnicode(text);
            string value = (text != null) ? (text + "=") : string.Empty;
            string[] values = collection.GetValues(i);
            if (stringBuilder.Length > 0)
            {
                stringBuilder.Append('&');
            }
            if (values == null || values.Length == 0)
            {
                stringBuilder.Append(value);
            }
            else
            {
                if (values.Length == 1)
                {
                    stringBuilder.Append(value);
                    string text2 = values[0];
                    text2 = HttpUtility.UrlEncodeUnicode(text2);
                    stringBuilder.Append(text2);
                }
                else
                {
                    for (int j = 0; j < values.Length; j++)
                    {
                        if (j > 0)
                        {
                            stringBuilder.Append('&');
                        }
                        stringBuilder.Append(value);
                        string text2 = values[j];
                        text2 = HttpUtility.UrlEncodeUnicode(text2);
                        stringBuilder.Append(text2);
                    }
                }
            }
        }

        return stringBuilder.ToString();
    }
}

Save file Javascript with file name

Use the filename property like this:

uriContent = "data:application/octet-stream;filename=filename.txt," + 
              encodeURIComponent(codeMirror.getValue());
newWindow=window.open(uriContent, 'filename.txt');

EDIT:

Apparently, there is no reliable way to do this. See: Is there any way to specify a suggested filename when using data: URI?

TypeScript error: Type 'void' is not assignable to type 'boolean'

It means that the callback function you passed to this.dataStore.data.find should return a boolean and have 3 parameters, two of which can be optional:

  • value: Conversations
  • index: number
  • obj: Conversation[]

However, your callback function does not return anything (returns void). You should pass a callback function with the correct return value:

this.dataStore.data.find((element, index, obj) => {
    // ...

    return true; // or false
});

or:

this.dataStore.data.find(element => {
    // ...

    return true; // or false
});

Reason why it's this way: the function you pass to the find method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find method can determine which value to find.

In practice, this means that the predicate is called for each item in data, and the first item in data for which your predicate returns true is the value returned by find.

Run a command shell in jenkins

Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"

*Don't write bin at the end

Static Vs. Dynamic Binding in Java

The compiler only knows that the type of "a" is Animal; this happens at compile time, because of which it is called static binding (Method overloading). But if it is dynamic binding then it would call the Dog class method. Here is an example of dynamic binding.

public class DynamicBindingTest {

    public static void main(String args[]) {
        Animal a= new Dog(); //here Type is Animal but object will be Dog
        a.eat();       //Dog's eat called because eat() is overridden method
    }
}

class Animal {

    public void eat() {
        System.out.println("Inside eat method of Animal");
    }
}

class Dog extends Animal {

    @Override
    public void eat() {
        System.out.println("Inside eat method of Dog");
    }
}

Output: Inside eat method of Dog

iPhone viewWillAppear not firing

For Swift. First create the protocol to call what you wanted to call in viewWillAppear

protocol MyViewWillAppearProtocol{func myViewWillAppear()}

Second, create the class

class ForceUpdateOnViewAppear: NSObject, UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool){
    if let updatedCntllr: MyViewWillAppearProtocol = viewController as? MyViewWillAppearProtocol{
        updatedCntllr.myViewWillAppear()
    }
}

}

Third, make the instance of ForceUpdateOnViewAppear to be the member of the appropriate class that have the access to the Navigation Controller and exists as long as Navigation controller exists. It may be for example the root view controller of the navigation controller or the class that creates or present it. Then assign the instance of ForceUpdateOnViewAppear to the Navigation Controller delegate property as early as possible.

How does ifstream's eof() work?

-1 is get's way of saying you've reached the end of file. Compare it using the std::char_traits<char>::eof() (or std::istream::traits_type::eof()) - avoid -1, it's a magic number. (Although the other one is a bit verbose - you can always just call istream::eof)

The EOF flag is only set once a read tries to read past the end of the file. If I have a 3 byte file, and I only read 3 bytes, EOF is false, because I've not tried to read past the end of the file yet. While this seems confusing for files, which typically know their size, EOF is not known until a read is attempted on some devices, such as pipes and network sockets.

The second example works as inf >> foo will always return inf, with the side effect of attempt to read something and store it in foo. inf, in an if or while, will evaluate to true if the file is "good": no errors, no EOF. Thus, when a read fails, inf evaulates to false, and your loop properly aborts. However, take this common error:

while(!inf.eof())  // EOF is false here
{
    inf >> x;      // read fails, EOF becomes true, x is not set
    // use x       // we use x, despite our read failing.
}

However, this:

while(inf >> x)  // Attempt read into x, return false if it fails
{
    // will only be entered if read succeeded.
}

Which is what we want.

Why is this printing 'None' in the output?

Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.

Use return statement at end of function to return value.

e.g.:

Return None value.

>>> def test1():
...    print "In function."
... 
>>> a = test1()
In function.
>>> print a
None
>>> 
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>> 

Use return statement

>>> def test():
...   return "ACV"
... 
>>> print test()
ACV
>>> 
>>> a = test()
>>> print a
ACV
>>> 

Could not load type from assembly error

The solution to this for me was not mentioned above, so I thought I would add my answer to the long tail...

I ended up having an old reference to a class (an HttpHandler) in web.config that was no longer being used (and was no longer a valid reference). For some reason it was ignored while running in Studio (or maybe I have that class still accessible within my dev setup?) and so I only got this error once I tried deploying to IIS. I searched on the assembly name in web.config, removed the unused handler reference, then this error went away and everything works great. Hope this helps someone else.

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

Javascript ajax call on page onload

This is really easy using a JavaScript library, e.g. using jQuery you could write:

$(document).ready(function(){
$.ajax({ url: "database/update.html",
        context: document.body,
        success: function(){
           alert("done");
        }});
});

Without jQuery, the simplest version might be as follows, but it does not account for browser differences or error handling:

<html>
  <body onload="updateDB();">
  </body>
  <script language="javascript">
    function updateDB() {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "database/update.html", true);
      xhr.send(null);
      /* ignore result */
    }
  </script>
</html>

See also:

OwinStartup not firing

Make sure you have installed Microsoft.Owin.Host.SystemWeb package in the project. This package is needed for startup detection in IIS hosted applications. For more information you can refer to this article.

How to receive POST data in django

You should have access to the POST dictionary on the request object.

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

How does one get started with procedural generation?

Procedural generation is used heavily in the demoscene to create complex graphics in a small executable. Will Wright even said that he was inspired by the demoscene while making Spore. That may be your best place to start.

http://en.wikipedia.org/wiki/Demoscene

Take a char input from the Scanner

you just need to write this for getting value in char type.

char c = reader.next().charAt(0);

Invalid character in identifier

My solution was to switch my Mac keyboard from Unicode to U.S. English.

How to prevent Browser cache for php site

Here, if you want to control it through HTML: do like below Option 1:

<meta http-equiv="expires" content="Sun, 01 Jan 2014 00:00:00 GMT"/>
<meta http-equiv="pragma" content="no-cache" />

And if you want to control it through PHP: do it like below Option 2:

header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');

AND Option 2 IS ALWAYS BETTER in order to avoid proxy based caching issue.

Retrieving an element from array list in Android?

public class DemoActivity extends Activity {
    /** Called when the activity is first created. */
    ArrayList<String> al = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



        // add elements to the array list

        al.add("C");
        al.add("A");
        al.add("E");
        al.add("B");
        al.add("D");
        al.add("F");

        // retrieve elements from array

        String data = al.get(pass the index here);
        System.out.println("Data is "+ data);

This is another way of getting element

        Iterator<String> it = al.iterator();
        while (it.hasNext()) {
            System.out.println("Data is "+ it.next());
        }
    }

How do I detect if I am in release or debug mode?

Yes, you will have no problems using:

if (BuildConfig.DEBUG) {
   //It's not a release version.
}

Unless you are importing the wrong BuildConfig class. Make sure you are referencing your project's BuildConfig class, not from any of your dependency libraries.

enter image description here

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

@mikemaccana answer is useful.

And I also used https://github.com/ryanseddon/H5F. Found on http://microjs.com. It's some kind of polyfill and you can use it as follows (jQuery is used in example):

if ( $('form')[0].checkValidity() ) {
    // the form is valid
}

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

Try indextank.

As the case of elastic search, it was conceived to be much easier to use than lucene/solr. It also includes very flexible scoring system that can be tweaked without reindexing.

Delete empty rows

DELETE FROM table WHERE edit_user IS NULL;

How to draw a rectangle around a region of interest in python

As the other answers said, the function you need is cv2.rectangle(), but keep in mind that the coordinates for the bounding box vertices need to be integers if they are in a tuple, and they need to be in the order of (left, top) and (right, bottom). Or, equivalently, (xmin, ymin) and (xmax, ymax).

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

If you want to convert string to double data type then most choose parseDouble() method. See the example code:

String str = "123.67";
double d = parseDouble(str);

You will get the value in double. See the StringToDouble tutorial at tutorialData.

Javascript parse float is ignoring the decimals after my comma

It is better to use this syntax to replace all the commas in a case of a million 1,234,567

var string = "1,234,567";
string = string.replace(/[^\d\.\-]/g, ""); 
var number = parseFloat(string);
console.log(number)

The g means to remove all commas.

Check the Jsfiddle demo here.

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

None of the other answers worked for me.

This did: (in Startup.cs)

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();

        WebApiConfig.Register(config);

        // Here: 
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
    }
}

(or you can put it in WebApiConfig.cs):

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // Here: 
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
    }
}

How to include vars file in a vars file with ansible?

I know it's an old post but I had the same issue today, what I did is simple : changing my script that send my playbook from my local host to the server, before sending it with maven command, I did this :

cat common_vars.yml > vars.yml
cat snapshot_vars.yml >> vars.yml
# or 
#cat release_vars.yml >> vars.yml
mvn ....

How can I make an "are you sure" prompt in a Windows batchfile?

If you want to the batch program to exit back to the prompt and not close the prompt (A.K.A cmd.exe) you can use "exit /b".

This may help.

set /p _sure="Are you sure?"
::The underscore is used to ensure that "sure" is not an enviroment
::varible
if /I NOT "_sure"=="y" (
::the /I makes it so you can
exit /b
) else (
::Any other modifications...
)

Or if you don't want to use as many lines...

Set /p _sure="Are you sure?"
if /I NOT "_sure"=="y" exit /b
::Any other modifications and commands.

Hope this helps...

Summarizing multiple columns with dplyr?

The dplyr package contains summarise_all for this aim:

library(dplyr)
# summarise_all was replaced with the summarise(acrosss(..)) syntax dplyr >=1.00
df %>% group_by(grp) %>% summarise(across(everything(), list(mean)))
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Alternatively, the purrrlyr package provides the same functionality:

library(purrrlyr)
df %>% slice_rows("grp") %>% dmap(mean)
#> # A tibble: 3 x 5
#>     grp     a     b     c     d
#>   <int> <dbl> <dbl> <dbl> <dbl>
#> 1     1  3.08  2.98  2.98  2.91
#> 2     2  3.03  3.04  2.97  2.87
#> 3     3  2.85  2.95  2.95  3.06

Also don't forget about data.table (use keyby to sort sort groups):

library(data.table)
setDT(df)[, lapply(.SD, mean), keyby = grp]
#>    grp        a        b        c        d
#> 1:   1 3.079412 2.979412 2.979412 2.914706
#> 2:   2 3.029126 3.038835 2.967638 2.873786
#> 3:   3 2.854701 2.948718 2.951567 3.062678

Let's try to compare performance.

library(dplyr)
library(purrrlyr)
library(data.table)
library(bench)
set.seed(123)
n <- 10000
df <- data.frame(
  a = sample(1:5, n, replace = TRUE), 
  b = sample(1:5, n, replace = TRUE), 
  c = sample(1:5, n, replace = TRUE), 
  d = sample(1:5, n, replace = TRUE), 
  grp = sample(1:3, n, replace = TRUE)
)
dt <- setDT(df)
mark(
  dplyr = df %>% group_by(grp) %>% summarise(across(everything(), list(mean))),
  purrrlyr = df %>% slice_rows("grp") %>% dmap(mean),
  data.table = dt[, lapply(.SD, mean), keyby = grp],
  check = FALSE
)
#> # A tibble: 3 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 dplyr        2.81ms   2.85ms      328.        NA     17.3
#> 2 purrrlyr     7.96ms   8.04ms      123.        NA     24.5
#> 3 data.table 596.33µs 707.91µs     1409.        NA     10.3

How do I zip two arrays in JavaScript?

Use the map method:

_x000D_
_x000D_
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
  return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
_x000D_
_x000D_

DEMO

Remove last 3 characters of string or number in javascript

you just need to divide the Date Time stamp by 1000 like:

var a = 1437203995000;
a = (a)/1000;

How to adjust text font size to fit textview

/* get your context */
Context c = getActivity().getApplicationContext();

LinearLayout l = new LinearLayout(c);
l.setOrientation(LinearLayout.VERTICAL);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 0);

l.setLayoutParams(params);
l.setBackgroundResource(R.drawable.border);

TextView tv=new TextView(c);
tv.setText(" your text here");

/* set typeface if needed */
Typeface tf = Typeface.createFromAsset(c.getAssets(),"fonts/VERDANA.TTF");  
tv.setTypeface(tf);

// LayoutParams lp = new LayoutParams();

tv.setTextColor(Color.parseColor("#282828"));

tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
//  tv.setLayoutParams(lp);

tv.setTextSize(20);
l.addView(tv);

return l;

How do I redirect users after submit button click?

Using jquery you can do it this way

$("#order").click(function(e){
    e.preventDefault();
    window.location="login.php";
});

Also in HMTL you can do it this way

<form name="frm" action="login.php" method="POST">
...
</form>

Hope this helps

Call Stored Procedure within Create Trigger in SQL Server

The following should do the trick - Only SqlServer


Alter TRIGGER Catagory_Master_Date_update ON Catagory_Master AFTER delete,Update
AS
BEGIN

SET NOCOUNT ON;

Declare @id int
DECLARE @cDate as DateTime
    set @cDate =(select Getdate())

select @id=deleted.Catagory_id from deleted
print @cDate

execute dbo.psp_Update_Category @id

END

Alter PROCEDURE dbo.psp_Update_Category
@id int
AS
BEGIN

DECLARE @cDate as DateTime
    set @cDate =(select Getdate())
    --Update Catagory_Master Set Modify_date=''+@cDate+'' Where Catagory_ID=@id   --@UserID
    Insert into Catagory_Master (Catagory_id,Catagory_Name) values(12,'Testing11')
END 

Woocommerce, get current product id

Since WooCommerce 2.2 you are able to simply use the wc_get_product Method. As an argument you can pass the ID or simply leave it empty if you're already in the loop.

wc_get_product()->get_id();

OR with 2 lines

$product = wc_get_product();
$id = $product->get_id();

Compiling a C++ program with gcc

use g++ instead of gcc.

Default value in an asp.net mvc view model

Create a base class for your ViewModels with the following constructor code which will apply the DefaultValueAttributeswhen any inheriting model is created.

public abstract class BaseViewModel
{
    protected BaseViewModel()
    {
        // apply any DefaultValueAttribute settings to their properties
        var propertyInfos = this.GetType().GetProperties();
        foreach (var propertyInfo in propertyInfos)
        {
            var attributes = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
            if (attributes.Any())
            {
                var attribute = (DefaultValueAttribute) attributes[0];
                propertyInfo.SetValue(this, attribute.Value, null);
            }
        }
    }
}

And inherit from this in your ViewModels:

public class SearchModel : BaseViewModel
{
    [DefaultValue(true)]
    public bool IsMale { get; set; }
    [DefaultValue(true)]
    public bool IsFemale { get; set; }
}

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Undefined reference to `sin`

I had the same problem, which went away after I listed my library last: gcc prog.c -lm

How to use Morgan logger?

I think I have a way where you may not get exactly get what you want, but you can integrate Morgan's logging with log4js -- in other words, all your logging activity can go to the same place. I hope this digest from an Express server is more or less self-explanatory:

var express = require("express");
var log4js = require("log4js");
var morgan = require("morgan");
...
var theAppLog = log4js.getLogger();
var theHTTPLog = morgan({
  "format": "default",
  "stream": {
    write: function(str) { theAppLog.debug(str); }
  }
});
....
var theServer = express();
theServer.use(theHTTPLog);

Now you can write whatever you want to theAppLog and Morgan will write what it wants to the same place, using the same appenders etc etc. Of course, you can call info() or whatever you like in the stream wrapper instead of debug() -- that just reflects the logging level you want to give to Morgan's req/res logging.

How to pick element inside iframe using document.getElementById

In my case I was trying to grab pdfTron toolbar, but unfortunately its ID changes every-time you refresh the page.

So, I ended up grabbing it by doing so.

const pdfToolbar = document.getElementsByTagName('iframe')[0].contentWindow.document.getElementById('HeaderItems');

As in the array written by tagName you will always have the fixed index for iFrames in your application.

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

My solution is similar to Payam's, except I am using

//older code
//postman.setGlobalVariable("currentDate", new Date().toLocaleDateString());
pm.globals.set("currentDate", new Date().toLocaleDateString());

If you hit the "3 dots" on the folder and click "Edit"

enter image description here

Then set Pre-Request Scripts for the all calls, so the global variable is always available.

enter image description here

Init method in Spring Controller (annotation version)

Alternatively you can have your class implement the InitializingBean interface to provide a callback function (afterPropertiesSet()) which the ApplicationContext will invoke when the bean is constructed.

jquery AJAX and json format

Currently you are sending the data as typical POST values, which look like this:

first_name=somename&last_name=somesurname

If you want to send data as json you need to create an object with data and stringify it.

data: JSON.stringify(someobject)

How to write a multiline Jinja statement

According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    line_statement_prefix='#'
)

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'

/bin/sh: apt-get: not found

The image you're using is Alpine based, so you can't use apt-get because it's Ubuntu's package manager.

To fix this just use:

apk update and apk add

Implement Stack using Two Queues

#include "stdio.h"
#include "stdlib.h"

typedef struct {
    int *q;
    int size;
    int front;
    int rear;
} Queue;
typedef struct {
    Queue *q1;
    Queue *q2;
} Stack;

int queueIsEmpty(Queue *q) {
    if (q->front == -1 && q->rear == -1) {
        printf("\nQUEUE is EMPTY\n");
        return 1;
    }
    return 0;
}
int queueIsFull(Queue *q) {
    if (q->rear == q->size-1) {
        return 1;
    }
    return 0;
}
int queueTop(Queue *q) {
    if (queueIsEmpty(q)) {
        return -1;
    }
    return q->q[q->front];
}
int queuePop(Queue *q) {
    if (queueIsEmpty(q)) {
        return -1;
    }
    int item = q->q[q->front];
    if (q->front == q->rear) {
        q->front = q->rear = -1;
    }
    else {
        q->front++;
    }
    return item;
}
void queuePush(Queue *q, int val) {
    if (queueIsFull(q)) {
        printf("\nQUEUE is FULL\n");
        return;
    }
    if (queueIsEmpty(q)) {
        q->front++;
        q->rear++;
    } else {
        q->rear++;
    }
    q->q[q->rear] = val;
}
Queue *queueCreate(int maxSize) {
    Queue *q = (Queue*)malloc(sizeof(Queue));
    q->front = q->rear = -1;
    q->size = maxSize;
    q->q = (int*)malloc(sizeof(int)*maxSize);
    return q;
}
/* Create a stack */
void stackCreate(Stack *stack, int maxSize) {
    Stack **s = (Stack**) stack;
    *s = (Stack*)malloc(sizeof(Stack));
    (*s)->q1 = queueCreate(maxSize);
    (*s)->q2 = queueCreate(maxSize);
}

/* Push element x onto stack */
void stackPush(Stack *stack, int element) {
    Stack **s = (Stack**) stack;
    queuePush((*s)->q2, element);
    while (!queueIsEmpty((*s)->q1)) {
        int item = queuePop((*s)->q1);
        queuePush((*s)->q2, item);
    }
    Queue *tmp = (*s)->q1;
    (*s)->q1 = (*s)->q2;
    (*s)->q2 = tmp;
}

/* Removes the element on top of the stack */
void stackPop(Stack *stack) {
    Stack **s = (Stack**) stack;
    queuePop((*s)->q1);
}

/* Get the top element */
int stackTop(Stack *stack) {
    Stack **s = (Stack**) stack;
    if (!queueIsEmpty((*s)->q1)) {
      return queueTop((*s)->q1);
    }
    return -1;
}

/* Return whether the stack is empty */
bool stackEmpty(Stack *stack) {
    Stack **s = (Stack**) stack;
    if (queueIsEmpty((*s)->q1)) {
        return true;
    }
    return false;
}

/* Destroy the stack */
void stackDestroy(Stack *stack) {
    Stack **s = (Stack**) stack;
    free((*s)->q1);
    free((*s)->q2);
    free((*s));
}

int main()
{
  Stack *s = NULL;
  stackCreate((Stack*)&s, 10);
  stackPush((Stack*)&s, 44);
  //stackPop((Stack*)&s);
  printf("\n%d", stackTop((Stack*)&s));
  stackDestroy((Stack*)&s);
  return 0;
}

JSON forEach get Key and Value

Use forEach in combo with Object.entries().

_x000D_
_x000D_
const WALLPAPERS = [{
  WALLPAPER_KEY: 'wallpaper.image',
  WALLPAPER_VALID_KEY: 'wallpaper.image.valid',
}, {
  WALLPAPER_KEY: 'lockscreen.image',
  WALLPAPER_VALID_KEY: 'lockscreen.image.valid',
}];

WALLPAPERS.forEach((obj) => {
  for (const [key, value] of Object.entries(obj)) {
    console.log(`${key} - ${value}`);
  }
});
_x000D_
_x000D_
_x000D_

Get epoch for a specific date using Javascript

new Date("2016-3-17").valueOf() 

will return a long epoch

Creating custom function in React component

You can try this.

// Author: Hannad Rehman Sat Jun 03 2017 12:59:09 GMT+0530 (India Standard Time)

import React from 'react';
import RippleButton from '../../Components/RippleButton/rippleButton.jsx';

class HtmlComponents extends React.Component {

    constructor(props){
        super(props);
        this.rippleClickFunction=this.rippleClickFunction.bind(this);
    }

    rippleClickFunction(){
        //do stuff. 
        // foo==bar
    }

    render() {
      return (
         <article>
             <h1>React Components</h1>
             <RippleButton onClick={this.rippleClickFunction}/>
         </article>
      );
   }
}

export default HtmlComponents;

Yhe only concern is you have to bind the context to the function

How can I get a specific parameter from location.search?

I played a bit with this problem and at this end I used this:

function getJsonFromUrl() {
  return Object.assign(...location.search.substr(1).split("&").map(sliceProperty));
}
  • Object.assign to transform a list of object into one object
  • Spread operator ... to transform an array into a list
  • location.search.substr(1).split("&") to get all parameters as array of properties (foo=bar)
  • map walk each properties and split them into an array (either call splitProperty or sliceProperty).

splitProperty:

  function splitProperty(pair) {
    [key, value] = pair.split("=")
    return { [key]: decodeURIComponent(value) }
  }
  • Split by =
  • Deconstruct the array into an array of two elements
  • Return a new object with the dynamic property syntax

sliceProperty:

  function sliceProperty(pair) {
    const position = pair.indexOf("="),
      key = pair.slice(0, position),
      value = pair.slice(position + 1, pair.length);
    return { [key]: decodeURIComponent(value) }
  }
  • Set the position of =, key and value
  • Return a new object with the dynamic property syntax

I think splitProperty is prettier but sliceProperty is faster. Run JsPerf for more information.

WCF named pipe minimal example

Check out my highly simplified Echo example: It is designed to use basic HTTP communication, but it can easily be modified to use named pipes by editing the app.config files for the client and server. Make the following changes:

Edit the server's app.config file, removing or commenting out the http baseAddress entry and adding a new baseAddress entry for the named pipe (called net.pipe). Also, if you don't intend on using HTTP for a communication protocol, make sure the serviceMetadata and serviceDebug is either commented out or deleted:

<configuration>
    <system.serviceModel>
        <services>
            <service name="com.aschneider.examples.wcf.services.EchoService">
                <host>
                    <baseAddresses>
                        <add baseAddress="net.pipe://localhost/EchoService"/>
                    </baseAddresses>
                </host>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors></serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>

Edit the client's app.config file so that the basicHttpBinding is either commented out or deleted and a netNamedPipeBinding entry is added. You will also need to change the endpoint entry to use the pipe:

<configuration>
    <system.serviceModel>
        <bindings>
            <netNamedPipeBinding>
                <binding name="NetNamedPipeBinding_IEchoService"/>
            </netNamedPipeBinding>
        </bindings>
        <client>
            <endpoint address              = "net.pipe://localhost/EchoService"
                      binding              = "netNamedPipeBinding"
                      bindingConfiguration = "NetNamedPipeBinding_IEchoService"
                      contract             = "EchoServiceReference.IEchoService"
                      name                 = "NetNamedPipeBinding_IEchoService"/>
        </client>
    </system.serviceModel>
</configuration>

The above example will only run with named pipes, but nothing is stopping you from using multiple protocols to run your service. AFAIK, you should be able to have a server run a service using both named pipes and HTTP (as well as other protocols).

Also, the binding in the client's app.config file is highly simplified. There are many different parameters you can adjust, aside from just specifying the baseAddress...

SQL Server CTE and recursion example

I haven't tested your code, just tried to help you understand how it operates in comment;

WITH
  cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
  AS
  (
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
-- In a rCTE, this block is called an [Anchor]
-- The query finds all root nodes as described by WHERE ManagerID IS NULL
    SELECT EmployeeID, FirstName, LastName, ManagerID, 1
    FROM Employees
    WHERE ManagerID IS NULL
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
    UNION ALL
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>    
-- This is the recursive expression of the rCTE
-- On the first "execution" it will query data in [Employees],
-- relative to the [Anchor] above.
-- This will produce a resultset, we will call it R{1} and it is JOINed to [Employees]
-- as defined by the hierarchy
-- Subsequent "executions" of this block will reference R{n-1}
    SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
      r.EmpLevel + 1
    FROM Employees e
      INNER JOIN cteReports r
        ON e.ManagerID = r.EmpID
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
  )
SELECT
  FirstName + ' ' + LastName AS FullName,
  EmpLevel,
  (SELECT FirstName + ' ' + LastName FROM Employees
    WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID

The simplest example of a recursive CTE I can think of to illustrate its operation is;

;WITH Numbers AS
(
    SELECT n = 1
    UNION ALL
    SELECT n + 1
    FROM Numbers
    WHERE n+1 <= 10
)
SELECT n
FROM Numbers

Q 1) how value of N is getting incremented. if value is assign to N every time then N value can be incremented but only first time N value was initialize.

A1: In this case, N is not a variable. N is an alias. It is the equivalent of SELECT 1 AS N. It is a syntax of personal preference. There are 2 main methods of aliasing columns in a CTE in T-SQL. I've included the analog of a simple CTE in Excel to try and illustrate in a more familiar way what is happening.

--  Outside
;WITH CTE (MyColName) AS
(
    SELECT 1
)
-- Inside
;WITH CTE AS
(
    SELECT 1 AS MyColName
    -- Or
    SELECT MyColName = 1  
    -- Etc...
)

Excel_CTE

Q 2) now here about CTE and recursion of employee relation the moment i add two manager and add few more employee under second manager then problem start. i want to display first manager detail and in the next rows only those employee details will come those who are subordinate of that manager

A2:

Does this code answer your question?

--------------------------------------------
-- Synthesise table with non-recursive CTE
--------------------------------------------
;WITH Employee (ID, Name, MgrID) AS 
(
    SELECT 1,      'Keith',      NULL   UNION ALL
    SELECT 2,      'Josh',       1      UNION ALL
    SELECT 3,      'Robin',      1      UNION ALL
    SELECT 4,      'Raja',       2      UNION ALL
    SELECT 5,      'Tridip',     NULL   UNION ALL
    SELECT 6,      'Arijit',     5      UNION ALL
    SELECT 7,      'Amit',       5      UNION ALL
    SELECT 8,      'Dev',        6   
)
--------------------------------------------
-- Recursive CTE - Chained to the above CTE
--------------------------------------------
,Hierarchy AS
(
    --  Anchor
    SELECT   ID
            ,Name
            ,MgrID
            ,nLevel = 1
            ,Family = ROW_NUMBER() OVER (ORDER BY Name)
    FROM Employee
    WHERE MgrID IS NULL

    UNION ALL
    --  Recursive query
    SELECT   E.ID
            ,E.Name
            ,E.MgrID
            ,H.nLevel+1
            ,Family
    FROM Employee   E
    JOIN Hierarchy  H ON E.MgrID = H.ID
)
SELECT *
FROM Hierarchy
ORDER BY Family, nLevel

Another one sql with tree structure

SELECT ID,space(nLevel+
                    (CASE WHEN nLevel > 1 THEN nLevel ELSE 0 END)
                )+Name
FROM Hierarchy
ORDER BY Family, nLevel

Passing a string array as a parameter to a function java

I think you forget to register the parameter as String[]

In Node.js, how do I "include" functions from my other files?

If, despite all the other answers, you still want to traditionally include a file in a node.js source file, you can use this:

var fs = require('fs');

// file is included here:
eval(fs.readFileSync('tools.js')+'');
  • The empty string concatenation +'' is necessary to get the file content as a string and not an object (you can also use .toString() if you prefer).
  • The eval() can't be used inside a function and must be called inside the global scope otherwise no functions or variables will be accessible (i.e. you can't create a include() utility function or something like that).

Please note that in most cases this is bad practice and you should instead write a module. However, there are rare situations, where pollution of your local context/namespace is what you really want.

Update 2015-08-06

Please also note this won't work with "use strict"; (when you are in "strict mode") because functions and variables defined in the "imported" file can't be accessed by the code that does the import. Strict mode enforces some rules defined by newer versions of the language standard. This may be another reason to avoid the solution described here.

Vue.js toggle class on click

In addition to NateW's answer, if you have hyphens in your css class name, you should wrap that class within (single) quotes:

<th 
  class="initial " 
  v-on:click="myFilter"
  v-bind:class="{ 'is-active' : isActive}"
>

 <span class="wkday">M</span>
 </th>

See this topic for more on the subject.

How to center an element horizontally and vertically

In order to vertically and horizontally center an element we can also use below mentioned properties.

This CSS property aligns-items vertically and accepts the following values:

flex-start: Items align to the top of the container.

flex-end: Items align to the bottom of the container.

center: Items align at the vertical center of the container.

baseline: Items display at the baseline of the container.

stretch: Items are stretched to fit the container.

This CSS property justify-content , which aligns items horizontally and accepts the following values:

flex-start: Items align to the left side of the container.

flex-end: Items align to the right side of the container.

center: Items align at the center of the container.

space-between: Items display with equal spacing between them.

space-around: Items display with equal spacing around them.

ASP.net page without a code behind

You can actually have all the code in the aspx page. As explained here.

Sample from here:

<%@ Language=C# %>
<HTML>
   <script runat="server" language="C#">
   void MyButton_OnClick(Object sender, EventArgs e)
   {
      MyLabel.Text = MyTextbox.Text.ToString();
   }
   </script>
   <body>
      <form id="MyForm" runat="server">
         <asp:textbox id="MyTextbox" text="Hello World" runat="server"></asp:textbox>
         <asp:button id="MyButton" text="Echo Input" OnClick="MyButton_OnClick" runat="server"></asp:button>
         <asp:label id="MyLabel" runat="server"></asp:label>
      </form>
   </body>
</HTML>

How do I interpret precision and scale of a number in a database?

Precision of a number is the number of digits.

Scale of a number is the number of digits after the decimal point.

What is generally implied when setting precision and scale on field definition is that they represent maximum values.

Example, a decimal field defined with precision=5 and scale=2 would allow the following values:

  • 123.45 (p=5,s=2)
  • 12.34 (p=4,s=2)
  • 12345 (p=5,s=0)
  • 123.4 (p=4,s=1)
  • 0 (p=0,s=0)

The following values are not allowed or would cause a data loss:

  • 12.345 (p=5,s=3) => could be truncated into 12.35 (p=4,s=2)
  • 1234.56 (p=6,s=2) => could be truncated into 1234.6 (p=5,s=1)
  • 123.456 (p=6,s=3) => could be truncated into 123.46 (p=5,s=2)
  • 123450 (p=6,s=0) => out of range

Note that the range is generally defined by the precision: |value| < 10^p ...

Reading Space separated input in python

a=[]
for j in range(3):
    a.append([int(i) for  i in input().split()])

In this above code the given input i.e Mike 18 Kevin 35 Angel 56, will be stored in an array 'a' and gives the output as [['Mike', '18'], ['Kevin', '35'], ['Angel', '56']].

C++ Boost: undefined reference to boost::system::generic_category()

After testing the proposed solutions described above, I found only these few of lines would work.

I am using Ubuntu 16.04.

cmake_minimum_required(VERSION 3.13)
project(myProject)

set(CMAKE_CXX_STANDARD 11)
add_executable(myProject main.cpp)

find_package(Boost 1.58.0 REQUIRED COMPONENTS system filesystem)
target_link_libraries(myProject ${Boost_LIBRARIES})

How to include PHP files that require an absolute path?

If you are going to include specific path in most of the files in your application, create a Global variable to your root folder.

define("APPLICATION_PATH", realpath(dirname(__FILE__) . '/../app'));
or 
define("APPLICATION_PATH", realpath(DIR(__FILE__) . '/../app'));

Now this Global variable "APPLICATION_PATH" can be used to include all the files instead of calling realpath() everytime you include a new file.

EX:

include(APPLICATION_PATH ."/config/config.ini";

Hope it helps ;-)

How to set the maxAllowedContentLength to 500MB while running on IIS7?

IIS v10 (but this should be the same also for IIS 7.x)

Quick addition for people which are looking for respective max values

Max for maxAllowedContentLength is: UInt32.MaxValue 4294967295 bytes : ~4GB

Max for maxRequestLength is: Int32.MaxValue 2147483647 bytes : ~2GB

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <!-- ~ 2GB -->
    <httpRuntime maxRequestLength="2147483647" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- ~ 4GB -->
        <requestLimits maxAllowedContentLength="4294967295" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

HTML iframe - disable scroll

Add this styles..for your iframe tag..

overflow-x:hidden;
overflow-y:hidden;

MySQL config file location - redhat linux server

In the docker containers(centos based images) it is located at

/etc/mysql/my.cnf

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

in my case there was 2 reasons (checked) that my genymotion device couldn't run on windows 10/64bit

1. VPN was running and connected

2. amount of "base memory" :

run virtual box > choose your device in the list > Settings > System (left list) > set your base memory on 1024

Should I use alias or alias_method?

A year after asking the question comes a new article on the subject:

http://erniemiller.org/2014/10/23/in-defense-of-alias/

It seems that "so many men, so many minds." From the former article author encourages to use alias_method, while the latter suggests using alias.

However there's a common overview of these methods in both blogposts and answers above:

  • use alias when you want to limit aliasing to the scope where it's defined
  • use alias_method to allow inherited classes to access it

jQuery show for 5 seconds then hide

You can use .delay() before an animation, like this:

$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:

$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

Or, another option is to use .delay() and .queue() yourself, like this:

$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});

SQL 'like' vs '=' performance

It's a measureable difference.

Run the following:

Create Table #TempTester (id int, col1 varchar(20), value varchar(20))
go

INSERT INTO #TempTester (id, col1, value)
VALUES
(1, 'this is #1', 'abcdefghij')
GO

INSERT INTO #TempTester (id, col1, value)
VALUES
(2, 'this is #2', 'foob'),
(3, 'this is #3', 'abdefghic'),
(4, 'this is #4', 'other'),
(5, 'this is #5', 'zyx'),
(6, 'this is #6', 'zyx'),
(7, 'this is #7', 'zyx'),
(8, 'this is #8', 'klm'),
(9, 'this is #9', 'klm'),
(10, 'this is #10', 'zyx')
GO 10000

CREATE CLUSTERED INDEX ixId ON #TempTester(id)CREATE CLUSTERED INDEX ixId ON #TempTester(id)

CREATE NONCLUSTERED INDEX ixTesting ON #TempTester(value)

Then:

SET SHOWPLAN_XML ON

Then:

SELECT * FROM #TempTester WHERE value LIKE 'abc%'

SELECT * FROM #TempTester WHERE value = 'abcdefghij'

The resulting execution plan shows you that the cost of the first operation, the LIKE comparison, is about 10 times more expensive than the = comparison.

If you can use an = comparison, please do so.

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

I'm using Laravel Lumen to build a small application.
For me it was because I didn't had the DB_USERNAME defined in my .env file.

DB_USERNAME=root

Setting this solved my problem.

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

Jackson marshalling/unmarshalling requires following jar files of same version.

  1. jackson-core

  2. jackson-databind

  3. jackson-annotations

    Make sure that you have added all these with same version in your classpath. In your case jackson-annotations is missing in classpath.

How to paste text to end of every line? Sublime 2

Let's say you have these lines of code:

test line one
test line two
test line three
test line four

Using Search and Replace Ctrl+H with Regex let's find this: ^ and replace it with ", we'll have this:

"test line one
"test line two
"test line three
"test line four

Now let's search this: $ and replace it with ", now we'll have this:

"test line one"
"test line two"
"test line three"
"test line four"

How to scroll to top of long ScrollView layout?

This is worked for me

scroll_view.smoothScrollTo(0,0); // scroll to top of screen

customize Android Facebook Login button

You can modifiy the login button like this

<com.facebook.widget.LoginButton
            xmlns:fb="http://schemas.android.com/apk/res-auto"
            android:id="@+id/login_button"
            android:layout_width="249dp"
            android:layout_height="45dp"
            android:layout_above="@+id/textView1"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="30dp"
            android:layout_marginTop="30dp"
            android:contentDescription="@string/login_desc"
            android:scaleType="centerInside"
            fb:login_text=""
            fb:logout_text="" />

And in code I defined the background resource :

final LoginButton button = (LoginButton) findViewById(R.id.login_button);
button.setBackgroundResource(R.drawable.facebook);

Does svn have a `revert-all` command?

Use the recursive switch --recursive (-R)

svn revert -R .

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

Trust me, I am not joking. Remove all the System.Runtime dependencies from your app.config and it will start working.

Which type of folder structure should be used with Angular 2?

So after doing more investigating I ended up going with a slightly revised version of Method 3 (mgechev/angular2-seed).

I basically moved components to be a main level directory and then each feature will be inside of it.

Can the Unix list command 'ls' output numerical chmod permissions?

Closest I can think of (keeping it simple enough) is stat, assuming you know which files you're looking for. If you don't, * can find most of them:

/usr/bin$ stat -c '%a %n' *
755 [
755 a2p
755 a2ps
755 aclocal
...

It handles sticky, suid and company out of the box:

$ stat -c '%a %n' /tmp /usr/bin/sudo
1777 /tmp
4755 /usr/bin/sudo

How to test REST API using Chrome's extension "Advanced Rest Client"

The discoverability is dismal, but it's quite clever how Advanced Rest Client handles basic authentication. The shortcut abraham mentioned didn't work for me, but a little poking around revealed how it does it.

The first thing you need to do is add the Authorization header: menus

Then, a nifty little thing pops up when you focus the value input (note the "construct" box in the lower right): construct the auth value

Clicking it will bring up a box. It even does OAuth, if you want! convenient inputs

Tada! If you leave the value field blank when you click "construct," it will add the Basic part to it (I assume it will also add the necessary OAuth stuff, too, but I didn't try that, as my current needs were for basic authentication), so you don't need to do anything. fills in the field as needed

Checking the form field values before submitting that page

Don't know for sure, but it sounds like it is still submitting. I quick solution would be to change your (guessing at your code here):

<input type="submit" value="Submit" onclick="checkform()">

to a button:

<input type="button" value="Submit" onclick="checkform()">

That way your form still gets submitted (from the else part of your checkform()) and it shouldn't be reloading the page.

There are other, perhaps better, ways of handling it but this works in the mean time.

How to trim a string in SQL Server before 2017?

To trim any set of characters from the beginning and end of a string, you can do the following code where @TrimPattern defines the characters to be trimmed. In this example, Space, tab, LF and CR characters are being trimmed:

Declare @Test nvarchar(50) = Concat (' ', char(9), char(13), char(10), ' ', 'TEST', ' ', char(9), char(10), char(13),' ', 'Test', ' ', char(9), ' ', char(9), char(13), ' ')

DECLARE @TrimPattern nvarchar(max) = '%[^ ' + char(9) + char(13) + char(10) +']%'

SELECT SUBSTRING(@Test, PATINDEX(@TrimPattern, @Test), LEN(@Test) - PATINDEX(@TrimPattern, @Test) - PATINDEX(@TrimPattern, LTRIM(REVERSE(@Test))) + 2)

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

How to set thousands separator in Java?

For decimals:

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat dfDecimal = new DecimalFormat("###########0.00###");
dfDecimal.setDecimalFormatSymbols(symbols);
dfDecimal.setGroupingSize(3);
dfDecimal.setGroupingUsed(true);
System.out.println(dfDecimal.format(number));

Extract a substring from a string in Ruby using a regular expression

String1.scan(/<([^>]*)>/).last.first

scan creates an array which, for each <item> in String1 contains the text between the < and the > in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last gives you the last of those arrays and first then gives you the string in it.

python: How do I know what type of exception occurred?

You can start as Lauritz recommended, with:

except Exception as ex:

and then just to print ex like so:

try:
    #your try code here
except Exception as ex:
    print ex

jQuery if checkbox is checked

If checked:

$( "SELECTOR" ).attr( "checked" )  // Returns ‘true’ if present on the element, returns undefined if not present
$( "SELECTOR" ).prop( "checked" ) // Returns true if checked, false if unchecked.
$( "SELECTOR" ).is( ":checked" ) // Returns true if checked, false if unchecked.

Get the checked val:

$( "SELECTOR:checked" ).val()

Get the checked val numbers:

$( "SELECTOR:checked" ).length

Check or uncheck checkbox

$( "SELECTOR" ).prop( "disabled", false );
$( "SELECTOR" ).prop( "checked", true );

Android Webview - Webpage should fit the device screen

WebView webView = (WebView)findViewById(R.id.web_view);
webView.setInitialScale((int) getResources().getDimension(R.dimen._50sdp)); // getActivity(). if you are at Fragment
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.loadDataWithBaseURL(null,here comes html content,"text/html","UTF-8", null);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setDisplayZoomControls(true);
webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);

Running Python code in Vim

A simple method would be to type : while in normal mode, and then press the up arrow key on the keyboard and press Enter. This will repeat the last typed commands on VIM.

Unable to Install Any Package in Visual Studio 2015

I found a solution for this in my case, try to update the NuGet Package Manager.

To do this:

  1. From VS, go to Tools -> Extensions and Updates
  2. Open the Updates menu option at the left, then select Visual Studio Gallery.
  3. If there is an update for Nuget Package Installer, it should show in the list to the right. Click Update
  4. Restart Visual Studio

This let me install packages without problem again.

Hope this helps!

How to link home brew python version and set it as default

brew switch to python3 by default, so if you want to still set python2 as default bin python, running:

brew unlink python && brew link python2 --force

How can I debug my JavaScript code?

I used to use Firebug, until Internet Explorer 8 came out. I'm not a huge fan of Internet Explorer, but after spending some time with the built-in developer tools, which includes a really nice debugger, it seems pointless to use anything else. I have to tip my hat to Microsoft they did a fantastic job on this tool.

setting content between div tags using javascript

Try the following:

document.getElementById("successAndErrorMessages").innerHTML="someContent"; 

msdn link for detail : innerHTML Property

I want to align the text in a <td> to the top

Use <td valign="top" style="width: 259px"> instead...

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Above answers are correct. This version is easy to follow:

Because "Schema export directory is not provided to the annotation processor", So we need to provide the directory for schema export:

Step [1] In your file which extends the RoomDatabase, change the line to:

`@Database(entities = ???.class,version = 1, exportSchema = true)`

Or

`@Database(entities = ???.class,version = 1)` 

(because the default value is always true)

Step [2] In your build.gradle(project:????) file, inside the defaultConfig{ } (which is inside android{ } big section), add the javaCompileOptions{ } section, it will be like:

         android{
                defaultConfig{
                      //javaComplieOptions SECTION
                      javaCompileOptions {
                            annotationProcessorOptions {
                                     arguments = ["room.schemaLocation":"$projectDir/schemas".toString()]
                            }
                       }
                      //Other SECTION
                      ...
                }
         }

$projectDir:is a variable name, you cannot change it. it will get your own project directory

schemas:is a string, you can change it to any you like. For example: "$projectDir/MyOwnSchemas".toString()

CSS border less than 1px

A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).

Here is a test to prove this point:

_x000D_
_x000D_
div { border-color: blue; border-style: solid; margin: 2px; }

div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
_x000D_
_x000D_

Output

enter image description here

Which gives the illusion that the last DIV has a smaller border width, because the blue border blends more with the white background.


Edit: Alternate solution

Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.

_x000D_
_x000D_
.container {
  border-style: solid;
  border-width: 1px;
  
  margin-bottom: 10px;
}

.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
_x000D_
_x000D_

How to divide flask app into multiple py files?

You can use simple trick which is import flask app variable from main inside another file, like:

test-routes.py

from __main__ import app

@app.route('/test', methods=['GET'])
def test():
    return 'it works!'

and in your main files, where you declared flask app, import test-routes, like:

app.py

from flask import Flask, request, abort

app = Flask(__name__)

# import declared routes
import test-routes

It works from my side.

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

Remove element should clear out such errors. The reason behind this is the inherited settings. Your application will inherit some settings from its parent's config file and machine's (server) config files.
You can either remove such duplicates with the remove tag before adding them or make these tags non-inheritable in the upper level config files.

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

Bart Kiers, your regex has a couple issues. The best way to do that is this:

(.*[a-z].*)       // For lower cases
(.*[A-Z].*)       // For upper cases
(.*\d.*)          // For digits

In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.

JQuery Ajax Post results in 500 Internal Server Error

This is Ajax Request Simple Code To Fetch Data Through Ajax Request

$.ajax({
    type: "POST",
    url: "InlineNotes/Note.ashx",
    data: '{"id":"' + noteid+'"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data) {
        alert(data.d);
    },
    error: function(data){
        alert("fail");
    }
});

MySQL error 1241: Operand should contain 1 column(s)

Syntax error, remove the ( ) from select.

insert into table2 (name, subject, student_id, result)
select name, subject, student_id, result
from table1;

How can we generate getters and setters in Visual Studio?

If you're using ReSharper, go into the ReSharper menu → CodeGenerate...

(Or hit Alt + Ins inside the surrounding class), and you'll get all the options for generating getters and/or setters you can think of :-)

Python None comparison: should I use "is" or ==?

Summary:

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

Explanation:

You can have custom classes where my_var == None will return True

e.g:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is checks for object identity. There is only 1 object None, so when you do my_var is None, you're checking whether they actually are the same object (not just equivalent objects)

In other words, == is a check for equivalence (which is defined from object to object) whereas is checks for object identity:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

offsetting an html anchor to adjust for fixed header

I had been facing a similar issue, unfortunately after implementing all the solutions above, I came to the following conclusion.

  1. My inner elements had a fragile CSS structure and implementing a position relative / absolute play, was completely breaking the page design.
  2. CSS is not my strong suit.

I wrote this simple scrolling js, that accounts for the offset caused due to the header and relocated the div about 125 pixels below. Please use it as you see fit.

The HTML

<div id="#anchor"></div> <!-- #anchor here is the anchor tag which is on your URL -->

The JavaScript

 $(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
&& location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 125 //offsets for fixed header
        }, 1000);
        return false;
      }
    }
  });
  //Executed on page load with URL containing an anchor tag.
  if($(location.href.split("#")[1])) {
      var target = $('#'+location.href.split("#")[1]);
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 125 //offset height of header here too.
        }, 1000);
        return false;
      }
    }
});

See a live implementation here.

How to use Typescript with native ES6 Promises

I had to downgrade @types/core-js to 9.36 to get it to work with "target": "es5" set in my tsconfig.

"@types/core-js": "0.9.36",

how to write an array to a file Java

You can use the ObjectOutputStream class to write objects to an underlying stream.

outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.writeObject(x);

And read the Object back like -

inputStream = new ObjectInputStream(new FileInputStream(filename));
x = (int[])inputStream.readObject()

LINQ to Entities does not recognize the method

As you've figured out, Entity Framework can't actually run your C# code as part of its query. It has to be able to convert the query to an actual SQL statement. In order for that to work, you will have to restructure your query expression into an expression that Entity Framework can handle.

public System.Linq.Expressions.Expression<Func<Charity, bool>> IsSatisfied()
{
    string name = this.charityName;
    string referenceNumber = this.referenceNumber;
    return p => 
        (string.IsNullOrEmpty(name) || 
            p.registeredName.ToLower().Contains(name.ToLower()) ||
            p.alias.ToLower().Contains(name.ToLower()) ||
            p.charityId.ToLower().Contains(name.ToLower())) &&
        (string.IsNullOrEmpty(referenceNumber) ||
            p.charityReference.ToLower().Contains(referenceNumber.ToLower()));
}

axios post request to send form data

The above method worked for me but since it was something I needed often, I used a basic method for flat object. Note, I was also using Vue and not REACT

packageData: (data) => {
  const form = new FormData()
  for ( const key in data ) {
    form.append(key, data[key]);
  }
  return form
}

Which worked for me until I ran into more complex data structures with nested objects and files which then let to the following

packageData: (obj, form, namespace) => {
  for(const property in obj) {
    // if form is passed in through recursion assign otherwise create new
    const formData = form || new FormData()
    let formKey

    if(obj.hasOwnProperty(property)) {
      if(namespace) {
        formKey = namespace + '[' + property + ']';
      } else {
        formKey = property;
      }

      // if the property is an object, but not a File, use recursion.
      if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
        packageData(obj[property], formData, property);
      } else {
        // if it's a string or a File
      formData.append(formKey, obj[property]);
      }
    }
  }
  return formData;
}

How to convert hex strings to byte values in Java

You can try something similar to this :

String s = "65";

byte value = Byte.valueOf(s);

Use the Byte.ValueOf() method for all the elements in the String array to convert them into Byte values.

How to know whether refresh button or browser back button is clicked in Firefox

Use for on refresh event

window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};

https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload?redirectlocale=en-US&redirectslug=DOM%2Fwindow.onbeforeunload

And

$(window).unload(function() {
      alert('Handler for .unload() called.');
});

Can't install Scipy through pip

The easiest way is in the following steps: Fixing scipy for python [ 2.n < python < 3.n ]

Download the necessary files from: http://www.lfd.uci.edu/~gohlke/pythonlibs/

Download the version of numpy+mkl (needed to run scipy) and then download scipy for your python type (2.n python written as 2n) or (3.n python written as 3n), n is a variable. Note you must know whether you have a 32bit or 64bit processor.

Create a directory somewhere on your computer, example [C:\DIRECTORY] to install the files numpy+mkd.whl and scipy.whl

Once both file are downloaded, find the location of the file on your computer and move it to the directory you created.

Example: First file installation is needed for scipy is in

C:\DIRECTORY\numpy\numpy-0.0.0+mkl-cp2n-cp2nm-win_amd32.whl

Example: Second file installation is in

C:\DIRECTORY\scipy\scipy-0.0.0-cp2n-cp2nm-win_amd32.whl

Go to your command prompt and proceed the following example for a python version 2.n:

py -2.n -m pip install C:\DIRECTORY\numpy\numpy-0.0.0+mkl-cp2n-cp2nm-win_amd32.whl

should install

py -2.n -m pip install C:\DIRECTORY\scipy\scipy-0.0.0-cp2n-cp2nm-win_amd32.whl

should install

Test both modules on your python IDLE as following:

import numpy

import scipy

the modules are working if no errors are returned.

IFDAAS

IndexError: tuple index out of range ----- Python

This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

The documentation on MSDN about the ItemsSource of the DataGridComboBoxColumn says that only static resources, static code or inline collections of combobox items can be bound to the ItemsSource:

To populate the drop-down list, first set the ItemsSource property for the ComboBox by using one of the following options:

  • A static resource. For more information, see StaticResource Markup Extension.
  • An x:Static code entity. For more information, see x:Static Markup Extension.
  • An inline collection of ComboBoxItem types.

Binding to a DataContext's property is not possible if I understand that correctly.

And indeed: When I make CompanyItems a static property in ViewModel ...

public static ObservableCollection<CompanyItem> CompanyItems { get; set; }

... add the namespace where the ViewModel is located to the window ...

xmlns:vm="clr-namespace:DataGridComboBoxColumnApp"

... and change the binding to ...

<DataGridComboBoxColumn
    ItemsSource="{Binding Source={x:Static vm:ViewModel.CompanyItems}}" 
    DisplayMemberPath="Name"
    SelectedValuePath="ID"
    SelectedValueBinding="{Binding CompanyID}" />

... then it works. But having the ItemsSource as a static property might be sometimes OK, but it is not always what I want.

How to run cron once, daily at 10pm

The syntax for crontab

* * * * * 

Minute(0-59) Hour(0-24) Day_of_month(1-31) Month(1-12) Day_of_week(0-6) Command_to_execute

Your syntax

* 22 * * * test > /dev/null

your job will Execute every minute at 22:00 hrs all week, month and year.

adding an option (0-59) at the minute place will run it once at 22:00 hrs all week, month and year.

0 22 * * * command_to_execute 

Source https://www.adminschoice.com/crontab-quick-reference

How to format current time using a yyyyMMddHHmmss format?

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
        t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

Why does "return list.sort()" return None, not the list?

Python habitually returns None from functions and methods that mutate the data, such as list.sort, list.append, and random.shuffle, with the idea being that it hints to the fact that it was mutating.

If you want to take an iterable and return a new, sorted list of its items, use the sorted builtin function.

Windows equivalent of the 'tail' command

As a contemporary answer, if running Windows 10 you can use the "Linux Subsystem for Windows".

https://docs.microsoft.com/en-us/windows/wsl/install-win10

This will allow you to run native linux commands from within windows and thus run tail exactly how you would in linux.

Flask Python Buttons

Apply (different) name attribute to both buttons like

<button name="one">

and catch them in request.data.

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

Since this question was closed, I'm posting here for how you do it using SQLAlchemy. Via recursion, it retries a bulk insert or update to combat race conditions and validation errors.

First the imports

import itertools as it

from functools import partial
from operator import itemgetter

from sqlalchemy.exc import IntegrityError
from app import session
from models import Posts

Now a couple helper functions

def chunk(content, chunksize=None):
    """Groups data into chunks each with (at most) `chunksize` items.
    https://stackoverflow.com/a/22919323/408556
    """
    if chunksize:
        i = iter(content)
        generator = (list(it.islice(i, chunksize)) for _ in it.count())
    else:
        generator = iter([content])

    return it.takewhile(bool, generator)


def gen_resources(records):
    """Yields a dictionary if the record's id already exists, a row object 
    otherwise.
    """
    ids = {item[0] for item in session.query(Posts.id)}

    for record in records:
        is_row = hasattr(record, 'to_dict')

        if is_row and record.id in ids:
            # It's a row but the id already exists, so we need to convert it 
            # to a dict that updates the existing record. Since it is duplicate,
            # also yield True
            yield record.to_dict(), True
        elif is_row:
            # It's a row and the id doesn't exist, so no conversion needed. 
            # Since it's not a duplicate, also yield False
            yield record, False
        elif record['id'] in ids:
            # It's a dict and the id already exists, so no conversion needed. 
            # Since it is duplicate, also yield True
            yield record, True
        else:
            # It's a dict and the id doesn't exist, so we need to convert it. 
            # Since it's not a duplicate, also yield False
            yield Posts(**record), False

And finally the upsert function

def upsert(data, chunksize=None):
    for records in chunk(data, chunksize):
        resources = gen_resources(records)
        sorted_resources = sorted(resources, key=itemgetter(1))

        for dupe, group in it.groupby(sorted_resources, itemgetter(1)):
            items = [g[0] for g in group]

            if dupe:
                _upsert = partial(session.bulk_update_mappings, Posts)
            else:
                _upsert = session.add_all

            try:
                _upsert(items)
                session.commit()
            except IntegrityError:
                # A record was added or deleted after we checked, so retry
                # 
                # modify accordingly by adding additional exceptions, e.g.,
                # except (IntegrityError, ValidationError, ValueError)
                db.session.rollback()
                upsert(items)
            except Exception as e:
                # Some other error occurred so reduce chunksize to isolate the 
                # offending row(s)
                db.session.rollback()
                num_items = len(items)

                if num_items > 1:
                    upsert(items, num_items // 2)
                else:
                    print('Error adding record {}'.format(items[0]))

Here's how you use it

>>> data = [
...     {'id': 1, 'text': 'updated post1'}, 
...     {'id': 5, 'text': 'updated post5'}, 
...     {'id': 1000, 'text': 'new post1000'}]
... 
>>> upsert(data)

The advantage this has over bulk_save_objects is that it can handle relationships, error checking, etc on insert (unlike bulk operations).

How to create a simple proxy in C#?

I wouldn't use HttpListener or something like that, in that way you'll come across so many issues.

Most importantly it'll be a huge pain to support:

  • Proxy Keep-Alives
  • SSL won't work (in a correct way, you'll get popups)
  • .NET libraries strictly follows RFCs which causes some requests to fail (even though IE, FF and any other browser in the world will work.)

What you need to do is:

  • Listen a TCP port
  • Parse the browser request
  • Extract Host connect to that host in TCP level
  • Forward everything back and forth unless you want to add custom headers etc.

I wrote 2 different HTTP proxies in .NET with different requirements and I can tell you that this is the best way to do it.

Mentalis doing this, but their code is "delegate spaghetti", worse than GoTo :)

Removing duplicates from a list of lists

Strangely, the answers above removes the 'duplicates' but what if I want to remove the duplicated value also?? The following should be useful and does not create a new object in memory!

def dictRemoveDuplicates(self):
    a=[[1,'somevalue1'],[1,'somevalue2'],[2,'somevalue1'],[3,'somevalue4'],[5,'somevalue5'],[5,'somevalue1'],[5,'somevalue1'],[5,'somevalue8'],[6,'somevalue9'],[6,'somevalue0'],[6,'somevalue1'],[7,'somevalue7']]


print(a)
temp = 0
position = -1
for pageNo, item in a:
    position+=1
    if pageNo != temp:
        temp = pageNo
        continue
    else:
        a[position] = 0
        a[position - 1] = 0
a = [x for x in a if x != 0]         
print(a)

and the o/p is:

[[1, 'somevalue1'], [1, 'somevalue2'], [2, 'somevalue1'], [3, 'somevalue4'], [5, 'somevalue5'], [5, 'somevalue1'], [5, 'somevalue1'], [5, 'somevalue8'], [6, 'somevalue9'], [6, 'somevalue0'], [6, 'somevalue1'], [7, 'somevalue7']]
[[2, 'somevalue1'], [3, 'somevalue4'], [7, 'somevalue7']]

What is the easiest way to initialize a std::vector with hardcoded elements?

One method would be to use the array to initialize the vector

static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );

Disable back button in android

For me just overriding onBackPressed() did not work but explicit pointing which activity it should start worked well:

@Override
public void onBackPressed(){
  Intent intent = new Intent(this, ActivityYouWanToGoBack.class);
  startActivity(intent);
}

Table header to stay fixed at the top when user scrolls it out of view with jQuery

I found a solution without jquery

HTML

<table class="fixed_header">
  <thead>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
      <th>Col 3</th>
      <th>Col 4</th>
      <th>Col 5</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>row 1-0</td>
      <td>row 1-1</td>
      <td>row 1-2</td>
      <td>row 1-3</td>
      <td>row 1-4</td>
    </tr>
    <tr>
      <td>row 2-0</td>
      <td>row 2-1</td>
      <td>row 2-2</td>
      <td>row 2-3</td>
      <td>row 2-4</td>
    </tr>
    <tr>
      <td>row 3-0</td>
      <td>row 3-1</td>
      <td>row 3-2</td>
      <td>row 3-3</td>
      <td>row 3-4</td>
    </tr>
    <tr>
      <td>row 4-0</td>
      <td>row 4-1</td>
      <td>row 4-2</td>
      <td>row 4-3</td>
      <td>row 4-4</td>
    </tr>
    <tr>
      <td>row 5-0</td>
      <td>row 5-1</td>
      <td>row 5-2</td>
      <td>row 5-3</td>
      <td>row 5-4</td>
    </tr>
    <tr>
      <td>row 6-0</td>
      <td>row 6-1</td>
      <td>row 6-2</td>
      <td>row 6-3</td>
      <td>row 6-4</td>
    </tr>
    <tr>
      <td>row 7-0</td>
      <td>row 7-1</td>
      <td>row 7-2</td>
      <td>row 7-3</td>
      <td>row 7-4</td>
    </tr>
  </tbody>
</table>

CSS

.fixed_header{
    width: 400px;
    table-layout: fixed;
    border-collapse: collapse;
}

.fixed_header tbody{
  display:block;
  width: 100%;
  overflow: auto;
  height: 100px;
}

.fixed_header thead tr {
   display: block;
}

.fixed_header thead {
  background: black;
  color:#fff;
}

.fixed_header th, .fixed_header td {
  padding: 5px;
  text-align: left;
  width: 200px;
}

You can see it working here: https://jsfiddle.net/lexsoul/fqbsty3h

Source: https://medium.com/@vembarrajan/html-css-tricks-scroll-able-table-body-tbody-d23182ae0fbc

Convert CString to const char*

I had a similar problem. I had a char* buffer with the .so name in it.
I could not convert the char* variable to LPCTSTR. Here's how I got around it...

char *fNam;
...
LPCSTR nam = fNam;
dll = LoadLibraryA(nam);

Entity Framework rollback and remove bad migration

For EF 6 here's a one-liner if you're re-scaffolding a lot in development. Just update the vars and then keep using the up arrow in package manager console to rinse and repeat.

$lastGoodTarget = "OldTargetName"; $newTarget = "NewTargetName"; Update-Database -TargetMigration "$lastGoodTarget" -Verbose; Add-Migration "$newTarget" -Verbose -Force

Why is this necessary you ask? Not sure which versions of EF6 this applies but if your new migration target has already been applied then using '-Force' to re-scaffold in Add-Migration will not actually re-scaffold, but instead make a new file (this is a good thing though because you wouldn't want to lose your 'Down'). The above snippet does the 'Down' first if necessary then -Force works properly to re-scaffold.

Equivalent of "continue" in Ruby

Use next, it will bypass that condition and rest of the code will work. Below i have provided the Full script and out put

class TestBreak
  puts " Enter the nmber"
  no= gets.to_i
  for i in 1..no
    if(i==5)
      next
    else 
      puts i
    end
  end
end

obj=TestBreak.new()

Output: Enter the nmber 10

1 2 3 4 6 7 8 9 10

How to check if an element is off-screen

You could check the position of the div using $(div).position() and check if the left and top margin properties are less than 0 :

if($(div).position().left < 0 && $(div).position().top < 0){
    alert("off screen");
}

Should I use @EJB or @Inject

The @EJB is used to inject EJB's only and is available for quite some time now. @Inject can inject any managed bean and is a part of the new CDI specification (since Java EE 6).

In simple cases you can simply change @EJB to @Inject. In more advanced cases (e.g. when you heavily depend on @EJB's attributes like beanName, lookup or beanInterface) than in order to use @Inject you would need to define a @Producer field or method.

These resources might be helpful to understand the differences between @EJB and @Produces and how to get the best of them:

Antonio Goncalves' blog:
CDI Part I
CDI Part II
CDI Part III

JBoss Weld documentation:
CDI and the Java EE ecosystem

StackOverflow:
Inject @EJB bean based on conditions

How do I change the default schema in sql developer?

I don't know of any way doing this in SQL Developer. You can see all the other schemas and their objects (if you have the correct privileges) when looking in "Other Users" -> "< Schemaname >".

In your case, either use the method described above or create a new connection for the schema in which you want to work or create synonyms for all the tables you wish to access.

If you would work in SQL*Plus, issuing ALTER SESSION SET CURRENT_SCHEMA=MY_NAME would set your current schema (This is probably what your DBA means).

Swift Error: Editor placeholder in source file

you had this

destination = Node(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double)

which was place holder text above you need to insert some values

class Edge{

}

public class Node{

  var key: String?
  var neighbors: [Edge]
  var visited: Bool = false
  var lat: Double
  var long: Double

  init(key: String?, neighbors: [Edge], visited: Bool, lat: Double, long: Double) {
    self.neighbors = [Edge]()
    self.key = key
    self.visited = visited
    self.lat = lat
    self.long = long
  }

}

class Path {

  var total: Int!
  var destination: Node
  var previous: Path!

  init(){
    destination = Node(key: "", neighbors: [], visited: true, lat: 12.2, long: 22.2)
  }
}

Making a WinForms TextBox behave like your browser's address bar

I created a new VB.Net Wpf project. I created one TextBox and used the following for the codebehind:

Class MainWindow 

    Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        AddHandler PreviewMouseLeftButtonDown, New MouseButtonEventHandler(AddressOf SelectivelyIgnoreMouseButton)
        AddHandler GotKeyboardFocus, New KeyboardFocusChangedEventHandler(AddressOf SelectAllText)
        AddHandler MouseDoubleClick, New MouseButtonEventHandler(AddressOf SelectAllText)
    End Sub

    Private Shared Sub SelectivelyIgnoreMouseButton(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
        ' Find the TextBox
        Dim parent As DependencyObject = TryCast(e.OriginalSource, UIElement)
        While parent IsNot Nothing AndAlso Not (TypeOf parent Is TextBox)
            parent = VisualTreeHelper.GetParent(parent)
        End While

        If parent IsNot Nothing Then
            Dim textBox As Object = DirectCast(parent, TextBox)
            If Not textBox.IsKeyboardFocusWithin Then
                ' If the text box is not yet focussed, give it the focus and
                ' stop further processing of this click event.
                textBox.Focus()
                e.Handled = True
            End If
        End If
    End Sub

    Private Shared Sub SelectAllText(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim textBox As Object = TryCast(e.OriginalSource, TextBox)
        If textBox IsNot Nothing Then
            textBox.SelectAll()
        End If
    End Sub

End Class

Adding three months to a date in PHP

Following should work

$d = strtotime("+1 months",strtotime("2015-05-25"));
echo   date("Y-m-d",$d); // This will print **2015-06-25** 

Is there a color code for transparent in HTML?

{background-color: transparent;}

In Swift how to call method with parameters on GCD main thread?

Reload collectionView on Main Thread

DispatchQueue.main.async {
    self.collectionView.reloadData()
}

Adding Jar files to IntellijIdea classpath

Go to File-> Project Structure-> Libraries and click green "+" to add the directory folder that has the JARs to CLASSPATH. Everything in that folder will be added to CLASSPATH.

Update:

It's 2018. It's a better idea to use a dependency manager like Maven and externalize your dependencies. Don't add JAR files to your project in a /lib folder anymore.

Screenshot

Raise warning in Python without interrupting program

You shouldn't raise the warning, you should be using warnings module. By raising it you're generating error, rather than warning.

Convert tabs to spaces in Notepad++

CLR Tabs to Spaces plugin should be a good option. I have used it and it worked.

Shorthand if/else statement Javascript

Another way to write it shortly

bePlanVar = !!((bePlanVar == false));

// is equivalent to

bePlanVar = (bePlanVar == false) ? true : false;

// and 

if (bePlanVar == false) {
    bePlanVar = true;
} else {
    bePlanVar = false;
}

How do I catch a PHP fatal (`E_ERROR`) error?

You can't catch/handle fatal errors, but you can log/report them. For quick debugging I modified one answer to this simple code

function __fatalHandler()
{
    $error = error_get_last();

    // Check if it's a core/fatal error, otherwise it's a normal shutdown
    if ($error !== NULL && in_array($error['type'],
        array(E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING,
              E_COMPILE_ERROR, E_COMPILE_WARNING,E_RECOVERABLE_ERROR))) {

        echo "<pre>fatal error:\n";
        print_r($error);
        echo "</pre>";
        die;
    }
}

register_shutdown_function('__fatalHandler');

When to use async false and async true in ajax function in jquery

ShowPopUpForToDoList: function (id, apprId, tab) {
    var snapShot = "isFromAlert";
    if (tab != "Request")
        snapShot = "isFromTodoList";
    $.ajax({
        type: "GET",
        url: common.GetRootUrl('ActionForm/SetParamForToDoList'),
        data: { id: id, tab: tab },
        async:false,
        success: function (data) {
            ActionForm.EditActionFormPopup(id, snapShot);
        }
    });
},

Here SetParamForToDoList will be excecuted first after the function ActionForm.EditActionFormPopup will fire.

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

For me, the cause of the error message

No tests found for given includes

was having inadvertently added a .java test file under my src/test/kotlin test directory. Upon moving the file to the correct directory, src/test/java, the test executed as expected again.

Delete commit on gitlab

We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:

https://gitlab.example.com/<group>/<project>/commit/<commit hash>

We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.

Socket.IO - how do I get a list of connected sockets/clients?

Using Socket.IO 1.x:

Get array of the connected clients:

io.engine === io.eio // => true
Object.keys(io.engine.clients) // => [ 'US8AxrUrrDF_G7ZUAAAA', 'Ov2Ca24Olkhf2NHbAAAB' ]
Object.keys(io.eio.clients)    // => [ 'US8AxrUrrDF_G7ZUAAAA', 'Ov2Ca24Olkhf2NHbAAAB' ]

Get the number of connected clients:

io.engine.clientsCount // => 2
io.eio.clientsCount    // => 2

How can I pass a parameter to a Java Thread?

When you create a thread, you need an instance of Runnable. The easiest way to pass in a parameter would be to pass it in as an argument to the constructor:

public class MyRunnable implements Runnable {

    private volatile String myParam;

    public MyRunnable(String myParam){
        this.myParam = myParam;
        ...
    }

    public void run(){
        // do something with myParam here
        ...
    }

}

MyRunnable myRunnable = new myRunnable("Hello World");
new Thread(myRunnable).start();

If you then want to change the parameter while the thread is running, you can simply add a setter method to your runnable class:

public void setMyParam(String value){
    this.myParam = value;
}

Once you have this, you can change the value of the parameter by calling like this:

myRunnable.setMyParam("Goodbye World");

Of course, if you want to trigger an action when the parameter is changed, you will have to use locks, which makes things considerably more complex.

Compiler error: "initializer element is not a compile-time constant"

A global variable has to be initialized to a constant value, like 4 or 0.0 or @"constant string" or nil. A object constructor, such as init, does not return a constant value.

If you want to have a global variable, you should initialize it to nil and then return it using a class method:

NSImage *segment = nil;

+ (NSImage *)imageSegment
{
    if (segment == nil) segment = [[NSImage alloc] initWithContentsOfFile:@"/user/asd.jpg"];
    return segment;
}

Convert array of indices to 1-hot encoded numpy array

Here is an example function that I wrote to do this based upon the answers above and my own use case:

def label_vector_to_one_hot_vector(vector, one_hot_size=10):
    """
    Use to convert a column vector to a 'one-hot' matrix

    Example:
        vector: [[2], [0], [1]]
        one_hot_size: 3
        returns:
            [[ 0.,  0.,  1.],
             [ 1.,  0.,  0.],
             [ 0.,  1.,  0.]]

    Parameters:
        vector (np.array): of size (n, 1) to be converted
        one_hot_size (int) optional: size of 'one-hot' row vector

    Returns:
        np.array size (vector.size, one_hot_size): converted to a 'one-hot' matrix
    """
    squeezed_vector = np.squeeze(vector, axis=-1)

    one_hot = np.zeros((squeezed_vector.size, one_hot_size))

    one_hot[np.arange(squeezed_vector.size), squeezed_vector] = 1

    return one_hot

label_vector_to_one_hot_vector(vector=[[2], [0], [1]], one_hot_size=3)

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

The import org.apache.commons cannot be resolved in eclipse juno

You could also add the external jar file to the project. Go to your project-->properties-->java build path-->libraries, add external JARS. Then add your downloaded jar file.

Batch Renaming of Files in a Directory

directoryName = "Photographs"
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"

for counter, filename in enumerate(os.listdir(directoryName)):

    filenameWithPath = os.path.join(filePathWithSlash, filename)

    os.rename(filenameWithPath, filenameWithPath.replace(filename,"DSC_" + \
          str(counter).zfill(4) + ".jpg" ))

# e.g. filename = "photo1.jpg", directory = "c:\users\Photographs"        
# The string.replace call swaps in the new filename into 
# the current filename within the filenameWitPath string. Which    
# is then used by os.rename to rename the file in place, using the  
# current (unmodified) filenameWithPath.

# os.listdir delivers the filename(s) from the directory
# however in attempting to "rename" the file using os 
# a specific location of the file to be renamed is required.

# this code is from Windows 

Div Height in Percentage

It doesn't take the 50% of the whole page is because the "whole page" is only how tall your contents are. Change the enclosing html and body to 100% height and it will work.

html, body{
    height: 100%;
}
div{
    height: 50%;
}

http://jsfiddle.net/DerekL/5YukJ/1/

enter image description here

^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.

enter image description here

^ Now if you change the height of the document to the height of the whole page (150px), 50% of 150px is 75px, then it will work.

Replacing &nbsp; from javascript dom text node

I think when you define a function with "var foo = function() {...};", the function is only defined after that line. In other words, try this:

var replaceHtmlEntites = (function() {
  var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
  var translate = {
    "nbsp": " ",
    "amp" : "&",
    "quot": "\"",
    "lt"  : "<",
    "gt"  : ">"
  };
  return function(s) {
    return ( s.replace(translate_re, function(match, entity) {
      return translate[entity];
    }) );
  }
})();

var cleanText = text.replace(/^\xa0*([^\xa0]*)\xa0*$/g,"");
cleanText = replaceHtmlEntities(text);

Edit: Also, only use "var" the first time you declare a variable (you're using it twice on the cleanText variable).

Edit 2: The problem is the spelling of the function name. You have "var replaceHtmlEntites =". It should be "var replaceHtmlEntities ="

how to use free cloud database with android app?

As Wingman said, Google App Engine is a great solution for your scenario.

You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android

And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

This should be very simple if Google Calendar does not require the *.ics-extension (which will require some URL rewriting in the server).

$ical = "BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
UID:" . md5(uniqid(mt_rand(), true)) . "@yourhost.test
DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z
DTSTART:19970714T170000Z
DTEND:19970715T035959Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR";

//set correct content-type-header
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=calendar.ics');
echo $ical;
exit;

That's essentially all you need to make a client think that you're serving a iCalendar file, even though there might be some issues regarding caching, text encoding and so on. But you can start experimenting with this simple code.

How to evaluate http response codes from bash/shell script?

Here is my implementation, which is a bit more verbose than some of the previous answers

curl https://somewhere.com/somepath   \
--silent \
--insecure \
--request POST \
--header "your-curl-may-want-a-header" \
--data @my.input.file \
--output site.output \
--write-out %{http_code} \
  > http.response.code 2> error.messages
errorLevel=$?
httpResponse=$(cat http.response.code)


jq --raw-output 'keys | @csv' site.output | sed 's/"//g' > return.keys
hasErrors=`grep --quiet --invert errors return.keys;echo $?`

if [[ $errorLevel -gt 0 ]] || [[ $hasErrors -gt 0 ]] || [[ "$httpResponse" != "200" ]]; then
  echo -e "Error POSTing https://somewhere.com/somepath with input my.input (errorLevel $errorLevel, http response code $httpResponse)" >> error.messages
  send_exit_message # external function to send error.messages to whoever.
fi

How should I print types like off_t and size_t?

Which version of C are you using?

In C90, the standard practice is to cast to signed or unsigned long, as appropriate, and print accordingly. I've seen %z for size_t, but Harbison and Steele don't mention it under printf(), and in any case that wouldn't help you with ptrdiff_t or whatever.

In C99, the various _t types come with their own printf macros, so something like "Size is " FOO " bytes." I don't know details, but that's part of a fairly large numeric format include file.

Use Expect in a Bash script to provide a password to an SSH command

A simple Expect script:

File Remotelogin.exp

    #!/usr/bin/expect
    set user [lindex $argv 1]
    set ip [lindex $argv 0]
    set password [lindex $argv 2]
    spawn ssh $user@$ip
    expect "password"
    send "$password\r"
    interact

Example:

./Remotelogin.exp <ip> <user name> <password>

Free c# QR-Code generator

ZXing is an open source project that can detect and parse a number of different barcodes. It can also generate QR-codes. (Only QR-codes, though).

There are a number of variants for different languages: ActionScript, Android (java), C++, C#, IPhone (Obj C), Java ME, Java SE, JRuby, JSP. Support for generating QR-codes comes with some of those: ActionScript, Android, C# and the Java variants.

How to change the port of Tomcat from 8080 to 80?

Running the command below worked with. Tried changing server.xml and the conf file but both didn't work.

/sbin/iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT

/sbin/iptables -A INPUT -i eth0 -p tcp --dport 8080 -j ACCEPT

/sbin/iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

Why is it said that "HTTP is a stateless protocol"?

What is stateless??

Once the request is made and the response is rendered back to the client the connection will be dropped or terminated. The server will forget all about the requester.

Why stateless??

The web chooses to go for the stateless protocol. It was a genius choice because the original goal of the web was to allow documents(web pages) to be served to extremely large no. of people using very basic hardware for the server.

Maintaining a long-running connection would have been extremely resource-intensive.

If the web were chosen the stateful protocol then the load on the server would have been increased to maintain the visitor's connection.

Get Cell Value from Excel Sheet with Apache Poi

May be by:-

    for(Row row : sheet) {          
        for(Cell cell : row) {              
            System.out.print(cell.getStringCellValue());

        }
    }       

For specific type of cell you can try:

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
    cellValue = cell.getStringCellValue();
    break;

case Cell.CELL_TYPE_FORMULA:
    cellValue = cell.getCellFormula();
    break;

case Cell.CELL_TYPE_NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        cellValue = cell.getDateCellValue().toString();
    } else {
        cellValue = Double.toString(cell.getNumericCellValue());
    }
    break;

case Cell.CELL_TYPE_BLANK:
    cellValue = "";
    break;

case Cell.CELL_TYPE_BOOLEAN:
    cellValue = Boolean.toString(cell.getBooleanCellValue());
    break;

}

Python script to copy text to clipboard

One more answer to improve on: https://stackoverflow.com/a/4203897/2804197 and https://stackoverflow.com/a/25476462/1338797 (Tkinter).

Tkinter is nice, because it's either included with Python (Windows) or easy to install (Linux), and thus requires little dependencies for the end user.

Here I have a "full-blown" example, which copies the arguments or the standard input, to clipboard, and - when not on Windows - waits for the user to close the application:

import sys

try:
    from Tkinter import Tk
except ImportError:
    # welcome to Python3
    from tkinter import Tk
    raw_input = input

r = Tk()
r.withdraw()
r.clipboard_clear()

if len(sys.argv) < 2:
    data = sys.stdin.read()
else:
    data = ' '.join(sys.argv[1:])

r.clipboard_append(data)

if sys.platform != 'win32':
    if len(sys.argv) > 1:
        raw_input('Data was copied into clipboard. Paste and press ENTER to exit...')
    else:
        # stdin already read; use GUI to exit
        print('Data was copied into clipboard. Paste, then close popup to exit...')
        r.deiconify()
        r.mainloop()
else:
    r.destroy()

This showcases:

  • importing Tk across Py2 and Py3
  • raw_input and print() compatibility
  • "unhiding" Tk root window when needed
  • waiting for exit on Linux in two different ways.

Twitter Bootstrap - add top space between rows

Editing or overriding the row in Twitter bootstrap is a bad idea, because this is a core part of the page scaffolding and you will need rows without a top margin.

To solve this, instead create a new class "top-buffer" that adds the standard margin that you need.

.top-buffer { margin-top:20px; }

And then use it on the row divs where you need a top margin.

<div class="row top-buffer"> ...

How to remove all options from a dropdown using jQuery / JavaScript

Anyone using JavaScript (as opposed to JQuery), might like to try this solution, where 'models' is the ID of the select field containing the list :-

var DDlist = document.getElementById("models");
while(DDlist.length>0){DDlist.remove(0);}

Creating Threads in python

Did you override the run() method? If you overrided __init__, did you make sure to call the base threading.Thread.__init__()?

After starting the two threads, does the main thread continue to do work indefinitely/block/join on the child threads so that main thread execution does not end before the child threads complete their tasks?

And finally, are you getting any unhandled exceptions?

Get keys of a Typescript interface as array of strings

You will need to make a class that implements your interface, instantiate it and then use Object.keys(yourObject) to get the properties.

export class YourClass implements IMyTable {
    ...
}

then

let yourObject:YourClass = new YourClass();
Object.keys(yourObject).forEach((...) => { ... });

Hunk #1 FAILED at 1. What's that mean?

In some cases, there is no difference in file versions, but only in indentation, spacing, line ending or line numbers.

To patch despite those differences, it's possible to use the following two arguments :

--ignore-whitespace : It ignores whitespace differences (indentation, etc).

--fuzz 3 : the "--fuzz X" option sets the maximum fuzz factor to lines. This option only applies to context and unified diffs; it ignores up to X lines while looking for the place to install a hunk. Note that a larger fuzz factor increases the odds of making a faulty patch. The default fuzz factor is 2; there is no point to setting it to more than the number of lines of context in the diff, ordinarily 3.

Don't forget to user "--dry-run" : It'll try the patch without applying it.

Example :

patch --verbose --dry-run --ignore-whitespace --fuzz 3 < /path/to/patch.patch

More informations about Fuzz :

https://www.gnu.org/software/diffutils/manual/html_node/Inexact.html

How to determine the installed webpack version

For those who are using yarn

yarn list webpack will do the trick

$ yarn list webpack
yarn list v0.27.5
+- [email protected]
Done in 1.24s.

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

You are missing <context:annotation-config /> from your spring context so the annotations are not being scanned!

What is the difference between a URI, a URL and a URN?

They're the same thing. A URI is a generalization of a URL. Originally, URIs were planned to be divided into URLs (addresses) and URNs (names) but then there was little difference between a URL and URI and http URIs were used as namespaces even though they didn't actually locate any resources.

How to create a Java / Maven project that works in Visual Studio Code?

Here is a complete list of steps - you may not need steps 1-3 but am including them for completeness:-

  1. Download VS Code and Apache Maven and install both.
  2. Install the Visual Studio extension pack for Java - e.g. by pasting this URL into a web browser: vscode:extension/vscjava.vscode-java-pack and then clicking on the green Install button after it opens in VS Code.
  3. NOTE: See the comment from ADTC for an "Easier GUI version of step 3...(Skip step 4)." If necessary, the Maven quick start archetype could be used to generate a new Maven project in an appropriate local folder: mvn archetype:generate -DgroupId=com.companyname.appname-DartifactId=appname-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false. This will create an appname folder with Maven's Standard Directory Layout (i.e. src/main/java/com/companyname/appname and src/main/test/com/companyname/appname to begin with and a sample "Hello World!" Java file named appname.java and associated unit test named appnameTest.java).*
  4. Open the Maven project folder in VS Code via File menu -> Open Folder... and select the appname folder.
  5. Open the Command Palette (via the View menu or by right-clicking) and type in and select Tasks: Configure task then select Create tasks.json from template.
  6. Choose maven ("Executes common Maven commands"). This creates a tasks.json file with "verify" and "test" tasks. More can be added corresponding to other Maven Build Lifecycle phases. To specifically address your requirement for classes to be built without a JAR file, a "compile" task would need to be added as follows:

    {
        "label": "compile",
        "type": "shell",
        "command": "mvn -B compile",
        "group": "build"
    },
    
  7. Save the above changes and then open the Command Palette and select "Tasks: Run Build Task" then pick "compile" and then "Continue without scanning the task output". This invokes Maven, which creates a target folder at the same level as the src folder with the compiled class files in the target\classes folder.


Addendum: How to run/debug a class

Following a question in the comments, here are some steps for running/debugging:-

  1. Show the Debug view if it is not already shown (via View menu - Debug or CtrlShiftD).
  2. Click on the green arrow in the Debug view and select "Java".
  3. Assuming it hasn't already been created, a message "launch.json is needed to start the debugger. Do you want to create it now?" will appear - select "Yes" and then select "Java" again.
  4. Enter the fully qualified name of the main class (e.g. com.companyname.appname.App) in the value for "mainClass" and save the file.
  5. Click on the green arrow in the Debug view again.

How to assign multiple classes to an HTML container?

you need to put a dot between the class like

class="column.wrapper">

cmake - find_library - custom library location

I saw that two people put that question to their favorites so I will try to answer the solution which works for me: Instead of using find modules I'm writing configuration files for all libraries which are installed. Those files are extremly simple and can also be used to set non-standard variables. CMake will (at least on windows) search for those configuration files in

CMAKE_PREFIX_PATH/<<package_name>>-<<version>>/<<package_name>>-config.cmake

(which can be set through an environment variable). So for example the boost configuration is in the path

CMAKE_PREFIX_PATH/boost-1_50/boost-config.cmake

In that configuration you can set variables. My config file for boost looks like that:

set(boost_INCLUDE_DIRS ${boost_DIR}/include)
set(boost_LIBRARY_DIR ${boost_DIR}/lib)
foreach(component ${boost_FIND_COMPONENTS}) 
    set(boost_LIBRARIES ${boost_LIBRARIES} debug ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-gd-1_50.lib)
    set(boost_LIBRARIES ${boost_LIBRARIES} optimized ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-1_50.lib)
endforeach()
add_definitions( -D_WIN32_WINNT=0x0501 )

Pretty straight forward + it's possible to shrink the size of the config files even more when you write some helper functions. The only issue I have with this setup is that I havn't found a way to give config files a priority over find modules - so you need to remove the find modules.

Hope this this is helpful for other people.

Omitting one Setter/Getter in Lombok

If you have setter and getter as private it will come up in PMD checks.

Difference between JPanel, JFrame, JComponent, and JApplet

Those classes are common extension points for Java UI designs. First off, realize that they don't necessarily have much to do with each other directly, so trying to find a relationship between them might be counterproductive.

JApplet - A base class that let's you write code that will run within the context of a browser, like for an interactive web page. This is cool and all but it brings limitations which is the price for it playing nice in the real world. Normally JApplet is used when you want to have your own UI in a web page. I've always wondered why people don't take advantage of applets to store state for a session so no database or cookies are needed.

JComponent - A base class for objects which intend to interact with Swing.

JFrame - Used to represent the stuff a window should have. This includes borders (resizeable y/n?), titlebar (App name or other message), controls (minimize/maximize allowed?), and event handlers for various system events like 'window close' (permit app to exit yet?).

JPanel - Generic class used to gather other elements together. This is more important with working with the visual layout or one of the provided layout managers e.g. gridbaglayout, etc. For example, you have a textbox that is bigger then the area you have reserved. Put the textbox in a scrolling pane and put that pane into a JPanel. Then when you place the JPanel, it will be more manageable in terms of layout.