Programs & Examples On #Archiva

[Apache Archiva](http://archiva.apache.org/) is an open source repository management software

Maven fails to find local artifact

The local Maven repo tracks where artifacts originally came from using a file named "_maven.repositories" in the artifact directory. After removing it, the build worked. This answer fixed the problem for me.

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

For me, it works when I double checked the parent´s "group ID" and "artifact ID" that in my case were the wrong ones and that was the problem.

T-SQL STOP or ABORT command in SQL Server

Despite its very explicit and forceful description, RETURN did not work for me inside a stored procedure (to skip further execution). I had to modify the condition logic. Happens on both SQL 2008, 2008 R2:

create proc dbo.prSess_Ins
(
    @sSessID    varchar( 32 )
,   @idSess     int out
)
as
begin
    set nocount on

    select  @id=    idSess
        from    tbSess
        where   sSessID = @sSessID

    if  @idSess > 0 return  -- exit sproc here

    begin   tran
        insert  tbSess  ( sSessID ) values  ( @sSessID )
        select  @idSess=    scope_identity( )
    commit
end

had to be changed into:

    if  @idSess is null
    begin
        begin   tran
            insert  tbSess  ( sSessID ) values  ( @sSessID )
            select  @idSess=    scope_identity( )
        commit
    end

Discovered as a result of finding duplicated rows. Debugging PRINTs confirmed that @idSess had value greater than zero in the IF check - RETURN did not break execution!

How to do a background for a label will be without color?

This uses Graphics.CopyFromScreen so the control needs to be added when it's visable on screen.

public partial class TransparentLabelControl : Label
{
    public TransparentLabelControl()
    {
        this.AutoSize = true;
        this.Visible = false;

        this.ImageAlign = ContentAlignment.TopLeft;
        this.Visible = true;

        this.Resize += TransparentLabelControl_Resize;
        this.LocationChanged += TransparentLabelControl_LocationChanged;
        this.TextChanged += TransparentLabelControl_TextChanged;
        this.ParentChanged += TransparentLabelControl_ParentChanged;
    }

    #region Events
    private void TransparentLabelControl_ParentChanged(object sender, EventArgs e)
    {
        SetTransparent();
        if (this.Parent != null)
        {
            this.Parent.ControlAdded += Parent_ControlAdded;
            this.Parent.ControlRemoved += Parent_ControlRemoved;
        }
    }

    private void Parent_ControlRemoved(object sender, ControlEventArgs e)
    {
        SetTransparent();
    }

    private void Parent_ControlAdded(object sender, ControlEventArgs e)
    {
        if (this.Bounds.IntersectsWith(e.Control.Bounds))
        {
            SetTransparent();
        }
    }

    private void TransparentLabelControl_TextChanged(object sender, EventArgs e)
    {
        SetTransparent();
    }

    private void TransparentLabelControl_LocationChanged(object sender, EventArgs e)
    {

        SetTransparent();
    }

    private void TransparentLabelControl_Resize(object sender, EventArgs e)
    {
        SetTransparent();
    }
    #endregion

    public void SetTransparent()
    {
        if (this.Parent!= null)
        {
            this.Visible = false;
            this.Image = this.takeComponentScreenShot(this.Parent);
            this.Visible = true;                
        }
    }

    private  Bitmap takeComponentScreenShot(Control control)
    {
        Rectangle rect = control.RectangleToScreen(this.Bounds);
        if (rect.Width == 0 || rect.Height == 0)
        {
            return null;
        }
        Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
        Graphics g = Graphics.FromImage(bmp);

        g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);

        return bmp;
    }

}

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

How to load image (and other assets) in Angular an project?

In my project I am using the following syntax in my app.component.html:

<img src="/assets/img/1.jpg" alt="image">

or

<img src='http://mruanova.com/img/1.jpg' alt='image'>

use [src] as a template expression when you are binding a property using interpolation:

<img [src]="imagePath" />

is the same as:

<img src={{imagePath}} />

Source: how to bind img src in angular 2 in ngFor?

Pandas: sum DataFrame rows for given columns

The shortest and simpliest way here is to use

    df.eval('e = a + b + d')

Jquery get form field value

if you know the id of the inputs you only need to use this:

var value = $("#inputID").val();

Sorting a tab delimited file

If you want to make it easier for yourself by only having tabs, replace the spaces with tabs:

tr " " "\t" < <file> | sort <options>

best practice font size for mobile

The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.

Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.

Using CSS to insert text

The answer using jQuery that everyone seems to like has a major flaw, which is it is not scalable (at least as it is written). I think Martin Hansen has the right idea, which is to use HTML5 data-* attributes. And you can even use the apostrophe correctly:

html:

<div class="task" data-task-owner="Joe">mop kitchen</div>
<div class="task" data-task-owner="Charles" data-apos="1">vacuum hallway</div>

css:

div.task:before { content: attr(data-task-owner)"'s task - " ; }
div.task[data-apos]:before { content: attr(data-task-owner)"' task - " ; }

output:

Joe's task - mop kitchen
Charles' task - vacuum hallway

How do I POST urlencoded form data with $http without jQuery?

The problem is the JSON string format, You can use a simple URL string in data:

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

What is (x & 1) and (x >>= 1)?

These are Bitwise Operators (reference).

x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation.

x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift.

Note: The value of the most significant bit after the shift is zero for values of unsigned type. For values of signed type the most significant bit is copied from the sign bit of the value prior to shifting as part of sign extension, so the loop will never finish if x is a signed type, and the initial value is negative.

Oracle Add 1 hour in SQL

To add/subtract from a DATE, you have 2 options :

Method #1 : The easiest way is to use + and - to add/subtract days, hours, minutes, seconds, etc.. from a DATE, and ADD_MONTHS() function to add/subtract months and years from a DATE. Why ? That's because from days, you can get hours and any smaller unit (1 hour = 1/24 days), (1 minute = 1/1440 days), etc... But you cannot get months and years, as that depends on the month and year themselves, hence ADD_MONTHS() and no add_years(), because from months, you can get years (1 year = 12 months).

Let's try them :

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS')             FROM dual;        -- prints current date:    19-OCT-2019 20:42:02 
SELECT TO_CHAR((SYSDATE + 1/24), 'DD-MON-YYYY HH24:MI:SS')    FROM dual;        -- prints date + 1 hour:   19-OCT-2019 21:42:02
SELECT TO_CHAR((SYSDATE + 1/1440), 'DD-MON-YYYY HH24:MI:SS')  FROM dual;        -- prints date + 1 minute: 19-OCT-2019 20:43:02 
SELECT TO_CHAR((SYSDATE + 1/86400), 'DD-MON-YYYY HH24:MI:SS') FROM dual;        -- prints date + 1 second: 19-OCT-2019 20:42:03 
-- Same goes for subtraction.

SELECT SYSDATE                  FROM dual;       -- prints current date:     19-OCT-19
SELECT ADD_MONTHS(SYSDATE, 1)   FROM dual;       -- prints date + 1 month:   19-NOV-19
SELECT ADD_MONTHS(SYSDATE, 12)  FROM dual;       -- prints date + 1 year:    19-OCT-20
SELECT ADD_MONTHS(SYSDATE, -3)  FROM dual;       -- prints date - 3 months:  19-JUL-19

Method #2 : Using INTERVALs, you can or subtract an interval (duration) from a date easily. More than that, you can combine to add or subtract multiple units at once (e.g 5 hours and 6 minutes, etc..) Examples :

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS')                                        FROM dual;        -- prints current date:                 19-OCT-2019 21:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' HOUR), 'DD-MON-YYYY HH24:MI:SS')                  FROM dual;        -- prints date + 1 hour:                19-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' MINUTE), 'DD-MON-YYYY HH24:MI:SS')                FROM dual;        -- prints date + 1 minute:              19-OCT-2019 21:35:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' SECOND), 'DD-MON-YYYY HH24:MI:SS')                FROM dual;        -- prints date + 1 second:              19-OCT-2019 21:34:16
SELECT TO_CHAR((SYSDATE + INTERVAL '01:05:00' HOUR TO SECOND), 'DD-MON-YYYY HH24:MI:SS') FROM dual;        -- prints date + 1 hour and 5 minutes:  19-OCT-2019 22:39:15
SELECT TO_CHAR((SYSDATE + INTERVAL '3 01' DAY TO HOUR), 'DD-MON-YYYY HH24:MI:SS')        FROM dual;        -- prints date + 3 days and 1 hour:     22-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE - INTERVAL '10-3' YEAR TO MONTH), 'DD-MON-YYYY HH24:MI:SS')      FROM dual;        -- prints date - 10 years and 3 months: 19-JUL-2009 21:34:15

Parsing boolean values with argparse

As an improvement to @Akash Desarda 's answer, you could do

import argparse
from distutils.util import strtobool

parser = argparse.ArgumentParser()
parser.add_argument("--foo", 
    type=lambda x:bool(strtobool(x)),
    nargs='?', const=True, default=False)
args = parser.parse_args()
print(args.foo)

And it supports python test.py --foo

(base) [costa@costa-pc code]$ python test.py
False
(base) [costa@costa-pc code]$ python test.py --foo 
True
(base) [costa@costa-pc code]$ python test.py --foo True
True
(base) [costa@costa-pc code]$ python test.py --foo False
False

Pygame Drawing a Rectangle

import pygame, sys
from pygame.locals import *

def main():
    pygame.init()

    DISPLAY=pygame.display.set_mode((500,400),0,32)

    WHITE=(255,255,255)
    BLUE=(0,0,255)

    DISPLAY.fill(WHITE)

    pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))

    while True:
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

main()

This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect to go about this, and you add the DISPLAY constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.

Look up pygame.org for more info

How to center a component in Material-UI and make it responsive?

All you have to do is wrap your content inside a Grid Container tag, specify the spacing, then wrap the actual content inside a Grid Item tag.

 <Grid container spacing={24}>
    <Grid item xs={8}>
      <leftHeaderContent/>
    </Grid>

    <Grid item xs={3}>
      <rightHeaderContent/>
    </Grid>
  </Grid>

Also, I've struggled with material grid a lot, I suggest you checkout flexbox which is built into CSS automatically and you don't need any addition packages to use. Its very easy to learn.

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Passing two command parameters using a WPF binding

If your values are static, you can use x:Array:

<Button Command="{Binding MyCommand}">10
  <Button.CommandParameter>
    <x:Array Type="system:Object">
       <system:String>Y</system:String>
       <system:Double>10</system:Double>
    </x:Array>
  </Button.CommandParameter>
</Button>

How do you append an int to a string in C++?

These work for general strings (in case you do not want to output to file/console, but store for later use or something).

boost.lexical_cast

MyStr += boost::lexical_cast<std::string>(MyInt);

String streams

//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();

// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;

'console' is undefined error for Internet Explorer

You can use console.log(...) directly in Firefox but not in IEs. In IEs you have to use window.console.

How to uninstall with msiexec using product id guid without .msi file present

you need /q at the end

MsiExec.exe /x {2F808931-D235-4FC7-90CD-F8A890C97B2F} /q

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry

public static String getRealPathFromUri(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

This will end up giving you an absolute file path that you can construct a file uri from

In a bootstrap responsive page how to center a div

jsFiddle

HTML:

<div class="container" id="parent">
  <div class="row">
    <div class="col-lg-12">text
      <div class="row ">
        <div class="col-md-4 col-md-offset-4" id="child">TEXT</div>
      </div>
    </div>
  </div>
</div>

CSS:

#parent {    
    text-align: center;
}
#child {
    margin: 0 auto;
    display: inline-block;
    background: red;
    color: white;
}

