Programs & Examples On #Defn

Android Studio: Add jar as library?

Here are the instructions for adding a local jar file as a library to a module:

  1. Create a 'libs' folder in the top level of the module directory (the same directory that contains the 'src' directory)

  2. In the build.gradle file add the following so that your dependencies closure has:

    dependencies {
        // ... other dependencies
        compile files('libs/<your jar's name here>')
    }
    
  3. Android Studio should have already setup a gradlew wrapper. From the command line, navigate to the top level of your project (the directory that has a gradlew file).

    Run ./gradlew assemble. This should compile the project with the library. You may need to fix errors in your build.gradle file as necessary.

  4. In order to have Android Studio recognize the local jar files as libraries for support while coding in the IDE, you need to take a few more steps:

    4.1. Right click on the module in the left hand panel and choose Open Library Settings.

    4.2. On the left panel of the dialog, choose Libraries.

    4.3. Click the + sign above the panel second from the left -> Java

    Menu

    4.4. Select your local jar and add it to the project.

  5. You may need to run the above ./gradlew command one more time

Android java.lang.NoClassDefFoundError

Imaage

Go to Order and export from project properties and make sure you're including the required jars in the export, this did it for me

unique() for more than one variable

How about using unique() itself?

df <- data.frame(yad = c("BARBIE", "BARBIE", "BAKUGAN", "BAKUGAN"),
                 per = c("AYLIK",  "AYLIK",  "2 AYLIK", "2 AYLIK"),
                 hmm = 1:4)

df
#       yad     per hmm
# 1  BARBIE   AYLIK   1
# 2  BARBIE   AYLIK   2
# 3 BAKUGAN 2 AYLIK   3
# 4 BAKUGAN 2 AYLIK   4

unique(df[c("yad", "per")])
#       yad     per
# 1  BARBIE   AYLIK
# 3 BAKUGAN 2 AYLIK

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

As an update for fedora user , alternatives set current java directory to /usr/java/default

so you have to set your JAVA_HOME to /usr/java/default to always have alternatives curent selection in your classpath

HTH !

Using sed, how do you print the first 'N' characters of a line?

Don't use sed, use cut:

grep .... | cut -c 1-N

If you MUST use sed:

grep ... | sed -e 's/^\(.\{12\}\).*/\1/'

How to delete columns in a CSV file?

Off the top of my head, this will do it without any sort of error checking nor ability to configure anything. That is "left to the reader".

outFile = open( 'newFile', 'w' )
for line in open( 'oldFile' ):
   items = line.split( ',' )
   outFile.write( ','.join( items[:2] + items[ 3: ] ) )
outFile.close()

CSS3 transition doesn't work with display property

When you need to toggle an element away, and you don't need to animate the margin property. You could try margin-top: -999999em. Just don't transition all.

how to display a javascript var in html body

Index.html:

<html>
<body>
    Javascript Version: <b id="version"></b>
    <script src="app.js"></script>
</body>
</html>

app.js:

var ver="1.1";
document.getElementById("version").innerHTML = ver;

How to use "not" in xpath?

None of these answers worked for me for python. I solved by this

a[not(@id='XX')]

Also you can use or condition in your xpath by | operator. Such as

a[not(@id='XX')]|a[not(@class='YY')]

Sometimes we want element which has no class. So you can do like

a[not(@class)]

How to find index of STRING array in Java from a given value?

Use Arrays class to do this

Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");

Data binding to SelectedItem in a WPF Treeview

You might also be able to use TreeViewItem.IsSelected property

What is javax.inject.Named annotation supposed to be used for?

The primary role of the @Named annotation is to define a bean for the purpose of resolving EL statements within the application, usually through JSF EL resolvers. Injection can be performed using names but this was not how injection in CDI was meant to work since CDI gives us a much richer way to express injection points and the beans to be injected into them.

React - How to get parameter value from query string?

In the component where you need to access the parameters you can use

this.props.location.state.from.search

which will reveal the whole query string (everything after the ? sign)

Correct way to create rounded corners in Twitter Bootstrap

Without less, ans simply for a given div :

In a css :

.footer {
background-color: #ab0000;
padding-top: 40px;
padding-bottom: 10px;
border-radius:5px;
}

In html :

 <div class="footer">
        <p>blablabla</p>
      </div>

Disable Pinch Zoom on Mobile Web

This is all I needed:

<meta name="viewport" content="user-scalable=no"/>

onKeyPress Vs. onKeyUp and onKeyDown

Check here for the archived link originally used in this answer.

From that link:

In theory, the onKeyDown and onKeyUp events represent keys being pressed or released, while the onKeyPress event represents a character being typed. The implementation of the theory is not same in all browsers.

Angles between two n-dimensional vectors in Python

Using numpy (highly recommended), you would do:

from numpy import (array, dot, arccos, clip)
from numpy.linalg import norm

u = array([1.,2,3,4])
v = ...
c = dot(u,v)/norm(u)/norm(v) # -> cosine of the angle
angle = arccos(clip(c, -1, 1)) # if you really want the angle

How to get some values from a JSON string in C#?

Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.

Here is an example on how to parse a JSON string into a dynamic object:

string source = "{\r\n   \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\",  \r\n   \"first_name\": \"Jerard\", \r\n   \"last_name\": \"Jones\", \r\n   \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n   \"username\": \"Jerard.Jones\", \r\n   \"gender\": \"female\", \r\n   \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
Console.WriteLine(data.first_name);
Console.WriteLine(data.last_name);
Console.WriteLine(data.gender);
Console.WriteLine(data.locale);

Happy coding!

How can I symlink a file in Linux?

To create a symbolic link /soft link, use:

ln -s {source-filename} {symbolic-filename}

e.g.:

ln -s file1 link1

@font-face src: local - How to use the local font if the user already has it?

I haven’t actually done anything with font-face, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.

The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.

Does Firefox download the font when you actually use it in a font declaration? (e.g. h1 { font: 'DejaVu Serif';)?

SQL query for extracting year from a date

How about this one?

SELECT TO_CHAR(ASOFDATE, 'YYYY') FROM PSASOFDATE

How to select all columns, except one column in pandas?

When the columns are not a MultiIndex, df.columns is just an array of column names so you can do:

df.loc[:, df.columns != 'b']

          a         c         d
0  0.561196  0.013768  0.772827
1  0.882641  0.615396  0.075381
2  0.368824  0.651378  0.397203
3  0.788730  0.568099  0.869127

Scale the contents of a div by a percentage?

You can simply use the zoom property:

#myContainer{
    zoom: 0.5;
    -moz-transform: scale(0.5);
}

Where myContainer contains all the elements you're editing. This is supported in all major browsers.

How to launch a Google Chrome Tab with specific URL using C#

If the user doesn't have Chrome, it will throw an exception like this:

    //chrome.exe http://xxx.xxx.xxx --incognito
    //chrome.exe http://xxx.xxx.xxx -incognito
    //chrome.exe --incognito http://xxx.xxx.xxx
    //chrome.exe -incognito http://xxx.xxx.xxx
    private static void Chrome(string link)
    {
        string url = "";

        if (!string.IsNullOrEmpty(link)) //if empty just run the browser
        {
            if (link.Contains('.')) //check if it's an url or a google search
            {
                url = link;
            }
            else
            {
                url = "https://www.google.com/search?q=" + link.Replace(" ", "+");
            }
        }

        try
        {
            Process.Start("chrome.exe", url + " --incognito");
        }
        catch (System.ComponentModel.Win32Exception e)
        {
            MessageBox.Show("Unable to find Google Chrome...",
                "chrome.exe not found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

SQL ROWNUM how to return rows between a specific range

SELECT  *
FROM    (
        SELECT  q.*, rownum rn
        FROM    (
                SELECT  *
                FROM    maps006
                ORDER BY
                        id
                ) q
        )
WHERE   rn BETWEEN 50 AND 100

Note the double nested view. ROWNUM is evaluated before ORDER BY, so it is required for correct numbering.

If you omit ORDER BY clause, you won't get consistent order.

Bootstrap with jQuery Validation Plugin

for bootstrap 4 this work with me good

    $.validator.setDefaults({
    highlight: function(element) {
        $(element).closest('.form-group').find(".form-control:first").addClass('is-invalid');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').find(".form-control:first").removeClass('is-invalid');
        $(element).closest('.form-group').find(".form-control:first").addClass('is-valid');

    },
    errorElement: 'span',
    errorClass: 'invalid-feedback',
    errorPlacement: function(error, element) {
        if(element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    }
});

hope it will help !

Self Join to get employee manager name

As Jesse said, use self join:

SELECT 
  e.emp_id
  , e.emp_name
  , e.emp_mgr_id
  , m.emp_name AS mgr_name 
FROM [dbo].[tblEmployeeDetails] e 
LEFT JOIN [dbo].[tblEmployeeDetails] m ON e.emp_mgr_id = m.emp_id

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

Java 8 Distinct by property

I made a generic version:

private <T, R> Collector<T, ?, Stream<T>> distinctByKey(Function<T, R> keyExtractor) {
    return Collectors.collectingAndThen(
            toMap(
                    keyExtractor,
                    t -> t,
                    (t1, t2) -> t1
            ),
            (Map<R, T> map) -> map.values().stream()
    );
}

An exemple:

Stream.of(new Person("Jean"), 
          new Person("Jean"),
          new Person("Paul")
)
    .filter(...)
    .collect(distinctByKey(Person::getName)) // return a stream of Person with 2 elements, jean and Paul
    .map(...)
    .collect(toList())

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

What does $(function() {} ); do?

I think you may be confusing Javascript with jQuery methods. Vanilla or plain Javascript is something like:

function example() {
}

A function of that nature can be called at any time, anywhere.

jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is:

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

So a jQuery function, which is prefixed with the $ or the word jQuery generally is called from within that method.

$(document).ready(function() {        
    // Assign all list items on the page to be the  color red.  
    //      This does not work until AFTER the entire DOM is "ready", hence the $(document).ready()
    $('li').css('color', 'red');   
});

The pseudo-code for that block is:

When the document object model $(document) is ready .ready(), call the following function function() { }. In that function, check for all <li>'s on the page $('li') and using the jQuery method .CSS() to set the CSS property "color" to the value "red" .css('color', 'red');

Get filename in batch for loop

or Just %~F will give you the full path and full file name.

For example, if you want to register all *.ax files in the current directory....

FOR /R C:. %F in (*.ax) do regsvr32 "%~F"

This works quite nicely in Win7 (64bit) :-)

Bootstrap change carousel height

The following should work

.carousel .item {
  height: 300px;
}

.item img {
    position: absolute;
    top: 0;
    left: 0;
    min-height: 300px;
}

JSFille for reference.

Propagate all arguments in a bash shell script

Works fine, except if you have spaces or escaped characters. I don't find the way to capture arguments in this case and send to a ssh inside of script.

This could be useful but is so ugly

_command_opts=$( echo "$@" | awk -F\- 'BEGIN { OFS=" -" } { for (i=2;i<=NF;i++) { gsub(/^[a-z] /,"&@",$i) ; gsub(/ $/,"",$i );gsub (/$/,"@",$i) }; print $0 }' | tr '@' \' )

Cleanest way to reset forms

this.<your_form>.form.markAsPristine();
this.<your_form>.form.markAsUntouched();
this.<your_form>.form.updateValueAndValidity();

can also help

How can I run multiple npm scripts in parallel?

Quick Solution

In this case, I'd say the best bet If this script is for a private module intended to run only on *nix-based machines, you can use the control operator for forking processes, which looks like this: &

An example of doing this in a partial package.json file:

{
  "name": "npm-scripts-forking-example",
  "scripts": {
    "bundle": "watchify -vd -p browserify-hmr index.js -o bundle.js",
    "serve":  "http-server -c 1 -a localhost",
    "serve-bundle": "npm run bundle & npm run serve &"
  }

You'd then execute them both in parallel via npm run serve-bundle. You can enhance the scripts to output the pids of the forked process to a file like so:

"serve-bundle": "npm run bundle & echo \"$!\" > build/bundle.pid && npm run serve & echo \"$!\" > build/serve.pid && npm run open-browser",

Google something like bash control operator for forking to learn more on how it works. I've also provided some further context regarding leveraging Unix techniques in Node projects below:

Further Context RE: Unix Tools & Node.js

If you're not on Windows, Unix tools/techniques often work well to achieve something with Node scripts because:

  1. Much of Node.js lovingly imitates Unix principles
  2. You're on *nix (incl. OS X) and NPM is using a shell anyway

Modules for system tasks in Nodeland are also often abstractions or approximations of Unix tools, from fs to streams.

compareTo() vs. equals()

I believe equals and equalsIgnoreCase methods of String return true and false which is useful if you wanted to compare the values of the string object, But in case of implementing compareTo and compareToIgnoreCase methods returns positive, negative and zero value which will be useful in case of sorting.

How to detect tableView cell touched or clicked in swift

Problem was solved by myself using tutorial of weheartswift

enter image description here

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Batch File; List files in directory, only filenames?

dir /s/d/a:-d "folderpath*.*" > file.txt

And, lose the /s if you do not need files from subfolders

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

With JDBC, that error usually occurs because your JDBC driver implements an older version of the JDBC API than the one included in your JRE. These older versions are fine so long as you don't try and use a method that appeared in the newer API.

I'm not sure what version of JDBC setBinaryStream appeared in. It's been around for a while, I think.

Regardless, your JDBC driver version (10.2.0.4.0) is quite old, I recommend upgrading it to the version that was released with 11g (download here), and try again.

less than 10 add 0 to number

Make a function that you can reuse:

function minTwoDigits(n) {
  return (n < 10 ? '0' : '') + n;
}

Then use it in each part of the coordinates:

c += minTwoDigits(deg) + "° ";

and so on.

How to delete a record in Django models?

There are a couple of ways:

To delete it directly:

SomeModel.objects.filter(id=id).delete()

To delete it from an instance:

instance = SomeModel.objects.get(id=id)
instance.delete()

ruby 1.9: invalid byte sequence in UTF-8

This seems to work:

def sanitize_utf8(string)
  return nil if string.nil?
  return string if string.valid_encoding?
  string.chars.select { |c| c.valid_encoding? }.join
end

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

In my case I was using XAMPP, and there was a log that told me the error. To find it, go to the XAMPP control panel, and click "Configure" for MySQL, then click on "Open Log."

The most current data of the log is at the bottom, and the log is organized by date, time, some number, and text in brackets that may say "Note" or "Error." One that says "Error" is likely causing the issue.

For me, my error was a tablespace that was causing an issue, so I deleted the database files at the given location.

Note: The tablespace files for your installation of XAMPP may be at a different location, but they were in /opt/lampp/var/mysql for me. I think that's typical of XAMPP on Debian-based distributions. Also, my instructions on what to click in the control panel to see the log may be a bit different for you because I'm running XAMPP on an Ubuntu-based distribution of Linux (Feren OS).

How do I get the localhost name in PowerShell?

All above questions are correct but if you want the hostname and domain name try this:

 [System.Net.DNS]::GetHostByName('').HostName

Changing fonts in ggplot2

You just missed an initialization step I think.

You can see what fonts you have available with the command windowsFonts(). For example mine looks like this when I started looking at this:

> windowsFonts()
$serif
[1] "TT Times New Roman"

$sans
[1] "TT Arial"

$mono
[1] "TT Courier New"

After intalling the package extraFont and running font_import like this (it took like 5 minutes):

library(extrafont)
font_import()
loadfonts(device = "win")

I had many more available - arguable too many, certainly too many to list here.

Then I tried your code:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16,  family="Comic Sans MS"))
print(a)

yielding this:

enter image description here

Update:

You can find the name of a font you need for the family parameter of element_text with the following code snippet:

> names(wf[wf=="TT Times New Roman"])
[1] "serif"

And then:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text=element_text(size=16,  family="serif"))
print(a)

yields: enter image description here

CSS way to horizontally align table

Simple. IE6 and above will happily center your table with "margin: 0 auto;" if only the page renders in "standards" mode. To make this happen you need a valid doctype declaration, such as

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

or

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

True, IE5.5 and below will still refuse to center the table but perhaps you can live with that, especially if the page is still functional with the table left aligned. I think by now users of IE5.5 and below are fairly used to some odd looking websites - but you still need to ensure that those visual glitches don't render your site unusable.

Happy coding!

EDIT: Sorry, I should perhaps point out that you do not have to have a "strict" doctype to get IE6 and up into "standards" rendering mode. I realised it might seem that way from the doctype examples I posted above. For example, this doctype declaration will of course work equally:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

How to reset the use/password of jenkins on windows?

You can try to re-set your Jenkins security:

  1. Stop the Jenkins service
  2. Open the config.xml with a text editor (i.e notepad++), maybe be in C:\jenkins\config.xml (could backup it also).
  3. Find this <useSecurity>true</useSecurity> and change it to <useSecurity>false</useSecurity>
  4. Start Jenkins service

You might create an admin user and enable security again.

How to create User/Database in script for Docker Postgres

I add custom commands to a environment evoked in a CMD after starting services... I haven't done it with postgres, but with Oracle:

#set up var with noop command
RUN export POST_START_CMDS=":"
RUN mkdir /scripts
ADD script.sql /scripts
CMD service oracle-xe start; $POST_START_CMDS; tail -f /var/log/dmesg

and start with

docker run -d ... -e POST_START_CMDS="su - oracle -c 'sqlplus @/scripts/script' " <image>

.

How do I run msbuild from the command line using Windows SDK 7.1?

Using the "Developer Command Prompt for Visual Studio 20XX" instead of "cmd" will set the path for msbuild automatically without having to add it to your environment variables.

Properties order in Margin

There are three unique situations:

  • 4 numbers, e.g. Margin="a,b,c,d".
  • 2 numbers, e.g. Margin="a,b".
  • 1 number, e.g. Margin="a".

4 Numbers

If there are 4 numbers, then its left, top, right, bottom (a clockwise circle starting from the middle left margin). First number is always the "West" like "WPF":

<object Margin="left,top,right,bottom"/>

Example: if we use Margin="10,20,30,40" it generates:

enter image description here

2 Numbers

If there are 2 numbers, then the first is left & right margin thickness, the second is top & bottom margin thickness. First number is always the "West" like "WPF":

<object Margin="a,b"/> // Equivalent to Margin="a,b,a,b".

Example: if we use Margin="10,30", the left & right margin are both 10, and the top & bottom are both 30.

enter image description here

1 Number

If there is 1 number, then the number is repeated (its essentially a border thickness).

<object Margin="a"/> // Equivalent to Margin="a,a,a,a".

Example: if we use Margin="20" it generates:

enter image description here

Update 2020-05-27

Have been working on a large-scale WPF application for the past 5 years with over 100 screens. Part of a team of 5 WPF/C#/Java devs. We eventually settled on either using 1 number (for border thickness) or 4 numbers. We never use 2. It is consistent, and seems to be a good way to reduce cognitive load when developing.


The rule:

All width numbers start on the left (the "West" like "WPF") and go clockwise (if two numbers, only go clockwise twice, then mirror the rest).

Get a list of dates between two dates using a function

Try something like this:

CREATE FUNCTION dbo.ExplodeDates(@startdate datetime, @enddate datetime)
returns table as
return (
with 
 N0 as (SELECT 1 as n UNION ALL SELECT 1)
,N1 as (SELECT 1 as n FROM N0 t1, N0 t2)
,N2 as (SELECT 1 as n FROM N1 t1, N1 t2)
,N3 as (SELECT 1 as n FROM N2 t1, N2 t2)
,N4 as (SELECT 1 as n FROM N3 t1, N3 t2)
,N5 as (SELECT 1 as n FROM N4 t1, N4 t2)
,N6 as (SELECT 1 as n FROM N5 t1, N5 t2)
,nums as (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as num FROM N6)
SELECT DATEADD(day,num-1,@startdate) as thedate
FROM nums
WHERE num <= DATEDIFF(day,@startdate,@enddate) + 1
);

You then use:

SELECT *
FROM dbo.ExplodeDates('20090401','20090531') as d;

Edited (after the acceptance):

Please note... if you already have a sufficiently large nums table then you should use:

CREATE FUNCTION dbo.ExplodeDates(@startdate datetime, @enddate datetime)
returns table as
return (
SELECT DATEADD(day,num-1,@startdate) as thedate
FROM nums
WHERE num <= DATEDIFF(day,@startdate,@enddate) + 1
);

And you can create such a table using:

CREATE TABLE dbo.nums (num int PRIMARY KEY);
INSERT dbo.nums values (1);
GO
INSERT dbo.nums SELECT num + (SELECT COUNT(*) FROM nums) FROM nums
GO 20

These lines will create a table of numbers containing 1M rows... and far quicker than inserting them one by one.

You should NOT create your ExplodeDates function using a function that involves BEGIN and END, as the Query Optimizer becomes unable to simplify the query at all.

java.math.BigInteger cannot be cast to java.lang.Long

Imagine d.getId is a Long, then wrap like this:

BigInteger l  = BigInteger.valueOf(d.getId());

Differences between Oracle JDK and OpenJDK

  1. Oracle will deliver releases every three years, while OpenJDK will be released every six months.
  2. Oracle provides long term support for its releases. On the other hand, OpenJDK supports the changes to a release only until the next version is released.
  3. Oracle JDK was licensed under Oracle Binary Code License Agreement, whereas OpenJDK has the GNU General Public License (GNU GPL) version 2 with a linking exception.
  4. Oracle product has Flight Recorder, Java Mission Control, and Application Class-Data Sharing features, while OpenJDK has the Font Renderer feature.Also, Oracle has more Garbage Collection options and better renderers,
  5. Oracle JDK is fully developed by Oracle Corporation whereas the OpenJDK is developed by Oracle, OpenJDK, and the Java Community. However, the top-notch companies like Red Hat, Azul Systems, IBM, Apple Inc., SAP AG also take an active part in its development.

From Java 11 turn to a big change

Oracle will change its historical “BCL” license with a combination of an open source and commercial license

  • Oracle’s kit for Java 11 emits a warning when using the -XX:+UnlockCommercialFeatures option, whereas in OpenJDK builds, this option results in an error
  • Oracle JDK offers a configuration to provide usage log data to the “Advanced Management Console” tool
  • Oracle has always required third party cryptographic providers to be signed by a known certificate, while cryptography framework in OpenJDK has an open cryptographic interface, which means there is no restriction as to which providers can be used
  • Oracle JDK 11 will continue to include installers, branding, and JRE packaging, whereas OpenJDK builds are currently available as zip and tar.gz files
  • The javac –release command behaves differently for the Java 9 and Java 10 targets due to the presence of some additional modules in Oracle’s release
  • The output of the java –version and java -fullversion commands will distinguish Oracle’s builds from OpenJDK builds


Update : 25-Aug-2019



enter image description here

for more details oracle-vs-openjdk

android.app.Application cannot be cast to android.app.Activity

You are getting this error because the parameter required is Activity and you are passing it the Application. So, either you cast application to the Activity like: (Activity)getApplicationContext(); Or you can just type the Activity like: MyActivity.this

Get docker container id from container name

Thanks for the answer of https://stackoverflow.com/a/65513726/889126, it gave me an idea to make a complete bash script as it is

export api_image_id=$(docker inspect --format="{{.Id}}" <image-name> | sed '/^[[:space:]]*$/d')

sudo docker exec -i -t ${api_image_id} /bin/bash

I need a specific container and make a script to extract some info from it in a quick sight.

Hope this would help others.

PreparedStatement with list of parameters in a IN clause

Many DBs have a concept of a temporary table, even assuming you don't have a temporary table you can always generate one with a unique name and drop it when you are done. While the overhead of creating and dropping a table is large, this may be reasonable for very large operations, or in cases where you are using the database as a local file or in memory (SQLite).

An example from something I am in the middle of (using Java/SqlLite):

String tmptable = "tmp" + UUID.randomUUID();

sql = "create table " + tmptable + "(pagelist text not null)";
cnn.createStatement().execute(sql);

cnn.setAutoCommit(false);
stmt = cnn.prepareStatement("insert into "+tmptable+" values(?);");
for(Object o : rmList){
    Path path = (Path)o;
    stmt.setString(1, path.toString());
    stmt.execute();
}
cnn.commit();
cnn.setAutoCommit(true);

stmt = cnn.prepareStatement(sql);
stmt.execute("delete from filelist where path + page in (select * from "+tmptable+");");
stmt.execute("drop table "+tmptable+");");

Note that the fields used by my table are created dynamically.

This would be even more efficient if you are able to reuse the table.

ERROR: ld.so: object LD_PRELOAD cannot be preloaded: ignored

It means the path you input caused an error. In your LD_PRELOAD command, modify the path like the error tips:

/usr/lib/liblunar-calendar-preload.so

Negation in Python

The negation operator in Python is not. Therefore just replace your ! with not.

For your example, do this:

if not os.path.exists("/usr/share/sounds/blues") :
    proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
    proc.wait()

For your specific example (as Neil said in the comments), you don't have to use the subprocess module, you can simply use os.mkdir() to get the result you need, with added exception handling goodness.

Example:

blues_sounds_path = "/usr/share/sounds/blues"
if not os.path.exists(blues_sounds_path):
    try:
        os.mkdir(blues_sounds_path)
    except OSError:
        # Handle the case where the directory could not be created.

Adding integers to an int array

An array doesn't have an add method. You assign a value to an element of the array with num[i]=value;.

public static void main(String[] args) {
    int[] num = new int[args.length];
    for (int i=0; i < num.length; i++){
      int neki = Integer.parseInt(args[i]);
      num[i]=neki;
    }
}

How to change the background color on a Java panel?

I am assuming that we are dealing with a JFrame? The visible portion in the content pane - you have to use jframe.getContentPane().setBackground(...);

Get the correct week number of a given date

Based on il_guru's answer, I created this version for my own needs that also returns the year component.

    /// <summary>
    /// This presumes that weeks start with Monday.
    /// Week 1 is the 1st week of the year with a Thursday in it.
    /// </summary>
    /// <param name="time">The date to calculate the weeknumber for.</param>
    /// <returns>The year and weeknumber</returns>
    /// <remarks>
    /// Based on Stack Overflow Answer: https://stackoverflow.com/a/11155102
    /// </remarks>
    public static (short year, byte week) GetIso8601WeekOfYear(DateTime time)
    {
        // Seriously cheat.  If its Monday, Tuesday or Wednesday, then it'll
        // be the same week# as whatever Thursday, Friday or Saturday are,
        // and we always get those right
        DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
        if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
        {
            time = time.AddDays(3);
        }
        // Return the week of our adjusted day
        var week = (byte)CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
        return ((short)(week >= 52 & time.Month == 1 ? time.Year - 1 : time.Year), week);
    }

Getting list of items inside div using Selenium Webdriver

I'm not sure if your findElements statement gets you all the divs. I would try the following:

List<WebElement> elementsRoot = driver.findElements(By.xpath("//div[@class=\"facetContainerDiv\"]/div));

for(int i = 0; i < elementsRoot.size(); ++i) {
     WebElement checkbox = elementsRoot.get(i).findElement(By.xpath("./label/input"));
     checkbox.click();
     blah blah blah
}

The idea here is that you get the root element then use another a 'sub' xpath or any selector you like to find the node element. Of course the xpath or selector may need to be adjusted to properly find the element you want.

What does !important mean in CSS?

It changes the rules for override priority of css cascades. See the CSS2 spec.

How to redirect to previous page in Ruby On Rails?

In rails 5, as per the instructions in Rails Guides, you can use:

redirect_back(fallback_location: root_path)

The 'back' location is pulled from the HTTP_REFERER header which is not guaranteed to be set by the browser. Thats why you should provide a 'fallback_location'.

What is the Java equivalent for LINQ?

For basic functional collections, Java 8 has it built in, most of the major non-Java JVM languages have it built in (Scala, Clojure, etc), and you can get add on libs for earlier Java versions.

For full language integrated access to a SQL database, Scala (runs on the JVM) has Slick

Trying to add adb to PATH variable OSX

Why are you trying to run "./adb"? That skips the path variable entirely and only looks for "adb" in the current directory. Try running "adb" instead.

Edit: your path looks wrong. You say you get

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/Libs/android-sdk-mac_x86/tools:/Libs/android-sdk-mac_x86/platform-tools

You're missing the /Users/simon part.

Also note that if you have both .profile and .bash_profile files, only the latter gets executed.

Django DateField default options

This should do the trick:

models.DateTimeField(_("Date"), auto_now_add = True)

Regex to match string containing two names in any order

Vim has a branch operator \& that is useful when searching for a line containing a set of words, in any order. Moreover, extending the set of required words is trivial.

For example,

/.*jack\&.*james

will match a line containing jack and james, in any order.

See this answer for more information on usage. I am not aware of any other regex flavor that implements branching; the operator is not even documented on the Regular Expression wikipedia entry.

How to edit a text file in my terminal

You can open the file again using vi helloworld.txt and then use cat /path/your_file to view it.

Max length for client ip address

There's a caveat with the general 39 character IPv6 structure. For IPv4 mapped IPv6 addresses, the string can be longer (than 39 characters). An example to show this:

IPv6 (39 characters) :

ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD

IPv4-mapped IPv6 (45 characters) :

ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:192.168.158.190

Note: the last 32-bits (that correspond to IPv4 address) can need up to 15 characters (as IPv4 uses 4 groups of 1 byte and is formatted as 4 decimal numbers in the range 0-255 separated by dots (the . character), so the maximum is DDD.DDD.DDD.DDD).

The correct maximum IPv6 string length, therefore, is 45.

This was actually a quiz question in an IPv6 training I attended. (We all answered 39!)

How to make a new line or tab in <string> XML (eclipse/android)?

\n didn't work for me. So I used <br></br> HTML tag

    <string name="message_register_success">
Sign up is complete. <br></br>
 Enjoy a new shopping life at MageMobile!!
</string>

Why does sudo change the PATH?

The PATH will be reset when using su or sudo by the definition of ENV_SUPATH, and ENV_PATH defined in /etc/login.defs

Android Studio rendering problems

  1. Open AndroidManifest.xml
  2. Change:

    android:theme="@style/AppTheme"

    to something like:

    android:theme="@style/Theme.AppCompat.Light"
  3. Hit "refresh" button in the "Previev" tab.

Creating an instance using the class name and calling constructor

If anyone is looking for a way to create an instance of a class despite the class following the Singleton Pattern, here is a way to do it.

// Get Class instance
Class<?> clazz = Class.forName("myPackage.MyClass");

// Get the private constructor.
Constructor<?> cons = clazz.getDeclaredConstructor();

// Since it is private, make it accessible.
cons.setAccessible(true);

// Create new object. 
Object obj = cons.newInstance();

This only works for classes that implement singleton pattern using a private constructor.

How to modify memory contents using GDB?

Expanding on the answers provided here.

You can just do set idx = 1 to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1 would not be valid.

This means that you should prefer the syntax: set variable idx = 1 or set var idx = 1.

Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.

(gdb) p idx = 1
$1 = 1

You can read more about gdb here.

e.printStackTrace equivalent in python

Adding to the other great answers, we can use the Python logging library's debug(), info(), warning(), error(), and critical() methods. Quoting from the docs for Python 3.7.4,

There are three keyword arguments in kwargs which are inspected: exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message.

What this means is, you can use the Python logging library to output a debug(), or other type of message, and the logging library will include the stack trace in its output. With this in mind, we can do the following:

import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

def f():
    a = { 'foo': None }
    # the following line will raise KeyError
    b = a['bar']

def g():
    f()

try:
    g()
except Exception as e:
    logger.error(str(e), exc_info=True)

And it will output:

'bar'
Traceback (most recent call last):
  File "<ipython-input-2-8ae09e08766b>", line 18, in <module>
    g()
  File "<ipython-input-2-8ae09e08766b>", line 14, in g
    f()
  File "<ipython-input-2-8ae09e08766b>", line 10, in f
    b = a['bar']
KeyError: 'bar'

How can I pass selected row to commandLink inside dataTable or ui:repeat?

Thanks to this site by Mkyong, the only solution that actually worked for us to pass a parameter was this

<h:commandLink action="#{user.editAction}">
    <f:param name="myId" value="#{param.id}" />
</h:commandLink>

with

public String editAction() {

  Map<String,String> params = 
            FacesContext.getExternalContext().getRequestParameterMap();
  String idString = params.get("myId");
  long id = Long.parseLong(idString);
  ...
}

Technically, that you cannot pass to the method itself directly, but to the JSF request parameter map.

How to get rows count of internal table in abap?

You can use the following function:

 DESCRIBE TABLE <itab-Name> LINES <variable>

After the call, variable contains the number of rows of the internal table .

HTML checkbox - allow to check only one checkbox

$('#OvernightOnshore').click(function () {
    if ($('#OvernightOnshore').prop("checked") == true) {
        if ($('#OvernightOffshore').prop("checked") == true) {
            $('#OvernightOffshore').attr('checked', false)
        }
    }
})

$('#OvernightOffshore').click(function () {
    if ($('#OvernightOffshore').prop("checked") == true) {
        if ($('#OvernightOnshore').prop("checked") == true) {
            $('#OvernightOnshore').attr('checked', false);
        }
    }
})

This above code snippet will allow you to use checkboxes over radio buttons, but have the same functionality of radio buttons where you can only have one selected.

How do I list / export private keys from a keystore?

Another less-conventional but arguably easier way of doing this is with JXplorer. Although this tool is designed to browse LDAP directories, it has an easy-to-use GUI for manipulating keystores. One such function on the GUI can export private keys from a JKS keystore.

How does internationalization work in JavaScript?

Some of it is native, the rest is available through libraries.

For example Datejs is a good international date library.

For the rest, it's just about language translation, and JavaScript is natively Unicode compatible (as well as all major browsers).

How to concatenate characters in java?

You need to tell the compiler you want to do String concatenation by starting the sequence with a string, even an empty one. Like so:

System.out.println("" + char1 + char2 + char3...);

How to limit file upload type file size in PHP?

Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:

if(isset($_FILES['uploaded_file'])) {
    $errors     = array();
    $maxsize    = 2097152;
    $acceptable = array(
        'application/pdf',
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
    );

    if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
        $errors[] = 'File too large. File must be less than 2 megabytes.';
    }

    if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
        $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
    }

    if(count($errors) === 0) {
        move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
    } else {
        foreach($errors as $error) {
            echo '<script>alert("'.$error.'");</script>';
        }

        die(); //Ensure no more processing is done
    }
}

Look into the docs for move_uploaded_file() (it's called move not store) for more.

Correct way to delete cookies server-side

Use Max-Age=-1 rather than "Expires". It is shorter, less picky about the syntax, and Max-Age takes precedence over Expires anyway.

Change the "No file chosen":

Something like this could work

input(type='file', name='videoFile', value = "Choose a video please")

Type converting slices of interfaces

Here is the official explanation: https://github.com/golang/go/wiki/InterfaceSlice

var dataSlice []int = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
    interfaceSlice[i] = d
}

How do you use subprocess.check_output() in Python?

The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])

To demonstrate, here are my two programs:

py2.py:

import sys
print sys.argv

py3.py:

import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])

