Programs & Examples On #User defined types

User-Defined Type (UDT) is a type that customize by user. And also called as User-Defined Data Type in database management systems. It's usually used for making some integrations and applying standards. Some related systems are SQL Server, Oracle, PostgreSQL, C++, Visual Basic and etc.

How to check existence of user-define table type in SQL Server 2008?

IF EXISTS(SELECT 1 FROM sys.types WHERE name = 'Person' AND is_table_type = 1 AND SCHEMA_ID('VAB') = schema_id)
DROP TYPE VAB.Person;
go
CREATE TYPE VAB.Person AS TABLE
(    PersonID               INT
    ,FirstName              VARCHAR(255)
    ,MiddleName             VARCHAR(255)
    ,LastName               VARCHAR(255)
    ,PreferredName          VARCHAR(255)
);

Altering user-defined table types in SQL Server

As of my knowledge it is impossible to alter/modify a table type.You can create the type with a different name and then drop the old type and modify it to the new name

Credits to jkrajes

As per msdn, it is like 'The user-defined table type definition cannot be modified after it is created'.

How to disable Compatibility View in IE

Adding a tag to your page will not control the UI in the Internet Control Panel (the dialog that appears when you selection Tools -> Options). If you're looking at your homepage which could be google.com, msn.com, about:blank or example.com, the Internet Control Panel has no way of knowing what the contents of your page may be, and it will not download it in the background.

Have a look at this document on MSDN which discussed compatibility mode and how to turn it off for your site.

How to check if a Unix .tar.gz file is a valid file without uncompressing?

> use the -O option. [...] If the tar file is corrupt, the process will abort with an error.

Sometimes yes, but sometimes not. Let's see an example of a corrupted file:

echo Pete > my_name
tar -cf my_data.tar my_name 

# // Simulate a corruption
sed < my_data.tar 's/Pete/Fool/' > my_data_now.tar
# // "my_data_now.tar" is the corrupted file

tar -xvf my_data_now.tar -O

It shows:

my_name
Fool  

Even if you execute

echo $?

tar said that there was no error:

0

but the file was corrupted, it has now "Fool" instead of "Pete".

How can I get the current network interface throughput statistics on Linux/UNIX?

I got another quick'n'dirty bash script for that:

#!/bin/bash
IF=$1
if [ -z "$IF" ]; then
        IF=`ls -1 /sys/class/net/ | head -1`
fi
RXPREV=-1
TXPREV=-1
echo "Listening $IF..."
while [ 1 == 1 ] ; do
        RX=`cat /sys/class/net/${IF}/statistics/rx_bytes`
        TX=`cat /sys/class/net/${IF}/statistics/tx_bytes`
        if [ $RXPREV -ne -1 ] ; then
                let BWRX=$RX-$RXPREV
                let BWTX=$TX-$TXPREV
                echo "Received: $BWRX B/s    Sent: $BWTX B/s"
        fi
        RXPREV=$RX
        TXPREV=$TX
        sleep 1
done

It's considering that sleep 1 will actually last exactly one second, which is not true, but good enough for a rough bandwidth assessment.

Thanks to @ephemient for the /sys/class/net/<interface>! :)

Check if a string is palindrome