Eliminate extra separators below UITableView

In case you have a searchbar in your view (to limit the number of results for example), you have to also add the following in shouldReloadTableForSearchString and shouldReloadTableForSearchScope:

controller.searchResultsTable.footerView = [ [ UIView alloc ] initWithFrame:CGRectZero ];

How to generate a random number between 0 and 1?

Have you tried with: replacing ((rand() % 10000) / 10000.0), with:(rand() % 2). This worked for me!

So you could do something like this:

double r2()
{
     srand(time(NULL));
     return(rand() % 2);
}

Android - Dynamically Add Views into View

It looks like what you really want a ListView with a custom adapter to inflate the specified layout. Using an ArrayAdapter and the method notifyDataSetChanged() you have full control of the Views generation and rendering.

Take a look at these tutorials

Eclipse error: "Editor does not contain a main type"

private int user_movie_matrix[][];Th. should be `private int user_movie_matrix[][];.

private int user_movie_matrix[][]; should be private static int user_movie_matrix[][];

cfiltering(numberOfUsers, numberOfMovies); should be new cfiltering(numberOfUsers, numberOfMovies);

Whether or not the code works as intended after these changes is beyond the scope of this answer; there were several syntax/scoping errors.

How do I return multiple values from a function?

In languages like Python, I would usually use a dictionary as it involves less overhead than creating a new class.

However, if I find myself constantly returning the same set of variables, then that probably involves a new class that I'll factor out.

Linux / Bash, using ps -o to get process by specific name?

This is a bit old, but I guess what you want is: ps -o pid -C PROCESS_NAME, for example:

ps -o pid -C bash

EDIT: Dependening on the sort of output you expect, pgrep would be more elegant. This, in my knowledge, is Linux specific and result in similar output as above. For example:

pgrep bash

Set form backcolor to custom color

If you want to set the form's back color to some arbitrary RGB value, you can do this:

this.BackColor = Color.FromArgb(255, 232, 232); // this should be pink-ish

When is a CDATA section necessary within a script tag?

A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) and you want to be able to write literal i<10 and a && b instead of i&lt;10 and a &amp;&amp; b, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will probably want to use a CDATA section.

Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue.

For a good writeup on the subject, see https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/vnd.microsoft.icon"
     href="http://example.com/favicon.ico" />

or

<link rel="icon" type="image/png"
     href="http://example.com/image.png" />

or

<link rel="apple-touch-icon"
     href="http://example.com//apple-touch-icon.png">

for the shortcut icon:

<link rel="shortcut icon"
     href="http://example.com/favicon.ico" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

How to run PowerShell in CMD

Try just:

powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"

How to make a round button?

  1. Create a drawable/button_states.xml file containing:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="false"> 
            <shape android:shape="rectangle">
            <corners android:radius="1000dp" />
            <solid android:color="#41ba7a" />
            <stroke
                android:width="2dip"
                android:color="#03ae3c" />
            <padding
                android:bottom="4dp"
                android:left="4dp"
                android:right="4dp"
                android:top="4dp" />
            </shape>
        </item>
        <item android:state_pressed="true"> 
            <shape android:shape="rectangle">
            <corners android:radius="1000dp" />
            <solid android:color="#3AA76D" />
            <stroke
                android:width="2dip"
                android:color="#03ae3c" />
            <padding
                android:bottom="4dp"
                android:left="4dp"
                android:right="4dp"
                android:top="4dp" />
            </shape>
        </item>
    </selector>
    
  2. Use it in button tag in any layout file

    <Button
        android:layout_width="220dp"
        android:layout_height="220dp"
        android:background="@drawable/button_states"
        android:text="@string/btn_scan_qr"
        android:id="@+id/btn_scan_qr"
        android:textSize="15dp"
    />
    

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

This answer may not apply universally, but it fixed the occurrence of this error I was encountering when importing a small text file. The flat file provider was importing based on fixed 50-character text columns in the source, which was incorrect. No amount of remapping the destination columns affected the issue.

To solve the issue, in the "Choose a Data Source" for the flat-file provider, after selecting the file, a "Suggest Types.." button appears beneath the input column list. After hitting this button, even if no changes were made to the enusing dialog, the Flat File provider then re-queried the source .csv file and then correctly determined the lengths of the fields in the source file.

Once this was done, the import proceeded with no further issues.

Session only cookies with Javascript

Yes, that is correct.

Not putting an expires part in will create a session cookie, whether it is created in JavaScript or on the server.

See https://stackoverflow.com/a/532660/1901857

How do I write a "tab" in Python?

Here are some more exotic Python 3 ways to get "hello" TAB "alex" (tested with Python 3.6.10):

"hello\N{TAB}alex"

"hello\N{tab}alex"

"hello\N{TaB}alex"

"hello\N{HT}alex"

"hello\N{CHARACTER TABULATION}alex"

"hello\N{HORIZONTAL TABULATION}alex"

"hello\x09alex"

"hello\u0009alex"

"hello\U00000009alex"

Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:

"hello alex"

If the tab in the string above won't be lost anywhere during copying the string then "print(repr(< string from above >)" should print 'hello\talex'.

See respective Python documentation for reference.

Compiling php with curl, where is curl installed?

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

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

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

How can I revert a single file to a previous version?

Extracted from here: http://git.661346.n2.nabble.com/Revert-a-single-commit-in-a-single-file-td6064050.html

 git revert <commit> 
 git reset 
 git add <path> 
 git commit ... 
 git reset --hard # making sure you didn't have uncommited changes earlier 

It worked very fine to me.

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

Using NULL in C++?

The downside of NULL in C++ is that it is a define for 0. This is a value that can be silently converted to pointer, a bool value, a float/double, or an int.

That is not very type safe and has lead to actual bugs in an application I worked on.

Consider this:

void Foo(int i);
void Foo(Bar* b);
void Foo(bool b);


main()
{
     Foo(0);         
     Foo(NULL); // same as Foo(0)
} 

C++11 defines a nullptr that is convertible to a null pointer but not to other scalars. This is supported in all modern C++ compilers, including VC++ as of 2008. In older versions of GCC there is a similar feature, but then it was called __null.

*ngIf and *ngFor on same element causing error

Updated to angular2 beta 8

Now as from angular2 beta 8 we can use *ngIf and *ngFor on same component see here.

Alternate:

Sometimes we can't use HTML tags inside another like in tr, th (table) or in li (ul). We cannot use another HTML tag but we have to perform some action in same situation so we can HTML5 feature tag <template> in this way.

ngFor using template:

<template ngFor #abc [ngForOf]="someArray">
    code here....
</template>

ngIf using template:

<template [ngIf]="show">
    code here....
</template>    

For more information about structural directives in angular2 see here.

How to Set Focus on JTextField?

If you want your JTextField to be focused when your GUI shows up, you can use this:

in = new JTextField(40);
f.addWindowListener( new WindowAdapter() {
    public void windowOpened( WindowEvent e ){
        in.requestFocus();
    }
}); 

Where f would be your JFrame and in is your JTextField.

How can I get the source directory of a Bash script from within the script itself?

This is what I crafted throughout the years to use as a header on my Bash scripts:

## BASE BRAIN - Get where you're from and who you are.
MYPID=$$
ORIGINAL_DIR="$(pwd)" # This is not a hot air balloon ride..
fa="$0" # First Assumption
ta= # Temporary Assumption
wa= # Weighed Assumption
while true; do
    [ "${fa:0:1}" = "/" ] && wa=$0 && break
    [ "${fa:0:2}" = "./" ] && ta="${ORIGINAL_DIR}/${fa:2}" && [ -e "$ta" ] && wa="$ta" && break
    ta="${ORIGINAL_DIR}/${fa}" && [ -e "$ta" ] && wa="$ta" && break
done
SW="$wa"
SWDIR="$(dirname "$wa")"
SWBIN="$(basename "$wa")"
unset ta fa wa
( [ ! -e "$SWDIR/$SWBIN" ] || [ -z "$SW" ] ) && echo "I could not find my way around :( possible bug in the TOP script" && exit 1

At this point, your variables SW, SWDIR, and SWBIN contain what you need.

Run JavaScript in Visual Studio Code

I faced this exact problem, when i first start to use VS Code with extension Code Runner

The things you need to do is set the node.js path in User Settings

You need to set the Path as you Install it in your Windows Machine.

For mine It was \"C:\\Program Files\\nodejs\\node.exe\"

As I have a Space in my File Directory Name

See this Image below. I failed to run the code at first cause i made a mistake in the Path Name enter image description here

Hope this will help you.

And ofcourse, Your Question helped me, as i was also come here to get a help to run JS in my VS CODE

How to change the color of an image on hover

An alternative solution would be to use the new CSS mask image functionality which works in everything apart from IE (still not supported in IE11). This would be more versatile and maintainable than some of the other solutions suggested here. You could also more generally use SVG. e.g.

item { mask: url('/mask-image.png'); }

There is an example of using a mask image here:

http://codepen.io/zerostyle/pen/tHimv

and lots of examples here:

http://codepen.io/yoksel/full/fsdbu/

How to read an external local JSON file in JavaScript?

I took Stano's excellent answer and wrapped it in a promise. This might be useful if you don't have an option like node or webpack to fall back on to load a json file from the file system:

// wrapped XMLHttpRequest in a promise
const readFileP = (file, options = {method:'get'}) => 
  new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.onload = resolve;
    request.onerror = reject;
    request.overrideMimeType("application/json");
    request.open(options.method, file, true);
    request.onreadystatechange = () => {
        if (request.readyState === 4 && request.status === "200") {
            resolve(request.responseText);
        }
    };
    request.send(null);
});

You can call it like this:

readFileP('<path to file>')
    .then(d => {
      '<do something with the response data in d.srcElement.response>'
    });

How do you find all subclasses of a given class in Java?

Don't forget that the generated Javadoc for a class will include a list of known subclasses (and for interfaces, known implementing classes).

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

This is an informational message only. What the message is telling you is that the chromedriver executable will only accept connections from the local machine.

Most driver implementations (the Chrome driver and the IE driver for sure) create a HTTP server. The language bindings (Java, Python, Ruby, .NET, etc.) all use a JSON-over-HTTP protocol to communicate with the driver and automate the browser. Since the HTTP server is simply listening on an open port for HTTP requests generated by the language bindings, connections to the HTTP server started by the language bindings are only allowed to come from other processes on the same host. Note carefully that this limitation does not apply to connections the browser can make to outside websites; rather it simply prevents incoming connections from other websites.

Error 0x80005000 and DirectoryServices

I encounter this error when I'm querying an entry of another domain of the forrest and this entry have some custom attribut of the other domain.

To solve this error, I only need to specify the server in the url LDAP :

Path with error = LDAP://CN=MyObj,DC=DOMAIN,DC=COM

Path without error : LDAP://domain.com:389/CN=MyObj,DC=Domain,DC=COM

"unrecognized selector sent to instance" error in Objective-C

I'm replying to Leonard Challis, since I was also taking the Stanford iOS class C193P, as was user "oli206"

"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:"

The problem was that I had the "Enter" button on the calculator connected twice,and a friend pointed out that doing an inspection of the button in the Storyboard showed that 2 entries were on the "Touch Up Inside" attributes when I right clicked on the "Enter" button. Erasing one of the two "Touch Up Inside" "Sent Events" solved the problem.

This showed that the problem is triggered (for the C193P video class on the Calculator Walkthrough on Assignment 1) as 2 sent events, one of which was causing the exception.

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

@Nickparsa … you have 2 issues:

1). mysql -uroot -p should be typed in bash (also known as your terminal) not in MySQL command-line. You fix this error by typing

exit

in your MySQL command-line. Now you are back in your bash/terminal command-line.

2). You have a syntax error:

mysql -uroot -p; 

the semicolon in front of -p needs to go. The correct syntax is:

mysql -uroot -p

type the correct syntax in your bash commandline. Enter a password if you have one set up; else just hit the enter button. You should get a response that is similar to this: enter image description here

Hope this helps!

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

After lots of struggle I found here you go:

  1. open folder -> xampp
  2. then open -> phpmyadmin
  3. finally open -> config.inc
$cfg['blowfish_secret'] = ''; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */
  1. Put SHA256 inside single quotations like this one

830bbca930d5e417ae4249931838e2c70ca0365044268fa0ede75e33aff677de

$cfg['blowfish_secret'] = '830bbca930d5e417ae4249931838e2c70ca0365044268fa0ede75e33aff677de
';

I found this when I was downloading updated version of phpmyadmin. I wish this solution help you. enter image description here

How to apply Hovering on html area tag?

for complete this script , the function for draw circle ,

    function drawCircle(coordon)
    {
        var coord = coordon.split(',');

        var c = document.getElementById("myCanvas");
        var hdc = c.getContext("2d");
        hdc.beginPath();

        hdc.arc(coord[0], coord[1], coord[2], 0, 2 * Math.PI);
        hdc.stroke();
    }

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

In Python 3 the dict.values() method returns a dictionary view object, not a list like it does in Python 2. Dictionary views have a length, can be iterated, and support membership testing, but don't support indexing.

To make your code work in both versions, you could use either of these:

{names[i]:value for i,value in enumerate(d.values())}

    or

values = list(d.values())
{name:values[i] for i,name in enumerate(names)}

By far the simplest, fastest way to do the same thing in either version would be:

dict(zip(names, d.values()))

Note however, that all of these methods will give you results that will vary depending on the actual contents of d. To overcome that, you may be able use an OrderedDict instead, which remembers the order that keys were first inserted into it, so you can count on the order of what is returned by the values() method.

Get min and max value in PHP Array

foreach ($array as $k => $v) {
  $tArray[$k] = $v['Weight'];
}
$min_value = min($tArray);
$max_value = max($tArray);

Difference between binary semaphore and mutex

Mutex and binary semaphore are both of the same usage, but in reality, they are different.

In case of mutex, only the thread which have locked it can unlock it. If any other thread comes to lock it, it will wait.

In case of semaphone, that's not the case. Semaphore is not tied up with a particular thread ID.

How to change password using TortoiseSVN?

I changed windows password today then Tortoise declined to connect me to SVN server. I got around it by opening a Dos box and doing an "svn co ...". It prompted for the new credential then happily did its work. After that, Tortoise works also.

Android TextView padding between lines

You can use TextView.setLineSpacing(n,m) function.

static files with express.js

res.sendFile & express.static both will work for this

var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');

// viewed at http://localhost:8080
app.get('/', function(req, res) {
    res.sendFile(path.join(public, 'index.html'));
});

app.use('/', express.static(public));

app.listen(8080);

Where public is the folder in which the client side code is

As suggested by @ATOzTOA and clarified by @Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.

How to completely uninstall Android Studio on Mac?

Some of the files individually listed by Simon would also be found with something like the following command, but with some additional assurance about thoroughness, and without the recklessness of using rm -rf with wildcards:

find ~ \
  -path ~/Library/Caches/Metadata/Safari -prune -o \
  -iname \*android\*studio\* -print -prune

Also don't forget about the SDK, which is now separate from the application, and ~/.gradle/ (see vijay's answer).

jquery to validate phone number

function validatePhone(txtPhone) {
    var a = document.getElementById(txtPhone).value;
    var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
    if (filter.test(a)) {
        return true;
    }
    else {
        return false;
    }
}

Demo http://jsfiddle.net/dishantd/JLJMW/496/

Is there any way to kill a Thread?

Here's yet another way to do it, but with extremely clean and simple code, that works in Python 3.7 in 2021:

import ctypes 

def kill_thread(thread):
    """
    thread: a threading.Thread object
    """
    thread_id = thread.ident
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(SystemExit))
    if res > 1:
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
        print('Exception raise failure')

Adapted from here: https://www.geeksforgeeks.org/python-different-ways-to-kill-a-thread/

Is there a Python equivalent of the C# null-coalescing operator?

The two functions below I have found to be very useful when dealing with many variable testing cases.

def nz(value, none_value, strict=True):
    ''' This function is named after an old VBA function. It returns a default
        value if the passed in value is None. If strict is False it will
        treat an empty string as None as well.

        example:
        x = None
        nz(x,"hello")
        --> "hello"
        nz(x,"")
        --> ""
        y = ""   
        nz(y,"hello")
        --> ""
        nz(y,"hello", False)
        --> "hello" '''

    if value is None and strict:
        return_val = none_value
    elif strict and value is not None:
        return_val = value
    elif not strict and not is_not_null(value):
        return_val = none_value
    else:
        return_val = value
    return return_val 

def is_not_null(value):
    ''' test for None and empty string '''
    return value is not None and len(str(value)) > 0

Angular: Can't find Promise, Map, Set and Iterator

my file structure is as below:

project
 |--node-modules
 |   |--angular2
 |   |   |--typings
 |   |   |   |--browser.d.ts
 |--src
 |--app.ts

paste the below into the top of your app.ts and your problem solved

/// <reference path=">../../../node_modules/angular2/typings/browser.d.ts" />

How to send Request payload to REST API in java?

I tried with a rest client.

Headers :

  • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • Host: git.eclipse.org
  • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
  • Accept: application/json
  • Accept-Language: null
  • Accept-Encoding: gzip,deflate,sdch
  • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • Content-Type: application/json; charset=UTF-8
  • Content-Length: 73
  • Connection: keep-alive

it works fine. I retrieve 200 OK with a good body.

Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

Getting started with Haskell

I do think that realizing Haskell's feature by examples is the best way to start above all.

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

Here is tricky typeclasses including monads and arrows

http://www.haskell.org/haskellwiki/Typeclassopedia

for real world problems and bigger project, remember these tags: GHC(most used compiler), Hackage(libraryDB), Cabal(building system), darcs(another building system).

A integrated system can save your time: http://hackage.haskell.org/platform/

the package database for this system: http://hackage.haskell.org/

GHC compiler's wiki: http://www.haskell.org/haskellwiki/GHC

After Haskell_98_features and Typeclassopedia, I think you already can find and read the documention about them yourself

By the way, you may want to test some GHC's languages extension which may be a part of haskell standard in the future.

this is my best way for learning haskell. i hope it can help you.

Datagridview: How to set a cell in editing mode?

Setting the CurrentCell and then calling BeginEdit(true) works well for me.

The following code shows an eventHandler for the KeyDown event that sets a cell to be editable.

My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            e.Handled = true;
            DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
            dataGridView1.CurrentCell = cell;
            dataGridView1.BeginEdit(true);               
        }
    }

If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.

Playing MP4 files in Firefox using HTML5 video

This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.

Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:

http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/

phpmyadmin "Not Found" after install on Apache, Ubuntu

You will need to configure your apache2.conf to make phpMyAdmin works.

sudo nano /etc/apache2/apache2.conf

Then add the following line to the end of the file.

Include /etc/phpmyadmin/apache.conf

Then restart apache

sudo service apache2 restart

Rules for C++ string literals escape character

With the magic of user-defined literals, we have yet another solution to this. C++14 added a std::string literal operator.

using namespace std::string_literals;
auto const x = "\0" "0"s;

Constructs a string of length 2, with a '\0' character (null) followed by a '0' character (the digit zero). I am not sure if it is more or less clear than the initializer_list<char> constructor approach, but it at least gets rid of the ' and , characters.

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Vue v-on:click does not work on component

Native events of components aren't directly accessible from parent elements. Instead you should try v-on:click.native="testFunction", or you can emit an event from Test component as well. Like v-on:click="$emit('click')".

Throw away local commits in Git

To see/get the SHA-1 id of the commit you want to come back too

gitk --all

To roll back to that commit

git reset --hard sha1_id

!Note. All the commits that were made after that commit will be deleted (and all your modification to the project). So first better clone the project to another branch or copy to another directory.

Get value of Span Text

Judging by your other post: How to Get the inner text of a span in PHP. You're quite new to web programming, and need to learn about the differences between code on the client (JavaScript) and code on the server (PHP).

As for the correct approach to grabbing the span text from the client I recommend Johns answer.

These are a good place to get started.

JavaScript: https://stackoverflow.com/questions/11246/best-resources-to-learn-javascript

PHP: https://stackoverflow.com/questions/772349/what-is-a-good-online-tutorial-for-php

Also I recommend using jQuery (Once you've got some JavaScript practice) it will eliminate most of the cross-browser compatability issues that you're going to have. But don't use it as a crutch to learn on, it's good to understand JavaScript too. http://jquery.com/

How to change a dataframe column from String type to Double type in PySpark?

pyspark version:

  df = <source data>
  df.printSchema()

  from pyspark.sql.types import *

  # Change column type
  df_new = df.withColumn("myColumn", df["myColumn"].cast(IntegerType()))
  df_new.printSchema()
  df_new.select("myColumn").show()

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

The problem is caused by accessing an attribute with the hibernate session closed. You have not a hibernate transaction in the controller.

Possible solutions:

  1. Do all this logic, in the service layer, (with the @Transactional), not in the controller. There should be the right place to do this, it is part of the logic of the app, not in the controller (in this case, an interface to load the model). All the operations in the service layer should be transactional. i.e.: Move this line to the TopicService.findTopicByID method:

    Collection commentList = topicById.getComments();

  2. Use 'eager' instead of 'lazy'. Now you are not using 'lazy' .. it is not a real solution, if you want to use lazy, works like a temporary (very temporary) workaround.

  3. use @Transactional in the Controller. It should not be used here, you are mixing service layer with presentation, it is not a good design.
  4. use OpenSessionInViewFilter, many disadvantages reported, possible instability.

In general, the best solution is the 1.

How to read a file line-by-line into a list?

I would try one of the below mentioned methods. The example file that I use has the name dummy.txt. You can find the file here. I presume, that the file is in the same directory as the code (you can change fpath to include the proper file name and folder path.)

In both the below mentioned examples, the list that you want is given by lst.

1.> First method:

fpath = 'dummy.txt'
with open(fpath, "r") as f: lst = [line.rstrip('\n \t') for line in f]

print lst
>>>['THIS IS LINE1.', 'THIS IS LINE2.', 'THIS IS LINE3.', 'THIS IS LINE4.']

2.> In the second method, one can use csv.reader module from Python Standard Library:

import csv
fpath = 'dummy.txt'
with open(fpath) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='   ')
    lst = [row[0] for row in csv_reader] 

print lst
>>>['THIS IS LINE1.', 'THIS IS LINE2.', 'THIS IS LINE3.', 'THIS IS LINE4.']

You can use either of the two methods. Time taken for the creation of lst is almost equal in the two methods.

How to find all occurrences of a substring?

this is an old thread but i got interested and wanted to share my solution.

def find_all(a_string, sub):
    result = []
    k = 0
    while k < len(a_string):
        k = a_string.find(sub, k)
        if k == -1:
            return result
        else:
            result.append(k)
            k += 1 #change to k += len(sub) to not search overlapping results
    return result

It should return a list of positions where the substring was found. Please comment if you see an error or room for improvment.

Preferred way to create a Scala list

To create a list of string, use the following:

val l = List("is", "am", "are", "if")

How to make an app's background image repeat

Expanding on plowman's answer, here is the non-deprecated version of changing the background image with java.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap bmp = BitmapFactory.decodeResource(getResources(),
            R.drawable.texture);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(),bmp);
    bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT,
            Shader.TileMode.REPEAT);
    setBackground(bitmapDrawable);
}

How to select the first row of each group?

Window functions:

Something like this should do the trick:

import org.apache.spark.sql.functions.{row_number, max, broadcast}
import org.apache.spark.sql.expressions.Window

val df = sc.parallelize(Seq(
  (0,"cat26",30.9), (0,"cat13",22.1), (0,"cat95",19.6), (0,"cat105",1.3),
  (1,"cat67",28.5), (1,"cat4",26.8), (1,"cat13",12.6), (1,"cat23",5.3),
  (2,"cat56",39.6), (2,"cat40",29.7), (2,"cat187",27.9), (2,"cat68",9.8),
  (3,"cat8",35.6))).toDF("Hour", "Category", "TotalValue")

val w = Window.partitionBy($"hour").orderBy($"TotalValue".desc)

val dfTop = df.withColumn("rn", row_number.over(w)).where($"rn" === 1).drop("rn")

dfTop.show
// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

This method will be inefficient in case of significant data skew.

Plain SQL aggregation followed by join:

Alternatively you can join with aggregated data frame:

val dfMax = df.groupBy($"hour".as("max_hour")).agg(max($"TotalValue").as("max_value"))

val dfTopByJoin = df.join(broadcast(dfMax),
    ($"hour" === $"max_hour") && ($"TotalValue" === $"max_value"))
  .drop("max_hour")
  .drop("max_value")

dfTopByJoin.show

// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

It will keep duplicate values (if there is more than one category per hour with the same total value). You can remove these as follows:

dfTopByJoin
  .groupBy($"hour")
  .agg(
    first("category").alias("category"),
    first("TotalValue").alias("TotalValue"))

Using ordering over structs:

Neat, although not very well tested, trick which doesn't require joins or window functions:

val dfTop = df.select($"Hour", struct($"TotalValue", $"Category").alias("vs"))
  .groupBy($"hour")
  .agg(max("vs").alias("vs"))
  .select($"Hour", $"vs.Category", $"vs.TotalValue")

dfTop.show
// +----+--------+----------+
// |Hour|Category|TotalValue|
// +----+--------+----------+
// |   0|   cat26|      30.9|
// |   1|   cat67|      28.5|
// |   2|   cat56|      39.6|
// |   3|    cat8|      35.6|
// +----+--------+----------+

With DataSet API (Spark 1.6+, 2.0+):

Spark 1.6:

case class Record(Hour: Integer, Category: String, TotalValue: Double)

df.as[Record]
  .groupBy($"hour")
  .reduce((x, y) => if (x.TotalValue > y.TotalValue) x else y)
  .show

// +---+--------------+
// | _1|            _2|
// +---+--------------+
// |[0]|[0,cat26,30.9]|
// |[1]|[1,cat67,28.5]|
// |[2]|[2,cat56,39.6]|
// |[3]| [3,cat8,35.6]|
// +---+--------------+

Spark 2.0 or later:

df.as[Record]
  .groupByKey(_.Hour)
  .reduceGroups((x, y) => if (x.TotalValue > y.TotalValue) x else y)

The last two methods can leverage map side combine and don't require full shuffle so most of the time should exhibit a better performance compared to window functions and joins. These cane be also used with Structured Streaming in completed output mode.

Don't use:

df.orderBy(...).groupBy(...).agg(first(...), ...)

It may seem to work (especially in the local mode) but it is unreliable (see SPARK-16207, credits to Tzach Zohar for linking relevant JIRA issue, and SPARK-30335).

The same note applies to

df.orderBy(...).dropDuplicates(...)

which internally uses equivalent execution plan.

How to reset AUTO_INCREMENT in MySQL?

I googled and found this question, but the answer I am really looking for fulfils two criteria:

  1. using purely MySQL queries
  2. reset an existing table auto-increment to max(id) + 1

Since I couldn't find exactly what I want here, I have cobbled the answer from various answers and sharing it here.

Few things to note:

  1. the table in question is InnoDB
  2. the table uses the field id with type as int as primary key
  3. the only way to do this purely in MySQL is to use stored procedure
  4. my images below are using SequelPro as the GUI. You should be able to adapt it based on your preferred MySQL editor
  5. I have tested this on MySQL Ver 14.14 Distrib 5.5.61, for debian-linux-gnu

Step 1: Create Stored Procedure

create a stored procedure like this:

DELIMITER //
CREATE PROCEDURE reset_autoincrement(IN tablename varchar(200))
BEGIN

      SET @get_next_inc = CONCAT('SELECT @next_inc := max(id) + 1 FROM ',tablename,';');
      PREPARE stmt FROM @get_next_inc; 
      EXECUTE stmt; 
      SELECT @next_inc AS result;
      DEALLOCATE PREPARE stmt; 

      set @alter_statement = concat('ALTER TABLE ', tablename, ' AUTO_INCREMENT = ', @next_inc, ';');
      PREPARE stmt FROM @alter_statement;
      EXECUTE stmt;
      DEALLOCATE PREPARE stmt;
END //
DELIMITER ;

Then run it.

Before run, it looks like this when you look under Stored Procedures in your database.

enter image description here

When I run, I simply select the stored procedure and press Run Selection

enter image description here

Note: the delimiters part are crucial. Hence if you copy and paste from the top selected answers in this question, they tend not to work for this reason.

After I run, I should see the stored procedure

enter image description here

If you need to change the stored procedure, you need to delete the stored procedure, then select to run again.

Step 2: Call the stored procedure

This time you can simply use normal MySQL queries.

call reset_autoincrement('products');

Originally from my own SQL queries notes in https://simkimsia.com/library/sql-queries/#mysql-reset-autoinc and adapted for StackOverflow

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

Dim thisMonth As New DateTime(DateTime.Today.Year, DateTime.Today.Month, 1)
Dim firstDayLastMonth As DateTime
Dim lastDayLastMonth As DateTime

firstDayLastMonth = thisMonth.AddMonths(-1)
lastDayLastMonth = thisMonth.AddDays(-1)

Build fails with "Command failed with a nonzero exit code"

I got this error while trying to run my unit tests in a submodule. What I have done is:

Change the simulator => Clean the project => Build the project => Run unit tests.

After this, my unit tests ran without any issue.

How to run Selenium WebDriver test cases in Chrome

I included the binary into my projects resources directory like so:

src\main\resources\chrome\chromedriver_win32.zip
src\main\resources\chrome\chromedriver_mac64.zip
src\main\resources\chrome\chromedriver_linux64.zip

Code:

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.*;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public WebDriver getWebDriver() throws IOException {
    File tempDir = Files.createTempDirectory("chromedriver").toFile();
    tempDir.deleteOnExit();
    File chromeDriverExecutable;

    final String zipResource;
    if (SystemUtils.IS_OS_WINDOWS) {
        zipResource = "chromedriver_win32.zip";
    } else if (SystemUtils.IS_OS_LINUX) {
        zipResource = "chromedriver_linux64.zip";
    } else if (SystemUtils.IS_OS_MAC) {
        zipResource = "chrome/chromedriver_mac64.zip";
    } else {
        throw new RuntimeException("Unsuppoerted OS");
    }

    try (InputStream is = getClass().getResourceAsStream("/chrome/" + zipResource)) {
        try (ZipInputStream zis = new ZipInputStream(is)) {
            ZipEntry entry;
            entry = zis.getNextEntry();
            chromeDriverExecutable = new File(tempDir, entry.getName());
            chromeDriverExecutable.deleteOnExit();
            try (OutputStream out = new FileOutputStream(chromeDriverExecutable)) {
                IOUtils.copy(zis, out);
            }
        }
    }

    System.setProperty("webdriver.chrome.driver", chromeDriverExecutable.getAbsolutePath());
    return new ChromeDriver();
}

Display a RecyclerView in Fragment

You should retrieve RecyclerView in a Fragment after inflating core View using that View. Perhaps it can't find your recycler because it's not part of Activity

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
    final FragmentActivity c = getActivity();
    final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(c);
    recyclerView.setLayoutManager(layoutManager);

    new Thread(new Runnable() {
        @Override
        public void run() {
            final RecyclerAdapter adapter = new RecyclerAdapter(c);
            c.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recyclerView.setAdapter(adapter);
                }
            });
        }
    }).start();

    return view;
}

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

I'll try to make you understand with the help of an example. Suppose you had a relational table (STUDENT) with two columns and ID(int) and NAME(String). Now as ORM you would've made an entity class somewhat like as follows:-

package com.kashyap.default;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author vaibhav.kashyap
 *
 */
@Entity
@Table(name = "STUDENT")
public class Student implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -1354919370115428781L;

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "NAME")
    private String name;

    public Student(){

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Lets assume table already had entries. Now if somebody asks you add another column of "AGE" (int)

ALTER TABLE STUDENT ADD AGE int NULL

You'll have to set default values as NULL to add another column in a pre-filled table. This makes you add another field in the class. Now the question arises whether you'll be using a primitive data type or non primitive wrapper data type for declaring the field.

@Column(name = "AGE")
private int age;

or

@Column(name = "AGE")
private INTEGER age;

you'll have to declare the field as non primitive wrapper data type because the container will try to map the table with the entity. Hence it wouldn't able to map NULL values (default) if you won't declare field as wrapper & would eventually throw "Null value was assigned to a property of primitive type setter" Exception.

Convert list or numpy array of single element to float in python

np.asscalar(a) is deprecated since NumPy v1.16, use a.item() instead.

For example:

a = np.array([[0.6813]])
print(a.item())

gives:

0.6813

Plotting a 3d cube, a sphere and a vector in Matplotlib

My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)


# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)

# tails of the arrows
tails= np.zeros(len(bvecs))

# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
          length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('b-vectors on unit sphere')

plt.show()

Should I use Java's String.format() if performance is important?

Generally you should use String.Format because it's relatively fast and it supports globalization (assuming you're actually trying to write something that is read by the user). It also makes it easier to globalize if you're trying to translate one string versus 3 or more per statement (especially for languages that have drastically different grammatical structures).

Now if you never plan on translating anything, then either rely on Java's built in conversion of + operators into StringBuilder. Or use Java's StringBuilder explicitly.

Replacing few values in a pandas dataframe column with another value

This solution will change the existing dataframe itself:

mydf = pd.DataFrame({"BrandName":["A", "B", "ABC", "D", "AB"], "Speciality":["H", "I", "J", "K", "L"]})
mydf["BrandName"].replace(["ABC", "AB"], "A", inplace=True)

JavaScriptSerializer.Deserialize - how to change field names

Json.NET will do what you want (disclaimer: I'm the author of the package). It supports reading DataContract/DataMember attributes as well as its own to change the property names. Also there is the StringEnumConverter class for serializing enum values as the name rather than the number.

jQuery remove options from select

For jquery < 1.8 you can use :

$('#selectedId option').slice(index1,index2).remove()

to remove a especific range of the select options.

HTML select form with option to enter custom value

You can't really. You'll have to have both the drop down, and the text box, and have them pick or fill in the form. Without javascript you could create a separate radio button set where they choose dropdown or text input, but this seems messy to me. With some javascript you could toggle disable one or the other depending on which one they choose, for instance, have an 'other' option in the dropdown that triggers the text field.

Modifying a file inside a jar

This may be more work than you're looking to deal with in the short term, but I suspect in the long term it would be very beneficial for you to look into using Ant (or Maven, or even Bazel) instead of building jar's manually. That way you can just click on the ant file (if you use Eclipse) and rebuild the jar.

Alternatively, you may want to actually not have these config files in the jar at all - if you're expecting to need to replace these files regularly, or if it's supposed to be distributed to multiple parties, the config file should not be part of the jar at all.

Preloading CSS Images

Preloading images using CSS only

In the below code I am randomly choosing the body element, since it is one of the only elements guaranteed to exist on the page.

For the "trick" to work, we shall use the content property which comfortably allows setting multiple URLs to be loaded, but as shown, the ::after pseudo element is kept hidden so the images won't be rendered:

body::after{
   position:absolute; width:0; height:0; overflow:hidden; z-index:-1; // hide images
   content:url(img1.png) url(img2.png) url(img3.gif) url(img4.jpg);   // load images
}

Demo


it's better to use a sprite image to reduce http requests...(if there are many relatively small sized images) and make sure the images are hosted where HTTP2 is used.

How to check if a word is an English word with Python?

For a semantic web approach, you could run a sparql query against WordNet in RDF format. Basically just use urllib module to issue GET request and return results in JSON format, parse using python 'json' module. If it's not English word you'll get no results.

As another idea, you could query Wiktionary's API.

How to open a web page automatically in full screen mode

It's better to try to simulate a webbrowser by yourself.You don't have to stick with Chrome or IE or else thing.

If you're using Python,you can try package pyQt4 which helps you to simulate a webbrowser. By doing this,there will not be any security reasons and you can set the webbrowser to show in full screen mode automatically.

How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

When creating your own library, you can can create *.d.ts files by using the tsc (TypeScript Compiler) command like so: (assuming you're building your library to the dist/lib folder)

tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly
  • -d (--declaration): generates the *.d.ts files
  • --declarationDir dist/lib: Output directory for generated declaration files.
  • --declarationMap: Generates a sourcemap for each corresponding ‘.d.ts’ file.
  • --emitDeclarationOnly: Only emit ‘.d.ts’ declaration files. (no compiled JS)

(see the docs for all command line compiler options)

Or for instance in your package.json:

"scripts": {
    "build:types": "tsc -d --declarationDir dist/lib --declarationMap --emitDeclarationOnly",
}

and then run: yarn build:types (or npm run build:types)

Nullable property to entity field, Entity Framework through Code First

The other option is to tell EF to allow the column to be null:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();            
        base.OnModelCreating(modelBuilder);
}

This code should be in the object that inherits from DbContext.

VMWare Player vs VMWare Workstation

re: VMware Workstation support for physical disks vs virtual disks.

I run Player with the VM Disk files on their own dedicated fast hard drive, independent from the OS hard drive. This allows both the OS and Player to simultaneously independently read/write to their own drives, the performance difference is noticeable, and a second WD Black or Raptor or SSD is cheap. Placing the VM disk file on a second drive also works with Microsoft Virtual PC.

How to pass multiple checkboxes using jQuery ajax post

Here's a more flexible way.

let's say this is your form.

<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>

And this is your jquery ajax below...

                // Don't get confused at this portion right here
                // cuz "var data" will get all the values that the form
                // has submitted in the $_POST. It doesn't matter if you 
                // try to pass a text or password or select form element.
                // Remember that the "form" is not a name attribute
                // of the form, but the "form element" itself that submitted
                // the current post method
                var data = $("form").serialize(); 

                $.ajax({
                    url: "link/of/your/ajax.php", // link of your "whatever" php
                    type: "POST",
                    async: true,
                    cache: false,
                    data: data, // all data will be passed here
                    success: function(data){ 
                        alert(data) // The data that is echoed from the ajax.php
                    }
                });

And in your ajax.php, you try echoing or print_r your post to see what's happening inside it. This should look like this. Only checkboxes that you checked will be returned. If you didn't checked any, it will return an error.

<?php 
    print_r($_POST); // this will be echoed back to you upon success.
    echo "This one too, will be echoed back to you";

Hope that is clear enough.

Importing JSON into an Eclipse project

Download java-json.jar from here, which contains org.json.JSONArray

http://www.java2s.com/Code/JarDownload/java/java-json.jar.zip

nzip and add to your project's library: Project > Build Path > Configure build path> Select Library tab > Add External Libraries > Select the java-json.jar file.

In Python, how do you convert a `datetime` object to seconds?

The standard way to find the processing time in ms of a block of code in python 3.x is the following:

import datetime

t_start = datetime.datetime.now()

# Here is the python3 code, you want 
# to check the processing time of

t_end = datetime.datetime.now()
print("Time taken : ", (t_end - t_start).total_seconds()*1000, " ms")

How to remove all CSS classes using jQuery/JavaScript?

Let's use this example. Maybe you want the user of your website to know a field is valid or it needs attention by changing the background color of the field. If the user hits reset then your code should only reset the fields that have data and not bother to loop through every other field on your page.

This jQuery filter will remove the class "highlightCriteria" only for the input or select fields that have this class.

$form.find('input,select').filter(function () {
    if((!!this.value) && (!!this.name)) {
        $("#"+this.id).removeClass("highlightCriteria");
    }
});

Mockito How to mock only the call of a method of the superclass

Even if i totally agree with iwein response (

favor composition over inheritance

), i admit there are some times inheritance seems just natural, and i don't feel breaking or refactor it just for the sake of a unit test.

So, my suggestion :

/**
 * BaseService is now an asbtract class encapsulating 
 * some common logic callable by child implementations
 */
abstract class BaseService {  
    protected void commonSave() {
        // Put your common work here
    }

    abstract void save();
}

public ChildService extends BaseService {  
    public void save() {
        // Put your child specific work here
        // ...

        this.commonSave();
    }  
}

And then, in the unit test :

    ChildService childSrv = Mockito.mock(ChildService.class, Mockito.CALLS_REAL_METHODS);

    Mockito.doAnswer(new Answer<Void>() {
        @Override
        public Boolean answer(InvocationOnMock invocation)
                throws Throwable {
            // Put your mocked behavior of BaseService.commonSave() here
            return null;
        }
    }).when(childSrv).commonSave();

    childSrv.save();

    Mockito.verify(childSrv, Mockito.times(1)).commonSave();

    // Put any other assertions to check child specific work is done

Javascript / Chrome - How to copy an object from the webkit inspector as code

Using "Store as a Global Variable" works, but it only gets the final instance of the object, and not the moment the object is being logged (since you're likely wanting to compare changes to the object as they happen). To get the object at its exact point in time of being modified, I use this...

function logObject(object) {
    console.info(JSON.stringify(object).replace(/,/g, ",\n"));
}

Call it like so...

logObject(puzzle);

You may want to remove the .replace(/./g, ",\n") regex if your data happens to have comma's in it.

What is the simplest way to convert array to vector?

Use the vector constructor that takes two iterators, note that pointers are valid iterators, and use the implicit conversion from arrays to pointers:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + sizeof x / sizeof x[0]);
test(v);

or

test(std::vector<int>(x, x + sizeof x / sizeof x[0]));

where sizeof x / sizeof x[0] is obviously 3 in this context; it's the generic way of getting the number of elements in an array. Note that x + sizeof x / sizeof x[0] points one element beyond the last element.

How to split a long array into smaller arrays, with JavaScript

as a function

var arrayChunk = function (array, chunkSize) {
            var arrayOfArrays = [];

            if (array.length <= chunkSize) {
                arrayOfArrays.push(array);
            } else {
                for (var i=0; i<array.length; i+=chunkSize) {
                    arrayOfArrays.push(array.slice(i,i+chunkSize));
                }
            }
            return arrayOfArrays;
        }

to use

arrayChunk(originalArray, 10) //10 being the chunk size.

Multiple types were found that match the controller named 'Home'

What others said is correct but for those who still face the same problem:
In my case it happened because I copied another project n renamed it to something else BUT previous output files in bin folder were still there... And unfortunately, hitting Build -> Clean Solution after renaming the project and its Namespaces doesn't remove them... so deleting them manually solved my problem!

get string value from HashMap depending on key name

Suppose you declared HashMap as :-

HashMap<Character,Integer> hs = new HashMap<>();

Then,key in map is of type Character data type and value of int type.Now,to get value corresponding to key irrespective of type of key,value type, syntax is :-

    char temp = 'a';
    if(hs.containsKey(temp)){
`       int val = hs.get(temp); //val is the value corresponding to key temp
    }