First, str('python py2.py') is exactly the same thing as 'python py2.py'—you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python py2.py can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py. Which you're not; you're trying to run, say, /usr/bin/python with first argument py2.py. So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".

Also:

-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

Check if option is selected with jQuery, if not select a default

<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length)
   $("#mySelect").val( 3 );

});
</script>

Emulator in Android Studio doesn't start

I had the same issue in Android Studio 2.3.3 on Mac OS X 10.12.6 and the issue was caused by Android Studio using an old version of HAXM (6.0.3 when it should have been 6.2.1):

$ kextstat | grep intel
  148    0 0xffffff7f8342c000 0x14000    0x14000    com.intel.kext.intelhaxm (6.0.3) 50449AFC-F7C6-38A0-B820-233E8A050FD6 <7 5 4 3 1>

Removing and reintalling HAXM from within Android Studio according to the instructions didn't work: https://software.intel.com/en-us/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-mac-os-x

Instead, download the HAXM installer manually or if that link expires, find it under https://software.intel.com/en-us/android/tools under Intel® Hardware Accelerated Execution Manager (Intel® HAXM).

After running the installer, it now shows that the current version of HAXM is installed:

$ kextstat | grep intel
  169    0 0xffffff7f83472000 0x1d000    0x1d000    com.intel.kext.intelhaxm (6.2.1) 7B6ABC56-699C-3449-A0EC-BEB36C154E3C <7 5 4 3 1>