bool IsPalindrome(const char* psz)
{
    int i = 0;
    int j;

    if ((psz == NULL) || (psz[0] == '\0'))
    {
        return false;
    }

    j = strlen(psz) - 1;
    while (i < j)
    {
        if (psz[i] != psz[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;

}

// STL string version:

bool IsPalindrome(const string& str)
{
    if (str.empty())
        return false;

    int i = 0;                // first characters
    int j = str.length() - 1; // last character

    while (i < j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

A Java collection of value pairs? (tuples?)

What about "Apache Commons Lang 3" Pair class and the relative subclasses ?

    import org.apache.commons.lang3.tuple.ImmutablePair;
    import org.apache.commons.lang3.tuple.Pair;
    ...
    @SuppressWarnings("unchecked")
    Pair<String, Integer>[] arr = new ImmutablePair[]{
            ImmutablePair.of("A", 1),
            ImmutablePair.of("B", 2)};

    // both access the 'left' part
    String key = arr[0].getKey();
    String left = arr[0].getLeft();

    // both access the 'right' part
    Integer value = arr[0].getValue();
    Integer right = arr[0].getRight();

ImmutablePair is a specific subclass that does not allow the values in the pair to be modified, but there are others implementations with different semantic. These are the Maven coordinates, if you need them.

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>

jQuery lose focus event

blur event: when the element loses focus.

focusout event: when the element, or any element inside of it, loses focus.

As there is nothing inside the filter element, both blur and focusout will work in this case.

$(function() {
  $('#filter').blur(function() {
    $('#options').hide();
  });
})

jsfiddle with blur: http://jsfiddle.net/yznhb8pc/

$(function() {
  $('#filter').focusout(function() {
    $('#options').hide();
  });
})

jsfiddle with focusout: http://jsfiddle.net/yznhb8pc/1/

Checking if an object is a number in C#

Take advantage of the IsPrimitive property to make a handy extension method:

public static bool IsNumber(this object obj)
{
    if (Equals(obj, null))
    {
        return false;
    }

    Type objType = obj.GetType();
    objType = Nullable.GetUnderlyingType(objType) ?? objType;

    if (objType.IsPrimitive)
    {
        return objType != typeof(bool) && 
            objType != typeof(char) && 
            objType != typeof(IntPtr) && 
            objType != typeof(UIntPtr);
    }

    return objType == typeof(decimal);
}

EDIT: Fixed as per comments. The generics were removed since .GetType() boxes value types. Also included fix for nullable values.

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

VB.net: Date without time

Either use one of the standard date and time format strings which only specifies the date (e.g. "D" or "d"), or a custom date and time format string which only uses the date parts (e.g. "yyyy/MM/dd").

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

On top of @unutbu answer, you could coerce pandas numpy object array to native (float64) type, something along the line

import pandas as pd
pd.to_numeric(df['tester'], errors='coerce')

Specify errors='coerce' to force strings that can't be parsed to a numeric value to become NaN. Column type would be dtype: float64, and then isnan check should work

Select and display only duplicate records in MySQL

SELECT id, payer_email
FROM paypal_ipn_orders
WHERE payer_email IN (
    SELECT payer_email
    FROM paypal_ipn_orders
    GROUP BY payer_email
    HAVING COUNT(id) > 1
)

sqlfiddle

Convert a video to MP4 (H.264/AAC) with ffmpeg

You need to recompile ffmpeg (from source) so that it supports x264. If you follow the instructions in this page, then you will be able to peform any kind of conversion you want.

Set initial value in datepicker with jquery?

Use it after initialization code to get current date (in datepicker format):

$(".ui-datepicker-today").trigger("click");

Struct like objects in Java

This is a commonly discussed topic. The drawback of creating public fields in objects is that you have no control over the values that are set to it. In group projects where there are many programmers using the same code, it's important to avoid side effects. Besides, sometimes it's better to return a copy of field's object or transform it somehow etc. You can mock such methods in your tests. If you create a new class you might not see all possible actions. It's like defensive programming - someday getters and setters may be helpful, and it doesn't cost a lot to create/use them. So they are sometimes useful.

In practice, most fields have simple getters and setters. A possible solution would look like this:

public property String foo;   
a->Foo = b->Foo;

Update: It's highly unlikely that property support will be added in Java 7 or perhaps ever. Other JVM languages like Groovy, Scala, etc do support this feature now. - Alex Miller

Colon (:) in Python list index

a[len(a):] - This gets you the length of a to the end. It selects a range. If you reverse a[:len(a)] it will get you the beginning to whatever is len(a).

How to get the Full file path from URI

I had a hard time trying to figure this out on Xamarin. From the suggestions above I came up with this solution.

private string getRealPathFromURI(Android.Net.Uri contentUri)
{
    string filename = "";
    string thepath = "";
    Android.Net.Uri filePathUri;
    ICursor cursor = this.ContentResolver.Query(contentUri, null, null, null, null);

    if (cursor.MoveToFirst())
    {
        int column_index = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
        filePathUri = Android.Net.Uri.Parse(cursor.GetString(column_index));
        filename = filePathUri.LastPathSegment;
        thepath = filePathUri.Path;
    }

    return thepath;
}

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

Sometimes you just need to suppress only some warnings and you want to keep other warnings, just to be safe. In your code, you can suppress the warnings for variables and even formal parameters by using GCC's unused attribute. Lets say you have this code snippet:

void func(unsigned number, const int version)
{
  unsigned tmp;
  std::cout << number << std::endl;
}

There might be a situation, when you need to use this function as a handler - which (imho) is quite common in C++ Boost library. Then you need the second formal parameter version, so the function's signature is the same as the template the handler requires, otherwise the compilation would fail. But you don't really need it in the function itself either...

The solution how to mark variable or the formal parameter to be excluded from warnings is this:

void func(unsigned number, const int version __attribute__((unused)))
{
  unsigned tmp __attribute__((unused));
  std::cout << number << std::endl;
}

GCC has many other parameters, you can check them in the man pages. This also works for the C programs, not only C++, and I think it can be used in almost every function, not just handlers. Go ahead and try it! ;)

P.S.: Lately I used this to suppress warnings of Boosts' serialization in template like this:

template <typename Archive>
void serialize(Archive &ar, const unsigned int version __attribute__((unused)))

EDIT: Apparently, I didn't answer your question as you needed, drak0sha done it better. It's because I mainly followed the title of the question, my bad. Hopefully, this might help other people, who get here because of that title... :)

Make HTML5 video poster be same size as video itself

Depending on what browsers you're targeting, you could go for the object-fit property to solve this:

object-fit: cover;

or maybe fill is what you're looking for. Still under consideration for IE.

How to create a timer using tkinter?

from tkinter import *
import time
tk=Tk()
def clock():
    t=time.strftime('%I:%M:%S',time.localtime())
    if t!='':
        label1.config(text=t,font='times 25')
    tk.after(100,clock)
label1=Label(tk,justify='center')
label1.pack()
clock()
tk.mainloop()

JavaScript string newline character?

Don't use "\n". Just try this:

var string = "this\
is a multi\
line\
string";

Just enter a back-slash and keep on truckin'! Works like a charm.

Inline elements shifting when made bold on hover

It's better to use a::before instead a::after like this:

_x000D_
_x000D_
.breadcrumb {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  list-style: none;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.breadcrumb li, _x000D_
.breadcrumb li a {_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.breadcrumb li:not(:last-child)::after {_x000D_
  content: '>'; /* or anything else */_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.breadcrumb a:hover {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.breadcrumb a::before {_x000D_
  display: block;_x000D_
  content: attr(data-label);_x000D_
  font-weight: bold;_x000D_
  height: 0;_x000D_
  overflow: hidden;_x000D_
  visibility: hidden;_x000D_
}
_x000D_
<ul class="breadcrumb">_x000D_
  <li><a data-label="one" href="https://www.google.fr/" target="_blank">one</a></li>_x000D_
  <li><a data-label="two" href="https://duckduckgo.com/" target="_blank">two</a></li>_x000D_
  <li><a data-label="three" href="#">three</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

For more details: https://jsfiddle.net/r25foavy/

How to fill 100% of remaining height?

Create a div, which contains both divs (full and someid) and set the height of that div to the following:

height: 100vh;

The height of the containing divs (full and someid) should be set to "auto". That's all.

Make outer div be automatically the same height as its floating content

First of all you don't use width=300px that's an attribute setting for the tag not CSS, use width: 300px; instead.

I would suggest applying the clearfix technique on the #outerdiv. Clearfix is a general solution to clear 2 floating divs so the parent div will expand to accommodate the 2 floating divs.

<div id='outerdiv' class='clearfix' style='width:600px; background-color: black;'>
    <div style='width:300px; float: left;'>
        <p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
    </div>

    <div style='width:300px; float: left;'>
        <p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzz</p>
    </div>
</div>

Here is an example of your situation and what Clearfix does to resolve it.

How to put a UserControl into Visual Studio toolBox

Recompiling did the trick for me!

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

If you need to allow html input for action-method parameter (opposed to "model property") there's no built-in way to do that but you can easily achieve this using a custom model binder:

public ActionResult AddBlogPost(int userId,
    [ModelBinder(typeof(AllowHtmlBinder))] string htmlBody)
{
    //...
}

The AllowHtmlBinder code:

public class AllowHtmlBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;
        var name = bindingContext.ModelName;
        return request.Unvalidated[name]; //magic happens here
    }
}

Find the complete source code and the explanation in my blog post: https://www.jitbit.com/alexblog/273-aspnet-mvc-allowing-html-for-particular-action-parameters/

Missing Microsoft RDLC Report Designer in Visual Studio

In VS 2017, i have checked SQL Server Data Tools during the installation and it doesn't help. So I have downloaded and installed Microsoft.RdlcDesigner.vsix

Now it works.

UPDATE

Another way is to use Extensions and Updates.

Go to Tools > Extensions and Updates choose Online then search for Microsoft Rdlc Report Designer for Visual studio and click Download. It need to close VS to start installation. After installation you will be able to use rdlc designer.

Hope this helps!

jQuery UI Color Picker

You can find some demos and plugins here.

http://jqueryui.pbworks.com/ColorPicker

Returning data from Axios API

The issue is that the original axiosTest() function isn't returning the promise. Here's an extended explanation for clarity:

function axiosTest() {
    // create a promise for the axios request
    const promise = axios.get(url)

    // using .then, create a new promise which extracts the data
    const dataPromise = promise.then((response) => response.data)

    // return it
    return dataPromise
}

// now we can use that data from the outside!
axiosTest()
    .then(data => {
        response.json({ message: 'Request received!', data })
    })
    .catch(err => console.log(err))

The function can be written more succinctly:

function axiosTest() {
    return axios.get(url).then(response => response.data)
}

Or with async/await:

async function axiosTest() {
    const response = await axios.get(url)
    return response.data
}

Default value in Go's method

No, the powers that be at Google chose not to support that.

https://groups.google.com/forum/#!topic/golang-nuts/-5MCaivW0qQ

How can I convert radians to degrees with Python?

Python includes two functions in the math package; radians converts degrees to radians, and degrees converts radians to degrees.

To match the output of your calculator you need:

>>> math.cos(math.radians(1))
0.9998476951563913

Note that all of the trig functions convert between an angle and the ratio of two sides of a triangle. cos, sin, and tan take an angle in radians as input and return the ratio; acos, asin, and atan take a ratio as input and return an angle in radians. You only convert the angles, never the ratios.

How to get a product's image in Magento?

echo $_product->getImageUrl();

This method of the Product class should do the trick for you.

Warning about `$HTTP_RAW_POST_DATA` being deprecated

It turns out that my understanding of the error message was wrong. I'd say it features very poor choice of words. Googling around shown me someone else misunderstood the message exactly like I did - see PHP bug #66763.

After totally unhelpful "This is the way the RMs wanted it to be." response to that bug by Mike, Tyrael explains that setting it to "-1" doesn't make just the warning to go away. It does the right thing, i.e. it completely disables populating the culprit variable. Turns out that having it set to 0 STILL populates data under some circumstances. Talk about bad design! To cite PHP RFC:

Change always_populate_raw_post_data INI setting to accept three values instead of two.

  • -1: The behavior of master; don't ever populate $GLOBALS[HTTP_RAW_POST_DATA]
  • 0/off/whatever: BC behavior (populate if content-type is not registered or request method is other than POST)
  • 1/on/yes/true: BC behavior (always populate $GLOBALS[HTTP_RAW_POST_DATA])

So yeah, setting it to -1 not only avoids the warning, like the message said, but it also finally disables populating this variable, which is what I wanted.

SQL Server query to find all current database names

Here is a query for showing all databases in one Sql engine

Select * from Sys.Databases

How to install Jdk in centos

There are JDK versions available from the base CentOS repositories. Depending on your version of CentOS, and the JDK you want to install, the following as root should give you what you want:

OpenJDK Runtime Environment (Java SE 6)

yum install java-1.6.0-openjdk

OpenJDK Runtime Environment (Java SE 7)

yum install java-1.7.0-openjdk

OpenJDK Development Environment (Java SE 7)

yum install java-1.7.0-openjdk-devel

OpenJDK Development Environment (Java SE 6)

yum install java-1.6.0-openjdk-devel

Update for Java 8

In CentOS 6.6 or later, Java 8 is available. Similar to 6 and 7 above, the packages are as follows:

OpenJDK Runtime Environment (Java SE 8)

yum install java-1.8.0-openjdk

OpenJDK Development Environment (Java SE 8)

yum install java-1.8.0-openjdk-devel

There's also a 'headless' JRE package that is the same as the above JRE, except it doesn't contain audio/video support. This can be used for a slightly more minimal installation:

OpenJDK Runtime Environment - Headless (Java SE 8)

yum install java-1.8.0-openjdk-headless

How do you use variables in a simple PostgreSQL script?

Building on @nad2000's answer and @Pavel's answer here, this is where I ended up for my Flyway migration scripts. Handling for scenarios where the database schema was manually modified.

DO $$
BEGIN
    IF NOT EXISTS(
        SELECT TRUE FROM pg_attribute 
        WHERE attrelid = (
            SELECT c.oid
            FROM pg_class c
            JOIN pg_namespace n ON n.oid = c.relnamespace
            WHERE 
                n.nspname = CURRENT_SCHEMA() 
                AND c.relname = 'device_ip_lookups'
            )
        AND attname = 'active_date'
        AND NOT attisdropped
        AND attnum > 0
        )
    THEN
        RAISE NOTICE 'ADDING COLUMN';        
        ALTER TABLE device_ip_lookups
            ADD COLUMN active_date TIMESTAMP;
    ELSE
        RAISE NOTICE 'SKIPPING, COLUMN ALREADY EXISTS';
    END IF;
END $$;

jQuery attr('onclick')

Do it the jQuery way (and fix the errors):

$('#stop').click(function() {
     $('#next').click(stopMoving);
     // ^-- missing #
});  // <-- missing );

If the element already has a click handler attached via the onclick attribute, you have to remove it:

$('#next').attr('onclick', '');

Update: As @Drackir pointed out, you might also have to call $('#next').unbind('click'); in order to remove other click handlers attached via jQuery.

But this is guessing here. As always: More information => better answers.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Is it better to use NOT or <> when comparing values?

The latter (<>), because the meaning of the former isn't clear unless you have a perfect understanding of the order of operations as it applies to the Not and = operators: a subtlety which is easy to miss.

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.

I did it a different way, without using VBA, by using a table containing the query parameters.

E.g:

SELECT a_table.a_field 
FROM QueryParameters, a_table 
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min 
AND QueryParameters.a_field_max

Where QueryParameters is a table with two fields, a_field_min and a_field_max

It can even be used with GROUP BY, if you include the query parameter fields in the GROUP BY clause, and the FIRST operator on the parameter fields in the HAVING clause.

automating telnet session using bash scripts

#!/bin/bash
ping_count="4"
avg_max_limit="1500"
router="sagemcom-fast-2804-v2"
adress="192.168.1.1"
user="admin"
pass="admin"

VAR=$(
expect -c " 
        set timeout 3
        spawn telnet "$adress"
        expect \"Login:\" 
        send \"$user\n\"
        expect \"Password:\"
        send \"$pass\n\"
        expect \"commands.\"
        send \"ping ya.ru -c $ping_count\n\"
        set timeout 9
        expect \"transmitted\"
        send \"exit\"
        ")

count_ping=$(echo "$VAR" | grep packets | cut -c 1)
avg_ms=$(echo "$VAR" | grep round-trip | cut -d '/' -f 4 | cut -d '.' -f 1)

echo "1_____ping___$count_ping|||____$avg_ms"
echo "$VAR"

how can select from drop down menu and call javascript function

<script type="text/javascript">
function report(func)
{
    func();
}

function daily()
{
    alert('daily');
}

function monthly()
{
    alert('monthly');
}
</script>

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

View.GONE This view is invisible, and it doesn't take any space for layout purposes.

View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.

dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
btn2.setVisibility(View.INVISIBLE);

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

I was getting similar errors and eventually found just that cleaning the build folder resolved my issue.

mvn clean install

jQuery UI DatePicker to show year only

I had the same problem and, after a day of research, I came up with this solution: http://jsfiddle.net/konstantc/4jkef3a1/

_x000D_
_x000D_
// *** (month and year only) ***_x000D_
$(function() { _x000D_
  $('#datepicker1').datepicker( {_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: true,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: true,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('MM yy (M y) (mm/y)', new Date(year, month, 1)));_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only) ***_x000D_
$(function() { _x000D_
  $('#datepicker2').datepicker( {_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: false,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: true,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-month").hide();_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $(".ui-datepicker-prev").hide();_x000D_
    $(".ui-datepicker-next").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only, no controls) ***_x000D_
$(function() { _x000D_
  $('#datepicker3').datepicker( {_x000D_
    dateFormat: "yy",_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: false,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: false,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
    },_x000D_
    onChangeMonthYear : function () {_x000D_
      $(this).datepicker( "hide" );_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-month").hide();_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $(".ui-datepicker-prev").hide();_x000D_
    $(".ui-datepicker-next").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
  <h2 class="font-weight-light text-lg-left mt-4 mb-0"><b>jQuery UI Datepicker</b> custom select</h2>_x000D_
_x000D_
  <hr class="mt-2 mb-3">_x000D_
  <div class="row text-lg-left">_x000D_
    <div class="col-12">_x000D_
_x000D_
      <form>_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker1">(month and year only : <code>id="datepicker1"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker1" _x000D_
                 placeholder="(month and year only)" />_x000D_
        </div>_x000D_
_x000D_
        <hr />_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker2">(year only : <code>input id="datepicker2"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker2" _x000D_
                 placeholder="(year only)" />_x000D_
        </div>_x000D_
_x000D_
        <hr />_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker3">(year only, no controls : <code>input id="datepicker3"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker3" _x000D_
                 placeholder="(year only, no controls)" />_x000D_
        </div>_x000D_
_x000D_
      </form>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

I know this question is pretty old but I thought that my solution can be of use to others that encounter this problem. Hope it helps.

iconv - Detected an illegal character in input string

I found one Solution :

echo iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($string));

use utf8_encode()

C++ - struct vs. class

Ok, POD means plain old data. That usually refers to structs without any methods because these types are then used to structure multiple data that belong together.

As for structs not having methods: I have seen more than once that a struct had methods, and I don't feel that this would be unnatural.

How to run Tensorflow on CPU

In my case, for tensorflow 2.4.0, none of the previous answer works unless you install tensorflow-cpu

pip install tensorflow-cpu

How to check all versions of python installed on osx and centos

we can directly use this to see all the pythons installed both by current user and the root by the following: whereis python

how to get list of port which are in use on the server

TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.

http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx

wait until all threads finish their work in java

Have a look at various solutions.

  1. join() API has been introduced in early versions of Java. Some good alternatives are available with this concurrent package since the JDK 1.5 release.

  2. ExecutorService#invokeAll()

    Executes the given tasks, returning a list of Futures holding their status and results when everything is completed.

    Refer to this related SE question for code example:

    How to use invokeAll() to let all thread pool do their task?

  3. CountDownLatch

    A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

    A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

    Refer to this question for usage of CountDownLatch

    How to wait for a thread that spawns it's own thread?

  4. ForkJoinPool or newWorkStealingPool() in Executors

  5. Iterate through all Future objects created after submitting to ExecutorService

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

How to click a href link using Selenium

Use

driver.findElement(By.linkText("App Configuration")).click()

Other Approaches will be

JavascriptLibrary jsLib = new JavascriptLibrary(); 
jsLib.callEmbeddedSelenium(selenium, "triggerMouseEventAt", elementToClick,"click", "0,0");

or

((JavascriptExecutor) driver).executeScript("arguments[0].click();", elementToClick);

For detailed answer, View this post

How to set opacity to the background color of a div?

You can use CSS3 RGBA in this way:

rgba(255, 0, 0, 0.7);

0.7 means 70% opacity.

Declaring an enum within a class

Nowadays - using C++11 - you can use enum class for this:

enum class Color { RED, BLUE, WHITE };

AFAII this does exactly what you want.

Smooth GPS data

Going back to the Kalman Filters ... I found a C implementation for a Kalman filter for GPS data here: http://github.com/lacker/ikalman I haven't tried it out yet, but it seems promising.

How do I check if there are duplicates in a flat list?

A more simple solution is as follows. Just check True/False with pandas .duplicated() method and then take sum. Please also see pandas.Series.duplicated — pandas 0.24.1 documentation

import pandas as pd

def has_duplicated(l):
    return pd.Series(l).duplicated().sum() > 0

print(has_duplicated(['one', 'two', 'one']))
# True
print(has_duplicated(['one', 'two', 'three']))
# False

Defining Z order of views of RelativeLayout in Android

The easiest way is simply to pay attention to the order in which the Views are added to your XML file. Lower down in the file means higher up in the Z-axis.

Edit: This is documented here and here on the Android developer site. (Thanks @flightplanner)

/usr/bin/ld: cannot find

Add -L/opt/lib to your compiler parameters, this makes the compiler and linker search that path for libcalc.so in that folder.

SQL multiple columns in IN clause

Determine whether the list of names is different with each query or reused. If it is reused, it belongs to the database.

Even if it is unique with each query, it may be useful to load it to a temporary table (#table syntax) for performance reasons - in that case you will be able to avoid recompilation of a complex query.

If the maximum number of names is fixed, you should use a parametrized query.

However, if none of the above cases applies, I would go with inlining the names in the query as in your approach #1.

JavaScript function in href vs. onclick

In addition to all here, the href is shown on browser's status bar, and onclick not. I think it's not user friendly to show javascript code there.

vuejs update parent data from child component

I don't know why, but I just successfully updated parent data with using data as object, :set & computed

Parent.vue

<!-- check inventory status - component -->
    <CheckInventory :inventory="inventory"></CheckInventory>

data() {
            return {
                inventory: {
                    status: null
                },
            }
        },

Child.vue

<div :set="checkInventory">

props: ['inventory'],

computed: {
            checkInventory() {

                this.inventory.status = "Out of stock";
                return this.inventory.status;

            },
        }

How do I get the path of a process in Unix / Linux

thanks : Kiwy
with AIX:

getPathByPid()
{
    if [[ -e /proc/$1/object/a.out ]]; then
        inode=`ls -i /proc/$1/object/a.out 2>/dev/null | awk '{print $1}'`
        if [[ $? -eq 0 ]]; then
            strnode=${inode}"$"
            strNum=`ls -li /proc/$1/object/ 2>/dev/null | grep $strnode | awk '{print $NF}' | grep "[0-9]\{1,\}\.[0-9]\{1,\}\."`
            if [[ $? -eq 0 ]]; then
                # jfs2.10.6.5869
                n1=`echo $strNum|awk -F"." '{print $2}'`
                n2=`echo $strNum|awk -F"." '{print $3}'`
                # brw-rw----    1 root     system       10,  6 Aug 23 2013  hd9var
                strexp="^b.*"$n1,"[[:space:]]\{1,\}"$n2"[[:space:]]\{1,\}.*$"   # "^b.*10, \{1,\}5 \{1,\}.*$"
                strdf=`ls -l /dev/ | grep $strexp | awk '{print $NF}'`
                if [[ $? -eq 0 ]]; then
                    strMpath=`df | grep $strdf | awk '{print $NF}'`
                    if [[ $? -eq 0 ]]; then
                        find $strMpath -inum $inode 2>/dev/null
                        if [[ $? -eq 0 ]]; then
                            return 0
                        fi
                    fi
                fi
            fi
        fi
    fi
    return 1
}

Datepicker: How to popup datepicker when click on edittext

I've tried every way that was suggested but all of them have their own problems.

The best solution in my opinion would be to use a frame layout like below:

<FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                .... />

            <View
                android:id="@+id/invisible_click_watcher"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:clickable="true" />

</FrameLayout>

and then adding the DatePickerDialog code which was beautifully written in @Android's answer.

How to define relative paths in Visual Studio Project?

I have used a syntax like this before:

$(ProjectDir)..\headers

or

..\headers

As other have pointed out, the starting directory is the one your project file is in(vcproj or vcxproj), not where your main code is located.

How to remove the underline for anchors(links)?

Use CSS to remove text-decorations.

a {
    text-decoration: none;
}

Simple JavaScript login form validation

Here is some useful links with example Login form Validation in javascript

function validate() {
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        if (username == null || username == "") {
            alert("Please enter the username.");
            return false;
        }
        if (password == null || password == "") {
            alert("Please enter the password.");
            return false;
        }
        alert('Login successful');

    } 

  <input type="text" name="username" id="username" />
  <input type="password" name="password" id="password" />
  <input type="button" value="Login" id="submit" onclick="validate();" />

Binding to static property

In .NET 4.5 it's possible to bind to static properties, read more

You can use static properties as the source of a data binding. The data binding engine recognizes when the property's value changes if a static event is raised. For example, if the class SomeClass defines a static property called MyProperty, SomeClass can define a static event that is raised when the value of MyProperty changes. The static event can use either of the following signatures:

public static event EventHandler MyPropertyChanged; 
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged; 

Note that in the first case, the class exposes a static event named PropertyNameChanged that passes EventArgs to the event handler. In the second case, the class exposes a static event named StaticPropertyChanged that passes PropertyChangedEventArgs to the event handler. A class that implements the static property can choose to raise property-change notifications using either method.

How to copy directories with spaces in the name

robocopy "C:\Users\Angie\My Documents" "C:\test-backup\My Documents" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Music" "C:\test-backup\My Music" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Pictures" "C:\test-backup\My Pictures" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"

How to change Elasticsearch max memory size

Previous answers were insufficient in my case, probably because I'm on Debian 8, while they were referred to some previous distribution.

On Debian 8 modify the service script normally place in /usr/lib/systemd/system/elasticsearch.service, and add Environment=ES_HEAP_SIZE=8G just below the other "Environment=*" lines.

Now reload the service script with systemctl daemon-reload and restart the service. The job should be done!

Strings in C, how to get subString

You'll need to allocate memory for the new string otherString. In general for a substring of length n, something like this may work for you (don't forget to do bounds checking...)

char *subString(char *someString, int n) 
{
   char *new = malloc(sizeof(char)*n+1);
   strncpy(new, someString, n);
   new[n] = '\0';
   return new;
}

This will return a substring of the first n characters of someString. Make sure you free the memory when you are done with it using free().

Scraping html tables into R data frames using the XML package

…or a shorter try:

library(XML)
library(RCurl)
library(rlist)
theurl <- getURL("https://en.wikipedia.org/wiki/Brazil_national_football_team",.opts = list(ssl.verifypeer = FALSE) )
tables <- readHTMLTable(theurl)
tables <- list.clean(tables, fun = is.null, recursive = FALSE)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))

the picked table is the longest one on the page

tables[[which.max(n.rows)]]

Regular vs Context Free Grammars

The difference between regular and context free grammar: (N, S, P, S) : terminals, nonterminals, productions, starting state Terminal symbols

? elementary symbols of the language defined by a formal grammar

? abc

Nonterminal symbols (or syntactic variables)

? replaced by groups of terminal symbols according to the production rules

? ABC

regular grammar: right or left regular grammar right regular grammar, all rules obey the forms

  1. B ? a where B is a nonterminal in N and a is a terminal in S
  2. B ? aC where B and C are in N and a is in S
  3. B ? e where B is in N and e denotes the empty string, i.e. the string of length 0

left regular grammar, all rules obey the forms

  1. A ? a where A is a nonterminal in N and a is a terminal in S
  2. A ? Ba where A and B are in N and a is in S
  3. A ? e where A is in N and e is the empty string

context free grammar (CFG)

? formal grammar in which every production rule is of the form V ? w

? V is a single nonterminal symbol

? w is a string of terminals and/or nonterminals (w can be empty)

How to generate a random number in C++?

Here is a simple random generator with approx. equal probability of generating positive and negative values around 0:

  int getNextRandom(const size_t lim) 
  {
        int nextRand = rand() % lim;
        int nextSign = rand() % lim;
        if (nextSign < lim / 2)
            return -nextRand;
        return nextRand;
  }


   int main()
   {
        srand(time(NULL));
        int r = getNextRandom(100);
        cout << r << endl;
        return 0;
   }

How to match "anything up until this sequence of characters" in a regular expression?

This will make sense about regex.

  1. The exact word can be get from the following regex command:

("(.*?)")/g

Here, we can get the exact word globally which is belonging inside the double quotes. For Example, If our search text is,

This is the example for "double quoted" words

then we will get "double quoted" from that sentence.

How to round to 2 decimals with Python?

As you want your answer in decimal number so you dont need to typecast your answer variable to str in printC() function.

and then use printf-style String Formatting

How to set space between listView Items in Android

For my application, i have done this way

 <ListView
    android:id="@+id/staff_jobassigned_listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@null"
    android:dividerHeight="10dp">

</ListView>

just set the divider to null and providing height to the divider did for me.

Example :

android:divider="@null"

or

android:divider="@android:color/transparent"

and this is result

enter image description here

adding css class to multiple elements

You need to qualify the a part of the selector too:

.button input, .button a {
    //css stuff here
}

Basically, when you use the comma to create a group of selectors, each individual selector is completely independent. There is no relationship between them.

Your original selector therefore matched "all elements of type 'input' that are descendants of an element with the class name 'button', and all elements of type 'a'".

Android Material and appcompat Manifest merger failed

I had the same error when working with Groupie. implementation 'com.xwray:groupie:2.3.0'

I solved it by changing version to implementation 'com.xwray:groupie:2.1.0'

Extract and delete all .gz in a directory- Linux

Try:

ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 tar xvfz

Then Try:

ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 rm

This will untar all .tar.gz files in the current directory and then delete all the .tar.gz files. If you want an explanation, the "|" takes the stdout of the command before it, and uses that as the stdin of the command after it. Use "man command" w/o the quotes to figure out what those commands and arguments do. Or, you can research online.

Convert date field into text in Excel

If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P

How can I get Android Wifi Scan Results into a list?

Find a complete working example below:

The code by @Android is very good but has few issues, namely:

  1. Populating to ListView code needs to be moved to onReceive of BroadCastReceiver where only the result will be available. In the case result is obtained at 2nd attempt.
  2. BroadCastReceiver needs to be unregistered after the results are obtained.
  3. size = size -1 seems unnecessary.

Find below the modified code of @Android as a working example:

WifiScanner.java which is the Main Activity

package com.arjunandroid.wifiscanner;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class WifiScanner extends Activity implements View.OnClickListener{


    WifiManager wifi;
    ListView lv;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<String> arraylist = new ArrayList<>();
    ArrayAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getActionBar().setTitle("Widhwan Setup Wizard");

        setContentView(R.layout.activity_wifi_scanner);

        buttonScan = (Button) findViewById(R.id.scan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.wifilist);


        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }
        this.adapter =  new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arraylist);
        lv.setAdapter(this.adapter);

        scanWifiNetworks();
    }

    public void onClick(View view)
    {
        scanWifiNetworks();
    }

    private void scanWifiNetworks(){

        arraylist.clear();
        registerReceiver(wifi_receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        wifi.startScan();

        Log.d("WifScanner", "scanWifiNetworks");

        Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();

    }

    BroadcastReceiver wifi_receiver= new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context c, Intent intent)
        {
            Log.d("WifScanner", "onReceive");
            results = wifi.getScanResults();
            size = results.size();
            unregisterReceiver(this);

            try
            {
                while (size >= 0)
                {
                    size--;
                    arraylist.add(results.get(size).SSID);
                    adapter.notifyDataSetChanged();
                }
            }
            catch (Exception e)
            {
                Log.w("WifScanner", "Exception: "+e);

            }


        }
    };

}

activity_wifi_scanner.xml which is the layout file for the Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/wifilist"
        android:layout_width="match_parent"
        android:layout_height="312dp"
        android:layout_weight="0.97" />


    <Button
        android:id="@+id/scan"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="bottom"
        android:layout_margin="15dp"
        android:background="@android:color/holo_green_light"
        android:text="Scan Again" />
</LinearLayout>

Also as mentioned above, do not forget to add Wifi permissions in the AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 

How to downgrade php from 5.5 to 5.3

It is possible! Yes

In many cases, you might want to use XAMPP with a different PHP version than the one that comes preinstalled. You might do this to get the benefits of a newer version of PHP, or to reproduce bugs using an earlier version of PHP.

To use a different version of PHP with XAMPP, follow these steps:

  1. Download a binary build of the PHP version that you wish to use from the PHP website, and extract the contents of the compressed archive file to your XAMPP installation directory (usually, C:\xampp). Ensure that you give it a different directory name to avoid overwriting the existing PHP version. For example, in this tutorial, we’ll call the new directory C:\xampp\php5-6-0. NOTE : Ensure that the PHP build you download matches the Apache build (VC9 or VC11) in your XAMPP platform.

  2. Within the new directory, rename the php.ini-development file to php.ini. If you prefer to use production settings, you could instead rename the php.ini-production file to php.ini.

  3. Edit the httpd-xampp.conf file in the apache\conf\extra\ subdirectory of your XAMPP installation directory. Within this file, search for all instances of the old PHP directory path and replace them with the path to the new PHP directory created in Step 1. In particular, be sure to change the lines

    LoadFile "/xampp/php/php5ts.dll"
    LoadFile "/xampp/php/libpq.dll"
    LoadModule php5_module "/xampp/php/php5apache2_4.dll"

to

    LoadFile "/xampp/php5-6-0/php5ts.dll"
    LoadFile "/xampp/php5-6-0/libpq.dll"
    LoadModule php5_module "/xampp/php5-6-0/php5apache2_4.dll"

NOTE : Remember to adjust the file and directory paths above to reflect valid paths on your system.

  1. Restart your Apache server through the XAMPP control panel for your changes to take effect. The new version of PHP should now be active. To verify this, browse to the URL http://localhost/xampp/phpinfo.php, which displays the output of the phpinfo() command, and check the version number at the top of the page.

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

How can I put CSS and HTML code in the same file?

Is this what you're looking for? You place you CSS between style tags in the HTML document header. I'm guessing for iPhone it's webkit so it should work.

<html>
<head>
    <style type="text/css">
    .title { color: blue; text-decoration: bold; text-size: 1em; }
    .author { color: gray; }
    </style>
</head>
<body>
    <p>
    <span class="title">La super bonne</span>
    <span class="author">proposée par Jérém</span>
    </p>
</body>
</html>

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

Tkinter module not found on Ubuntu

sudo apt-get install python3-tk

IntelliJ - Convert a Java project/module into a Maven project/module

A visual for those that benefit from it.

enter image description here

After right-clicking the project name ("test" in this example), select "Add framework support" and check the "Maven" option.

Automated way to convert XML files to SQL database?

If there is XML file with 2 different tables then will:

LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1 
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table2

work

Adding +1 to a variable inside a function

Move points into test:

def test():
    points = 0
    addpoint = raw_input ("type ""add"" to add a point")
    ...

or use global statement, but it is bad practice. But better way it move points to parameters:

def test(points=0):
    addpoint = raw_input ("type ""add"" to add a point")
    ...

Copying files using rsync from remote server to local machine

If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.

scp user@host:/path/file /localpath/file

Wild card characters are supported, so

scp user@host:/path/folder/* /localpath/folder

will copy all of the remote files in that folder.If copying more then one directory.

note -r will copy all sub-folders and content too.

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

Rollback... will prompt you to select a folder to rollback, ie, it will work on specific folders, and you can rollback to labels or changlists or dates. Back out works on the files in specific changelists.

PHP - how to create a newline character?

Use the PHP nl2br to get the newlines in a text string..

$text = "Manu is a good boy.(Enter)He can code well.

echo nl2br($text);

Result.

Manu is a good boy.

He can code well.

What's the purpose of META-INF?

All answers are correct. Meta-inf has many purposes. In addition, here is an example about using tomcat container.

Go to Tomcat Doc and check " Standard Implementation > copyXML " attribute.

Description is below.

Set to true if you want a context XML descriptor embedded inside the application (located at /META-INF/context.xml) to be copied to the owning Host's xmlBase when the application is deployed. On subsequent starts, the copied context XML descriptor will be used in preference to any context XML descriptor embedded inside the application even if the descriptor embedded inside the application is more recent. The flag's value defaults to false. Note if the deployXML attribute of the owning Host is false or if the copyXML attribute of the owning Host is true, this attribute will have no effect.

MySQL error 1449: The user specified as a definer does not exist

If the user exists, then:

mysql> flush privileges;

How to calculate rolling / moving average using NumPy / SciPy?

Starting in Numpy 1.20, the sliding_window_view provides a way to slide/roll through windows of elements. Windows that you can then individually average.

For instance, for a 4-element window:

from numpy.lib.stride_tricks import sliding_window_view

# values = np.array([5, 3, 8, 10, 2, 1, 5, 1, 0, 2])
np.average(sliding_window_view(values, window_shape = 4), axis=1)
# array([6.5, 5.75, 5.25, 4.5, 2.25, 1.75, 2])

Note the intermediary result of sliding_window_view:

# values = np.array([5, 3, 8, 10, 2, 1, 5, 1, 0, 2])
sliding_window_view(values, window_shape = 4)
# array([[ 5,  3,  8, 10],
#        [ 3,  8, 10,  2],
#        [ 8, 10,  2,  1],
#        [10,  2,  1,  5],
#        [ 2,  1,  5,  1],
#        [ 1,  5,  1,  0],
#        [ 5,  1,  0,  2]])

How do you return the column names of a table?

This seems a bit easier then the above suggestions because it uses the OBJECT_ID() function to locate the table's id. Any column with that id is part of the table.

SELECT * 
  FROM syscolumns 
 WHERE id=OBJECT_ID('YOUR_TABLE') 

I commonly use a similar query to see if a column I know is part of a newer version is present. It is the same query with the addition of {AND name='YOUR_COLUMN'} to the where clause.

IF EXISTS (
        SELECT * 
          FROM syscolumns 
         WHERE id=OBJECT_ID('YOUR_TABLE') 
           AND name='YOUR_COLUMN'
        )
BEGIN
    PRINT 'Column found'
END

How do I create a table based on another table

select * into newtable from oldtable

How to convert a Django QuerySet to a list

You can directly convert using the list keyword. For example:

obj=emp.objects.all()
list1=list(obj)

Using the above code you can directly convert a query set result into a list.

Here list is keyword and obj is result of query set and list1 is variable in that variable we are storing the converted result which in list.

How to find an available port?

The Eclipse SDK contains a class SocketUtil, that does what you want. You may have a look into the git source code.

What does "|=" mean? (pipe equal operator)

It's a shortening for this:

notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;

And | is a bit-wise OR.

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

I think that all the answers missed a crucial point:

If you use the Ajax form so that it needs to update itself (and NOT another div outside of the form) then you need to put the containing div OUTSIDE of the form. For example:

 <div id="target">
 @using (Ajax.BeginForm("MyAction", "MyController",
            new AjaxOptions
            {
                HttpMethod = "POST",
                InsertionMode = InsertionMode.Replace,
                UpdateTargetId = "target"
            }))
 {
      <!-- whatever -->
 }
 </div>

Otherwise you will end like @David where the result is displayed in a new page.

Regex match digits, comma and semicolon?

word.matches("^[0-9,;]+$"); you were almost there

PHP display image BLOB from MySQL

This is what I use to display images from blob:

echo '<img src="data:image/jpeg;base64,'.base64_encode($image->load()) .'" />';

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

Just do it like this:

if(!document.getElementById("someId") { /Some code. Note the NOT (!) in the expresion/ };

If element with id "someId" does not exist expresion will return TRUE (NOT FALSE === TRUE) or !false === true;

try this code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="format-detection" content="telephone-no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, minimum-scale=1, maximum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi">
        <title>Test</title>
    </head>
    <body>
      <script>
var createPerson = function (name) {
    var person;
    if (!document.getElementById(name)) {
        alert("Element does not exist. Let's create it.");
      person = document.createElement("div");
//add argument name as the ID of the element
      person.id = name;
//append element to the body of the document
      document.body.appendChild(person);
    } else {
        alert("Element exists. Lets get it by ID!");
      person = document.getElementById(name);
    }
    person.innerHTML = "HI THERE!";

};
//run the function.
createPerson("someid");
          </script>
       </body>
</html>

Try this in your browser and it should alert "Element does not exist. Let's create it."

Now add

<div id="someid"></div>

to the body of the page and try again. Voila! :)

C# Pass Lambda Expression as Method Parameter

Lambda expressions have a type of Action<parameters> (in case they don't return a value) or Func<parameters,return> (in case they have a return value). In your case you have two input parameters, and you need to return a value, so you should use:

Func<FullTimeJob, Student, FullTimeJob>

Change border-bottom color using jquery?

$('#elementid').css('border-bottom', 'solid 1px red');

How to set a Timer in Java?

    new java.util.Timer().schedule(new TimerTask(){
        @Override
        public void run() {
            System.out.println("Executed...");
           //your code here 
           //1000*5=5000 mlsec. i.e. 5 seconds. u can change accordngly 
        }
    },1000*5,1000*5); 

Join two sql queries

I would just use a Union

In your second query add the extra column name and add a '' in all the corresponding locations in the other queries

Example

//reverse order to get the column names
select top 10 personId, '' from Telephone//No Column name assigned 
Union 
select top 10 personId, loanId from loan

Python Iterate Dictionary by Index

Since you want to iterate in order, you can use sorted:

for k, v in sorted(dict.items()):
    print k,v

pip install gives error: Unable to find vcvarsall.bat

I appreciate this might not be the answer to resolving on 3.4 but I tried a huge variety of things to fix this on 3.4 and thought this might be useful if someone is time pressed or doesn't have the know-how to correct it (in my case, work demands).

With exactly the same setup, I found that my installation problems only happened with Python 3.4. When I changed to 2.7, all my issues seemed to be resolved.

We have a rather overzealous security setup though so I'm going to try the same on my home version (still 3.4) and see if I have any more joy. My inclination is that my VS version has somehow been restricted and the answers above should help. If I find anything more tonight I'll add further detail.

This is my first reply, not the most technical I'm afraid!

Git - Ignore node_modules folder everywhere

Create .gitignore file in root folder directly by code editor or by command

For Mac & Linux

 touch .gitignore 

For Windows

 echo >.gitignore 

open .gitignore declare folder or file name like this /foldername

Dynamic SELECT TOP @var In SQL Server

SELECT TOP (@count) * FROM SomeTable

This will only work with SQL 2005+

Convert spark DataFrame column to python list

I ran a benchmarking analysis and list(mvv_count_df.select('mvv').toPandas()['mvv']) is the fastest method. I'm very surprised.

I ran the different approaches on 100 thousand / 100 million row datasets using a 5 node i3.xlarge cluster (each node has 30.5 GBs of RAM and 4 cores) with Spark 2.4.5. Data was evenly distributed on 20 snappy compressed Parquet files with a single column.

Here's the benchmarking results (runtimes in seconds):

+-------------------------------------------------------------+---------+-------------+
|                          Code                               | 100,000 | 100,000,000 |
+-------------------------------------------------------------+---------+-------------+
| df.select("col_name").rdd.flatMap(lambda x: x).collect()    |     0.4 | 55.3        |
| list(df.select('col_name').toPandas()['col_name'])          |     0.4 | 17.5        |
| df.select('col_name').rdd.map(lambda row : row[0]).collect()|     0.9 | 69          |
| [row[0] for row in df.select('col_name').collect()]         |     1.0 | OOM         |
| [r[0] for r in mid_df.select('col_name').toLocalIterator()] |     1.2 | *           |
+-------------------------------------------------------------+---------+-------------+

* cancelled after 800 seconds

Golden rules to follow when collecting data on the driver node:

  • Try to solve the problem with other approaches. Collecting data to the driver node is expensive, doesn't harness the power of the Spark cluster, and should be avoided whenever possible.
  • Collect as few rows as possible. Aggregate, deduplicate, filter, and prune columns before collecting the data. Send as little data to the driver node as you can.

toPandas was significantly improved in Spark 2.3. It's probably not the best approach if you're using a Spark version earlier than 2.3.

See here for more details / benchmarking results.

Remove x-axis label/text in chart.js

Inspired by christutty's answer, here is a solution that modifies the source but has not been tested thoroughly. I haven't had any issues yet though.

In the defaults section, add this line around line 71:

// Boolean - Omit x-axis labels
omitXLabels: true,

Then around line 2215, add this in the buildScale method:

//if omitting x labels, replace labels with empty strings           
if(Chart.defaults.global.omitXLabels){
    var newLabels=[];
    for(var i=0;i<labels.length;i++){
        newLabels.push('');
    }
    labels=newLabels;
}

This preserves the tool tips also.

How to run a shell script on a Unix console or Mac terminal?

For the bourne shell:

sh myscript.sh

For bash:

bash myscript.sh

How to change Maven local repository in eclipse

In newer versions of Eclipse the global configuration file can be set in

Windows > Preferences > Maven > User Settings > Global Settings

Don't beat me why global settings can be configured in user settings... Probably because of the same reason why you need to press "Start" to shutdown your PC on Windows... :D

:first-child not working as expected

:first-child selects the first h1 if and only if it is the first child of its parent element. In your example, the ul is the first child of the div.

The name of the pseudo-class is somewhat misleading, but it's explained pretty clearly here in the spec.

jQuery's :first selector gives you what you're looking for. You can do this:

$('.detail_container h1:first').css("color", "blue");

Rename Oracle Table or View

One can rename indexes the same way:

alter index owner.index_name rename to new_name;

What is the best IDE to develop Android apps in?

Eclipse is the best IDE. It easy to setup android and debug applications in eclipse

Will iOS launch my app into the background if it was force-quit by the user?

UPDATE2:

You can achieve this using the new PushKit framework, introduced in iOS 8. Though PushKit is used for VoIP. So your usage should be for VoIP related otherwise there is risk of app rejection. (See this answer).


UDPDATE1:

The documentation has been clarified for iOS8. The documentation can be read here. Here is a relevant excerpt:

Use this method to process incoming remote notifications for your app. Unlike the application:didReceiveRemoteNotification: method, which is called only when your app is running in the foreground, the system calls this method when your app is running in the foreground or background. In addition, if you enabled the remote notifications background mode, the system launches your app (or wakes it from the suspended state) and puts it in the background state when a push notification arrives. However, the system does not automatically launch your app if the user has force-quit it. In that situation, the user must relaunch your app or restart the device before the system attempts to launch your app automatically again.


Although this was not made clear by the WWDC video, a quick search on the developer forums turned this up:

https://devforums.apple.com/message/873265#873265 (login required)

Also keep in mind that if you kill your app from the app switcher (i.e. swiping up to kill the app) then the OS will never relaunch the app regardless of push notification or background fetch. In this case the user has to manually relaunch the app once and then from that point forward the background activities will be invoked. -pmarcos

That post was by an Apple employee so I think i can trust that this information is correct.

So it looks like when the app is killed from the app switcher (by swiping up), the app will never be launched, even for scheduled background fetches.

How to pass the button value into my onclick event function?

You can get value by using id for that element in onclick function

function dosomething(){
     var buttonValue = document.getElementById('buttonId').value;
}

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.addEventListener( 'click', function(){
  // delete the column here
} );

SpringMVC RequestMapping for GET parameters

You can add @RequestMapping like so:

@RequestMapping("/userGrid")
public @ResponseBody GridModel getUsersForGrid(
   @RequestParam("_search") String search,
   @RequestParam String nd,
   @RequestParam int rows,
   @RequestParam int page,
   @RequestParam String sidx) 
   @RequestParam String sord) {

Syntax error on print with Python 3

It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.

print('Hello world!')

GroupBy pandas DataFrame and select most common value

Pandas >= 0.16

pd.Series.mode is available!

Use groupby, GroupBy.agg, and apply the pd.Series.mode function to each group:

source.groupby(['Country','City'])['Short name'].agg(pd.Series.mode)

Country  City            
Russia   Sankt-Petersburg    Spb
USA      New-York             NY
Name: Short name, dtype: object

If this is needed as a DataFrame, use

source.groupby(['Country','City'])['Short name'].agg(pd.Series.mode).to_frame()

                         Short name
Country City                       
Russia  Sankt-Petersburg        Spb
USA     New-York                 NY

The useful thing about Series.mode is that it always returns a Series, making it very compatible with agg and apply, especially when reconstructing the groupby output. It is also faster.

# Accepted answer.
%timeit source.groupby(['Country','City']).agg(lambda x:x.value_counts().index[0])
# Proposed in this post.
%timeit source.groupby(['Country','City'])['Short name'].agg(pd.Series.mode)

5.56 ms ± 343 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.76 ms ± 387 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Dealing with Multiple Modes

Series.mode also does a good job when there are multiple modes:

source2 = source.append(
    pd.Series({'Country': 'USA', 'City': 'New-York', 'Short name': 'New'}),
    ignore_index=True)

# Now `source2` has two modes for the 
# ("USA", "New-York") group, they are "NY" and "New".
source2

  Country              City Short name
0     USA          New-York         NY
1     USA          New-York        New
2  Russia  Sankt-Petersburg        Spb
3     USA          New-York         NY
4     USA          New-York        New

source2.groupby(['Country','City'])['Short name'].agg(pd.Series.mode)

Country  City            
Russia   Sankt-Petersburg          Spb
USA      New-York            [NY, New]
Name: Short name, dtype: object

Or, if you want a separate row for each mode, you can use GroupBy.apply:

source2.groupby(['Country','City'])['Short name'].apply(pd.Series.mode)

Country  City               
Russia   Sankt-Petersburg  0    Spb
USA      New-York          0     NY
                           1    New
Name: Short name, dtype: object

If you don't care which mode is returned as long as it's either one of them, then you will need a lambda that calls mode and extracts the first result.

source2.groupby(['Country','City'])['Short name'].agg(
    lambda x: pd.Series.mode(x)[0])

Country  City            
Russia   Sankt-Petersburg    Spb
USA      New-York             NY
Name: Short name, dtype: object

Alternatives to (not) consider

You can also use statistics.mode from python, but...

source.groupby(['Country','City'])['Short name'].apply(statistics.mode)

Country  City            
Russia   Sankt-Petersburg    Spb
USA      New-York             NY
Name: Short name, dtype: object

...it does not work well when having to deal with multiple modes; a StatisticsError is raised. This is mentioned in the docs:

If data is empty, or if there is not exactly one most common value, StatisticsError is raised.

But you can see for yourself...

statistics.mode([1, 2])
# ---------------------------------------------------------------------------
# StatisticsError                           Traceback (most recent call last)
# ...
# StatisticsError: no unique mode; found 2 equally common values

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I've got the same error. I have been trying to fixing this by setting higher permission to account running SQL Client service, however it didnt help. The problem was that I run MS Sql Management studio just within my account. So, next time... assure that you are running it as Run as Administrator, if using Win7 with UAC enabled.

How can I show three columns per row?

Even though the above answer appears to be correct, I wanted to add a (hopefully) more readable example that also stays in 3 columns form at different widths:

_x000D_
_x000D_
.flex-row-container {_x000D_
    background: #aaa;_x000D_
    display: flex;_x000D_
    flex-wrap: wrap;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}_x000D_
.flex-row-container > .flex-row-item {_x000D_
    flex: 1 1 30%; /*grow | shrink | basis */_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
.flex-row-item {_x000D_
  background-color: #fff4e6;_x000D_
  border: 1px solid #f76707;_x000D_
}
_x000D_
<div class="flex-row-container">_x000D_
  <div class="flex-row-item">1</div>_x000D_
  <div class="flex-row-item">2</div>_x000D_
  <div class="flex-row-item">3</div>_x000D_
  <div class="flex-row-item">4</div>_x000D_
  <div class="flex-row-item">5</div>_x000D_
  <div class="flex-row-item">6</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope this helps someone else.

SVN Repository Search

I started using this tool

http://www.supose.org/wiki/supose

It works fine just lacking a visual UI, but is fast and somewhat maintained

Unable to copy file - access to the path is denied

I re-added all of my non-.NET dependencies / references and it did the trick.

Sql Server string to date conversion

dateadd(day,0,'10/15/2008 10:06:32 PM')

String in function parameter

Inside the function parameter list, char arr[] is absolutely equivalent to char *arr, so the pair of definitions and the pair of declarations are equivalent.

void function(char arr[]) { ... }
void function(char *arr)  { ... }

void function(char arr[]);
void function(char *arr);

The issue is the calling context. You provided a string literal to the function; string literals may not be modified; your function attempted to modify the string literal it was given; your program invoked undefined behaviour and crashed. All completely kosher.

Treat string literals as if they were static const char literal[] = "string literal"; and do not attempt to modify them.

Android EditText for password with android:hint

Here is your answer:

There are different category for inputType so I used for pssword is textPaswword

<EditText
    android:inputType="textPassword"
    android:id="@+id/passwor"
    android:textColorHint="#ffffff"
    android:layout_marginRight="15dp"
    android:layout_marginLeft="15dp"
    android:layout_width="fill_parent"
    android:layout_height="40dp"
    android:hint="********"
    />

make arrayList.toArray() return more specific types

A shorter version of converting List to Array of specific type (for example Long):

Long[] myArray = myList.toArray(Long[]::new);

html5 - canvas element - Multiple layers

You can create multiple canvas elements without appending them into document. These will be your layers:

Then do whatever you want with them and at the end just render their content in proper order at destination canvas using drawImage on context.

Example:

/* using canvas from DOM */
var domCanvas = document.getElementById('some-canvas');
var domContext = domCanvas.getContext('2d');
domContext.fillRect(50,50,150,50);

/* virtual canvase 1 - not appended to the DOM */
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50,50,150,150);

/* virtual canvase 2 - not appended to the DOM */    
var canvas2 = document.createElement('canvas')
var ctx2 = canvas2.getContext('2d');
ctx2.fillStyle = 'yellow';
ctx2.fillRect(50,50,100,50)

/* render virtual canvases on DOM canvas */
domContext.drawImage(canvas, 0, 0, 200, 200);
domContext.drawImage(canvas2, 0, 0, 200, 200);

And here is some codepen: https://codepen.io/anon/pen/mQWMMW

PreparedStatement IN clause alternatives?

An unpleasant work-around, but certainly feasible is to use a nested query. Create a temporary table MYVALUES with a column in it. Insert your list of values into the MYVALUES table. Then execute

select my_column from my_table where search_column in ( SELECT value FROM MYVALUES )

Ugly, but a viable alternative if your list of values is very large.

This technique has the added advantage of potentially better query plans from the optimizer (check a page for multiple values, tablescan only once instead once per value, etc) may save on overhead if your database doesn't cache prepared statements. Your "INSERTS" would need to be done in batch and the MYVALUES table may need to be tweaked to have minimal locking or other high-overhead protections.

Setting maxlength of textbox with JavaScript or jQuery

<head>
    <script type="text/javascript">
        function SetMaxLength () {
            var input = document.getElementById("myInput");
            input.maxLength = 10;
        }
    </script>
</head>
<body>
    <input id="myInput" type="text" size="20" />
</body>

ImportError: No module named requests

In my case requests was already installed, but needed an upgrade. The following command did the trick

$ sudo pip install requests --upgrade

Detach (move) subdirectory into separate Git repository

You might need something like "git reflog expire --expire=now --all" before the garbage collection to actually clean the files out. git filter-branch just removes references in the history, but doesn't remove the reflog entries that hold the data. Of course, test this first.

My disk usage dropped dramatically in doing this, though my initial conditions were somewhat different. Perhaps --subdirectory-filter negates this need, but I doubt it.

jQuery - Getting the text value of a table cell in the same row as a clicked element

This will also work

$(this).parent().parent().find('td').text()

Using setDate in PreparedStatement

Not sure, but what I think you're looking for is to create a java.util.Date from a String, then convert that java.util.Date to a java.sql.Date.

try this:

private static java.sql.Date getCurrentDate(String date) {

    java.util.Date today;
    java.sql.Date rv = null;
    try {

        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
        today = format.parse(date);
        rv = new java.sql.Date(today.getTime());
        System.out.println(rv.getTime());

    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    } finally {
        return rv;
    }

}    

Will return a java.sql.Date object for setDate();

The function above will print out a long value:

1375934400000

Java Webservice Client (Best way)

Some ideas in the following answer:

Steps in creating a web service using Axis2 - The client code

Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.

There are lots of web service frameworks out there...

Rock, Paper, Scissors Game Java

You could insert something like this:

personPlay = "B";

while (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S")) {

    //Get player's play from input-- note that this is 
    // stored as a string 
    System.out.println("Enter your play: "); 
    personPlay = scan.next();

    //Make player's play uppercase for ease of comparison 
    personPlay = personPlay.toUpperCase();

    if (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S"))
        System.out.println("Invalid move. Try again.");

}

How can I connect to Android with ADB over TCP?

For Windows users:

Step 1:
You have to enable Developer options in your Android phone.
You can enable Developer options using this way.
• Open Settings> About> Software Information> More.
• Then tap “Build number” seven times to enable Developer options.
• Go back to Settings menu and now you'll be able to see “Developer options” there.
• Tap it and turn on USB Debugging from the menu on the next screen.

Step 2:

Open cmd and type adb.
if you find that adb is not valid command then you have to add a path to the environment variable.

•First go to you SDK installed folder
Follow this path and this path is just for an example. D:\softwares\Development\Andoird\SDK\sdk\platform-tools\; D:\softwares\Development\Andoird\SDK\sdk\tools;
• Now search on windows system advanced setting

enter image description here

Open the Environment variable.

enter image description here

then open path and paste the following path this is an example.
You SDK path is different from mine please use yours. D:\softwares\Development\Andoird\SDK\sdk\platform-tools\;
D:\softwares\Development\Andoird\SDK\sdk\tools;

enter image description here

Step 3:

Open cmd and type adb. if you still see that adb is not valid command then your path has not set properly follow above steps.

enter image description here

Now you can connect your android phone to PC.

Open cmd and type adb devices and you can see your device. Find you phone ip address.

enter image description here

Type:- adb tcpip 5555

enter image description here

Get the IP address of your phone

adb shell netcfg

Now,

adb connect "IP address of your phone"

Now run your android project and if not see you device then type again adb connect IP address of your phone

enter image description here

enter image description here

For Linux and macOS users:

Step 1: open terminal and install adb using

sudo apt-get install android-tools-adb android-tools-fastboot

Connect your phone via USB cable to PC. Type following command in terminal

adb tcpip 5555

Using adb, connect your android phone ip address.

Remove your phone.

PHP: Possible to automatically get all POSTed data?

You can use $_REQUEST as well as $_POST to reach everything such as Post, Get and Cookie data.

Use a LIKE statement on SQL Server XML Datatype

This is what I am going to use based on marc_s answer:

SELECT 
SUBSTRING(DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)'),PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')) - 20,999)

FROM WEBPAGECONTENT 
WHERE COALESCE(PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')),0) > 0

Return a substring on the search where the search criteria exists

Displaying the Error Messages in Laravel after being Redirected from controller

to Make it look nice you can use little bootstrap help

@if(count($errors) > 0 )
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <ul class="p-0 m-0" style="list-style: none;">
        @foreach($errors->all() as $error)
        <li>{{$error}}</li>
        @endforeach
    </ul>
</div>
@endif

The equivalent of a GOTO in python

There's no goto instruction in the Python programming language. You'll have to write your code in a structured way... But really, why do you want to use a goto? that's been considered harmful for decades, and any program you can think of can be written without using goto.

Of course, there are some cases where an unconditional jump might be useful, but it's never mandatory, there will always exist a semantically equivalent, structured solution that doesn't need goto.

select certain columns of a data table

The question I would ask is, why are you including the extra columns in your DataTable if they aren't required?

Maybe you should modify your SQL select statement so that it is looking at the specific criteria you are looking for as you are populating your DataTable.

You could also use LINQ to query your DataTable as Enumerable and create a List Object that represents only certain columns.

Other than that, hide the DataGridView Columns that you don't require.

How to easily map c++ enums to strings

MSalters solution is a good one but basically re-implements boost::assign::map_list_of. If you have boost, you can use it directly:

#include <boost/assign/list_of.hpp>
#include <boost/unordered_map.hpp>
#include <iostream>

using boost::assign::map_list_of;

enum eee { AA,BB,CC };

const boost::unordered_map<eee,const char*> eeeToString = map_list_of
    (AA, "AA")
    (BB, "BB")
    (CC, "CC");

int main()
{
    std::cout << " enum AA = " << eeeToString.at(AA) << std::endl;
    return 0;
}

Why can't I have abstract static methods in C#?

Here is a situation where there is definitely a need for inheritance for static fields and methods:

abstract class Animal
{
  protected static string[] legs;

  static Animal() {
    legs=new string[0];
  }

  public static void printLegs()
  {
    foreach (string leg in legs) {
      print(leg);
    }
  }
}


class Human: Animal
{
  static Human() {
    legs=new string[] {"left leg", "right leg"};
  }
}


class Dog: Animal
{
  static Dog() {
    legs=new string[] {"left foreleg", "right foreleg", "left hindleg", "right hindleg"};
  }
}


public static void main() {
  Dog.printLegs();
  Human.printLegs();
}


//what is the output?
//does each subclass get its own copy of the array "legs"?

Trusting all certificates using HttpClient over HTTPS

Note: Do not implement this in production code you are ever going to use on a network you do not entirely trust. Especially anything going over the public internet.

Your question is just what I want to know. After I did some searches, the conclusion is as follows.

In HttpClient way, you should create a custom class from org.apache.http.conn.ssl.SSLSocketFactory, not the one org.apache.http.conn.ssl.SSLSocketFactory itself. Some clues can be found in this post Custom SSL handling stopped working on Android 2.2 FroYo.

An example is like ...

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;
public class MySSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}

and use this class while creating instance of HttpClient.

public HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

BTW, the link below is for someone who is looking for HttpURLConnection solution. Https Connection Android

I have tested the above two kinds of solutions on froyo, and they all work like a charm in my cases. Finally, using HttpURLConnection may face the redirect problems, but this is beyond the topic.

Note: Before you decide to trust all certificates, you probably should know the site full well and won't be harmful of it to end-user.

Indeed, the risk you take should be considered carefully, including the effect of hacker's mock site mentioned in the following comments that I deeply appreciated. In some situation, although it might be hard to take care of all certificates, you'd better know the implicit drawbacks to trust all of them.

How to extract code of .apk file which is not working?

Any .apk file from market or unsigned

  1. If you apk is downloaded from market and hence signed Install Astro File Manager from market. Open Astro > Tools > Application Manager/Backup and select the application to backup on to the SD card . Mount phone as USB drive and access 'backupsapps' folder to find the apk of target app (lets call it app.apk) . Copy it to your local drive same is the case of unsigned .apk.

  2. Download Dex2Jar zip from this link: SourceForge

  3. Unzip the downloaded zip file.

  4. Open command prompt & write the following command on reaching to directory where dex2jar exe is there and also copy the apk in same directory.

    dex2jar targetapp.apk file(./dex2jar app.apk on terminal)

  5. http://jd.benow.ca/ download decompiler from this link.

  6. Open ‘targetapp.apk.dex2jar.jar’ with jd-gui File > Save All Sources to sava the class files in jar to java files.

How to delete a line from a text file in C#?

I extended what Markus Olsson suggested, and came up with this class that adds multiple search strings and a couple of event:

public static class TextLineRemover
{
    public static void RemoveTextLines(IList<string> linesToRemove, string filename, string tempFilename)
    {
        // Initial values
        int lineNumber = 0;
        int linesRemoved = 0;
        DateTime startTime = DateTime.Now;

        // Read file
        using (var sr = new StreamReader(filename))
        {
            // Write new file
            using (var sw = new StreamWriter(tempFilename))
            {
                // Read lines
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    lineNumber++;
                    // Look for text to remove
                    if (!ContainsString(line, linesToRemove))
                    {
                        // Keep lines that does not match
                        sw.WriteLine(line);
                    }
                    else
                    {
                        // Ignore lines that DO match
                        linesRemoved++;
                        InvokeOnRemovedLine(new RemovedLineArgs { RemovedLine = line, RemovedLineNumber = lineNumber});
                    }
                }
            }
        }
        // Delete original file
        File.Delete(filename);

        // ... and put the temp file in its place.
        File.Move(tempFilename, filename);

        // Final calculations
        DateTime endTime = DateTime.Now;
        InvokeOnFinished(new FinishedArgs {LinesRemoved = linesRemoved, TotalLines = lineNumber, TotalTime = endTime.Subtract(startTime)});
    }

    private static bool ContainsString(string line, IEnumerable<string> linesToRemove)
    {
        foreach (var lineToRemove in linesToRemove)
        {
            if(line.Contains(lineToRemove))
                return true;
        }
        return false;
    }

    public static event RemovedLine OnRemovedLine;
    public static event Finished OnFinished;

    public static void InvokeOnFinished(FinishedArgs args)
    {
        Finished handler = OnFinished;
        if (handler != null) handler(null, args);
    }

    public static void InvokeOnRemovedLine(RemovedLineArgs args)
    {
        RemovedLine handler = OnRemovedLine;
        if (handler != null) handler(null, args);
    }
}

public delegate void Finished(object sender, FinishedArgs args);

public class FinishedArgs
{
    public int TotalLines { get; set; }
    public int LinesRemoved { get; set; }
    public TimeSpan TotalTime { get; set; }
}

public delegate void RemovedLine(object sender, RemovedLineArgs args);

public class RemovedLineArgs
{
    public string RemovedLine { get; set; }
    public int RemovedLineNumber { get; set; }
}

Usage:

TextLineRemover.OnRemovedLine += (o, removedLineArgs) => Console.WriteLine(string.Format("Removed \"{0}\" at line {1}", removedLineArgs.RemovedLine, removedLineArgs.RemovedLineNumber));
TextLineRemover.OnFinished += (o, finishedArgs) => Console.WriteLine(string.Format("{0} of {1} lines removed. Time used: {2}", finishedArgs.LinesRemoved, finishedArgs.TotalLines, finishedArgs.TotalTime.ToString()));
TextLineRemover.RemoveTextLines(new List<string> { "aaa", "bbb" }, fileName, fileName + ".tmp");

Chrome refuses to execute an AJAX script due to wrong MIME type

I encountered this error using IIS 7.0 with a custom 404 error page, although I suspect this will happen with any 404 page. The server returned an html 404 response with a text/html mime type which could not (rightly) be executed.

C# getting its own class name

Use this

Let say Application Test.exe is running and function is foo() in form1 [basically it is class form1], then above code will generate below response.

string s1 = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;

This will return .

s1 = "TEST.form1"

for function name:

string s1 = System.Reflection.MethodBase.GetCurrentMethod().Name;

will return

s1 = foo 

Note if you want to use this in exception use :

catch (Exception ex)
{

    MessageBox.Show(ex.StackTrace );

}

SQL query return data from multiple tables

Hopes this makes it find the tables as you're reading through the thing:

jsfiddle

mysql> show columns from colors;                                                         
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+           
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| color | varchar(15) | YES  |     | NULL    |                |
| paint | varchar(10) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

Global Angular CLI version greater than local version

In my case I just used this command into project:

ng update @angular/cli

Create Map in Java

Map <Integer, Point2D.Double> hm = new HashMap<Integer, Point2D>();
hm.put(1, new Point2D.Double(50, 50));

Extract the first (or last) n characters of a string

See ?substr

R> substr(a, 1, 4)
[1] "left"

Import SQL file into mysql

Finally, i solved the problem. I placed the `nitm.sql` file in `bin` file of the `mysql` folder and used the following syntax.

C:\wamp\bin\mysql\mysql5.0.51b\bin>mysql -u root nitm < nitm.sql

And this worked.

Bootstrap 3: Using img-circle, how to get circle from non-square image?

the problem mainly is because the width have to be == to the height, and in the case of bs, the height is set to auto so here is a fix for that in js instead

function img_circle() {
    $('.img-circle').each(function() {
        $w = $(this).width();
        $(this).height($w);
    });
}

$(document).ready(function() {
    img_circle();
});

$(window).resize(function() {
    img_circle();
});

JVM option -Xss - What does it do exactly?

Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.

Send email using java

Here is the working solution bro. It's guranteed.

  1. First of all open your gmail account from which you wanted to send mail, like in you case [email protected]
  2. Open this link below:

    https://support.google.com/accounts/answer/6010255?hl=en

  3. Click on "Go to the "Less secure apps" section in My Account." option
  4. Then turn on it
  5. That's it (:

Here is my code:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendEmail {

   final String senderEmailID = "Sender Email id";
final String senderPassword = "Sender Pass word";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "465";
String receiverEmailID = null;
static String emailSubject = "Test Mail";
static String emailBody = ":)";
public SendEmail(String receiverEmailID, String emailSubject, String emailBody)
{
this.receiverEmailID=receiverEmailID;
this.emailSubject=emailSubject;
this.emailBody=emailBody;
Properties props = new Properties();
props.put("mail.smtp.user",senderEmailID);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmailID));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmailID));
Transport.send(msg);
System.out.println("Message send Successfully:)");
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(senderEmailID, senderPassword);
}
}
    public static void main(String[] args) {
       SendEmail mailSender;
        mailSender = new SendEmail("Receiver Email id","Testing Code 2 example","Testing Code Body yess");
    }

}

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