So, according to your question you want to get string value corresponding to a key.For this, just declare HashMap as HashMap<"datatype of key","datatype of value" hs = new HashMap<>(); Using this will make your code cleaner and also you don't have to convert the result of hs.get("my_code") to string as by default it returns value of string if at entry time one has kept value as a string.

How to comment and uncomment blocks of code in the Office VBA Editor

With MZ-Tools installed, I comment/uncomment blocks in VBE by using the keyboard shortcut
Ctrl+Alt+C (MZ-Tools default)

Get Value From Select Option in Angular 4

HTML code

    <form class="form-inline" (ngSubmit)="HelloCorp(modelName)">
        <div class="select">
            <select class="form-control col-lg-8" [(ngModel)]="modelName" required>
                <option *ngFor="let corporation of corporations" [ngValue]="corporation">
                    {{corporation.corp_name}}
                </option>    
            </select>
            <button type="submit" class="btn btn-primary manage">Submit</button>
        </div> 
    </form>

Component code

HelloCorp(corporation) {
    var corporationObj = corporation.value;
}

Deleting elements from std::set while iterating

This is implementation dependent:

Standard 23.1.2.8:

The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

Maybe you could try this -- this is standard conforming:

for (auto it = numbers.begin(); it != numbers.end(); ) {
    if (*it % 2 == 0) {
        numbers.erase(it++);
    }
    else {
        ++it;
    }
}