After upgrading HAXM manually, I'm able to launch x86_64 emulators.


Old answer, which might work instead (note that this didn't work for me for x86_64 images):

Create a new device:

Tools->Android->AVD Manager

+ Create Virtual Device

Tablet -> Nexus 7 -> Next

The Recommended tab should be highlighted.

Even though I had the API Level 25 SDK installed, it showed:

Nougat Download 25 x86 Android 7.1.1 (Google APIs)

So I clicked Download link which seems to have repaired the API Level 25 SDK. I finished creating my new device and it ran fine.

Unfortunately I had already deleted my old device, so if this works for someone else, please leave a comment here to let us know if your original device worked afterwards, thanks!

How to use Checkbox inside Select Option

The best plugin so far is Bootstrap Multiselect

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<title>jQuery Multi Select Dropdown with Checkboxes</title>

<link rel="stylesheet" href="css/bootstrap-3.1.1.min.css" type="text/css" />
<link rel="stylesheet" href="css/bootstrap-multiselect.css" type="text/css" />

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/bootstrap-3.1.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap-multiselect.js"></script>

</head>

<body>

<form id="form1">

<div style="padding:20px">

<select id="chkveg" multiple="multiple">

    <option value="cheese">Cheese</option>
    <option value="tomatoes">Tomatoes</option>
    <option value="mozarella">Mozzarella</option>
    <option value="mushrooms">Mushrooms</option>
    <option value="pepperoni">Pepperoni</option>
    <option value="onions">Onions</option>

</select>

<br /><br />

<input type="button" id="btnget" value="Get Selected Values" />

<script type="text/javascript">

$(function() {

    $('#chkveg').multiselect({

        includeSelectAllOption: true
    });

    $('#btnget').click(function(){

        alert($('#chkveg').val());
    });
});

</script>

</div>

</form>

</body>
</html>

Here's the DEMO

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $('#chkveg').multiselect({_x000D_
    includeSelectAllOption: true_x000D_
  });_x000D_
_x000D_
  $('#btnget').click(function() {_x000D_
    alert($('#chkveg').val());_x000D_
  });_x000D_
});
_x000D_
.multiselect-container>li>a>label {_x000D_
  padding: 4px 20px 3px 20px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://davidstutz.de/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>_x000D_
<link href="https://davidstutz.de/bootstrap-multiselect/docs/css/bootstrap-3.3.2.min.css" rel="stylesheet"/>_x000D_
<link href="https://davidstutz.de/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" rel="stylesheet"/>_x000D_
<script src="https://davidstutz.de/bootstrap-multiselect/docs/js/bootstrap-3.3.2.min.js"></script>_x000D_
_x000D_
<form id="form1">_x000D_
  <div style="padding:20px">_x000D_
_x000D_
    <select id="chkveg" multiple="multiple">_x000D_
      <option value="cheese">Cheese</option>_x000D_
      <option value="tomatoes">Tomatoes</option>_x000D_
      <option value="mozarella">Mozzarella</option>_x000D_
      <option value="mushrooms">Mushrooms</option>_x000D_
      <option value="pepperoni">Pepperoni</option>_x000D_
      <option value="onions">Onions</option>_x000D_
    </select>_x000D_
    _x000D_
    <br /><br />_x000D_
_x000D_
    <input type="button" id="btnget" value="Get Selected Values" />_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

phpinfo() is not working on my CentOS server

Save the page which contains

<?php
    phpinfo();
?>

with the .php extension. Something like info.php, not info.html...

What is the difference between Digest and Basic Authentication?

Basic Authentication use base 64 Encoding for generating cryptographic string which contains the information of username and password.

Digest Access Authentication uses the hashing methodologies to generate the cryptographic result

Logger slf4j advantages of formatting with {} instead of string concatenation

I think from the author's point of view, the main reason is to reduce the overhead for string concatenation.I just read the logger's documentation, you could find following words:

/**
* <p>This form avoids superfluous string concatenation when the logger
* is disabled for the DEBUG level. However, this variant incurs the hidden
* (and relatively small) cost of creating an <code>Object[]</code> before 
  invoking the method,
* even if this logger is disabled for DEBUG. The variants taking
* {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
* arguments exist solely in order to avoid this hidden cost.</p>
*/
*
 * @param format    the format string
 * @param arguments a list of 3 or more arguments
 */
public void debug(String format, Object... arguments);

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I have found the problem.

The problem was that the HTML I was trying to validate was not contained within a <form>...</form> tag.

As soon as I did that, I had a context that was not null.

Jetty: HTTP ERROR: 503/ Service Unavailable

2012-04-20 11:14:32.617:WARN:oejx.XmlParser:FATAL@file:/C:/Users/***/workspace/Test/WEB-INF/web.xml line:1 col:7 : org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.

You Log says, that you web.xml is malformed. Line 1, colum 7. It may be a UTF-8 Byte-Order-Marker

Try to verify, that your xml is wellformed and does not have a BOM. Java doesn't use BOMs.

How does cellForRowAtIndexPath work?

Basically it's designing your cell, The cellforrowatindexpath is called for each cell and the cell number is found by indexpath.row and section number by indexpath.section . Here you can use a label, button or textfied image anything that you want which are updated for all rows in the table. Answer for second question In cell for row at index path use an if statement

In Objective C

-(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

 NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  if(tableView == firstTableView)
  {
      //code for first table view 
      [cell.contentView addSubview: someView];
  }

  if(tableview == secondTableView)
  {
      //code for secondTableView 
      [cell.contentView addSubview: someView];
  }
  return cell;
}

In Swift 3.0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

  if(tableView == firstTableView)   {
     //code for first table view 
  }

  if(tableview == secondTableView)      {
     //code for secondTableView 
  }

  return cell
}