The short version of the most voted answer has problems with TB values.

I adjusted it appropriately to handle also tb values and still without a loop and also added a little error checking for negative values. Here's my solution:

static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(long value, int decimalPlaces = 0)
{
    if (value < 0)
    {
        throw new ArgumentException("Bytes should not be negative", "value");
    }
    var mag = (int)Math.Max(0, Math.Log(value, 1024));
    var adjustedSize = Math.Round(value / Math.Pow(1024, mag), decimalPlaces);
    return String.Format("{0} {1}", adjustedSize, SizeSuffixes[mag]);
}

Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server

Declare @month as char(2)
Declare @date as char(2)
Declare @year as char(4)
declare @time as char(8)
declare @customdate as varchar(20)

set @month = MONTH(GetDate());
set @date = Day(GetDate());
set @year = year(GetDate());

set @customdate= @month+'/'+@date+'/'+@year+' '+ CONVERT(varchar(8), GETDATE(),108);
print(@customdate)

What is the difference between Collection and List in Java?

Collection is the root interface to the java Collections hierarchy. List is one sub interface which defines an ordered Collection, other sub interfaces are Queue which typically will store elements ready for processing (e.g. stack).

The following diagram demonstrates the relationship between the different java collection types:

java collections

git: can't push (unpacker error) related to permission issues