Note that it++ is postfix, hence it passes the old position to erase, but first jumps to a newer one due to the operator.

2015.10.27 update: C++11 has resolved the defect. iterator erase (const_iterator position); return an iterator to the element that follows the last element removed (or set::end, if the last element was removed). So C++11 style is:

for (auto it = numbers.begin(); it != numbers.end(); ) {
    if (*it % 2 == 0) {
        it = numbers.erase(it);
    }
    else {
        ++it;
    }
}

Converting java date to Sql timestamp

You can cut off the milliseconds using a Calendar:

java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));

Output:

2014-04-04 10:10:17.78
2014-04-04 10:10:17.0

Choosing a file in Python with simple Dialog

In Python 2 use the tkFileDialog module.

import tkFileDialog

tkFileDialog.askopenfilename()

In Python 3 use the tkinter.filedialog module.

import tkinter.filedialog

tkinter.filedialog.askopenfilename()

how to get the 30 days before date from Todays Date

SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE());

Example.

SELECT `name`, `phone`, `product` FROM `tbmMember` WHERE `dateofServicw` < (Day,-30,GETDATE()); 

Inserting data to table (mysqli insert)

Okay, of course the question has been answered, but no-one seems to notice the third line of your code. It continuosly bugged me.

    <?php
    mysqli_connect("localhost","root","","web_table");
    mysql_select_db("web_table") or die(mysql_error());