Android: How to use webcam in emulator?

Follow the below steps in Eclipse.

  1. Goto -> AVD Manager
  2. Create/Edit the AVD.
  3. Hardware > New:
  4. Configures camera facing back
  5. Click on the property value and choose = "webcam0".
  6. Once done all the above the webcam should be connected. If it doesnt then you need to check your WebCam drivers.

Check here for more information : How to use web camera in android emulator to capture a live image?

enter image description here

R - Concatenate two dataframes?

You want "rbind".

b$b <- NA
new <- rbind(a, b)

rbind requires the data frames to have the same columns.

The first line adds column b to data frame b.

Results

> a <- data.frame(a=c(0,1,2), b=c(3,4,5), c=c(6,7,8))
> a
  a b c
1 0 3 6
2 1 4 7
3 2 5 8
> b <- data.frame(a=c(9,10,11), c=c(12,13,14))
> b
   a  c
1  9 12
2 10 13
3 11 14
> b$b <- NA
> b
   a  c  b
1  9 12 NA
2 10 13 NA
3 11 14 NA
> new <- rbind(a,b)
> new
   a  b  c
1  0  3  6
2  1  4  7
3  2  5  8
4  9 NA 12
5 10 NA 13
6 11 NA 14

Make a simple fade in animation in Swift?

Swift only solution

Similar to Luca's anwer, I use a UIView extension. Compared to his solution I use DispatchQueue.main.async to make sure animations are done on the main thread, alpha parameter for fading to a specific value and optional duration parameters for cleaner code.

extension UIView {
  func fadeTo(_ alpha: CGFloat, duration: TimeInterval = 0.3) {
    DispatchQueue.main.async {
      UIView.animate(withDuration: duration) {
        self.alpha = alpha
      }
    }
  }

  func fadeIn(_ duration: TimeInterval = 0.3) {
    fadeTo(1.0, duration: duration)
  }

  func fadeOut(_ duration: TimeInterval = 0.3) {
    fadeTo(0.0, duration: duration)
  }
}

How to use it:

// fadeIn() - always animates to alpha = 1.0
yourView.fadeIn()     // uses default duration of 0.3
yourView.fadeIn(1.0)  // uses custom duration (1.0 in this example)

// fadeOut() - always animates to alpha = 0.0
yourView.fadeOut()    // uses default duration of 0.3
yourView.fadeOut(1.0) // uses custom duration (1.0 in this example)

// fadeTo() - used if you want a custom alpha value
yourView.fadeTo(0.5)  // uses default duration of 0.3
yourView.fadeTo(0.5, duration: 1.0)

Can I use a min-height for table, tr or td?

In CSS 2.1, the effect of 'min-height' and 'max-height' on tables, inline tables, table cells, table rows, and row groups is undefined.

So try wrapping the content in a div, and give the div a min-height jsFiddle here

<table cellspacing="0" cellpadding="0" border="0" style="width:300px">
    <tbody>
        <tr>
            <td>
                <div style="min-height: 100px; background-color: #ccc">
                    Hello World !
                </div>
            </td>
            <td>
                <div style="min-height: 100px; background-color: #f00">
                    Good Morning !
                </div>
            </td>
        </tr>
    </tbody>
</table>

How To Pass GET Parameters To Laravel From With GET Method ?

I was struggling with this too and finally got it to work.

routes.php

Route::get('people', 'PeopleController@index');
Route::get('people/{lastName}', 'PeopleController@show');
Route::get('people/{lastName}/{firstName}', 'PeopleController@show');
Route::post('people', 'PeopleController@processForm');

PeopleController.php

namespace App\Http\Controllers ;
use DB ;
use Illuminate\Http\Request ;
use App\Http\Requests ;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;

    public function processForm() {
        $lastName  = Input::get('lastName') ;
        $firstName = Input::get('firstName') ;
        return Redirect::to('people/'.$lastName.'/'.$firstName) ;
    }
    public function show($lastName,$firstName) {
        $qry = 'SELECT * FROM tableFoo WHERE LastName LIKE "'.$lastName.'" AND GivenNames LIKE "'.$firstName.'%" ' ;
        $ppl = DB::select($qry);
        return view('people.show', ['ppl' => $ppl] ) ;
    }

people/show.blade.php

<form method="post" action="/people">
    <input type="text" name="firstName" placeholder="First name">
    <input type="text" name="lastName" placeholder="Last name">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="submit" value="Search">
</form>

Notes:
I needed to pass two input fields into the URI.
I'm not using Eloquent yet, if you are, adjust the database logic accordingly.
And I'm not done securing the user entered data, so chill.
Pay attention to the "_token" hidden form field and all the "use" includes, they are needed.

PS: Here's another syntax that seems to work, and does not need the

use Illuminate\Support\Facades\Input;

.

public function processForm(Request $request) {
    $lastName  = addslashes($request->lastName) ;
    $firstName = addslashes($request->firstName) ;
    //add more logic to validate and secure user entered data before turning it loose in a query
    return Redirect::to('people/'.$lastName.'/'.$firstName) ;
}

Git's famous "ERROR: Permission to .git denied to user"

If problem is coming on windows then remove the Credentials from the Windows history.

  • Go to Credential Manager
  • Go to Windows Credentials
  • Delete the entries under Generic Credentials
  • Try connecting again.This time , it should prompt you for the correct username and password.

enter image description here enter image description here

remove credentials from git

jQuery checkbox event handling

$('#myform input:checkbox').click(
 function(e){
   alert($(this).is(':checked'))
 }
)

Open existing file, append a single line

You can use File.AppendAllText for that:

File.AppendAllText(@"c:\path\file.txt", "text content" + Environment.NewLine);

Java optional parameters

Short version :

Using three dots:

public void foo(Object... x) {
    String first    =  x.length > 0 ? (String)x[0]  : "Hello";
    int duration    =  x.length > 1 ? Integer.parseInt((String) x[1])     : 888;
}   
foo("Hii", ); 
foo("Hii", 146); 

(based on @VitaliiFedorenko's answer)

PHP write file from input to txt

A possible solution:

<?php
$txt = "data.txt"; 
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
    $fh = fopen($txt, 'a'); 
    $txt=$_POST['field1'].' - '.$_POST['field2']; 
    fwrite($fh,$txt); // Write information to the file
    fclose($fh); // Close the file
}
?>

You were closing the script before close de file.

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Arduino Tools > Serial Port greyed out

For a Windows solution I've found that disabling and re-enabling the Arduino in Device Manager, then restarting the Arduino IDE does the trick without fail (no unplugging necessary). Why this error occurs in the first place is beyond me. Perhaps the corresponding method for Linux will fix your problem.

Slightly related (not really), I had an issue with an AVR board a while back which was fixed by setting the device to a new COM port in the driver settings. Again, however you linux bunnies do it, I'm sure it'll be cookies and cream.

Cheers brother,

How I can get and use the header file <graphics.h> in my C++ program?

There is a modern port for this Turbo C graphics interface, it's called WinBGIM, which emulates BGI graphics under MinGW/GCC.

I haven't it tried but it looks promising. For example initgraph creates a window, and from this point you can draw into that window using the good old functions, at the end closegraph deletes the window. It also has some more advanced extensions (eg. mouse handling and double buffering).

When I first moved from DOS programming to Windows I didn't have internet, and I begged for something simple like this. But at the end I had to learn how to create windows and how to handle events and use device contexts from the offline help of the Windows SDK.

What is the difference between `git merge` and `git merge --no-ff`?

The --no-ff option ensures that a fast forward merge will not happen, and that a new commit object will always be created. This can be desirable if you want git to maintain a history of feature branches.             git merge --no-ff vs git merge In the above image, the left side is an example of the git history after using git merge --no-ff and the right side is an example of using git merge where an ff merge was possible.

EDIT: A previous version of this image indicated only a single parent for the merge commit. Merge commits have multiple parent commits which git uses to maintain a history of the "feature branch" and of the original branch. The multiple parent links are highlighted in green.

How to use a TRIM function in SQL Server

Example:

DECLARE @Str NVARCHAR(MAX) = N'
            foo   bar
        Foo           Bar        

'

PRINT '[' + @Str + ']'

DECLARE @StrPrv NVARCHAR(MAX) = N''

WHILE ((@StrPrv <> @Str) AND (@Str IS NOT NULL)) BEGIN
    SET @StrPrv = @Str

    -- Beginning
    IF EXISTS (SELECT 1 WHERE @Str LIKE '[' + CHAR(13) + CHAR(10) + CHAR(9) + ']%')
        SET @Str = LTRIM(RIGHT(@Str, LEN(@Str) - 1))

    -- Ending
    IF EXISTS (SELECT 1 WHERE @Str LIKE '%[' + CHAR(13) + CHAR(10) + CHAR(9) + ']')
        SET @Str = RTRIM(LEFT(@Str, LEN(@Str) - 1))
END

PRINT '[' + @Str + ']'

Result

[
            foo   bar
        Foo           Bar        

]
[foo   bar
        Foo           Bar]

Using fnTrim

Source: https://github.com/reduardo7/fnTrim

SELECT dbo.fnTrim(colName)

adding noise to a signal in python

For those who want to add noise to a multi-dimensional dataset loaded within a pandas dataframe or even a numpy ndarray, here's an example:

import pandas as pd
# create a sample dataset with dimension (2,2)
# in your case you need to replace this with 
# clean_signal = pd.read_csv("your_data.csv")   
clean_signal = pd.DataFrame([[1,2],[3,4]], columns=list('AB'), dtype=float) 
print(clean_signal)
"""
print output: 
    A    B
0  1.0  2.0
1  3.0  4.0
"""
import numpy as np 
mu, sigma = 0, 0.1 
# creating a noise with the same dimension as the dataset (2,2) 
noise = np.random.normal(mu, sigma, [2,2]) 
print(noise)

"""
print output: 
array([[-0.11114313,  0.25927152],
       [ 0.06701506, -0.09364186]])
"""
signal = clean_signal + noise
print(signal)
"""
print output: 
          A         B
0  0.888857  2.259272
1  3.067015  3.906358
""" 

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

Not sure where you add the json but if i do it like this with angular it works without the requestBody: angluar:

    const params: HttpParams = new HttpParams().set('str1','val1').set('str2', ;val2;);
    return this.http.post<any>( this.urlMatch,  params , { observe: 'response' } );

java:

@PostMapping(URL_MATCH)
public ResponseEntity<Void> match(Long str1, Long str2) {
  log.debug("found: {} and {}", str1, str2);
}

How to add border around linear layout except at the bottom?

Save this xml and add as a background for the linear layout....

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <stroke android:width="4dp" android:color="#FF00FF00" /> 
    <solid android:color="#ffffff" /> 
    <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="0dp" /> 
    <corners android:radius="4dp" /> 
</shape>

Hope this helps! :)

How to remove all whitespace from a string?

This way you can remove all spaces from all character variables in your data frame. If you would prefer to choose only some of the variables, use mutateor mutate_at.

library(dplyr)
library(stringr)

remove_all_ws<- function(string){
    return(gsub(" ", "", str_squish(string)))
}

df<-df %>%  mutate_if(is.character, remove_all_ws)

PHP: How to check if image file exists?

Try like this:

$file = '/path/to/foo.txt'; // 'images/'.$file (physical path)

if (file_exists($file)) {
    echo "The file $file exists";
} else {
    echo "The file $file does not exist";
}

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

GCC does actually optimize a*a*a*a*a*a to (a*a*a)*(a*a*a) when a is an integer. I tried with this command:

$ echo 'int f(int x) { return x*x*x*x*x*x; }' | gcc -o - -O2 -S -masm=intel -x c -

There are a lot of gcc flags but nothing fancy. They mean: Read from stdin; use O2 optimization level; output assembly language listing instead of a binary; the listing should use Intel assembly language syntax; the input is in C language (usually language is inferred from input file extension, but there is no file extension when reading from stdin); and write to stdout.

Here's the important part of the output. I've annotated it with some comments indicating what's going on in the assembly language:

; x is in edi to begin with.  eax will be used as a temporary register.
mov  eax, edi  ; temp = x
imul eax, edi  ; temp = x * temp
imul eax, edi  ; temp = x * temp
imul eax, eax  ; temp = temp * temp

I'm using system GCC on Linux Mint 16 Petra, an Ubuntu derivative. Here's the gcc version:

$ gcc --version
gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1

As other posters have noted, this option is not possible in floating point, because floating point arithmetic is not associative.

One DbContext per web request... why?

One thing that's not really addressed in the question or the discussion is the fact that DbContext can't cancel changes. You can submit changes, but you can't clear out the change tree, so if you use a per request context you're out of luck if you need to throw changes away for whatever reason.

Personally I create instances of DbContext when needed - usually attached to business components that have the ability to recreate the context if required. That way I have control over the process, rather than having a single instance forced onto me. I also don't have to create the DbContext at each controller startup regardless of whether it actually gets used. Then if I still want to have per request instances I can create them in the CTOR (via DI or manually) or create them as needed in each controller method. Personally I usually take the latter approach as to avoid creating DbContext instances when they are not actually needed.

It depends from which angle you look at it too. To me the per request instance has never made sense. Does the DbContext really belong into the Http Request? In terms of behavior that's the wrong place. Your business components should be creating your context, not the Http request. Then you can create or throw away your business components as needed and never worry about the lifetime of the context.

How to upload a project to Github

  1. Open Git Bash.
  2. Change the current working directory to your local project.
  3. Initialize the local directory as a Git repository: $ git init
  4. Add the files in your new local repository. This stages them for the first commit: $ git add .
  5. Commit the files that you've staged in your local repository: $ git commit -m "First commit"
  6. At the top of your GitHub repository's Quick Setup page, click to copy the remote repository URL.
  7. In the Command prompt, add the URL for the remote repository where your local repository will be pushed : $ git remote add origin remote repository URL
  8. Push the changes in your local repository to GitHub: $ git push origin master

Struct like objects in Java

It appears that many Java people are not familiar with the Sun Java Coding Guidelines which say it is quite appropriate to use public instance variable when the class is essentially a "Struct", if Java supported "struct" (when there is no behavior).

People tend to think getters and setters are the Java way, as if they are at the heart of Java. This is not so. If you follow the Sun Java Coding Guidelines, using public instance variables in appropriate situations, you are actually writing better code than cluttering it with needless getters and setters.

Java Code Conventions from 1999 and still unchanged.

10.1 Providing Access to Instance and Class Variables

Don't make any instance or class variable public without good reason. Often, instance variables don't need to be explicitly set or gotten-often that happens as a side effect of method calls.

One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it's appropriate to make the class's instance variables public.

http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#177

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

http://docs.oracle.com/javase/1.3/docs/guide/collections/designfaq.html#28

How to create a Jar file in Netbeans

Please do right click on the project and go to properties. Then go to Build and Packaging. You can see the JAR file location that is produced by defualt setting of netbean in the dist directory.

Reset all changes after last commit in git

There are two commands which will work in this situation,

root>git reset --hard HEAD~1

root>git push -f

For more git commands refer this page

Is the sizeof(some pointer) always equal to four?

In general, sizeof(pretty much anything) will change when you compile on different platforms. On a 32 bit platform, pointers are always the same size. On other platforms (64 bit being the obvious example) this can change.

Dynamically create checkbox with JQuery from text input

<div id="cblist">
    <input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />

<script type="text/javascript">
$(document).ready(function() {
    $('#btnSave').click(function() {
        addCheckbox($('#txtName').val());
    });
});

function addCheckbox(name) {
   var container = $('#cblist');
   var inputs = container.find('input');
   var id = inputs.length+1;

   $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
   $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>

Postgres could not connect to server

One of the cause will be make sure the size of the disk is not full execute the command postmaster -D path of the postgres

SQL to find the number of distinct values in a column

An sql sum of column_name's unique values and sorted by the frequency:

SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name ORDER BY 2 DESC;

Why and when to use angular.copy? (Deep Copy)

Javascript passes variables by reference, this means that:

var i = [];
var j = i;
i.push( 1 );

Now because of by reference part i is [1], and j is [1] as well, even though only i was changed. This is because when we say j = i javascript doesn't copy the i variable and assign it to j but references i variable through j.

Angular copy lets us lose this reference, which means:

var i = [];
var j = angular.copy( i );
i.push( 1 );

Now i here equals to [1], while j still equals to [].

There are situations when such kind of copy functionality is very handy.

Reorder / reset auto increment primary key

for InnoDB, do this (this will remove all records from a table, make a bakcup first):

SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS ;
SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION ;
SET NAMES utf8 ;
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 ;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 ;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' ;
SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 ;
/* ================================================= */

drop table tablename;
CREATE TABLE `tablename` (
   table structure here!

) ENGINE=InnoDB AUTO_INCREMENT=  ai number to reset  DEFAULT CHARSET= char set here;



/* ================================================= */
SET SQL_MODE=@OLD_SQL_MODE ;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS ;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS ;
SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT ;
SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS ;
SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION ;
SET SQL_NOTES=@OLD_SQL_NOTES ;

CSS3 equivalent to jQuery slideUp and slideDown?

You could do something like this:

#youritem .fade.in {
    animation-name: fadeIn;
}

#youritem .fade.out {
    animation-name: fadeOut;
}

@keyframes fadeIn {
    0% {
        opacity: 0;
        transform: translateY(startYposition);
    } 
    100% {
        opacity: 1;
        transform: translateY(endYposition);
    }
}