It is a permission error. The way that was most appropriate and secure for me was adding users to a supplementary group that the repo. is owned by (or vice versa):

groupadd git
chgrp -R git .git
chgrp -R git ./
usermod -G -a git $(whoami)

How to remove undefined and null values from an object using lodash?

if you are using lodash, you can use _.compact(array) to remove all falsely values from an array.

_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]

https://lodash.com/docs/4.17.4#compact

Viewing contents of a .jar file

My requirement was to view the content of a file (like a property file) inside the jar, without actually extracting the jar. If anyone reached this thread just like me, try this command -

unzip -p myjar.jar myfile.txt

This worked well for me!

Using python map and other functional tools

>>> from itertools import repeat
>>> for foo, bars in zip(foos, repeat(bars)):
...     print foo, bars
... 
1.0 [1, 2, 3]
2.0 [1, 2, 3]
3.0 [1, 2, 3]
4.0 [1, 2, 3]
5.0 [1, 2, 3]

How can I initialize an ArrayList with all zeroes in Java?

It's not like that. ArrayList just uses array as internal respentation. If you add more then 60 elements then underlaying array will be exapanded. How ever you can add as much elements to this array as much RAM you have.

Make a float only show two decimal places

You can also try using NSNumberFormatter:

NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];

You may need to also set the negative format, but I think it's smart enough to figure it out.