for some reason, you made a mysqli connection to server, but you are trying to make a mysql connection to database.To get going, rather use

       $link = mysqli_connect("localhost","root","","web_table");
       mysqli_select_db ($link , "web_table" ) or die.....

or for where i began

     <?php $connection = mysqli_connect("localhost","root","","web_table");       
      global $connection; // global connection to databases - kill it once you're done

or just query with a $connection parameter as the other argument like above. Get rid of that third line.

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

According to the GCC page for C++11:

To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.

Did you compile with -std=gnu++0x ?

Using Spring 3 autowire in a standalone Java application

I case you are running SpringBoot:

I just had the same problem, that I could not Autowire one of my services from the static main method.

See below an approach in case you are relying on SpringApplication.run:

@SpringBootApplication
public class PricingOnlineApplication {

    @Autowired
    OrchestratorService orchestratorService;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(PricingOnlineApplication.class, args);
        PricingOnlineApplication application = context.getBean(PricingOnlineApplication.class);

        application.start();
    }

    private void start() {
        orchestratorService.performPricingRequest(null);
    }

}

I noticed that SpringApplication.run returns a context which can be used similar to the above described approaches. From there, it is exactly the same as above ;-)

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

Class has no objects member

You can change the linter for Python extension for Visual Studio Code.