@keyframes fadeOut {
    0% {
        opacity: 1;
        transform: translateY(startYposition);
    } 
    100% {
        opacity: 0;
        transform: translateY(endYposition);
    }
}

Example - Slide and Fade:

This slides and animates the opacity - not based on height of the container, but on the top/coordinate. View example

Example - Auto-height/No Javascript: Here is a live sample, not needing height - dealing with automatic height and no javascript.
View example

PostgreSQL: Drop PostgreSQL database through command line

Try this. Note there's no database specified - it just runs "on the server"

psql -U postgres -c "drop database databasename"

If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts;

then for every id you see, run this:

ROLLBACK PREPARED '<id>';

What is the difference between concurrency and parallelism?

Imagine learning a new programming language by watching a video tutorial. You need to pause the video, apply what been said in code then continue watching. That's concurrency.

Now you're a professional programmer. And you enjoy listening to calm music while coding. That's Parallelism.

As Andrew Gerrand said in GoLang Blog

Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.

Enjoy.

Can I specify maxlength in css?

I don't think you can, and CSS is supposed to describe how the page looks not what it does, so even if you could, it's not really how you should be using it.

Perhaps you should think about using JQuery to apply common functionality to your form components?

Makefile, header dependencies

The following works for me:

DEPS := $(OBJS:.o=.d)

-include $(DEPS)

%.o: %.cpp
    $(CXX) $(CFLAGS) -MMD -c -o $@ $<

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

Had the same Issue when i decided to install another version of Android Studio, what worked for me was:

  • Creating a new project with the current version of Android Studio just to go check the classpath version at the project level build.gradle inside the dependencies section, at the time it was this:

classpath 'com.android.tools.build:gradle:3.5.0-rc01'

Copied that line and replaced it on the project i was working on.

Remove all whitespace in a string

To remove only spaces use str.replace:

sentence = sentence.replace(' ', '')

To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:

sentence = ''.join(sentence.split())

or a regular expression:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

If you want to only remove whitespace from the beginning and end you can use strip:

sentence = sentence.strip()

You can also use lstrip to remove whitespace only from the beginning of the string, and rstrip to remove whitespace from the end of the string.

How to create a button programmatically?

override func viewDidLoad() {

super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150));
    var image = UIImage(named: "BattleMapSplashScreen.png");
    imageView.image = image;
    self.view.addSubview(imageView);

}

Passing variable number of arguments around

You can use inline assembly for the function call. (in this code I assume the arguments are characters).

void format_string(char *fmt, ...);
void debug_print(int dbg_level, int numOfArgs, char *fmt, ...)
    {
        va_list argumentsToPass;
        va_start(argumentsToPass, fmt);
        char *list = new char[numOfArgs];
        for(int n = 0; n < numOfArgs; n++)
            list[n] = va_arg(argumentsToPass, char);
        va_end(argumentsToPass);
        for(int n = numOfArgs - 1; n >= 0; n--)
        {
            char next;
            next = list[n];
            __asm push next;
        }
        __asm push fmt;
        __asm call format_string;
        fprintf(stdout, fmt);
    }

Command not found error in Bash variable assignment

In the interactive mode everything looks fine:

$ str="Hello World"
$ echo $str
Hello World

Obviously(!) as Johannes said, no space around =. In case there is any space around = then in the interactive mode it gives errors as

No command 'str' found

Read a XML (from a string) and get some fields - Problems reading XML

Or use the XmlSerializer class.

XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));

How to cast Object to its actual type?

Casting to actual type is easy:

void MyMethod(Object obj) {
    ActualType actualyType = (ActualType)obj;
}

Are there constants in JavaScript?

If it is worth mentioning, you can define constants in angular using $provide.constant()

angularApp.constant('YOUR_CONSTANT', 'value');

filename.whl is not supported wheel on this platform

I am using Python2.7 and Windows 64-bit system. I was getting the same error for lxml-3.8.0-cp27-cp27m-win_amd64.whl while doing pip install lxml-3.8.0-cp27-cp27m-win_amd64.whl Run pip install lxml and it auto-detected and successfully installed the win32 version (though my system is Windows-64bit)

C:\Python27>pip install lxml
Collecting lxml
  Downloading lxml-3.8.0-cp27-cp27m-win32.whl (2.9MB)
    100% |################################| 2.9MB 20kB/s
Installing collected packages: lxml
Successfully installed lxml-3.8.0

So, I will go with @1man's answer.

Select from multiple tables without a join?

Union will fetch data by row not column,So If your are like me who is looking for fetching column data from two different table with no relation and without join.
In my case I am fetching state name and country name by id. Instead of writing two query you can do this way.

select 
   (
   select s.state_name from state s where s.state_id=3
   ) statename,
   (
   select c.description from country c where c.id=5
   ) countryname
   from dual;   

where dual is a dummy table with single column--anything just require table to view

How to detect a route change in Angular?

simple answer for Angular 8.*

constructor(private route:ActivatedRoute) {
  console.log(route);
}

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

use mysql_real_escape_string() instead of mysqli_real_escape_string()

like so:

$username = mysql_real_escape_string($_POST['username']);

Given a filesystem path, is there a shorter way to extract the filename without its extension?

Try this:

string fileName = Path.GetFileNameWithoutExtension(@"C:\Program Files\hello.txt");

This will return "hello" for fileName.

Checking if a collection is null or empty in Groovy

There is indeed a Groovier Way.

if(members){
    //Some work
}

does everything if members is a collection. Null check as well as empty check (Empty collections are coerced to false). Hail Groovy Truth. :)

Chrome desktop notification example

<!DOCTYPE html>

<html>

<head>
<title>Hello!</title>
<script>
function notify(){

if (Notification.permission !== "granted") {
Notification.requestPermission();
}
 else{
var notification = new Notification('hello', {
  body: "Hey there!",
});
notification.onclick = function () {
  window.open("http://google.com");
};
}
}
</script>
</head>

<body>
<button onclick="notify()">Notify</button>
</body>

How do I make an Event in the Usercontrol and have it handled in the Main Form?

one of the easy way to do that is use landa function without any problem like

userControl_Material1.simpleButton4.Click += (s, ee) =>
            {
                Save_mat(mat_global);
            };

Set attribute without value

You can do it without jQuery!

Example:

_x000D_
_x000D_
document.querySelector('button').setAttribute('disabled', '');
_x000D_
<button>My disabled button!</button>
_x000D_
_x000D_
_x000D_

To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.

From MDN Element.setAttribute()

How can I solve a connection pool problem between ASP.NET and SQL Server?

You have leaked connections on your code. You may try to use using to certify that you're closing them.

using (SqlConnection sqlconnection1 = new SqlConnection(“Server=.\\SQLEXPRESS ;Integrated security=sspi;connection timeout=5”)) 
{
    sqlconnection1.Open();
    SqlCommand sqlcommand1 = sqlconnection1.CreateCommand();
    sqlcommand1.CommandText = “raiserror (‘This is a fake exception’, 17,1)”;
    sqlcommand1.ExecuteNonQuery();  //this throws a SqlException every time it is called.
    sqlconnection1.Close(); //Still never gets called.
} // Here sqlconnection1.Dispose is _guaranteed_

https://blogs.msdn.microsoft.com/angelsb/2004/08/25/connection-pooling-and-the-timeout-expired-exception-faq/

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

How can I programmatically get the MAC address of an iphone

Now iOS 7 devices – are always returning a MAC address of 02:00:00:00:00:00.

So better use [UIDevice identifierForVendor].

so better to call this method to get app specific unique key

Category will more suitable

import "UIDevice+Identifier.h"

- (NSString *) identifierForVendor1
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)]) {
        return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    }
    return @"";
}

Now call above method to get unique address

NSString *like_UDID=[NSString stringWithFormat:@"%@",
                [[UIDevice currentDevice] identifierForVendor1]];

NSLog(@"%@",like_UDID);

check if array is empty (vba excel)

The problem with VBA is that there are both dynamic and static arrays...

Dynamic Array Example

Dim myDynamicArray() as Variant

Static Array Example

Dim myStaticArray(10) as Variant
Dim myOtherStaticArray(0 To 10) as Variant

Using error handling to check if the array is empty works for a Dynamic Array, but a static array is by definition not empty, there are entries in the array, even if all those entries are empty.

So for clarity's sake, I named my function "IsZeroLengthArray".

    Public Function IsZeroLengthArray(ByRef subject() As Variant) As Boolean
        'Tell VBA to proceed if there is an error to the next line.
        On Error Resume Next
    
        Dim UpperBound As Integer
        Dim ErrorNumber As Long
        Dim ErrorDescription As String
        Dim ErrorSource As String
    
        'If the array is empty this will throw an error because a zero-length 
          'array has no UpperBound (or LowerBound).
        'This only works for dynamic arrays.  If this was a static array there 
          'would be both an upper and lower bound.
        UpperBound = UBound(subject)


        'Store the Error Number and then clear the Error object 
         'because we want VBA to treat unintended errors normally
        ErrorNumber = Err.Number
        ErrorDescription = Err.Description
        ErrorSource = Err.Source
        Err.Clear
        On Error GoTo 0
    
        'Check the Error Object to see if we have a "subscript out of range" error.  
          'If we do (the number is 9) then we can assume that the array is zero-length.
        If ErrorNumber = 9 Then
            IsZeroLengthArray = True

        'If the Error number is something else then 9 we want to raise 
        'that error again...
        ElseIf ErrorNumber <> 0 Then
            Err.Raise ErrorNumber, ErrorSource, ErrorDescription

        'If the Error number is 0 then we have no error and can assume that the
         'array is not of zero-length
        ElseIf ErrorNumber = 0 Then
            IsZeroLengthArray = False
        End If
    End Function

I hope that this helps others as it helped me.

OpenCV with Network Cameras

Use ffmpeglib to connect to the stream.

These functions may be useful. But take a look in the docs

av_open_input_stream(...);
av_find_stream_info(...);
avcodec_find_decoder(...);
avcodec_open(...);
avcodec_alloc_frame(...);

You would need a little algo to get a complete frame, which is available here

http://www.dranger.com/ffmpeg/tutorial01.html

Once you get a frame you could copy the video data (for each plane if needed) into a IplImage which is an OpenCV image object.

You can create an IplImage using something like...

IplImage *p_gray_image = cvCreateImage(size, IPL_DEPTH_8U, 1);

Once you have an IplImage, you could perform all sorts of image operations available in the OpenCV lib

How do you manually execute SQL commands in Ruby On Rails using NuoDB

res = ActiveRecord::Base.connection_pool.with_connection { |con| con.exec_query( "SELECT 1;" ) }

The above code is an example for

  1. executing arbitrary SQL on your database-connection
  2. returning the connection back to the connection pool afterwards

What is the correct way to free memory in C#

Objects are eligable for garbage collection once they go out of scope become unreachable (thanks ben!). The memory won't be freed unless the garbage collector believes you are running out of memory.

For managed resources, the garbage collector will know when this is, and you don't need to do anything.

For unmanaged resources (such as connections to databases or opened files) the garbage collector has no way of knowing how much memory they are consuming, and that is why you need to free them manually (using dispose, or much better still the using block)

If objects are not being freed, either you have plenty of memory left and there is no need, or you are maintaining a reference to them in your application, and therefore the garbage collector will not free them (in case you actually use this reference you maintained)

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

How do I delete NuGet packages that are not referenced by any project in my solution?

Solution 1

Use the powershell pipeline to get packages and remove in single statement like this

Get-Package | Uninstall-Package

Solution 2