Using setTimeout to delay timing of jQuery actions

Try this:

function explode(){
  alert("Boom!");
}
setTimeout(explode, 2000);

Error :The remote server returned an error: (401) Unauthorized

The answers did help, but I think a full implementation of this will help a lot of people.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Dom
{
    class Dom
    {
        public static string make_Sting_From_Dom(string reportname)
        {
            try
            {
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                // Retrieve resource as a stream               
                Stream data = client.OpenRead(new Uri(reportname.Trim()));
                // Retrieve the text
                StreamReader reader = new StreamReader(data);
                string htmlContent = reader.ReadToEnd();
                string mtch = "TILDE";
                bool b = htmlContent.Contains(mtch);

                if (b)
                {
                    int index = htmlContent.IndexOf(mtch);
                    if (index >= 0)
                        Console.WriteLine("'{0} begins at character position {1}",
                        mtch, index + 1);
                }
                // Cleanup
                data.Close();
                reader.Close();
                return htmlContent;
            }
            catch (Exception)
            {
                throw;
            }
        }

        static void Main(string[] args)
        {
            make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
        }
    }
}

How do I get column names to print in this C# program?

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        ColumnName = column.ColumnName;
        ColumnData = row[column].ToString();
    }
}

Center a popup window on screen?

If you want to center it on the frame you are currently in, I would recommend this function:

function popupwindow(url, title, w, h) {
    var y = window.outerHeight / 2 + window.screenY - ( h / 2)
    var x = window.outerWidth / 2 + window.screenX - ( w / 2)
    return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + y + ', left=' + x);
} 

Similar to Crazy Tim's answer, but doesn't use window.top. This way, it will work even if the window is embedded in an iframe from a different domain.

public static const in TypeScript

The following solution also works as of TS 1.7.5.

// Constancts.ts    
export const kNotFoundInArray = -1;
export const AppConnectionError = new Error("The application was unable to connect!");
export const ReallySafeExtensions = ["exe", "virus", "1337h4x"];

To use:

// Main.ts    
import {ReallySafeExtensions, kNotFoundInArray} from "./Constants";

if (ReallySafeExtensions.indexOf("png") === kNotFoundInArray) {
    console.log("PNG's are really unsafe!!!");
}

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

From Android Studio 1.3, the ADB location is at:

C:\Users\USERNAME\AppData\Local\Android\sdk\platform-tools.

Now add this location to the end of PATH of environment variables. Eg:

;C:\Users\USERNAME\AppData\Local\Android\sdk\platform-tools

GetFiles with multiple extensions

I know there is a more elegant way to do this and I'm open to suggestions... this is what I did:

          try
            {


             // Set directory for list to be made of
                DirectoryInfo jpegInfo = new DirectoryInfo(destinationFolder);
                DirectoryInfo jpgInfo = new DirectoryInfo(destinationFolder);
                DirectoryInfo gifInfo = new DirectoryInfo(destinationFolder);
                DirectoryInfo tiffInfo = new DirectoryInfo(destinationFolder);
                DirectoryInfo bmpInfo = new DirectoryInfo(destinationFolder);

                // Set file type
                FileInfo[] Jpegs = jpegInfo.GetFiles("*.jpeg");
                FileInfo[] Jpgs = jpegInfo.GetFiles("*.jpg");
                FileInfo[] Gifs = gifInfo.GetFiles("*.gif");
                FileInfo[] Tiffs = gifInfo.GetFiles("*.tiff");
                FileInfo[] Bmps = gifInfo.GetFiles("*.bmp");

        //  listBox1.Items.Add(@"");  // Hack for the first list item no preview problem
        // Iterate through each file, displaying only the name inside the listbox...
        foreach (FileInfo file in Jpegs)
        {
                listBox1.Items.Add(file.Name);
                Photo curPhoto = new Photo();
                curPhoto.PhotoLocation = file.FullName;
                metaData.AddPhoto(curPhoto);
            }

          foreach (FileInfo file in Jpgs)
          {
              listBox1.Items.Add(file.Name);
                Photo curPhoto = new Photo();
                curPhoto.PhotoLocation = file.FullName;
                metaData.AddPhoto(curPhoto);
            }
          foreach (FileInfo file in Gifs)
          {
              listBox1.Items.Add(file.Name);
              Photo curPhoto = new Photo();
              curPhoto.PhotoLocation = file.FullName;
              metaData.AddPhoto(curPhoto);
          }
          foreach (FileInfo file in Tiffs)
          {
              listBox1.Items.Add(file.Name);
              Photo curPhoto = new Photo();
              curPhoto.PhotoLocation = file.FullName;
              metaData.AddPhoto(curPhoto);
          }
          foreach (FileInfo file in Bmps)
          {
              listBox1.Items.Add(file.Name);
              Photo curPhoto = new Photo();
              curPhoto.PhotoLocation = file.FullName;
              metaData.AddPhoto(curPhoto);
          }

How to share my Docker-Image without using the Docker-Hub?

Sending a docker image to a remote server can be done in 3 simple steps:

  1. Locally, save docker image as a .tar:
docker save -o <path for created tar file> <image name>
  1. Locally, use scp to transfer .tar to remote

  2. On remote server, load image into docker:

docker load -i <path to docker image tar file>

Subtract days, months, years from a date in JavaScript

You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.

You need to individually add/remove unit of time in date object

var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));