In VS open the Command Palette Ctrl+Shift+P and type in one of the following commands:

Python: Select Linter

when you select a linter it will be installed. I tried flake8 and it seems issue resolved for me.

How to find/identify large commits in git history?

I stumbled across this for the same reason as anyone else. But the quoted scripts didn't quite work for me. I've made one that is more a hybrid of those I've seen and it now lives here - https://gitlab.com/inorton/git-size-calc

SQL SERVER: Check if variable is null and then assign statement for Where Clause

is null is the syntax I use for such things, when COALESCE is of no help.

Try:

if (@zipCode is null)
  begin
    ([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)   
  end
else 
  begin
    ([Portal].[dbo].[Address].PostalCode=@zipCode )
  end  

Adding two Java 8 streams, or an extra element to a stream

Just do:

Stream.of(stream1, stream2, Stream.of(element)).flatMap(identity());

where identity() is a static import of Function.identity().

Concatenating multiple streams into one stream is the same as flattening a stream.

However, unfortunately, for some reason there is no flatten() method on Stream, so you have to use flatMap() with the identity function.

How to get the current time in Python

This is so simple. Try:

import datetime
date_time = str(datetime.datetime.now())
date = date_time.split()[0]
time = date_time.split()[1]

Why can't I initialize non-const static member or static array in class?

Why I can't initialize static data members in class?

The C++ standard allows only static constant integral or enumeration types to be initialized inside the class. This is the reason a is allowed to be initialized while others are not.

Reference:
C++03 9.4.2 Static data members
§4

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

What are integral types?

C++03 3.9.1 Fundamental types
§7

Types bool, char, wchar_t, and the signed and unsigned integer types are collectively called integral types.43) A synonym for integral type is integer type.

Footnote:

43) Therefore, enumerations (7.2) are not integral; however, enumerations can be promoted to int, unsigned int, long, or unsigned long, as specified in 4.5.

Workaround:

You could use the enum trick to initialize an array inside your class definition.

class A 
{
    static const int a = 3;
    enum { arrsize = 2 };

    static const int c[arrsize] = { 1, 2 };

};

Why does the Standard does not allow this?

Bjarne explains this aptly here:

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

Why are only static const integral types & enums allowed In-class Initialization?

The answer is hidden in Bjarne's quote read it closely,
"C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects."

Note that only static const integers can be treated as compile time constants. The compiler knows that the integer value will not change anytime and hence it can apply its own magic and apply optimizations, the compiler simply inlines such class members i.e, they are not stored in memory anymore, As the need of being stored in memory is removed, it gives such variables the exception to rule mentioned by Bjarne.

It is noteworthy to note here that even if static const integral values can have In-Class Initialization, taking address of such variables is not allowed. One can take the address of a static member if (and only if) it has an out-of-class definition.This further validates the reasoning above.

enums are allowed this because values of an enumerated type can be used where ints are expected.see citation above


How does this change in C++11?

C++11 relaxes the restriction to certain extent.

C++11 9.4.2 Static data members
§3

If a static data member is of const literal type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Also, C++11 will allow(§12.6.2.8) a non-static data member to be initialized where it is declared(in its class). This will mean much easy user semantics.

Note that these features have not yet been implemented in latest gcc 4.7, So you might still get compilation errors.

typecast string to integer - Postgres

I'm not able to comment (too little reputation? I'm pretty new) on Lukas' post.

On my PG setup to_number(NULL) does not work, so my solution would be:

SELECT CASE WHEN column = NULL THEN NULL ELSE column :: Integer END
FROM table

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

USE This Assembly Referance in your Project

Add a reference to System.Net.Http.Formatting.dll

QByteArray to QString

Use QString::fromUtf16((ushort *)Data.data()), as shown in the following code example:

#include <QCoreApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // QByteArray to QString
    // =====================

    const char c_test[10] = {'t', '\0', 'e', '\0', 's', '\0', 't', '\0', '\0', '\0'};
    QByteArray qba_test(QByteArray::fromRawData(c_test, 10));
    qDebug().nospace().noquote() << "qba_test[" << qba_test << "]"; // Should see: qba_test[t

    QString qstr_test = QString::fromUtf16((ushort *)qba_test.data());
    qDebug().nospace().noquote() << "qstr_test[" << qstr_test << "]"; // Should see: qstr_test[test]

    return a.exec();
}

This is an alternative solution to the one using QTextCodec. The code has been tested using Qt 5.4.

Get the closest number out of an array

Another variant here we have circular range connecting head to toe and accepts only min value to given input. This had helped me get char code values for one of the encryption algorithm.

function closestNumberInCircularRange(codes, charCode) {
  return codes.reduce((p_code, c_code)=>{
    if(((Math.abs(p_code-charCode) > Math.abs(c_code-charCode)) || p_code > charCode) && c_code < charCode){
      return c_code;
    }else if(p_code < charCode){
      return p_code;
    }else if(p_code > charCode && c_code > charCode){
      return Math.max.apply(Math, [p_code, c_code]);
    }
    return p_code;
  });
}

How to get UTF-8 working in Java webapps?

I want also to add from here this part solved my utf problem:

runtime.encoding=<encoding>

How to detect pressing Enter on keyboard using jQuery?

I think the simplest method would be using vanilla javacript:

document.onkeyup = function(event) {
   if (event.key === 13){
     alert("enter was pressed");
   }
}

What are the differences between a pointer variable and a reference variable in C++?

"I know references are syntactic sugar, so code is easier to read and write"

This. A reference is not another way to implement a pointer, although it covers a huge pointer use case. A pointer is a datatype -- an address that in general points to a actual value. However it can be set to zero, or a couple of places after the address using address arithmetic, etc. A reference is 'syntactic sugar' for a variable which has its own value.

C only had pass by value semantics. Getting the address of the data a variable was referring to and sending that to a function was a way to pass by 'reference'. A reference shortcuts this semantically by 'referring' to the original data location itself. So:

int x = 1;
int *y = &x;
int &z = x;

Y is an int pointer, pointing to the location where x is stored. X and Z refer to the same storage place (the stack or the heap).

Alot of people have talked about the difference between the two (pointers and references) as if they are the same thing with different usages. They are not the same at all.

1) "A pointer can be re-assigned any number of times while a reference cannot be re-assigned after binding." -- a pointer is an address data type which points to data. A reference is another name for the data. So you can 'reassign' a reference. You just can't reassign the data location it refers to. Just like you can't change the data location that 'x' refers to, you can't do that to 'z'.

x = 2;
*y = 2;
z = 2;

The same. It is a reassignment.

2) "Pointers can point nowhere (NULL), whereas a reference always refers to an object" -- again with the confusion. The reference is just another name for the object. A null pointer means (semantically) that it isn't referring to anything, whereas the reference was created by saying it was another name for 'x'. Since

3) "You can't take the address of a reference like you can with pointers" -- Yes you can. Again with the confusion. If you are trying to find the address of the pointer that is being used as a reference, that is a problem -- cause references are not pointers to the object. They are the object. So you can get the address of the object, and you can get the address of the pointer. Cause they are both getting the address of data (one the object's location in memory, the other the pointer to the objects location in memory).

int *yz = &z; -- legal
int **yy = &y; -- legal

int *yx = &x; -- legal; notice how this looks like the z example.  x and z are equivalent.

4) "There's no "reference arithmetic"" -- again with the confusion -- since the example above has z being a reference to x and both are therefore integers, 'reference' arithmetic means for example adding 1 to the value referred to by x.

x++;
z++;

*y++;  // what people assume is happening behind the scenes, but isn't. it would produce the same results in this example.
*(y++);  // this one adds to the pointer, and then dereferences it.  It makes sense that a pointer datatype (an address) can be incremented.  Just like an int can be incremented. 

Hive query output to file

Two ways can store HQL query results:

  1. Save into HDFS Location
INSERT OVERWRITE DIRECTORY "HDFS Path" ROW FORMAT DELIMITED FIELDS TERMINATED BY '|'
SELECT * FROM XXXX LIMIT 10;
  1. Save to Local File
$hive  -e "select * from table_Name" > ~/sample_output.txt
$hive -e "select * from table where city = 'London' and id >=100" > /home/user/outputdirectory/city details.csv

How can I find WPF controls by name or type?

Since the question is general enough that it might attract people looking for answers to very trivial cases: if you just want a child rather than a descendant, you can use Linq:

private void ItemsControlItem_Loaded(object sender, RoutedEventArgs e)
{
    if (SomeCondition())
    {
        var children = (sender as Panel).Children;
        var child = (from Control child in children
                 where child.Name == "NameTextBox"
                 select child).First();
        child.Focus();
    }
}

or of course the obvious for loop iterating over Children.

Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this?

For Ubuntu 18.04

If you are getting an error like

 tesseract is not installed or it's not in your path

 and 

 OSError: [Errno 12] Cannot allocate memory

That might be and issue with the swap memory allocation issue

You can check this answer allocating more swap memory Hope that helps :)

https://askubuntu.com/questions/920595/fallocate-fallocate-failed-text-file-busy-in-ubuntu-17-04?answertab=active#tab-top

What are POD types in C++?

As I understand POD (PlainOldData) is just a raw data - it does not need:

  • to be constructed,
  • to be destroyed,
  • to have custom operators.
  • Must not have virtual functions,
  • and must not override operators.

How to check if something is a POD? Well, there is a struct for that called std::is_pod:

namespace std {
// Could use is_standard_layout && is_trivial instead of the builtin.
template<typename _Tp>
  struct is_pod
  : public integral_constant<bool, __is_pod(_Tp)>
  { };
}

(From header type_traits)


Reference:

Get GPS location from the web browser

To give a bit more specific answer. HTML5 allows you to get the geo coordinates, and it does a pretty decent job. Overall the browser support for geolocation is pretty good, all major browsers except ie7 and ie8 (and opera mini). IE9 does the job but is the worst performer. Checkout caniuse.com:

http://caniuse.com/#search=geol

Also you need the approval of your user to access their location, so make sure you check for this and give some decent instructions in case it's turned off. Especially for Iphone turning permissions on for Safari is a bit cumbersome.

jQuery get the rendered height of an element?

It should just be

$('#someDiv').height();

with jQuery. This retrieves the height of the first item in the wrapped set as a number.

Trying to use

.style.height

only works if you have set the property in the first place. Not very useful!

fatal: Not a valid object name: 'master'

Git creates a master branch once you've done your first commit. There's nothing to have a branch for if there's no code in the repository.

HttpClient does not exist in .net 4.0: what can I do?

Agreeing with TrueWill's comment on a separate answer, the best way I've seen to use system.web.http on a .NET 4 targeted project under current Visual Studio is Install-Package Microsoft.AspNet.WebApi.Client -Version 4.0.30506

Calling a java method from c++ in Android

If it's an object method, you need to pass the object to CallObjectMethod:

jobject result = env->CallObjectMethod(obj, messageMe, jstr);

What you were doing was the equivalent of jstr.messageMe().

Since your is a void method, you should call:

env->CallVoidMethod(obj, messageMe, jstr);

If you want to return a result, you need to change your JNI signature (the ()V means a method of void return type) and also the return type in your Java code.

Choosing the default value of an Enum type without having to change values

The default value of any enum is zero. So if you want to set one enumerator to be the default value, then set that one to zero and all other enumerators to non-zero (the first enumerator to have the value zero will be the default value for that enum if there are several enumerators with the value zero).

enum Orientation
{
    None = 0, //default value since it has the value '0'
    North = 1,
    East = 2,
    South = 3,
    West = 4
}

Orientation o; // initialized to 'None'

If your enumerators don't need explicit values, then just make sure the first enumerator is the one you want to be the default enumerator since "By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1." (C# reference)

enum Orientation
{
    None, //default value since it is the first enumerator
    North,
    East,
    South,
    West
}

Orientation o; // initialized to 'None'

How to get selected option using Selenium WebDriver with Java

var option = driver.FindElement(By.Id("employmentType"));
        var selectElement = new SelectElement(option);
        Task.Delay(3000).Wait();
        selectElement.SelectByIndex(2);
        Console.Read();

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

  1. Delete these entries mentioned in this post: http://manfredlange.blogspot.ca/2008/03/visual-studio-unable-to-find-manifest.html.

  2. Also remove the .snk or .pfx files from the project root.

Don't forget to push these changes to GitHub, for Jenkins only pulls source from GitHub.

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

sqlplus statement from command line

My version

$ sqlplus -s username/password@host:port/service <<< "select 1 from dual;"


         1
----------
         1

EDIT:

For multiline you can use this

$ echo -e "select 1 from dual; \n select 2 from dual;" | sqlplus -s username/password@host:port/service


         1
----------
         1


         2
----------
         2

Using python map and other functional tools

Would this do it?

foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]

def maptest2(bar):
  print bar

def maptest(foo):
  print foo
  map(maptest2, bars)

map(maptest, foos)

How do I show running processes in Oracle DB?

This one shows SQL that is currently "ACTIVE":-

select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/

This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:

select
  object_name, 
  object_type, 
  session_id, 
  type,         -- Type or system/user lock
  lmode,        -- lock mode in which session holds lock
  request, 
  block, 
  ctime         -- Time since current mode was granted
from
  v$locked_object, all_objects, v$lock
where
  v$locked_object.object_id = all_objects.object_id AND
  v$lock.id1 = all_objects.object_id AND
  v$lock.sid = v$locked_object.session_id
order by
  session_id, ctime desc, object_name
/

This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.

COLUMN percent FORMAT 999.99 

SELECT sid, to_char(start_time,'hh24:mi:ss') stime, 
message,( sofar/totalwork)* 100 percent 
FROM v$session_longops
WHERE sofar/totalwork < 1
/

Can an Android NFC phone act as an NFC tag?

No, not at the moment. Google pointed out at the Google IO 2011, that card emulation is not supported and won't be supported for a while. Main (and easy to understand) problem: Which App should get the right on the phone to emulate a smartcard?

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

In our case, we were using Hibernate and we had many variables referencing the same Hibernate mapped entity. We were creating and saving these references in a loop. Each reference opened a cursor and kept it open.

We discovered this by using a query to check the number of open cursors while running our code, stepping through with a debugger and selectively commenting things out.

As to why each new reference opened another cursor - the entity in question had collections of other entities mapped to it and I think this had something to do with it (perhaps not just this alone but in combination with how we had configured the fetch mode and cache settings). Hibernate itself has had bugs around failing to close open cursors, though it looks like these have been fixed in later versions.

Since we didn't really need to have so many duplicate references to the same entity anyway, the solution was to stop creating and holding onto all those redundant references. Once we did that the problem when away.

Git workflow and rebase vs merge questions

With Git there is no “correct” workflow. Use whatever floats your boat. However, if you constantly get conflicts when merging branches maybe you should coordinate your efforts better with your fellow developer(s)? Sounds like the two of you keep editing the same files. Also, watch out for whitespace and subversion keywords (i.e., “$Id$” and others).

Javascript Regular Expression Remove Spaces

I would recommend you use the literal notation, and the \s character class:

//..
return str.replace(/\s/g, '');
//..

There's a difference between using the character class \s and just ' ', this will match a lot more white-space characters, for example '\t\r\n' etc.., looking for ' ' will replace only the ASCII 32 blank space.

The RegExp constructor is useful when you want to build a dynamic pattern, in this case you don't need it.

Moreover, as you said, "[\s]+" didn't work with the RegExp constructor, that's because you are passing a string, and you should "double escape" the back-slashes, otherwise they will be interpreted as character escapes inside the string (e.g.: "\s" === "s" (unknown escape)).

Change bundle identifier in Xcode when submitting my first app in IOS

This solve my problem.

Just change the Bundle identifier from Build Setting.

 Navigate to Project >> Build Setting >> Product Bundle Identifier 

'adb' is not recognized as an internal or external command, operable program or batch file

If you didn't set a path for ADB, you can run .\adb instead of adb at sdk/platformtools.

How to handle windows file upload using Selenium WebDriver?

// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");

Hey, that's mine from somewhere :).


In case of the Zamzar web, it should work perfectly. You don't click the element. You just type the path into it. To be concrete, this should be absolutely ok:

driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");

In the case of the Uploadify web, you're in a pickle, since the upload thing is no input, but a Flash object. There's no API for WebDriver that would allow you to work with browser dialogs (or Flash objects).

So after you click the Flash element, there'll be a window popping up that you'll have no control over. In the browsers and operating systems I know, you can pretty much assume that after the window has been opened, the cursor is in the File name input. Please, make sure this assumption is true in your case, too.

If not, you could try to jump to it by pressing Alt + N, at least on Windows...

If yes, you can "blindly" type the path into it using the Robot class. In your case, that would be something in the way of:

driver.findElement(By.id("SWFUpload_0")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C);        // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON);    // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH);    // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path

r.keyPress(KeyEvent.VK_ENTER);    // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);

It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar() which does similar work, but is available only from JDK7).


For Flash, the only alternative I know (from this discussion) is to use the dark technique:

First, you modify the source code of you the flash application, exposing internal methods using the ActionScript's ExternalInterface API. Once exposed, these methods will be callable by JavaScript in the browser.

Second, now that JavaScript can call internal methods in your flash app, you use WebDriver to make a JavaScript call in the web page, which will then call into your flash app.

This technique is explained further in the docs of the flash-selenium project. (http://code.google.com/p/flash-selenium/), but the idea behind the technique applies just as well to WebDriver.

Difference between Select Unique and Select Distinct

  1. Unique was the old syntax while Distinct is the new syntax,which is now the Standard sql.
  2. Unique creates a constraint that all values to be inserted must be different from the others. An error can be witnessed if one tries to enter a duplicate value. Distinct results in the removal of the duplicate rows while retrieving data.
  3. Example: SELECT DISTINCT names FROM student ;

    CREATE TABLE Persons ( Id varchar NOT NULL UNIQUE, Name varchar(20) );

How to Change Margin of TextView

        TextView tv = (TextView)findViewById(R.id.item_title));
        RelativeLayout.LayoutParams mRelativelp = (RelativeLayout.LayoutParams) tv
                    .getLayoutParams();
        mRelativelp.setMargins(DptoPxConvertion(15), 0, DptoPxConvertion (15), 0);
        tv.setLayoutParams(mRelativelp);

    private int DptoPxConvertion(int dpValue)
    {
       return (int)((dpValue * mContext.getResources().getDisplayMetrics().density) + 0.5);
    }

getLayoutParams() of textview should be casted to the corresponding Params based on the Parent of the textview in xml.

<RelativeLayout>
   <TextView
    android:id="@+id/item_title">
</RelativeLayout>

To render the same real size on different devices use DptoPxConvertion() method which I have used above. setMargin(left,top,right,bottom) params will take values in pixel not in dp. For further reference see this Link Answer

JQuery - Call the jquery button click event based on name property

You have to use the jquery attribute selector. You can read more here:

http://api.jquery.com/attribute-equals-selector/

In your case it should be:

$('input[name="btnName"]')

Mysql: Select rows from a table that are not in another

SELECT a.* FROM 
FROM tbl_1 a
MINUS
SELECT b.* FROM 
FROM tbl_2 b

java.lang.ClassNotFoundException: HttpServletRequest

you should add servler-api.jar file in WEB-INF/lib folder

Get the current year in JavaScript

Such is how I have it embedded and outputted to my HTML web page:

<div class="container">
    <p class="text-center">Copyright &copy; 
        <script>
            var CurrentYear = new Date().getFullYear()
            document.write(CurrentYear)
        </script>
    </p>
</div>

Output to HTML page is as follows:

Copyright © 2018

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I eventually figured out an easy way to do it:

  1. On your Twitter feed, click the date/time of the tweet containing the video. That will open the single tweet view
  2. Look for the down-pointing arrow at the top-right corner of the tweet, click it to open drop-down menue
  3. Select the "Embed Video" option and copy the HTML embed code and Paste it to Notepad
  4. Find the last "t.co" shortened URL inside the HTML code (should be something like this: https://``t.co/tQM43ftXyM). Copy this URL and paste it in a new browser tab.
  5. The browser will expand the shortened URL to something which looks like this: https://twitter.com/UserName/status/828267001496784896/video/1

This is the link to the Twitter Card containing the native video. Pasting this link in a new tweet or DM will include the native video in it!

gitignore all files of extension in directory

It would appear that the ** syntax is supported by git as of version 1.8.2.1 according to the documentation.

Two consecutive asterisks ("**") in patterns matched against full pathname may have special meaning:

  • A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".

  • A trailing "/**" matches everything inside. For example, "abc/**" matches all files inside directory "abc", relative to the location of the .gitignore file, with infinite depth.

  • A slash followed by two consecutive asterisks then a slash matches zero or more directories. For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.

  • Other consecutive asterisks are considered invalid.

Attach the Source in Eclipse of a jar

I faced the same issue and solved using the below steps. Go to Windows->preferences->Editors->File Associations

Here click on Add then type .class click on OK

again click on Add then type .classwithoughtsource click on OK

Now you will be able to see JadClipse option under Java section in Windows->Preferences

Please provide the path of jad.exe file as shown below.

Path for Decompiler-C:\Users\ahr\Documents\eclipse-jee-galileo-SR2-win32\jad.exe Directory for temporary Files-C:\Users\ahr.net.sf.jadclipse

click on Apply

Now you should be able to see the classfiles in proper format.

HttpGet with HTTPS : SSLPeerUnverifiedException

Your local JVM or remote server may not have the required ciphers. go here

https://www.oracle.com/java/technologies/javase-jce8-downloads.html

and download the zip file that contains: US_export_policy.jar and local_policy.jar

replace the existing files (you need to find the existing path in your JVM).

on a Mac, my path was here. /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/security

this worked for me.

VBA error 1004 - select method of range class failed

You can't select a range without having first selected the sheet it is in. Try to select the sheet first and see if you still get the problem:

sourceSheetSum.Select
sourceSheetSum.Range("C3").Select

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

I tried @knittl's write-tree/commit-tree approach.

branch-a: the kept branch

branch-b: the abandoned branch

// goto branch-a branch
$ git checkout branch-a

$ git write-tree
6fa6989240d2fc6490f8215682a20c63dac5560a // echo tree id? I guess

$ git commit-tree  -p branch-a -p branch-b 6fa6989240d2fc6490f8215682a20c63dac5560a
<type some commit message end with Ctrl-d>
20bc36a2b0f2537ed11328d1aedd9c3cff2e87e9 // echo new commit id

$ git reset --hard 20bc36a2b0f2537ed11328d1aedd9c3cff2e87e9

How do I get elapsed time in milliseconds in Ruby?

ezpz's answer is almost perfect, but I hope I can add a little more.

Geo asked about time in milliseconds; this sounds like an integer quantity, and I wouldn't take the detour through floating-point land. Thus my approach would be:

irb(main):038:0> t8 = Time.now
=> Sun Nov 01 15:18:04 +0100 2009
irb(main):039:0> t9 = Time.now
=> Sun Nov 01 15:18:18 +0100 2009
irb(main):040:0> dif = t9 - t8
=> 13.940166
irb(main):041:0> (1000 * dif).to_i
=> 13940

Multiplying by an integer 1000 preserves the fractional number perfectly and may be a little faster too.

If you're dealing with dates and times, you may need to use the DateTime class. This works similarly but the conversion factor is 24 * 3600 * 1000 = 86400000 .

I've found DateTime's strptime and strftime functions invaluable in parsing and formatting date/time strings (e.g. to/from logs). What comes in handy to know is:

  • The formatting characters for these functions (%H, %M, %S, ...) are almost the same as for the C functions found on any Unix/Linux system; and

  • There are a few more: In particular, %L does milliseconds!

Determine installed PowerShell version

The easiest way to forget this page and never return to it is to learn the Get-Variable:

Get-Variable | where {$_.Name -Like '*version*'} | %{$_[0].Value}

There is no need to remember every variable. Just Get-Variable is enough (and "There should be something about version").

What is the proper way to check if a string is empty in Perl?

To check for an empty string you could also do something as follows

if (!defined $val || $val eq '')
{
    # empty
}

Detect if string contains any spaces

var inValid = new RegExp('^[_A-z0-9]{1,}$');
var value = "test string";
var k = inValid.test(value);
alert(k);

How do I parse JSON from a Java HTTPResponse?

For Android, and using Apache's Commons IO Library for IOUtils:

// connection is a HttpURLConnection
InputStream inputStream = connection.getInputStream()
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(inputStream, baos);
JSONObject jsonObject = new JSONObject(baos.toString()); // JSONObject is part of Android library

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

you can try writing the command using 'sudo':

sudo mkdir DirName

How to write log to file

Declare up top in your global var so all your processes can access if needed.

package main

import (
    "log"
    "os"
)
var (
    outfile, _ = os.Create("path/to/my.log") // update path for your needs
    l      = log.New(outfile, "", 0)
)

func main() {
    l.Println("hello, log!!!")
}

How to remove new line characters from data rows in mysql?

1) Replace all new line and tab characters with spaces.