if you want to uninstall selected packages follow these steps

  1. Use GetPackages to get the list of packages
  2. Download Nimble text software
  3. Copy the output of GetPackages in NimbleText(For each row in the list window)
  4. Set Column Seperator to ( if required
  5. Type Uninstall-Package $0 (Substitute using pattern window)
  6. Copy the results and paste them in Package Manage Console

That be all folks.

PHP/MySQL: How to create a comment section in your website

This is my way i do comments (I think its secure):

<h1>Comment's:</h1>
<?php 
$i  = addslashes($_POST['a']);
$ip = addslashes($_POST['b']);
$a  = addslashes($_POST['c']);
$b  = addslashes($_POST['d']);
if(isset($i) & isset($ip) & isset($a) & isset($b))
{
    $r = mysql_query("SELECT COUNT(*) FROM $db.ban WHERE ip=$ip"); //Check if banned
    $r = mysql_fetch_array($r);
    if(!$r[0]) //Phew, not banned
    {
        if(mysql_query("INSERT INTO $db.com VALUES ($a, $b, $ip, $i)"))
        {
            ?>
            <script type="text/javascript">
                window.location="/index.php?id=".<?php echo $i; ?>;
            </script>
            <?php
        }
        else echo "Error, in mysql query";  
    }
    else echo "Error, You are banned.";
}
$x = mysql_query("SELECT * FROM $db.com WHERE i=$i");
while($r = mysql_fetch_object($x) echo '<div class="c">'.$r->a.'<p>'.$row->b.'</p> </div>';

?>  
<h1>Leave a comment, pl0x:</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="hidden" name="a" value="<?php $echo $_GET['id']; ?>" />
    <input type="hidden" name="b" value="<?php $echo $_SERVER['REMOTE_ADDR']; ?>" />
    <input type="text" name="c" value="Name"/></br>
    <textarea name="d">
    </textarea>
    <input type="submit" />
</form>

This does it all in one page (This is only the comments section, some configuration is needed)

What's the C# equivalent to the With statement in VB?

Aside from object initializers (usable only in constructor calls), the best you can get is:

var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

128M == 134217728, the number you are seeing.

The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.

Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.

Center a column using Twitter Bootstrap 3

My approach to center columns is to use display: inline-block for columns and text-align: center for the container parent.

You just have to add the CSS class 'centered' to the row.

HTML:

<div class="container-fluid">
  <div class="row centered">
    <div class="col-sm-4 col-md-4">
        Col 1
    </div>
    <div class="col-sm-4 col-md-4">
        Col 2
    </div>
    <div class="col-sm-4 col-md-4">
        Col 3
    </div>
  </div>
</div>

CSS:

.centered {
   text-align: center;
   font-size: 0;
}
.centered > div {
   float: none;
   display: inline-block;
   text-align: left;
   font-size: 13px;
}

JSFiddle: http://jsfiddle.net/steyffi/ug4fzcjd/

MessageBox with YesNoCancel - No & Cancel triggers same event

Just to add a bit to Darin's example, the below will show an icon with the boxes. http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=vs.110).aspx

Dim result = MessageBox.Show("Message To Display", "MessageBox Title", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

If result = DialogResult.Cancel Then

    MessageBox.Show("Cancel Button Pressed", "MessageBox Title",MessageBoxButtons.OK , MessageBoxIcon.Exclamation)

ElseIf result = DialogResult.No Then

    MessageBox.Show("No Button Pressed", "MessageBox Title", MessageBoxButtons.OK, MessageBoxIcon.Error)

ElseIf result = DialogResult.Yes Then

    MessageBox.Show("Yes Button Pressed", "MessageBox Title", MessageBoxButtons.OK, MessageBoxIcon.Information)

End If

Taking inputs with BufferedReader in Java

BufferedReader#read reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.

            String s= inp.readLine();
            int[] m= new int[2];
            String[] s1 = inp.readLine().split(" ");
            m[0]=Integer.parseInt(s1[0]);
            m[1]=Integer.parseInt(s1[1]);

            // Checking whether I am taking the inputs correctly
            System.out.println(s);
            System.out.println(m[0]);
            System.out.println(m[1]);

You can check also Scanner vs. BufferedReader.

Get all validation errors from Angular 2 FormGroup

Based on the @MixerOID response, here is my final solution as a component (maybe I create a library). I also support FormArray's:

import {Component, ElementRef, Input, OnInit} from '@angular/core';
import {FormArray, FormGroup, ValidationErrors} from '@angular/forms';
import {TranslateService} from '@ngx-translate/core';

interface AllValidationErrors {
  controlName: string;
  errorName: string;
  errorValue: any;
}

@Component({
  selector: 'app-form-errors',
  templateUrl: './form-errors.component.html',
  styleUrls: ['./form-errors.component.scss']
})
export class FormErrorsComponent implements OnInit {

  @Input() form: FormGroup;
  @Input() formRef: ElementRef;
  @Input() messages: Array<any>;

  private errors: AllValidationErrors[];

  constructor(
    private translateService: TranslateService
  ) {
    this.errors = [];
    this.messages = [];
  }

  ngOnInit() {
    this.form.valueChanges.subscribe(() => {
      this.errors = [];
      this.calculateErrors(this.form);
    });

    this.calculateErrors(this.form);
  }

  calculateErrors(form: FormGroup | FormArray) {
    Object.keys(form.controls).forEach(field => {
      const control = form.get(field);
      if (control instanceof FormGroup || control instanceof FormArray) {
        this.errors = this.errors.concat(this.calculateErrors(control));
        return;
      }

      const controlErrors: ValidationErrors = control.errors;
      if (controlErrors !== null) {
        Object.keys(controlErrors).forEach(keyError => {
          this.errors.push({
            controlName: field,
            errorName: keyError,
            errorValue: controlErrors[keyError]
          });
        });
      }
    });

    // This removes duplicates
    this.errors = this.errors.filter((error, index, self) => self.findIndex(t => {
      return t.controlName === error.controlName && t.errorName === error.errorName;
    }) === index);
    return this.errors;
  }

  getErrorMessage(error) {
    switch (error.errorName) {
      case 'required':
        return this.translateService.instant('mustFill') + ' ' + this.messages[error.controlName];
      default:
        return 'unknown error ' + error.errorName;
    }
  }
}

And the HTML:

<div *ngIf="formRef.submitted">
  <div *ngFor="let error of errors" class="text-danger">
    {{getErrorMessage(error)}}
  </div>
</div>

Usage:

<app-form-errors [form]="languageForm"
                 [formRef]="formRef"
                 [messages]="{language: 'Language'}">
</app-form-errors>

Is there a label/goto in Python?

Though there isn't any code equivalent to goto/label in Python, you could still get such functionality of goto/label using loops.

Lets take a code sample shown below where goto/label can be used in a arbitrary language other than python.

String str1 = 'BACK'

label1:
    print('Hello, this program contains goto code\n')
    print('Now type BACK if you want the program to go back to the above line of code. Or press the ENTER key if you want the program to continue with further lines of code')
    str1 = input()

if str1 == 'BACK'
    {
        GoTo label1
    }
print('Program will continue\nBla bla bla...\nBla bla bla...\nBla bla bla...')

Now the same functionality of the above code sample can be achieved in python by using a while loop as shown below.

str1 = 'BACK'

while str1 == 'BACK':
        print('Hello, this is a python program containing python equivalent code for goto code\n')
        print('Now type BACK if you want the program to go back to the above line of code. Or press the ENTER key if you want the program to continue with further lines of code')
        str1 = input()
print('Program will continue\nBla bla bla...\nBla bla bla...\nBla bla bla...')

Generate sha256 with OpenSSL and C++

std based

#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>

using namespace std;

#include <openssl/sha.h>
string sha256(const string str)
{
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, str.c_str(), str.size());
    SHA256_Final(hash, &sha256);
    stringstream ss;
    for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        ss << hex << setw(2) << setfill('0') << (int)hash[i];
    }
    return ss.str();
}

int main() {
    cout << sha256("1234567890_1") << endl;
    cout << sha256("1234567890_2") << endl;
    cout << sha256("1234567890_3") << endl;
    cout << sha256("1234567890_4") << endl;
    return 0;
}

CodeIgniter htaccess and URL rewrite issues

I had similar issue on Linux Ubuntu 14.

After constant 403 error messages in the browser and reading all answers here I could not figure out what was wrong.

Then I have reached for apache's error log, and finally got a hint that was a bit unexpected but perfectly logical.

the codeIgniter main folder had no X permission on folder rendering everything else unreadable by web server.

chmod ugo+x yourCodeIgniterFolder

fixed first problem. Killed 403 errors.

But then I started getting error 500.

Culprit was a wrong settings line in .htaccess

Then I started getting php errors.

Culprit was same problem as main folder no X flag for 'others' permission for inner folders in application and system folders.

My two cents for this question: READ Apache Error.log.

But, also be aware of security issues. CodeIgniter suggests moving application and system folder out of web space therefore changing permissions shall be taken with a great care if these folders remain in web space.

Another thing worth mentioning here is that I have unzipped downloaded CodeIgniter archive directly to the web space. Folder permissions are likely created straight from the archive. As given they are secure, but folder access issue (on unix like systems) is not mentioned in CodeIgniter manual https://codeigniter.com/user_guide/installation/index.html and perhaps it shall be mentioned there with guidelines on how to relax security for CodeIgniter to work while keeping security tight for the production system (some security hints are already there in the manual as mentioned beforehand).

Add element to a JSON file?

You can do this.

data[0]['f'] = var

Jquery change background color

This is how it should be:

Code:

$(function(){
  $("button").mouseover(function(){
    var $p = $("#P44");
    $p.stop()
      .css("background-color","yellow")
      .hide(1500, function() {
          $p.css("background-color","red")
            .show(1500);
      });
  });
});

Demo: http://jsfiddle.net/p7w9W/2/

Explanation:

You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p> there you shouldn't include a class in your selector.

I also enhanced your code (caching of the jQuery object, chaining, etc.)

Update: As suggested by VKolev the color is now changing when the item is hidden.

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

enter image description here enter image description here

My fix was similar to Gerard Grundy's. In creating a custom UITableViewCell using an XIB, I had mistakenly applied the Custom Class name to the File's Owner instead of to the UITableViewCell. Applying the class to the UITableViewCell on the canvas and connecting my IBOutlet properties to it solved the issue.

How to insert data into SQL Server

string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();

Viewing all `git diffs` with vimdiff

For people who want to use another diff tool not listed in git, say with nvim. here is what I ended up using:

git config --global alias.d difftool -x <tool name>

In my case, I set <tool name> to nvim -d and invoke the diff command with

git d <file>

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

Here's a project that combines the best parts (pros) of both redux-saga and redux-thunk: you can handle all side-effects on sagas while getting a promise by dispatching the corresponding action: https://github.com/diegohaz/redux-saga-thunk

class MyComponent extends React.Component {
  componentWillMount() {
    // `doSomething` dispatches an action which is handled by some saga
    this.props.doSomething().then((detail) => {
      console.log('Yaay!', detail)
    }).catch((error) => {
      console.log('Oops!', error)
    })
  }
}

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

that's why Idon't like NULL values in the database at all.
I hope you are having it for a reason.

if ($_POST['location_id'] === '') {
  $location_id = 'NULL';
} else {
  $location_id = "'".$_POST['location_id']."'";
}
$notes = mysql_real_escape_string($_POST['notes']);
$ipid  = mysql_real_escape_string($_POST['ipid']);

$sql="UPDATE addresses 
    SET notes='$notes', location_id=$location_id
    WHERE ipid = '$ipid'";

echo $sql; //to see different queries this code produces
// and difference between NULL and 'NULL' in the query

How to import a bak file into SQL Server Express

To do this via TSQL (ssms query window or sqlcmd.exe) just run:

RESTORE DATABASE MyDatabase FROM DISK='c:\backups\MyDataBase1.bak'

To do it via GUI - open SSMS, right click on Databases and follow the steps below

enter image description here enter image description here

Linq on DataTable: select specific column into datatable, not whole table

Here I get only three specific columns from mainDataTable and use the filter

DataTable checkedParams = mainDataTable.Select("checked = true").CopyToDataTable()
.DefaultView.ToTable(false, "lagerID", "reservePeriod", "discount");

Redefine tab as 4 spaces

To define this on a permanent basis for the current user, create (or edit) the .vimrc file:

$ vim ~/.vimrc

Then, paste the configuration below into the file. Once vim is restarted, the tab settings will apply.

set tabstop=4       " The width of a TAB is set to 4.
                    " Still it is a \t. It is just that
                    " Vim will interpret it to be having
                    " a width of 4.

set shiftwidth=4    " Indents will have a width of 4

set softtabstop=4   " Sets the number of columns for a TAB

set expandtab       " Expand TABs to spaces

How to customize Bootstrap 3 tab color

On the selector .nav-tabs > li > a:hover add !important to the background-color.

_x000D_
_x000D_
.nav-tabs{_x000D_
  background-color:#161616;_x000D_
}_x000D_
.tab-content{_x000D_
    background-color:#303136;_x000D_
    color:#fff;_x000D_
    padding:5px_x000D_
}_x000D_
.nav-tabs > li > a{_x000D_
  border: medium none;_x000D_
}_x000D_
.nav-tabs > li > a:hover{_x000D_
  background-color: #303136 !important;_x000D_
    border: medium none;_x000D_
    border-radius: 0;_x000D_
    color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul class="nav nav-tabs" id="myTab">_x000D_
    <li class="active"><a data-toggle="tab" href="#search">SEARCH</a></li>_x000D_
    <li><a data-toggle="tab" href="#advanced">ADVANCED</a></li>_x000D_
</ul>_x000D_
<div class="tab-content">_x000D_
    <div id="search" class="tab-pane fade in active">_x000D_
        Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel,_x000D_
        butcher voluptate nisi qui._x000D_
    </div>_x000D_
    <div id="advanced" class="tab-pane fade">_x000D_
        Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna._x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between _self, _top, and _parent in the anchor tag target attribute

Section 6.16 Frame target names in the HTML 4.01 spec defines the meanings, but it is partly outdated. It refers to “windows”, whereas HTML5 drafts more realistically speak about “browsing contexts”, since modern browsers often use tabs instead of windows in this context.

Briefly, _self is the default (current browsing context, i.e. current window or tab), so it is useful only to override a <base target=...> setting. The value _parent refers to the frameset that is the parent of the current frame, whereas _top “breaks out of all frames” and opens the linked document in the entire browser window.

pip install returning invalid syntax

Try running cmd as administrator (in the menu that pops up after right-clicking) and/or entering "pip" alone and then

Convert a string into an int

This is the simple solution for converting string to int

NSString *strNum = @"10";
int num = [strNum intValue];

but when you are getting value from the textfield then,

int num = [txtField.text intValue];

where txtField is an outlet of UITextField

Java: how do I initialize an array size if it's unknown?

If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.

import java.util.Scanner;

public class ArrayModify {

    public static void main(String[] args) {
        int[] list;
        String st;
        String[] stNew;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9 
        st = scan.nextLine();
        stNew = st.split("\\s+");
        list = new int[stNew.length]; // Sets array size to 5

        for (int i = 0; i < stNew.length; i++){
            list[i] =  Integer.parseInt(stNew[i]);
            System.out.println("You Enterred: " + list[i]);
        }
    }
}

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

In my case it was libjpeg. All I had to do was run brew reinstall libjpeg and everything just worked!

What port is used by Java RMI connection?

All the answers so far are incorrect. The Registry normally uses port 1099, but you can change it. But that's not the end of the story. Remote objects also use ports, and not necessarily 1099.

If you don't specify a port when exporting, RMI uses a random port. The solution is therefore to specify a port number when exporting. And this is a port that needs opening in the firewall, if any.

  • In the case where your remote object extends UnicastRemoteObject, have its constructor call super(port) with some non-zero port number.

  • In the case where it doesn't extend UnicastRemoteObject, provide a non-zero port number to UnicastRemoteObject.exportObject().

There are several wrinkles to this.

  • If you aren't using socket factories, and you provide a non-zero port number when exporting your first remote object, RMI will automatically share that port with subsequently exported remote objects without specified port numbers, or specifying zero. That first remote object includes a Registry created with LocateRegistry.createRegistry(). So if you create a Registry on port 1099, all other objects exported from that JVM can share port 1099.

  • If you are using socket factories, your RMIServerSocketFactory must have a sensible implementation of equals() for port sharing to work, i.e. one that doesn't just rely on object identity via == or Object.equals().

  • If either you don't provide a server socket factory, or you do provide one with a sensible equals() method, but not both, you can use the same non-zero explicit port number for all remote objects, e.g. createRegistry(1099) followed by any number of super(1099) or exportObject(..., 1099) calls.

Switch statement for greater-than/less-than

An alternative:

var scrollleft = 1000;
switch (true)
{
    case (scrollleft > 1000):
      alert('gt');
      break;
    case (scrollleft <= 1000):
      alert('lt');
      break; 
}

Demo: http://jsfiddle.net/UWYzr/

Loading inline content using FancyBox

Just something I found for Wordpress users,

As obvious as it sounds, If your div is returning some AJAX content based on say a header that would commonly link out to a new post page, some tutorials will say to return false since you're returning the post data on the same page and the return would prevent the page from moving. However if you return false, you also prevent Fancybox2 from doing it's thing as well. I spent hours trying to figure that stupid simple thing out.

So for these kind of links, just make sure that the href property is the hashed (#) div you wish to select, and in your javascript, make sure that you do not return false since you no longer will need to.

Simple I know ^_^

Draw in Canvas by finger, Android

I think it's important to add a thing, if you use the layout inflation that constructor in the drawview is not correct, add these constructors in the class:

public DrawingView(Context c, AttributeSet attrs) {
    super(c, attrs);
    ...
}

public DrawingView(Context c, AttributeSet attrs, int defStyle) {
    super(c, attrs, defStyle);
    ...
}

or the android system fails to inflate the layout file. I hope this could to help.

How to check string length with JavaScript

Basically: assign a keyup handler to the <textarea> element, in it count the length of the <textarea> and write the count to a separate <div> if its length is shorter than a minimum value.

Here's is an example-

_x000D_
_x000D_
var min = 15;_x000D_
document.querySelector('#tst').onkeyup = function(e){_x000D_
 document.querySelector('#counter').innerHTML = _x000D_
               this.value.length < min _x000D_
               ? (min - this.value.length)+' to go...'_x000D_
               : '';_x000D_
}_x000D_
    
_x000D_
body {font: normal 0.8em verdana, arial;}_x000D_
#counter {color: grey}
_x000D_
<textarea id="tst" cols="60" rows="10"></textarea>_x000D_
<div id="counter"></div>
_x000D_
_x000D_
_x000D_

How to reset postgres' primary key sequence when it falls out of sync?

So I can tell there aren't enough opinions or reinvented wheels in this thread, so I decided to spice things up.

Below is a procedure that:

  • is focused (only affects) on sequences that are associated with tables
  • works for both SERIAL and GENERATED AS IDENTITY columns
  • works for good_column_names and "BAD_column_123" names
  • automatically assigns the respective sequences' defined start value if the table is empty
  • allows for a specific sequences to be affected only (in schema.table.column notation)
  • has a preview mode
CREATE OR REPLACE PROCEDURE pg_reset_all_table_sequences(
    IN commit_mode BOOLEAN DEFAULT FALSE
,   IN mask_in TEXT DEFAULT NULL
) AS
$$
DECLARE
    sql_reset TEXT;
    each_sec RECORD;
    new_val TEXT;
BEGIN

sql_reset :=
$sql$
SELECT setval(pg_get_serial_sequence('%1$s.%2$s', '%3$s'), coalesce(max("%3$s"), %4$s), false) FROM %1$s.%2$s;
$sql$
;

FOR each_sec IN (

    SELECT
        quote_ident(table_schema) as table_schema
    ,   quote_ident(table_name) as table_name
    ,   column_name
    ,   coalesce(identity_start::INT, seqstart) as min_val
    FROM information_schema.columns
    JOIN pg_sequence ON seqrelid = pg_get_serial_sequence(quote_ident(table_schema)||'.'||quote_ident(table_name) , column_name)::regclass
    WHERE
        (is_identity::boolean OR column_default LIKE 'nextval%') -- catches both SERIAL and IDENTITY sequences

    -- mask on column address (schema.table.column) if supplied
    AND coalesce( table_schema||'.'||table_name||'.'||column_name = mask_in, TRUE )
)
LOOP

IF commit_mode THEN
    EXECUTE format(sql_reset, each_sec.table_schema, each_sec.table_name, each_sec.column_name, each_sec.min_val) INTO new_val;
    RAISE INFO 'Resetting sequence for: %.% (%) to %'
        ,   each_sec.table_schema
        ,   each_sec.table_name
        ,   each_sec.column_name
        ,   new_val
    ;
ELSE
    RAISE INFO 'Sequence found for resetting: %.% (%)'
        ,   each_sec.table_schema
        ,   each_sec.table_name
        ,   each_sec.column_name
    ;
END IF
;

END LOOP;

END
$$
LANGUAGE plpgsql
;

to preview:

call pg_reset_all_table_sequences();

to commit:

call pg_reset_all_table_sequences(true);

to specify only your target table:

call pg_reset_all_table_sequences('schema.table.column');

How to find SQL Server running port?

Try to enable the protocol by: Configuration Manger > SQL server Network Configuration > Protocols for MSSQLSERVER > properties of TCP/IP

Git ignore file for Xcode projects

Regarding the 'build' directory exclusion -

If you place your build files in a different directory from your source, as I do, you don't have the folder in the tree to worry about.

This also makes life simpler for sharing your code, preventing bloated backups, and even when you have dependencies to other Xcode projects (while require the builds to be in the same directory as each other)

You can grab an up-to-date copy from the Github gist https://gist.github.com/708713

My current .gitignore file is

# Mac OS X
*.DS_Store

# Xcode
*.pbxuser
*.mode1v3
*.mode2v3
*.perspectivev3
*.xcuserstate
project.xcworkspace/
xcuserdata/

# Generated files
*.o
*.pyc


#Python modules
MANIFEST
dist/
build/

# Backup files
*~.nib

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

You can't remove hidden without also removing system.

You want:

cd mydir
attrib -H -S /D /S

That will remove the hidden and system attributes from all the files/folders inside of your current directory.

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

@watson

On windows forms it is available, at the top of the class put

  static void Main(string[] args)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
       //other stuff here
    }

since windows is single threaded, its all you need, in the event its a service you need to put it right above the call to the service (since there is no telling what thread you'll be on).

using System.Security.Principal 

is also needed.

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

$("#ValuationName").bind("keypress", function (event) {
    if (event.charCode!=0) {
        var regex = new RegExp("^[a-zA-Z ]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    }
});

Create view with primary key?

This worked for me..

select ROW_NUMBER() over (order by column_name_of your choice ) as pri_key, the other columns of the view

Linking static libraries to other static libraries

On Linux or MingW, with GNU toolchain:

ar -M <<EOM
    CREATE libab.a
    ADDLIB liba.a
    ADDLIB libb.a
    SAVE
    END
EOM
ranlib libab.a

Of if you do not delete liba.a and libb.a, you can make a "thin archive":

ar crsT libab.a liba.a libb.a

On Windows, with MSVC toolchain:

lib.exe /OUT:libab.lib liba.lib libb.lib

How to change FontSize By JavaScript?

<span id="span">HOI</span>
<script>
   var span = document.getElementById("span");
   console.log(span);

   span.style.fontSize = "25px";
   span.innerHTML = "String";
</script>

You have two errors in your code:

  1. document.getElementById - This retrieves the element with an Id that is "span", you did not specify an id on the span-element.

  2. Capitals in Javascript - Also you forgot the capital of Size.

Can't get Gulp to run: cannot find module 'gulp-util'

Same issue here and whatever I tried after searching around, did not work. Until I saw a remark somewhere about global or local installs. Looking in:

C:\Users\YourName\AppData\Roaming\npm\gulp

I indeed found an outdated version. So I reinstalled gulp with:

npm install gulp --global

That magically solved my problem.

How to compare two List<String> to each other?

I discovered that SequenceEqual is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).

I wanted to test this myself so I created two methods:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
    {
        return list1.SequenceEqual(list2);
    }

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
    {
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
                return false;
        }

        return true;
    }

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

As it turns out, with two lists containing 32k strings, over 100 executions:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.

Edit:

I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920