Sorting Characters Of A C++ String

You have to include sort function which is in algorithm header file which is a standard template library in c++.

Usage: std::sort(str.begin(), str.end());

#include <iostream>
#include <algorithm>  // this header is required for std::sort to work
int main()
{
    std::string s = "dacb";
    std::sort(s.begin(), s.end());
    std::cout << s << std::endl;

    return 0;
}

OUTPUT:

abcd

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

Ball to Ball Collision - Detection and Handling

A good way of reducing the number of collision checks is to split the screen into different sections. You then only compare each ball to the balls in the same section.

fitting data with numpy

Unfortunately, np.polynomial.polynomial.polyfit returns the coefficients in the opposite order of that for np.polyfit and np.polyval (or, as you used np.poly1d). To illustrate:

In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]: 
array([  84.29340848, -100.53595376,   44.83281408,   -8.85931101,
          0.65459882])

In [41]: np.polyfit(x, y, 4)
Out[41]: 
array([   0.65459882,   -8.859311  ,   44.83281407, -100.53595375,
         84.29340846])

In general: np.polynomial.polynomial.polyfit returns coefficients [A, B, C] to A + Bx + Cx^2 + ..., while np.polyfit returns: ... + Ax^2 + Bx + C.

So if you want to use this combination of functions, you must reverse the order of coefficients, as in:

ffit = np.polyval(coefs[::-1], x_new)

However, the documentation states clearly to avoid np.polyfit, np.polyval, and np.poly1d, and instead to use only the new(er) package.

You're safest to use only the polynomial package:

import numpy.polynomial.polynomial as poly

coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)

Or, to create the polynomial function:

ffit = poly.Polynomial(coefs)    # instead of np.poly1d
plt.plot(x_new, ffit(x_new))

fit and data plot

Python: Importing urllib.quote

If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.

try:
    from urllib import quote  # Python 2.X
except ImportError:
    from urllib.parse import quote  # Python 3+

You could also use the python compatibility wrapper six to handle this.

from six.moves.urllib.parse import quote

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

I got this error in Ubuntu. I saw that /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts was a broken link to /etc/ssl/certs/java/cacerts. That lead me to this bug: https://bugs.launchpad.net/ubuntu/+source/ca-certificates-java/+bug/983302 The README for ca-certificates-java eventually showed the actual fix:

run

update-ca-certificates -f

apt-get install ca-certificates-java didn't work for me. It just marked it as manually installed.

Android get current Locale, not default

I´ve used this:

String currentLanguage = Locale.getDefault().getDisplayLanguage();
if (currentLanguage.toLowerCase().contains("en")) {
   //do something
}

Setting up a cron job in Windows

  1. Make sure you logged on as an administrator or you have the same access as an administrator.
  2. Start->Control Panel->System and Security->Administrative Tools->Task Scheduler
  3. Action->Create Basic Task->Type a name and Click Next
  4. Follow through the wizard.

Compare two objects' properties to find differences?

I know this is probably overkill, but here's my ObjectComparer class I use for this very purpose:

/// <summary>
/// Utility class for comparing objects.
/// </summary>
public static class ObjectComparer
{
    /// <summary>
    /// Compares the public properties of any 2 objects and determines if the properties of each
    /// all contain the same value.
    /// <para> 
    /// In cases where object1 and object2 are of different Types (both being derived from Type T) 
    /// we will cast both objects down to the base Type T to ensure the property comparison is only 
    /// completed on COMMON properties.
    /// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
    /// both objects will be cast to Foo for comparison)
    /// </para>
    /// </summary>
    /// <typeparam name="T">Any class with public properties.</typeparam>
    /// <param name="object1">Object to compare to object2.</param>
    /// <param name="object2">Object to compare to object1.</param>
    /// <param name="propertyInfoList">A List of <see cref="PropertyInfo"/> objects that contain data on the properties
    /// from object1 that are not equal to the corresponding properties of object2.</param>
    /// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
    public static bool GetDifferentProperties<T> ( T object1 , T object2 , out List<PropertyInfo> propertyInfoList )
        where T : class
    {
        return GetDifferentProperties<T>( object1 , object2 , null , out propertyInfoList );
    }

    /// <summary>
    /// Compares the public properties of any 2 objects and determines if the properties of each
    /// all contain the same value.
    /// <para> 
    /// In cases where object1 and object2 are of different Types (both being derived from Type T) 
    /// we will cast both objects down to the base Type T to ensure the property comparison is only 
    /// completed on COMMON properties.
    /// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
    /// both objects will be cast to Foo for comparison)
    /// </para>
    /// </summary>
    /// <typeparam name="T">Any class with public properties.</typeparam>
    /// <param name="object1">Object to compare to object2.</param>
    /// <param name="object2">Object to compare to object1.</param>
    /// <param name="ignoredProperties">A list of <see cref="PropertyInfo"/> objects
    /// to ignore when completing the comparison.</param>
    /// <param name="propertyInfoList">A List of <see cref="PropertyInfo"/> objects that contain data on the properties
    /// from object1 that are not equal to the corresponding properties of object2.</param>
    /// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
    public static bool GetDifferentProperties<T> ( T object1 , T object2 , List<PropertyInfo> ignoredProperties , out List<PropertyInfo> propertyInfoList )
        where T : class
    {
        propertyInfoList = new List<PropertyInfo>();

        // If either object is null, we can't compare anything
        if ( object1 == null || object2 == null )
        {
            return false;
        }

        Type object1Type = object1.GetType();
        Type object2Type = object2.GetType();

        // In cases where object1 and object2 are of different Types (both being derived from Type T) 
        // we will cast both objects down to the base Type T to ensure the property comparison is only 
        // completed on COMMON properties.
        // (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
        // both objects will be cast to Foo for comparison)
        if ( object1Type != object2Type )
        {
            object1Type = typeof ( T );
            object2Type = typeof ( T );
        }

        // Remove any properties to be ignored
        List<PropertyInfo> comparisonProps =
            RemoveProperties( object1Type.GetProperties() , ignoredProperties );

        foreach ( PropertyInfo object1Prop in comparisonProps )
        {
            Type propertyType = null;
            object object1PropValue = null;
            object object2PropValue = null;

            // Rule out an attempt to check against a property which requires
            // an index, such as one accessed via this[]
            if ( object1Prop.GetIndexParameters().GetLength( 0 ) == 0 )
            {
                // Get the value of each property
                object1PropValue = object1Prop.GetValue( object1 , null );
                object2PropValue = object2Type.GetProperty( object1Prop.Name ).GetValue( object2 , null );

                // As we are comparing 2 objects of the same type we know
                // that they both have the same properties, so grab the
                // first non-null value
                if ( object1PropValue != null )
                    propertyType = object1PropValue.GetType().GetInterface( "IComparable" );

                if ( propertyType == null )
                    if ( object2PropValue != null )
                        propertyType = object2PropValue.GetType().GetInterface( "IComparable" );
            }

            // If both objects have null values or were indexed properties, don't continue
            if ( propertyType != null )
            {
                // If one property value is null and the other is not null, 
                // they aren't equal; this is done here as a native CompareTo
                // won't work with a null value as the target
                if ( object1PropValue == null || object2PropValue == null )
                {
                    propertyInfoList.Add( object1Prop );
                }
                else
                {
                    // Use the native CompareTo method
                    MethodInfo nativeCompare = propertyType.GetMethod( "CompareTo" );

                    // Sanity Check:
                    // If we don't have a native CompareTo OR both values are null, we can't compare;
                    // hence, we can't confirm the values differ... just go to the next property
                    if ( nativeCompare != null )
                    {
                        // Return the native CompareTo result
                        bool equal = ( 0 == (int) ( nativeCompare.Invoke( object1PropValue , new object[] {object2PropValue} ) ) );

                        if ( !equal )
                        {
                            propertyInfoList.Add( object1Prop );
                        }
                    }
                }
            }
        }
        return propertyInfoList.Count == 0;
    }

    /// <summary>
    /// Compares the public properties of any 2 objects and determines if the properties of each
    /// all contain the same value.
    /// <para> 
    /// In cases where object1 and object2 are of different Types (both being derived from Type T) 
    /// we will cast both objects down to the base Type T to ensure the property comparison is only 
    /// completed on COMMON properties.
    /// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
    /// both objects will be cast to Foo for comparison)
    /// </para>
    /// </summary>
    /// <typeparam name="T">Any class with public properties.</typeparam>
    /// <param name="object1">Object to compare to object2.</param>
    /// <param name="object2">Object to compare to object1.</param>
    /// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
    public static bool HasSamePropertyValues<T> ( T object1 , T object2 )
        where T : class
    {
        return HasSamePropertyValues<T>( object1 , object2 , null );
    }

    /// <summary>
    /// Compares the public properties of any 2 objects and determines if the properties of each
    /// all contain the same value.
    /// <para> 
    /// In cases where object1 and object2 are of different Types (both being derived from Type T) 
    /// we will cast both objects down to the base Type T to ensure the property comparison is only 
    /// completed on COMMON properties.
    /// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
    /// both objects will be cast to Foo for comparison)
    /// </para>
    /// </summary>
    /// <typeparam name="T">Any class with public properties.</typeparam>
    /// <param name="object1">Object to compare to object2.</param>
    /// <param name="object2">Object to compare to object1.</param>
    /// <param name="ignoredProperties">A list of <see cref="PropertyInfo"/> objects
    /// to ignore when completing the comparison.</param>
    /// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
    public static bool HasSamePropertyValues<T> ( T object1 , T object2 , List<PropertyInfo> ignoredProperties )
        where T : class
    {

        // If either object is null, we can't compare anything
        if ( object1 == null || object2 == null )
        {
            return false;
        }

        Type object1Type = object1.GetType();
        Type object2Type = object2.GetType();

        // In cases where object1 and object2 are of different Types (both being derived from Type T) 
        // we will cast both objects down to the base Type T to ensure the property comparison is only 
        // completed on COMMON properties.
        // (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
        // both objects will be cast to Foo for comparison)
        if ( object1Type != object2Type )
        {
            object1Type = typeof ( T );
            object2Type = typeof ( T );
        }

        // Remove any properties to be ignored
        List<PropertyInfo> comparisonProps =
            RemoveProperties( object1Type.GetProperties() , ignoredProperties );

        foreach ( PropertyInfo object1Prop in comparisonProps )
        {
            Type propertyType = null;
            object object1PropValue = null;
            object object2PropValue = null;

            // Rule out an attempt to check against a property which requires
            // an index, such as one accessed via this[]
            if ( object1Prop.GetIndexParameters().GetLength( 0 ) == 0 )
            {
                // Get the value of each property
                object1PropValue = object1Prop.GetValue( object1 , null );
                object2PropValue = object2Type.GetProperty( object1Prop.Name ).GetValue( object2 , null );

                // As we are comparing 2 objects of the same type we know
                // that they both have the same properties, so grab the
                // first non-null value
                if ( object1PropValue != null )
                    propertyType = object1PropValue.GetType().GetInterface( "IComparable" );

                if ( propertyType == null )
                    if ( object2PropValue != null )
                        propertyType = object2PropValue.GetType().GetInterface( "IComparable" );
            }

            // If both objects have null values or were indexed properties, don't continue
            if ( propertyType != null )
            {
                // If one property value is null and the other is not null, 
                // they aren't equal; this is done here as a native CompareTo
                // won't work with a null value as the target
                if ( object1PropValue == null || object2PropValue == null )
                {
                    return false;
                }

                // Use the native CompareTo method
                MethodInfo nativeCompare = propertyType.GetMethod( "CompareTo" );

                // Sanity Check:
                // If we don't have a native CompareTo OR both values are null, we can't compare;
                // hence, we can't confirm the values differ... just go to the next property
                if ( nativeCompare != null )
                {
                    // Return the native CompareTo result
                    bool equal = ( 0 == (int) ( nativeCompare.Invoke( object1PropValue , new object[] {object2PropValue} ) ) );

                    if ( !equal )
                    {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /// <summary>
    /// Removes any <see cref="PropertyInfo"/> object in the supplied List of 
    /// properties from the supplied Array of properties.
    /// </summary>
    /// <param name="allProperties">Array containing master list of 
    /// <see cref="PropertyInfo"/> objects.</param>
    /// <param name="propertiesToRemove">List of <see cref="PropertyInfo"/> objects to
    /// remove from the supplied array of properties.</param>
    /// <returns>A List of <see cref="PropertyInfo"/> objects.</returns>
    private static List<PropertyInfo> RemoveProperties (
        IEnumerable<PropertyInfo> allProperties , IEnumerable<PropertyInfo> propertiesToRemove )
    {
        List<PropertyInfo> innerPropertyList = new List<PropertyInfo>();

        // Add all properties to a list for easy manipulation
        foreach ( PropertyInfo prop in allProperties )
        {
            innerPropertyList.Add( prop );
        }

        // Sanity check
        if ( propertiesToRemove != null )
        {
            // Iterate through the properties to ignore and remove them from the list of 
            // all properties, if they exist
            foreach ( PropertyInfo ignoredProp in propertiesToRemove )
            {
                if ( innerPropertyList.Contains( ignoredProp ) )
                {
                    innerPropertyList.Remove( ignoredProp );
                }
            }
        }

        return innerPropertyList;
    }
}

Angular 2 : No NgModule metadata found

I had the same problem and couldn't solve it after reading all the above answers. Then I noticed that an extra comma in declarations was creating a problem. Removed it, problem solved.

@NgModule({
    imports: [
        PagesRoutingModule,
        ThemeModule,
        DashboardModule,
    ],
    declarations: [
        ...PAGES_COMPONENTS,
        **,**
    ],
})

Regex to match any character including new lines

Yeap, you just need to make . match newline :

$string =~ /(START)(.+?)(END)/s;

What does "select 1 from" do?

select 1 from table

will return a column of 1's for every row in the table. You could use it with a where statement to check whether you have an entry for a given key, as in:

if exists(select 1 from table where some_column = 'some_value')

What your friend was probably saying is instead of making bulk selects with select * from table, you should specify the columns that you need precisely, for two reasons:

1) performance & you might retrieve more data than you actually need.

2) the query's user may rely on the order of columns. If your table gets updated, the client will receive columns in a different order than expected.

How to Get True Size of MySQL Database?

MySQL Utilities by Oracle have a command called mysqldiskusage that displays the disk usage of every database: https://dev.mysql.com/doc/mysql-utilities/1.6/en/mysqldiskusage.html

How do I time a method's execution in Java?

You can use Perf4j. Very cool utility. Usage is simple

String watchTag = "target.SomeMethod";
StopWatch stopWatch = new LoggingStopWatch(watchTag);
Result result = null; // Result is a type of a return value of a method
try {
    result = target.SomeMethod();
    stopWatch.stop(watchTag + ".success");
} catch (Exception e) {
    stopWatch.stop(watchTag + ".fail", "Exception was " + e);
    throw e; 
}

More information can be found in Developer Guide

Edit: Project seems dead

WPF Image Dynamically changing Image source during runtime

Hey, this one is kind of ugly but it's one line only:

imgTitle.Source = new BitmapImage(new Uri(@"pack://application:,,,/YourAssembly;component/your_image.png"));