2) Remove all leading and trailing spaces.

 UPDATE mytable SET `title` = TRIM(REPLACE(REPLACE(REPLACE(`title`, '\n', ' '), '\r', ' '), '\t', ' '));

How to implement a confirmation (yes/no) DialogPreference?

That is a simple alert dialog, Federico gave you a site where you can look things up.

Here is a short example of how an alert dialog can be built.

new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you really want to whatever?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int whichButton) {
        Toast.makeText(MainActivity.this, "Yaay", Toast.LENGTH_SHORT).show();
    }})
 .setNegativeButton(android.R.string.no, null).show();

Makefile ifeq logical or

ifeq ($(GCC_MINOR), 4)
    CFLAGS += -fno-strict-overflow
endif
ifeq ($(GCC_MINOR), 5)
    CFLAGS += -fno-strict-overflow
endif

Another you can consider using in this case is:

GCC42_OR_LATER = $(shell $(CXX) -v 2>&1 | $(EGREP) -c "^gcc version (4.[2-9]|[5-9])")

# -Wstrict-overflow: http://www.airs.com/blog/archives/120
ifeq ($(GCC42_OR_LATER),1)
  CFLAGS += -Wstrict-overflow
endif

I actually use the same in my code because I don't want to maintain a separate config or Configure.

But you have to use a portable, non-anemic make, like GNU make (gmake), and not Posix's make.

And it does not address the issue of logical AND and OR.

What does O(log n) mean exactly?

The complete binary example is O(ln n) because the search looks like this:

1 2 3 4 5 6 7 8 9 10 11 12

Searching for 4 yields 3 hits: 6, 3 then 4. And log2 12 = 3, which is a good apporximate to how many hits where needed.

Counting inversions in an array

public static int mergeSort(int[] a, int p, int r)
{
    int countInversion = 0;
    if(p < r)
    {
        int q = (p + r)/2;
        countInversion = mergeSort(a, p, q);
        countInversion += mergeSort(a, q+1, r);
        countInversion += merge(a, p, q, r);
    }
    return countInversion;
}

public static int merge(int[] a, int p, int q, int r)
{
    //p=0, q=1, r=3
    int countingInversion = 0;
    int n1 = q-p+1;
    int n2 = r-q;
    int[] temp1 = new int[n1+1];
    int[] temp2 = new int[n2+1];
    for(int i=0; i<n1; i++) temp1[i] = a[p+i];
    for(int i=0; i<n2; i++) temp2[i] = a[q+1+i];

    temp1[n1] = Integer.MAX_VALUE;
    temp2[n2] = Integer.MAX_VALUE;
    int i = 0, j = 0;

    for(int k=p; k<=r; k++)
    {
        if(temp1[i] <= temp2[j])
        {
            a[k] = temp1[i];
            i++;
        }
        else
        {
            a[k] = temp2[j];
            j++;
            countingInversion=countingInversion+(n1-i); 
        }
    }
    return countingInversion;
}
public static void main(String[] args)
{
    int[] a = {1, 20, 6, 4, 5};
    int countInversion = mergeSort(a, 0, a.length-1);
    System.out.println(countInversion);
}

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

Fill username and password using selenium in python

Use WebElement.send_keys method to simulate key typing.

name in the code (Username, Password) does not match actual name of the elements (username, password).


username = browser.find_element_by_name('username')
username.send_keys('user1')

password = browser.find_element_by_name('password')
password.send_keys('secret')

form = browser.find_element_by_id('loginForm')
form.submit()

# OR  browser.find_element_by_id('submit').click()

Merge two dataframes by index

you can use concat([df1, df2, ...], axis=1) in order to concatenate two or more DFs aligned by indexes:

pd.concat([df1, df2, df3, ...], axis=1)

or merge for concatenating by custom fields / indexes:

# join by _common_ columns: `col1`, `col3`
pd.merge(df1, df2, on=['col1','col3'])

# join by: `df1.col1 == df2.index`
pd.merge(df1, df2, left_on='col1' right_index=True)

or join for joining by index:

 df1.join(df2)

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This is the real proxy redirection to the intended server.

server {
  listen          80;
  server_name     localhost;
location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
    proxy_pass http://xx.xxx.xxx.xxx/;
    proxy_redirect off;
    proxy_set_header Host $host;

  }
}

jquery: change the URL address without redirecting?

This is achieved through URL rewriting, not through URL obfuscating, which can't be done.

Another way to do this, as has been mentioned is by changing the hashtag, with

window.location.hash = "/2131/"

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

How to use sed to replace only the first occurrence in a file?

i would do this with an awk script:

BEGIN {i=0}
(i==0) && /#include/ {print "#include \"newfile.h\""; i=1}
{print $0}    
END {}

then run it with awk:

awk -f awkscript headerfile.h > headerfilenew.h

might be sloppy, I'm new to this.

(HTML) Download a PDF file instead of opening them in browser when clicked

When you want to direct download any image or pdf file from browser instead on opening it in new tab then in javascript you should set value to download attribute of create dynamic link

    var path= "your file path will be here"; 
    var save = document.createElement('a');  
    save.href = filePath; 
    save.download = "Your file name here"; 
    save.target = '_blank'; 
    var event = document.createEvent('Event');
    event.initEvent('click', true, true); 
    save.dispatchEvent(event);
   (window.URL || window.webkitURL).revokeObjectURL(save.href);

For new Chrome update some time event is not working. for that following code will be use

  var path= "your file path will be here"; 
    var save = document.createElement('a');  
    save.href = filePath; 
    save.download = "Your file name here"; 
    save.target = '_blank'; 
    document.body.appendChild(save);
    save.click();
    document.body.removeChild(save);

Appending child and removing child is useful for Firefox, Internet explorer browser only. On chrome it will work without appending and removing child

EOL conversion in notepad ++

In Notepad++, use replace all with regular expression. This has advantage over conversion command in menu that you can operate on entire folder w/o having to open each file or drag n drop (on several hundred files it will noticeably become slower) plus you can also set filename wildcard filter.

(\r?\n)|(\r\n?)

to

\n

This will match every possible line ending pattern (single \r, \n or \r\n) back to \n. (Or \r\n if you are converting to windows-style)

To operate on multiple files, either:

  • Use "Replace All in all opened document" in "Replace" tab. You will have to drag and drop all files into Notepad++ first. It's good that you will have control over which file to operate on but can be slow if there several hundreds or thousands files.
  • "Replace in files" in "Find in files" tab, by file filter of you choice, e.g., *.cpp *.cs under one specified directory.

How do I hide anchor text without hiding the anchor?

Wrap the text in a span and set visibility:hidden; Visibility hidden will hide the element but it will still take up the same space on the page (conversely display: none removes it from the page as well).

What's the difference between implementation and compile in Gradle?

Since version 5.6.3 Gradle documentation provides simple rules of thumb to identify whether an old compile dependency (or a new one) should be replaced with an implementation or an api dependency:

  • Prefer the implementation configuration over api when possible

This keeps the dependencies off of the consumer’s compilation classpath. In addition, the consumers will immediately fail to compile if any implementation types accidentally leak into the public API.

So when should you use the api configuration? An API dependency is one that contains at least one type that is exposed in the library binary interface, often referred to as its ABI (Application Binary Interface). This includes, but is not limited to:

  • types used in super classes or interfaces
  • types used in public method parameters, including generic parameter types (where public is something that is visible to compilers. I.e. , public, protected and package private members in the Java world)
  • types used in public fields
  • public annotation types

By contrast, any type that is used in the following list is irrelevant to the ABI, and therefore should be declared as an implementation dependency:

  • types exclusively used in method bodies
  • types exclusively used in private members
  • types exclusively found in internal classes (future versions of Gradle will let you declare which packages belong to the public API)

Why am I getting a NoClassDefFoundError in Java?

In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.

See Stack Overflow question How to increase the Java stack size?.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

No, you'll have to specify the authentication method to use (typically "Basic") and the authentication realm. See http://en.wikipedia.org/wiki/Basic_access_authentication for an example request and response.

You might also want to read RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication.

iOS - Ensure execution on main thread

there any rule I can follow to be sure that my app executes my own code just in the main thread?

Typically you wouldn't need to do anything to ensure this — your list of things is usually enough. Unless you're interacting with some API that happens to spawn a thread and run your code in the background, you'll be running on the main thread.

If you want to be really sure, you can do things like

[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];

to execute a method on the main thread. (There's a GCD equivalent too.)

IsNull function in DB2 SQL?

In DB2 there is a function NVL(field, value if null).

Example:

SELECT ID, NVL(NAME, "Internal) AS NAME, NVL(PRICE,0) AS PRICE FROM PRODUCT WITH UR;

Java Regex to Validate Full Name allow only Spaces and Letters

To support language like Hindi which can contain /p{Mark} as well in between language characters. My solution is ^[\p{L}\p{M}]+([\p{L}\p{Pd}\p{Zs}'.]*[\p{L}\p{M}])+$|^[\p{L}\p{M}]+$

You can find all the test cases for this here https://regex101.com/r/3XPOea/1/tests