Programs & Examples On #Point

A point is a fundamental geometry entity.

Java: Calculating the angle between two points in degrees

The javadoc for Math.atan(double) is pretty clear that the returning value can range from -pi/2 to pi/2. So you need to compensate for that return value.

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

Convert Pixels to Points

Using wxPython on Mac to get the correct DPI as follows:

    from wx import ScreenDC
    from wx import Size

    size: Size = ScreenDC().GetPPI()
    print(f'x-DPI: {size.GetWidth()} y-DPI: {size.GetHeight()}')

This yields:

x-DPI: 72 y-DPI: 72

Thus, the formula is:

points: int = (pixelNumber * 72) // 72

How can I label points in this scatterplot?

You should use labels attribute inside plot function and the value of this attribute should be the vector containing the values that you want for each point to have.

SQL using sp_HelpText to view a stored procedure on a linked server

Little addition in answer if you have different user rather then dbo then do like this.

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText '[user].[storedProcName]'

MySQL select one column DISTINCT, with corresponding other columns

As pointed out by fyrye, the accepted answer pertains to older versions of MySQL in which ONLY_FULL_GROUP_BY had not yet been introduced. With MySQL 8.0.17 (used in this example), unless you disable ONLY_FULL_GROUP_BY you would get the following error message:

mysql> SELECT id, firstName, lastName FROM table_name GROUP BY firstName;

ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'mydatabase.table_name.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

One way to work around this not mentioned by fyrye, but described in https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html, is to apply the ANY_VALUE() function to the columns which are not in the GROUP BY clause (id and lastName in this example):

mysql> SELECT ANY_VALUE(id) as id, firstName, ANY_VALUE(lastName) as lastName FROM table_name GROUP BY firstName;
+----+-----------+----------+
| id | firstName | lastName |
+----+-----------+----------+
|  1 | John      | Doe      |
|  2 | Bugs      | Bunny    |
+----+-----------+----------+
2 rows in set (0.01 sec)

As written in the aforementioned docs,

In this case, MySQL ignores the nondeterminism of address values within each name group and accepts the query. This may be useful if you simply do not care which value of a nonaggregated column is chosen for each group. ANY_VALUE() is not an aggregate function, unlike functions such as SUM() or COUNT(). It simply acts to suppress the test for nondeterminism.

Routing with multiple Get methods in ASP.NET Web API

After reading lots of answers finally I figured out.

First, I added 3 different routes into WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "ApiById",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
        constraints: new { id = @"^[0-9]+$" }
    );

    config.Routes.MapHttpRoute(
        name: "ApiByName",
        routeTemplate: "api/{controller}/{action}/{name}",
        defaults: null,
        constraints: new { name = @"^[a-z]+$" }
    );

    config.Routes.MapHttpRoute(
        name: "ApiByAction",
        routeTemplate: "api/{controller}/{action}",
        defaults: new { action = "Get" }
    );
}

Then, removed ActionName, Route, etc.. from the controller functions. So basically this is my controller;

// GET: api/Countries/5
[ResponseType(typeof(Countries))]
//[ActionName("CountryById")]
public async Task<IHttpActionResult> GetCountries(int id)
{
    Countries countries = await db.Countries.FindAsync(id);
    if (countries == null)
    {
        return NotFound();
    }

    return Ok(countries);
}

// GET: api/Countries/tur
//[ResponseType(typeof(Countries))]
////[Route("api/CountriesByName/{anyString}")]
////[ActionName("CountriesByName")]
//[HttpGet]
[ResponseType(typeof(Countries))]
//[ActionName("CountryByName")]
public async Task<IHttpActionResult> GetCountriesByName(string name)
{
    var countries = await db.Countries
            .Where(s=>s.Country.ToString().StartsWith(name))
            .ToListAsync();

    if (countries == null)
    {
        return NotFound();
    }

    return Ok(countries);
}

Now I am able to run with following url samples(with name and with id);

http://localhost:49787/api/Countries/GetCountriesByName/France

http://localhost:49787/api/Countries/1

How to Correctly Use Lists in R?

Regarding vectors and the hash/array concept from other languages:

  1. Vectors are the atoms of R. Eg, rpois(1e4,5) (5 random numbers), numeric(55) (length-55 zero vector over doubles), and character(12) (12 empty strings), are all "basic".

  2. Either lists or vectors can have names.

    > n = numeric(10)
    > n
     [1] 0 0 0 0 0 0 0 0 0 0
    > names(n)
    NULL
    > names(n) = LETTERS[1:10]
    > n
    A B C D E F G H I J 
    0 0 0 0 0 0 0 0 0 0
    
  3. Vectors require everything to be the same data type. Watch this:

    > i = integer(5)
    > v = c(n,i)
    > v
    A B C D E F G H I J           
    0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
    > class(v)
    [1] "numeric"
    > i = complex(5)
    > v = c(n,i)
    > class(v)
    [1] "complex"
    > v
       A    B    C    D    E    F    G    H    I    J                          
    0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i 0+0i
    
  4. Lists can contain varying data types, as seen in other answers and the OP's question itself.

I've seen languages (ruby, javascript) in which "arrays" may contain variable datatypes, but for example in C++ "arrays" must be all the same datatype. I believe this is a speed/efficiency thing: if you have a numeric(1e6) you know its size and the location of every element a priori; if the thing might contain "Flying Purple People Eaters" in some unknown slice, then you have to actually parse stuff to know basic facts about it.

Certain standard R operations also make more sense when the type is guaranteed. For example cumsum(1:9) makes sense whereas cumsum(list(1,2,3,4,5,'a',6,7,8,9)) does not, without the type being guaranteed to be double.


As to your second question:

Lists can be returned from functions even though you never passed in a List when you called the function

Functions return different data types than they're input all the time. plot returns a plot even though it doesn't take a plot as an input. Arg returns a numeric even though it accepted a complex. Etc.

(And as for strsplit: the source code is here.)

How do I break out of a loop in Perl?

Oh, I found it. You use last instead of break

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Add repository annotation before your DAO Implementation Class. example:

@Repository
public class EmpDAOImpl extends BaseNamedParameterJdbcDaoSupportUAM 
implements EmpDAO{ 
}

SQL SERVER, SELECT statement with auto generate row id

Select (Select count(y.au_lname) from dbo.authors y
where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,
x.au_lname,x.au_fname from authors x group by au_lname,au_fname
order by Counterid --Alternatively that can be done which is equivalent as above..

How can I set the color of a selected row in DataGrid

The above solution left blue border around each cell in my case.

This is the solution that worked for me. It is very simple, just add this to your DataGrid. You can change it from a SolidColorBrush to any other brush such as linear gradient.

<DataGrid.Resources>
  <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
                   Color="#FF0000"/>
</DataGrid.Resources>

Fast way of finding lines in one file that are not in another?

Like konsolebox suggested, the posters grep solution

grep -v -f file2 file1

actually works great (fast) if you simply add the -F option, to treat the patterns as fixed strings instead of regular expressions. I verified this on a pair of ~1000 line file lists I had to compare. With -F it took 0.031 s (real), while without it took 2.278 s (real), when redirecting grep output to wc -l.

These tests also included the -x switch, which are necessary part of the solution in order to ensure totally accuracy in cases where file2 contains lines which match part of, but not all of, one or more lines in file1.

So a solution that does not require the inputs to be sorted, is fast, flexible (case sensitivity, etc) is:

grep -F -x -v -f file2 file1

This doesn't work with all versions of grep, for example it fails in macOS, where a line in file 1 will be shown as not present in file 2, even though it is, if it matches another line that is a substring of it. Alternatively you can install GNU grep on macOS in order to use this solution.

How to check whether java is installed on the computer

If java not installed yet. Then program written by java cannot be run to check if java is installed or not.

check output from CalledProcessError

If you want to get stdout and stderr back (including extracting it from the CalledProcessError in the event that one occurs), use the following:

import subprocess

command = ["ls", "-l"]
try:
    output = subprocess.check_output(command, stderr=subprocess.STDOUT).decode()
    success = True 
except subprocess.CalledProcessError as e:
    output = e.output.decode()
    success = False

print(output)

This is Python 2 and 3 compatible.

If your command is a string rather than an array, prefix this with:

import shlex
command = shlex.split(command)

How to shuffle an ArrayList

Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.

Sublime 3 - Set Key map for function Goto Definition

I'm using Sublime portable version (for Windows) and this (placing the mousemap in SublimeText\Packages\User folder) did not work for me.

I had to place the mousemap file in SublimeText\Data\Packages\User folder to get it to work where SublimeText is the installation directory for my portable version. Data\Packages\User is where I found the keymap file as well.

Examples for string find in Python

if x is a string and you search for y which also a string their is two cases : case 1: y is exist in x so x.find(y) = the index (the position) of the y in x . case 2: y is not exist so x.find (y) = -1 this mean y is not found in x.

Convert Pandas Series to DateTime in a DataFrame

You can't: DataFrame columns are Series, by definition. That said, if you make the dtype (the type of all the elements) datetime-like, then you can access the quantities you want via the .dt accessor (docs):

>>> df["TimeReviewed"] = pd.to_datetime(df["TimeReviewed"])
>>> df["TimeReviewed"]
205  76032930   2015-01-24 00:05:27.513000
232  76032930   2015-01-24 00:06:46.703000
233  76032930   2015-01-24 00:06:56.707000
413  76032930   2015-01-24 00:14:24.957000
565  76032930   2015-01-24 00:23:07.220000
Name: TimeReviewed, dtype: datetime64[ns]
>>> df["TimeReviewed"].dt
<pandas.tseries.common.DatetimeProperties object at 0xb10da60c>
>>> df["TimeReviewed"].dt.year
205  76032930    2015
232  76032930    2015
233  76032930    2015
413  76032930    2015
565  76032930    2015
dtype: int64
>>> df["TimeReviewed"].dt.month
205  76032930    1
232  76032930    1
233  76032930    1
413  76032930    1
565  76032930    1
dtype: int64
>>> df["TimeReviewed"].dt.minute
205  76032930     5
232  76032930     6
233  76032930     6
413  76032930    14
565  76032930    23
dtype: int64

If you're stuck using an older version of pandas, you can always access the various elements manually (again, after converting it to a datetime-dtyped Series). It'll be slower, but sometimes that isn't an issue:

>>> df["TimeReviewed"].apply(lambda x: x.year)
205  76032930    2015
232  76032930    2015
233  76032930    2015
413  76032930    2015
565  76032930    2015
Name: TimeReviewed, dtype: int64

Getting a File's MD5 Checksum in Java

Google guava provides a new API. Find the one below :

public static HashCode hash(File file,
            HashFunction hashFunction)
                     throws IOException

Computes the hash code of the file using hashFunction.

Parameters:
    file - the file to read
    hashFunction - the hash function to use to hash the data
Returns:
    the HashCode of all of the bytes in the file
Throws:
    IOException - if an I/O error occurs
Since:
    12.0

How to use 'git pull' from the command line?

Open up your git bash and type

echo $HOME

This shall be the same folder as you get when you open your command window (cmd) and type

echo %USERPROFILE%

And – of course – the .ssh folder shall be present on THAT directory.

justify-content property isn't working

I was having a lot of problems with justify-content, and I figured out the problem was "margin: 0 auto"

The auto part overrides the justify-content so its always displayed according to the margin and not to the justify-content.

C# Debug - cannot start debugging because the debug target is missing

Go to Project > properties > Debug Tab and set the Launch to "Project"

PHP Function Comments

You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().

http://www.php.net/manual/en/reflectionclass.getdoccomment.php

Check if element is visible in DOM

Use the same code as jQuery does:

jQuery.expr.pseudos.visible = function( elem ) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

So, in a function:

function isVisible(e) {
    return !!( e.offsetWidth || e.offsetHeight || e.getClientRects().length );
}

Works like a charm in my Win/IE10, Linux/Firefox.45, Linux/Chrome.52...

Many thanks to jQuery without jQuery!

How to check if a String contains any letter from a to z?

You could use RegEx:

Regex.IsMatch(hello, @"^[a-zA-Z]+$");

If you don't like that, you can use LINQ:

hello.All(Char.IsLetter);

Or, you can loop through the characters, and use isAlpha:

Char.IsLetter(character);

A non-blocking read on a subprocess.PIPE in Python

On Unix-like systems and Python 3.5+ there's os.set_blocking which does exactly what it says.

import os
import time
import subprocess

cmd = 'python3', '-c', 'import time; [(print(i), time.sleep(1)) for i in range(5)]'
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
os.set_blocking(p.stdout.fileno(), False)
start = time.time()
while True:
    # first iteration always produces empty byte string in non-blocking mode
    for i in range(2):    
        line = p.stdout.readline()
        print(i, line)
        time.sleep(0.5)
    if time.time() > start + 5:
        break
p.terminate()

This outputs:

1 b''
2 b'0\n'
1 b''
2 b'1\n'
1 b''
2 b'2\n'
1 b''
2 b'3\n'
1 b''
2 b'4\n'

With os.set_blocking commented it's:

0 b'0\n'
1 b'1\n'
0 b'2\n'
1 b'3\n'
0 b'4\n'
1 b''

Angularjs: input[text] ngChange fires while the value is changing

Override the default input onChange behavior (call the function only when control loss focus and value was change)

NOTE: ngChange is not similar to the classic onChange event it firing the event while the value is changing This directive stores the value of the element when it gets the focus
On blurs it checks whether the new value has changed and if so it fires the event

@param {String} - function name to be invoke when the "onChange" should be fired

@example < input my-on-change="myFunc" ng-model="model">

angular.module('app', []).directive('myOnChange', function () { 
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            myOnChange: '='
        },
        link: function (scope, elm, attr) {
            if (attr.type === 'radio' || attr.type === 'checkbox') {
                return;
            }
            // store value when get focus
            elm.bind('focus', function () {
                scope.value = elm.val();

            });

            // execute the event when loose focus and value was change
            elm.bind('blur', function () {
                var currentValue = elm.val();
                if (scope.value !== currentValue) {
                    if (scope.myOnChange) {
                        scope.myOnChange();
                    }
                }
            });
        }
    };
});

Strings in C, how to get subString

#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '\0'; // place the null terminator

What's the difference between unit, functional, acceptance, and integration tests?

Unit Testing - As the name suggests, this method tests at the object level. Individual software components are tested for any errors. Knowledge of the program is needed for this test and the test codes are created to check if the software behaves as it is intended to.

Functional Testing - Is carried out without any knowledge of the internal working of the system. The tester will try to use the system by just following requirements, by providing different inputs and testing the generated outputs. This test is also known as closed-box testing or black-box.

Acceptance Testing - This is the last test that is conducted before the software is handed over to the client. It is carried out to ensure that the developed software meets all the customer requirements. There are two types of acceptance testing - one that is carried out by the members of the development team, known as internal acceptance testing (Alpha testing), and the other that is carried out by the customer or end user known as (Beta testing)

Integration Testing - Individual modules that are already subjected to unit testing are integrated with one another. Generally the two approachs are followed :

1) Top-Down
2) Bottom-Up

Why is this rsync connection unexpectedly closed on Windows?

The trick for me was I had ssh conflict.

I have Git installed on my Windows path, which includes ssh. cwrsync also installs ssh.

The trick is to have make a batch file to set the correct paths:

rsync.bat

@echo off
SETLOCAL
SET CWRSYNCHOME=c:\commands\cwrsync
SET HOME=c:\Users\Petah\
SET CWOLDPATH=%PATH%
SET PATH=%CWRSYNCHOME%\bin;%PATH%
%~dp0\cwrsync\bin\rsync.exe %*

On Windows you can type where ssh to check if this is an issue. You will get something like this:

where ssh
C:\Program Files (x86)\Git\bin\ssh.exe
C:\Program Files\cwRsync\ssh.exe

How do I create a GUI for a windows application using C++?

For such a simple application even MFC would be overkill. If don't want to introduce another dependency just do it in plain vanilla Win32. It will be easier for you if you have never used MFC.

Check out the classic "Programming Windows" by Charles Petzold or some online tutorial (e.g. http://www.winprog.org/tutorial/) and you are ready to go.

Reference — What does this symbol mean in PHP?

Spaceship Operator <=> (Added in PHP 7)

Examples for <=> Spaceship operator (PHP 7, Source: PHP Manual):

Integers, Floats, Strings, Arrays & objects for Three-way comparison of variables.

// Integers
echo 10 <=> 10; // 0
echo 10 <=> 20; // -1
echo 20 <=> 10; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
// Comparison is case-sensitive
echo "B" <=> "a"; // -1

echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1

// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1

// Objects
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 0

$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "c"]; 
echo $a <=> $b; // -1

$a = (object) ["a" => "c"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 1

// only values are compared
$a = (object) ["a" => "b"]; 
$b = (object) ["b" => "b"]; 
echo $a <=> $b; // 1

Git push results in "Authentication Failed"

in Android studio canary build 3.1+, if you are using Android studio git tool, than you can use following :

  • Click on Android Studio
  • Click on Preferences...
  • GO in VersionControl -> Github
  • Here Change Auth type to Password
  • This step will require you to enter login and password. Enter you github user name a s login and github password as password.
  • Click on Test Button.

If connection is successful , than you are done and you can use android studio github UI client.

Viewing unpushed Git commits

This worked better for me:

git log --oneline @{upstream}..

or:

git log --oneline origin/(remotebranch)..

Linux: is there a read or recv from socket with timeout?

You can use the setsockopt function to set a timeout on receive operations:

SO_RCVTIMEO

Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementations allow this option to be set.

// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

Reportedly on Windows this should be done before calling bind. I have verified by experiment that it can be done either before or after bind on Linux and OS X.

Convert Datetime column from UTC to local time in select statement

Using new SQL Server 2016 opportunities:

CREATE FUNCTION ToLocalTime(@dtUtc datetime, @timezoneId nvarchar(256))
RETURNS datetime
AS BEGIN

return @dtUtc AT TIME ZONE 'UTC' AT TIME ZONE @timezoneId

/* -- second way, faster

return SWITCHOFFSET(@dtUtc , DATENAME(tz, @dtUtc AT TIME ZONE @timezoneId))

*/

/* -- third way

declare @dtLocal datetimeoffset
set @dtLocal = @dtUtc AT TIME ZONE @timezoneId
return dateadd(minute, DATEPART (TZoffset, @dtLocal), @dtUtc)

*/

END
GO

But clr procedure works in 5 times faster :'-(

Pay attention that Offset for one TimeZone can change to winter or summer time. For example

select cast('2017-02-08 09:00:00.000' as datetime) AT TIME ZONE 'Eastern Standard Time'
select cast('2017-08-08 09:00:00.000' as datetime) AT TIME ZONE 'Eastern Standard Time'

results:

2017-02-08 09:00:00.000 -05:00
2017-08-08 09:00:00.000 -04:00

You can't just add constant offset.

How to detect installed version of MS-Office?

Why not check HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\[office.exe], where [office.exe] stands for particular office product exe-filename, e.g. winword.exe, excel.exe etc. There you get path to executable and check version of that file.

How to check version of the file: in C++ / in C#

Any criticism towards such approach?

vi/vim editor, copy a block (not usual action)

I found the below command much more convenient. If you want to copy lines from 6 to 12 and paste from the current cursor position.

:6,12 co .

If you want to copy lines from 6 to 12 and paste from 100th line.

:6,12t100

Source: https://www.reddit.com/r/vim/comments/8i6vbd/efficient_ways_of_copying_few_lines/

Calendar Recurring/Repeating Events - Best Storage Method

Why not use a mechanism similar to Apache cron jobs? http://en.wikipedia.org/wiki/Cron

For calendar\scheduling I'd use slightly different values for "bits" to accommodate standard calendar reoccurence events - instead of [day of week (0 - 7), month (1 - 12), day of month (1 - 31), hour (0 - 23), min (0 - 59)]

-- I'd use something like [Year (repeat every N years), month (1 - 12), day of month (1 - 31), week of month (1-5), day of week (0 - 7)]

Hope this helps.

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

The solution without div is used a pseudo element like ::after into first td in row with min-height. Save your HTML clean.

table tr td:first-child::after {
   content: "";
   display: inline-block;
   vertical-align: top;
   min-height: 60px;
}

Fitting polynomial model to data in R

Regarding the question 'can R help me find the best fitting model', there is probably a function to do this, assuming you can state the set of models to test, but this would be a good first approach for the set of n-1 degree polynomials:

polyfit <- function(i) x <- AIC(lm(y~poly(x,i)))
as.integer(optimize(polyfit,interval = c(1,length(x)-1))$minimum)

Notes

  • The validity of this approach will depend on your objectives, the assumptions of optimize() and AIC() and if AIC is the criterion that you want to use,

  • polyfit() may not have a single minimum. check this with something like:

    for (i in 2:length(x)-1) print(polyfit(i))
    
  • I used the as.integer() function because it is not clear to me how I would interpret a non-integer polynomial.

  • for testing an arbitrary set of mathematical equations, consider the 'Eureqa' program reviewed by Andrew Gelman here

Update

Also see the stepAIC function (in the MASS package) to automate model selection.

SQL Server - Convert date field to UTC

If you have to convert dates other than today to different timezones you have to deal with daylight savings. I wanted a solution that could be done without worrying about database version, without using stored functions and something that could easily be ported to Oracle.

I think Warren is on the right track with getting the correct dates for daylight time, but to make it more useful for multiple time zone and different rules for countries and even the rule that changed in the US between 2006 and 2007, here a variation on the above solution. Notice that this not only has us time zones, but also central Europe. Central Europe follow the last sunday of april and last sunday of october. You will also notice that the US in 2006 follows the old first sunday in april, last sunday in october rule.

This SQL code may look a little ugly, but just copy and paste it into SQL Server and try it. Notice there are 3 section for years, timezones and rules. If you want another year, just add it to the year union. Same for another time zone or rule.

select yr, zone, standard, daylight, rulename, strule, edrule, yrstart, yrend,
    dateadd(day, (stdowref + stweekadd), stmonthref) dstlow,
    dateadd(day, (eddowref + edweekadd), edmonthref)  dsthigh
from (
  select yrs.yr, z.zone, z.standard, z.daylight, z.rulename, r.strule, r.edrule, 
    yrs.yr + '-01-01 00:00:00' yrstart,
    yrs.yr + '-12-31 23:59:59' yrend,
    yrs.yr + r.stdtpart + ' ' + r.cngtime stmonthref,
    yrs.yr + r.eddtpart + ' ' + r.cngtime edmonthref,
    case when r.strule in ('1', '2', '3') then case when datepart(dw, yrs.yr + r.stdtpart) = '1' then 0 else 8 - datepart(dw, yrs.yr + r.stdtpart) end
    else (datepart(dw, yrs.yr + r.stdtpart) - 1) * -1 end stdowref,
    case when r.edrule in ('1', '2', '3') then case when datepart(dw, yrs.yr + r.eddtpart) = '1' then 0 else 8 - datepart(dw, yrs.yr + r.eddtpart) end
    else (datepart(dw, yrs.yr + r.eddtpart) - 1) * -1 end eddowref,
    datename(dw, yrs.yr + r.stdtpart) stdow,
    datename(dw, yrs.yr + r.eddtpart) eddow,
    case when r.strule in ('1', '2', '3') then (7 * CAST(r.strule AS Integer)) - 7 else 0 end stweekadd,
    case when r.edrule in ('1', '2', '3') then (7 * CAST(r.edrule AS Integer)) - 7 else 0 end edweekadd
from (
    select '2005' yr union select '2006' yr -- old us rules
    UNION select '2007' yr UNION select '2008' yr UNION select '2009' yr UNION select '2010' yr UNION select '2011' yr
    UNION select '2012' yr UNION select '2013' yr UNION select '2014' yr UNION select '2015' yr UNION select '2016' yr
    UNION select '2017' yr UNION select '2018' yr UNION select '2019' yr UNION select '2020' yr UNION select '2021' yr
    UNION select '2022' yr UNION select '2023' yr UNION select '2024' yr UNION select '2025' yr UNION select '2026' yr
) yrs
cross join (
    SELECT 'ET' zone, '-05:00' standard, '-04:00' daylight, 'US' rulename
    UNION SELECT 'CT' zone, '-06:00' standard, '-05:00' daylight, 'US' rulename
    UNION SELECT 'MT' zone, '-07:00' standard, '-06:00' daylight, 'US' rulename
    UNION SELECT 'PT' zone, '-08:00' standard, '-07:00' daylight, 'US' rulename
    UNION SELECT 'CET' zone, '+01:00' standard, '+02:00' daylight, 'EU' rulename
) z
join (
    SELECT 'US' rulename, '2' strule, '-03-01' stdtpart, '1' edrule, '-11-01' eddtpart, 2007 firstyr, 2099 lastyr, '02:00:00' cngtime
    UNION SELECT 'US' rulename, '1' strule, '-04-01' stdtpart, 'L' edrule, '-10-31' eddtpart, 1900 firstyr, 2006 lastyr, '02:00:00' cngtime
    UNION SELECT  'EU' rulename, 'L' strule, '-03-31' stdtpart, 'L' edrule, '-10-31' eddtpart, 1900 firstyr, 2099 lastyr, '01:00:00' cngtime
) r on r.rulename = z.rulename
    and datepart(year, yrs.yr) between firstyr and lastyr
) dstdates

For the rules, use 1, 2, 3 or L for first, second, third or last sunday. The date part gives the month and depending on the rule, the first day of the month or the last day of the month for rule type L.

I put the above query into a view. Now, anytime I want a date with the time zone offset or converted to UTC time, I just join to this view and select get the date in the date format. Instead of datetime, I converted these to datetimeoffset.

select createdon, dst.zone
    , case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end pacificoffsettime
    , TODATETIMEOFFSET(createdon, case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end) pacifictime
    , SWITCHOFFSET(TODATETIMEOFFSET(createdon, case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end), '+00:00')  utctime
from (select '2014-01-01 12:00:00' createdon union select '2014-06-01 12:00:00' createdon) photos
left join US_DAYLIGHT_DATES dst on createdon between yrstart and yrend and zone = 'PT'

How do I access an access array item by index in handlebars?

The following, with an additional dot before the index, works just as expected. Here, the square brackets are optional when the index is followed by another property:

{{people.[1].name}}
{{people.1.name}}

However, the square brackets are required in:

{{#with people.[1]}}
  {{name}}
{{/with}}

In the latter, using the index number without the square brackets would get one:

Error: Parse error on line ...:
...     {{#with people.1}}                
-----------------------^
Expecting 'ID', got 'INTEGER'

As an aside: the brackets are (also) used for segment-literal syntax, to refer to actual identifiers (not index numbers) that would otherwise be invalid. More details in What is a valid identifier?

(Tested with Handlebars in YUI.)

2.xx Update

You can now use the get helper for this:

(get people index)

although if you get an error about index needing to be a string, do:

(get people (concat index ""))

How to set the matplotlib figure default size in ipython notebook?

I believe the following work in version 0.11 and above. To check the version:

$ ipython --version

It may be worth adding this information to your question.

Solution:

You need to find the file ipython_notebook_config.py. Depending on your installation process this should be in somewhere like

.config/ipython/profile_default/ipython_notebook_config.py

where .config is in your home directory.

Once you have located this file find the following lines

# Subset of matplotlib rcParams that should be different for the inline backend.
# c.InlineBackend.rc = {'font.size': 10, 'figure.figsize': (6.0, 4.0), 'figure.facecolor': 'white', 'savefig.dpi': 72, 'figure.subplot.bottom': 0.125, 'figure.edgecolor': 'white'}

Uncomment this line c.InlineBack... and define your default figsize in the second dictionary entry.

Note that this could be done in a python script (and hence interactively in IPython) using

pylab.rcParams['figure.figsize'] = (10.0, 8.0)

What is Ad Hoc Query?

Ad hoc queries are those that are not already defined that are not needed on a regular basis, so they're not included in the typical set of reports or queries

Spring REST Service: how to configure to remove null objects in json response

I've found a solution through configuring the Spring container, but it's still not exactly what I wanted.

I rolled back to Spring 3.0.5, removed and in it's place I changed my config file to:

    <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>
        </list>
    </property>
</bean>


<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="jacksonSerializationConfig" />
    <property name="targetMethod" value="setSerializationInclusion" />
    <property name="arguments">
        <list>
            <value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
        </list>
    </property>
</bean>

This is of course similar to responses given in other questions e.g.

configuring the jacksonObjectMapper not working in spring mvc 3

The important thing to note is that mvc:annotation-driven and AnnotationMethodHandlerAdapter cannot be used in the same context.

I'm still unable to get it working with Spring 3.1 and mvc:annotation-driven though. A solution that uses mvc:annotation-driven and all the benefits that accompany it would be far better I think. If anyone could show me how to do this, that would be great.

How to change an element's title attribute using jQuery

Another option, if you prefer, would be to get the DOM element from the jQuery object and use standard DOM accessors on it:

$("#myElement")[0].title = "new title value";

The "jQuery way", as mentioned by others, is to use the attr() method. See the API documentation for attr() here.

Format Date time in AngularJS

we can format the date on view side in angular is very easy....please check the below example:

{{dt | date : "dd-MM-yyyy"}}

Click in OK button inside an Alert (Selenium IDE)

Use chooseOkOnNextConfirmation() to dismiss the alert and getAlert() to verify that it has been shown (and optionally grab its text for verification).

selenium.chooseOkOnNextConfirmation();  // prepares Selenium to handle next alert
selenium.click(locator);
String alertText = selenium.getAlert(); // verifies that alert was shown
assertEquals("This is a popup window", alertText);
...

How to suppress "unused parameter" warnings in C?

You can use gcc/clang's unused attribute, however I use these macros in a header to avoid having gcc specific attributes all over the source, also having __attribute__ everywhere is a bit verbose/ugly.

#ifdef __GNUC__
#  define UNUSED(x) UNUSED_ ## x __attribute__((__unused__))
#else
#  define UNUSED(x) UNUSED_ ## x
#endif

#ifdef __GNUC__
#  define UNUSED_FUNCTION(x) __attribute__((__unused__)) UNUSED_ ## x
#else
#  define UNUSED_FUNCTION(x) UNUSED_ ## x
#endif

Then you can do...

void foo(int UNUSED(bar)) { ... }

I prefer this because you get an error if you try use bar in the code anywhere so you can't leave the attribute in by mistake.

and for functions...

static void UNUSED_FUNCTION(foo)(int bar) { ... }

Note 1):
As far as I know, MSVC doesn't have an equivalent to __attribute__((__unused__)).

Note 2):
The UNUSED macro won't work for arguments which contain parenthesis,
so if you have an argument like float (*coords)[3] you can't do,
float UNUSED((*coords)[3]) or float (*UNUSED(coords))[3], This is the only downside to the UNUSED macro I found so far, in these cases I fall back to (void)coords;

hexadecimal string to byte array in python

def hex2bin(s):
    hex_table = ['0000', '0001', '0010', '0011',
                 '0100', '0101', '0110', '0111',
                 '1000', '1001', '1010', '1011',
                 '1100', '1101', '1110', '1111']
    bits = ''
    for i in range(len(s)):
        bits += hex_table[int(s[i], base=16)]
    return bits

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

First off, if you're starting a new project, go with Entity Framework ("EF") - it now generates much better SQL (more like Linq to SQL does) and is easier to maintain and more powerful than Linq to SQL ("L2S"). As of the release of .NET 4.0, I consider Linq to SQL to be an obsolete technology. MS has been very open about not continuing L2S development further.

1) Performance

This is tricky to answer. For most single-entity operations (CRUD) you will find just about equivalent performance with all three technologies. You do have to know how EF and Linq to SQL work in order to use them to their fullest. For high-volume operations like polling queries, you may want to have EF/L2S "compile" your entity query such that the framework doesn't have to constantly regenerate the SQL, or you can run into scalability issues. (see edits)

For bulk updates where you're updating massive amounts of data, raw SQL or a stored procedure will always perform better than an ORM solution because you don't have to marshal the data over the wire to the ORM to perform updates.

2) Speed of Development

In most scenarios, EF will blow away naked SQL/stored procs when it comes to speed of development. The EF designer can update your model from your database as it changes (upon request), so you don't run into synchronization issues between your object code and your database code. The only time I would not consider using an ORM is when you're doing a reporting/dashboard type application where you aren't doing any updating, or when you're creating an application just to do raw data maintenance operations on a database.

3) Neat/Maintainable code

Hands down, EF beats SQL/sprocs. Because your relationships are modeled, joins in your code are relatively infrequent. The relationships of the entities are almost self-evident to the reader for most queries. Nothing is worse than having to go from tier to tier debugging or through multiple SQL/middle tier in order to understand what's actually happening to your data. EF brings your data model into your code in a very powerful way.

4) Flexibility

Stored procs and raw SQL are more "flexible". You can leverage sprocs and SQL to generate faster queries for the odd specific case, and you can leverage native DB functionality easier than you can with and ORM.

5) Overall

Don't get caught up in the false dichotomy of choosing an ORM vs using stored procedures. You can use both in the same application, and you probably should. Big bulk operations should go in stored procedures or SQL (which can actually be called by the EF), and EF should be used for your CRUD operations and most of your middle-tier's needs. Perhaps you'd choose to use SQL for writing your reports. I guess the moral of the story is the same as it's always been. Use the right tool for the job. But the skinny of it is, EF is very good nowadays (as of .NET 4.0). Spend some real time reading and understanding it in depth and you can create some amazing, high-performance apps with ease.

EDIT: EF 5 simplifies this part a bit with auto-compiled LINQ Queries, but for real high volume stuff, you'll definitely need to test and analyze what fits best for you in the real world.

How to push to History in React Router v4?

I struggled with the same topic. I'm using react-router-dom 5, Redux 4 and BrowserRouter. I prefer function based components and hooks.

You define your component like this

import { useHistory } from "react-router-dom";
import { useDispatch } from "react-redux";

const Component = () => {
  ...
  const history = useHistory();
  dispatch(myActionCreator(otherValues, history));
};

And your action creator is following

const myActionCreator = (otherValues, history) => async (dispatch) => {
  ...
  history.push("/path");
}

You can of course have simpler action creator if async is not needed

What JSON library to use in Scala?

I use uPickle which has the big advantage that it will handle nested case classes automatically:

object SerializingApp extends App {

  case class Person(name: String, address: Address)

  case class Address(street: String, town: String, zipCode: String)

  import upickle.default._

  val john = Person("John Doe", Address("Elm Street 1", "Springfield", "ABC123"))

  val johnAsJson = write(john)
  // Prints {"name":"John Doe","address":{"street":"Elm Street 1","town":"Springfield","zipCode":"ABC123"}}
  Console.println(johnAsJson)

  // Parse the JSON back into a Scala object
  Console.println(read[Person](johnAsJson))  
}

Add this to your build.sbt to use uPickle:

libraryDependencies += "com.lihaoyi" %% "upickle" % "0.4.3"

How to link a folder with an existing Heroku app

I've my project in github and heroku, for upload an heroku use :

heroku git:remote -a <project>

The doc it is:

https://devcenter.heroku.com/articles/git

How do I run PHP code when a user clicks on a link?

You cant run PHP when a user clicks on a link without leaving the page unless you use AJAX. PHP is a serverside scripting language, meaning the second that the browser sees the page, there is no PHP in it.

Unlike Javascript, PHP is ran completely on the server, and browser wouldn't know how to interpret it if it bit them on the rear. The only way to invoke PHP code is to make a Page request, by either refreshing the page, or using javascript to go fetch a page.

In an AJAX Solution, basically the page uses javascript to send a page request to another page on your domain. Javascript then gets whatever you decide to echo in the response, and it can parse it and do what it wants from there. When you are creating the response, you can also do any backend stuff like updating databases.

Converting any string into camel case

This builds on the answer by CMS by removing any non-alphabetic characters including underscores, which \w does not remove.

function toLowerCamelCase(str) {
    return str.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\b\w|\s+/g, function (match, index) {
        if (+match === 0 || match === '-' || match === '.' ) {
            return ""; // or if (/\s+/.test(match)) for white spaces
        }
        return index === 0 ? match.toLowerCase() : match.toUpperCase();
    });
}

toLowerCamelCase("EquipmentClass name");
toLowerCamelCase("Equipment className");
toLowerCamelCase("equipment class name");
toLowerCamelCase("Equipment Class Name");
toLowerCamelCase("Equipment-Class-Name");
toLowerCamelCase("Equipment_Class_Name");
toLowerCamelCase("Equipment.Class.Name");
toLowerCamelCase("Equipment/Class/Name");
// All output e

How can I populate a select dropdown list from a JSON feed with AngularJS?

The proper way to do it is using the ng-options directive. The HTML would look like this.

<select ng-model="selectedTestAccount" 
        ng-options="item.Id as item.Name for item in testAccounts">
    <option value="">Select Account</option>
</select>

JavaScript:

angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
    $scope.selectedTestAccount = null;
    $scope.testAccounts = [];

    $http({
            method: 'GET',
            url: '/Admin/GetTestAccounts',
            data: { applicationId: 3 }
        }).success(function (result) {
        $scope.testAccounts = result;
    });
});

You'll also need to ensure angular is run on your html and that your module is loaded.

<html ng-app="test">
    <body ng-controller="DemoCtrl">
    ....
    </body>
</html>

Convert a space delimited string to list

states = "Alaska Alabama Arkansas American Samoa Arizona California Colorado"
states_list = states.split (' ')

Using env variable in Spring Boot's application.properties

I faced the same issue as the author of the question. For our case answers in this question weren't enough since each of the members of my team had a different local environment and we definitely needed to .gitignore the file that had the different db connection string and credentials, so people don't commit the common file by mistake and break others' db connections.

On top of that when we followed the procedure below it was easy to deploy on different environments and as en extra bonus we didn't need to have any sensitive information in the version control at all.

Getting the idea from PHP Symfony 3 framework that has a parameters.yml (.gitignored) and a parameters.yml.dist (which is a sample that creates the first one through composer install),

I did the following combining the knowledge from answers below: https://stackoverflow.com/a/35534970/986160 and https://stackoverflow.com/a/35535138/986160.

Essentially this gives the freedom to use inheritance of spring configurations and choose active profiles through configuration at the top one plus any extra sensitive credentials as follows:

application.yml.dist (sample)

    spring:
      profiles:
        active: local/dev/prod
      datasource:
        username:
        password:
        url: jdbc:mysql://localhost:3306/db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

application.yml (.gitignore-d on dev server)

spring:
  profiles:
    active: dev
  datasource:
    username: root
    password: verysecretpassword
    url: jdbc:mysql://localhost:3306/real_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

application.yml (.gitignore-d on local machine)

spring:
  profiles:
    active: dev
  datasource:
    username: root
    password: rootroot
    url: jdbc:mysql://localhost:3306/xampp_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

application-dev.yml (extra environment specific properties not sensitive)

spring:
  datasource:
    testWhileIdle: true
    validationQuery: SELECT 1
  jpa:
    show-sql: true
    format-sql: true
    hibernate:
      ddl-auto: create-droop
      naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL57InnoDBDialect

Same can be done with .properties

Convert byte slice to io.Reader

To get a type that implements io.Reader from a []byte slice, you can use bytes.NewReader in the bytes package:

r := bytes.NewReader(byteData)

This will return a value of type bytes.Reader which implements the io.Reader (and io.ReadSeeker) interface.

Don't worry about them not being the same "type". io.Reader is an interface and can be implemented by many different types. To learn a little bit more about interfaces in Go, read Effective Go: Interfaces and Types.

Passing an integer by reference in Python

class Obj:
  def __init__(self,a):
    self.value = a
  def sum(self, a):
    self.value += a
    
a = Obj(1)
b = a
a.sum(1)
print(a.value, b.value)// 2 2

Performing Inserts and Updates with Dapper

You can try this:

 string sql = "UPDATE Customer SET City = @City WHERE CustomerId = @CustomerId";             
 conn.Execute(sql, customerEntity);

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

on ubuntu 18.04 in etc/phpmyadmin/config.inc.php comment all the block

Optional: User for advanced features

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

How to call on a function found on another file?

Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.

Perhaps declare it above your first while?

CASCADE DELETE just once

I took Joe Love's answer and rewrote it using the IN operator with sub-selects instead of = to make the function faster (according to Hubbitus's suggestion):

create or replace function delete_cascade(p_schema varchar, p_table varchar, p_keys varchar, p_subquery varchar default null, p_foreign_keys varchar[] default array[]::varchar[])
 returns integer as $$
declare

    rx record;
    rd record;
    v_sql varchar;
    v_subquery varchar;
    v_primary_key varchar;
    v_foreign_key varchar;
    v_rows integer;
    recnum integer;

begin

    recnum := 0;
    select ccu.column_name into v_primary_key
        from
        information_schema.table_constraints  tc
        join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema
        and tc.constraint_type='PRIMARY KEY'
        and tc.table_name=p_table
        and tc.table_schema=p_schema;

    for rx in (
        select kcu.table_name as foreign_table_name, 
        kcu.column_name as foreign_column_name, 
        kcu.table_schema foreign_table_schema,
        kcu2.column_name as foreign_table_primary_key
        from information_schema.constraint_column_usage ccu
        join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema 
        join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema
        join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema
        join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema
        where ccu.table_name=p_table  and ccu.table_schema=p_schema
        and TC.CONSTRAINT_TYPE='FOREIGN KEY'
        and tc2.constraint_type='PRIMARY KEY'
)
    loop
        v_foreign_key := rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name;
        v_subquery := 'select "'||rx.foreign_table_primary_key||'" as key from '||rx.foreign_table_schema||'."'||rx.foreign_table_name||'"
             where "'||rx.foreign_column_name||'"in('||coalesce(p_keys, p_subquery)||') for update';
        if p_foreign_keys @> ARRAY[v_foreign_key] then
            --raise notice 'circular recursion detected';
        else
            p_foreign_keys := array_append(p_foreign_keys, v_foreign_key);
            recnum:= recnum + delete_cascade(rx.foreign_table_schema, rx.foreign_table_name, null, v_subquery, p_foreign_keys);
            p_foreign_keys := array_remove(p_foreign_keys, v_foreign_key);
        end if;
    end loop;

    begin
        if (coalesce(p_keys, p_subquery) <> '') then
            v_sql := 'delete from '||p_schema||'."'||p_table||'" where "'||v_primary_key||'"in('||coalesce(p_keys, p_subquery)||')';
            --raise notice '%',v_sql;
            execute v_sql;
            get diagnostics v_rows = row_count;
            recnum := recnum + v_rows;
        end if;
        exception when others then recnum=0;
    end;

    return recnum;

end;
$$
language PLPGSQL;

Read data from a text file using Java

String file = "/path/to/your/file.txt";

try {

    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    String line;
    // Uncomment the line below if you want to skip the fist line (e.g if headers)
    // line = br.readLine();

    while ((line = br.readLine()) != null) {

        // do something with line

    }
    br.close();

} catch (IOException e) {
    System.out.println("ERROR: unable to read file " + file);
    e.printStackTrace();   
}

Running a single test from unittest.TestCase via the command line

Inspired by yarkee, I combined it with some of the code I already got. You can also call this from another script, just by calling the function run_unit_tests() without requiring to use the command line, or just call it from the command line with python3 my_test_file.py.

import my_test_file
my_test_file.run_unit_tests()

Sadly this only works for Python 3.3 or above:

import unittest

class LineBalancingUnitTests(unittest.TestCase):

    @classmethod
    def setUp(self):
        self.maxDiff = None

    def test_it_is_sunny(self):
        self.assertTrue("a" == "a")

    def test_it_is_hot(self):
        self.assertTrue("a" != "b")

Runner code:

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from .somewhere import LineBalancingUnitTests

def create_suite(classes, unit_tests_to_run):
    suite = unittest.TestSuite()
    unit_tests_to_run_count = len( unit_tests_to_run )

    for _class in classes:
        _object = _class()
        for function_name in dir( _object ):
            if function_name.lower().startswith( "test" ):
                if unit_tests_to_run_count > 0 \
                        and function_name not in unit_tests_to_run:
                    continue
                suite.addTest( _class( function_name ) )
    return suite

def run_unit_tests():
    runner = unittest.TextTestRunner()
    classes =  [
        LineBalancingUnitTests,
    ]

    # Comment all the tests names on this list, to run all Unit Tests
    unit_tests_to_run =  [
        "test_it_is_sunny",
        # "test_it_is_hot",
    ]
    runner.run( create_suite( classes, unit_tests_to_run ) )

if __name__ == "__main__":
    print( "\n\n" )
    run_unit_tests()

Editing the code a little, you can pass an array with all unit tests you would like to call:

...
def run_unit_tests(unit_tests_to_run):
    runner = unittest.TextTestRunner()

    classes = \
    [
        LineBalancingUnitTests,
    ]

    runner.run( suite( classes, unit_tests_to_run ) )
...

And another file:

import my_test_file

# Comment all the tests names on this list, to run all unit tests
unit_tests_to_run = \
[
    "test_it_is_sunny",
    # "test_it_is_hot",
]

my_test_file.run_unit_tests( unit_tests_to_run )

Alternatively, you can use load_tests Protocol and define the following method in your test module/file:

def load_tests(loader, standard_tests, pattern):
    suite = unittest.TestSuite()

    # To add a single test from this file
    suite.addTest( LineBalancingUnitTests( 'test_it_is_sunny' ) )

    # To add a single test class from this file
    suite.addTests( unittest.TestLoader().loadTestsFromTestCase( LineBalancingUnitTests ) )

    return suite

If you want to limit the execution to one single test file, you just need to set the test discovery pattern to the only file where you defined the load_tests() function.

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import unittest

test_pattern = 'mytest/module/name.py'
PACKAGE_ROOT_DIRECTORY = os.path.dirname( os.path.realpath( __file__ ) )

loader = unittest.TestLoader()
start_dir = os.path.join( PACKAGE_ROOT_DIRECTORY, 'testing' )

suite = loader.discover( start_dir, test_pattern )
runner = unittest.TextTestRunner( verbosity=2 )
results = runner.run( suite )

print( "results: %s" % results )
print( "results.wasSuccessful: %s" % results.wasSuccessful() )

sys.exit( not results.wasSuccessful() )

References:

  1. Problem with sys.argv[1] when unittest module is in a script
  2. Is there a way to loop through and execute all of the functions in a Python class?
  3. looping over all member variables of a class in python

Alternatively, to the last main program example, I came up with the following variation after reading the unittest.main() method implementation:

  1. https://github.com/python/cpython/blob/master/Lib/unittest/main.py#L65
#! /usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import unittest

PACKAGE_ROOT_DIRECTORY = os.path.dirname( os.path.realpath( __file__ ) )
start_dir = os.path.join( PACKAGE_ROOT_DIRECTORY, 'testing' )

from testing_package import main_unit_tests_module
testNames = ["TestCaseClassName.test_nameHelloWorld"]

loader = unittest.TestLoader()
suite = loader.loadTestsFromNames( testNames, main_unit_tests_module )

runner = unittest.TextTestRunner(verbosity=2)
results = runner.run( suite )

print( "results: %s" % results )
print( "results.wasSuccessful: %s" % results.wasSuccessful() )
sys.exit( not results.wasSuccessful() )

Vue-router redirect on page not found (404)

I think you should be able to use a default route handler and redirect from there to a page outside the app, as detailed below:

const ROUTER_INSTANCE = new VueRouter({
    mode: "history",
    routes: [
        { path: "/", component: HomeComponent },
        // ... other routes ...
        // and finally the default route, when none of the above matches:
        { path: "*", component: PageNotFound }
    ]
})

In the above PageNotFound component definition, you can specify the actual redirect, that will take you out of the app entirely:

Vue.component("page-not-found", {
    template: "",
    created: function() {
        // Redirect outside the app using plain old javascript
        window.location.href = "/my-new-404-page.html";
    }
}

You may do it either on created hook as shown above, or mounted hook also.

Please note:

  1. I have not verified the above. You need to build a production version of app, ensure that the above redirect happens. You cannot test this in vue-cli as it requires server side handling.

  2. Usually in single page apps, server sends out the same index.html along with app scripts for all route requests, especially if you have set <base href="/">. This will fail for your /404-page.html unless your server treats it as a special case and serves the static page.

Let me know if it works!

Update for Vue 3 onward:

You'll need to replace the '*' path property with '/:pathMatch(.*)*' if you're using Vue 3 as the old catch-all path of '*' is no longer supported. The route would then look something like this:

{ path: '/:pathMatch(.*)*', component: PathNotFound },

See the docs for more info on this update.

Getting current directory in .NET web application

The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath.

If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

Find duplicate lines in a file and count how many time each line was duplicated?

Assuming there is one number per line:

sort <file> | uniq -c

You can use the more verbose --count flag too with the GNU version, e.g., on Linux:

sort <file> | uniq --count

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

Make a bucket public in Amazon S3

You can set a bucket policy as detailed in this blog post:

http://ariejan.net/2010/12/24/public-readable-amazon-s3-bucket-policy/


As per @robbyt's suggestion, create a bucket policy with the following JSON:

{
  "Version": "2008-10-17",
  "Statement": [{
    "Sid": "AllowPublicRead",
    "Effect": "Allow",
    "Principal": { "AWS": "*" },
    "Action": ["s3:GetObject"],
    "Resource": ["arn:aws:s3:::bucket/*" ]
  }]
}

Important: replace bucket in the Resource line with the name of your bucket.

Need to combine lots of files in a directory

Yes , A plugin is available named "combine" for notepad++.Link: .>> Combine Plugin for Notepad++

You can install it via plugin manager. Extra benifit of this plugin is: "You can maintain the sequence of files while merging, it's according to the sequence of opened files are opened (see tabs)".

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

What the other answers suggest will work for the program in question, but it has the potential to cause breakage in other programs and unknown dependence elsewhere. It's better to make a tiny wrapper script:

#!/bin/sh
export LD_LIBRARY_PATH=/usr/local/lib64:$LD_LIBRARY_PATH
program_needing_different_run_time_library_path

This mostly avoids the problem described in Why LD_LIBRARY_PATH is bad by confining the effects to the program which needs them.

Note that despite the names LD_RUN_PATH works at link-time and is non-evil, while LD_LIBRARY_PATH works at both link and run time (and is evil :).

Get HTML code from website in C#

You can use WebClient to download the html for any url. Once you have the html, you can use a third-party library like HtmlAgilityPack to lookup values in the html as in below code -

public static string GetInnerHtmlFromDiv(string url)
    {
        string HTML;
        using (var wc = new WebClient())
        {
            HTML = wc.DownloadString(url);
        }
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(HTML);
        
        HtmlNode element = doc.DocumentNode.SelectSingleNode("//div[@id='<div id here>']");
        if (element != null)
        {
            return element.InnerHtml.ToString();
        }   
        return null;            
    }

Overriding fields or properties in subclasses

If you are building a class and you want there to be a base value for the property, then use the virtual keyword in the base class. This allows you to optionally override the property.

Using your example above:

//you may want to also use interfaces.
interface IFather
{
    int MyInt { get; set; }
}


public class Father : IFather
{
    //defaulting the value of this property to 1
    private int myInt = 1;

    public virtual int MyInt
    {
        get { return myInt; }
        set { myInt = value; }
    }
}

public class Son : Father
{
    public override int MyInt
    {
        get {

            //demonstrating that you can access base.properties
            //this will return 1 from the base class
            int baseInt = base.MyInt;

            //add 1 and return new value
            return baseInt + 1;
        }
        set
        {
            //sets the value of the property
            base.MyInt = value;
        }
    }
}

In a program:

Son son = new Son();
//son.MyInt will equal 2

Email and phone Number Validation in android

XML

<android.support.v7.widget.AppCompatEditText
    android:id="@+id/et_email_contact"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:maxLines="1"
    android:hint="Enter Email or Phone Number"/>

Java

private AppCompatEditText et_email_contact;
private boolean validEmail = false, validPhone = false;     

et_email_contact = findViewById(R.id.et_email_contact);
et_email_contact.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String regex = "^[+]?[0-9]{10,13}$";
        String emailContact = s.toString();
        if (TextUtils.isEmpty(emailContact)) {
            Log.e("Validation", "Enter Mobile No or Email");
        } else {
            if (emailContact.matches(regex)) {
                Log.e("Validation", "Valid Mobile No");
                validPhone = true;
                validEmail = false;
            } else if (Patterns.EMAIL_ADDRESS.matcher(emailContact).matches()) {
                Log.e("Validation", "Valid Email Address");
                validPhone = false;
                validEmail = true;
            } else {
                validPhone = false;
                validEmail = false;
                Log.e("Validation", "Invalid Mobile No or Email");
            }
        }
    }
});

if (validPhone || validEmail) {
    Toast.makeText(this, "Valid Email or Phone no", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(this, "InValid Email or Phone no", Toast.LENGTH_SHORT).show();
}

How to access your website through LAN in ASP.NET

You may also need to enable the World Wide Web Service inbound firewall rule.

On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules

Find World Wide Web Services (HTTP Traffic-In) in the list and select to enable the rule. Change is pretty much immediate.

How do you post data with a link

I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this:

<a href="house.php?id=<?php echo $house_id;?>">
  <?php echo $house_name;?>
</a>

Then in house.php, you would get the house id using $_GET['id'], validate it using is_numeric() and then display its info.

PHP Try and Catch for SQL Insert

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.

Where can I find the Java SDK in Linux after installing it?

Three Step Process: First: open Terminal->$ whereis java it would give output like this: java: /usr/bin/java /usr/share/java /usr/share/man/man1/java.1.gz

Second: ls -l /usr/bin/java It would give output like this: lrwxrwxrwx 1 root root 22 Feb 9 10:59 /usr/bin/java -> /etc/alternatives/java

Third: ls -l /etc/alternatives/java output is the JDK path: lrwxrwxrwx 1 root root 46 Feb 9 10:59 /etc/alternatives/java -> /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java

PHP mysql insert date format

You must make sure that the date format is YYYY-MM-DD on your jQuery output. I can see jQuery returns MM-DD-YYYY, which is not the valid MySQL date format and this is why it returns an error.

To convert it to the right one you could do this:

$dateFormated = split('/', $date);
$date = $dateFormated[2].'-'.$dateFormated[0].'-'.$dateFormated[1];

Then you will get formatted date that will be valid MySQL format, which is YYYY-MM-DD, i.e. 2012-08-25

I would also recommend using mysql_real_escape_string as you insert data into database to prevent SQL injections as a quick solution or better use PDO or MySQLi.

Your insert query using mysql_real_escape_string should rather look like this:

$sql = mysql_query( "INSERT INTO user_date VALUE( '', '" .mysql_real_escape_string($name). "', '" .mysql_real_escape_string($date). "'" ) or die ( mysql_error() );

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

127.0.0.1 is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1 for connections will only receive local connections on that socket.

"localhost" is normally the hostname for the 127.0.0.1 IP address. It's usually set in /etc/hosts (or the Windows equivalent named "hosts" somewhere under %WINDIR%). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1.

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000 is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

How to secure database passwords in PHP?

For extremely secure systems we encrypt the database password in a configuration file (which itself is secured by the system administrator). On application/server startup the application then prompts the system administrator for the decryption key. The database password is then read from the config file, decrypted, and stored in memory for future use. Still not 100% secure since it is stored in memory decrypted, but you have to call it 'secure enough' at some point!

Explain the concept of a stack frame in a nutshell

A quick wrap up. Maybe someone has a better explanation.

A call stack is composed of 1 or many several stack frames. Each stack frame corresponds to a call to a function or procedure which has not yet terminated with a return.

To use a stack frame, a thread keeps two pointers, one is called the Stack Pointer (SP), and the other is called the Frame Pointer (FP). SP always points to the "top" of the stack, and FP always points to the "top" of the frame. Additionally, the thread also maintains a program counter (PC) which points to the next instruction to be executed.

The following are stored on the stack: local variables and temporaries, actual parameters of the current instruction (procedure, function, etc.)

There are different calling conventions regarding the cleaning of the stack.

Apply function to pandas groupby

apply takes a function to apply to each value, not the series, and accepts kwargs. So, the values do not have the .size() method.

Perhaps this would work:

from pandas import *

d = {"my_label": Series(['A','B','A','C','D','D','E'])}
df = DataFrame(d)


def as_perc(value, total):
    return value/float(total)

def get_count(values):
    return len(values)

grouped_count = df.groupby("my_label").my_label.agg(get_count)
data = grouped_count.apply(as_perc, total=df.my_label.count())

The .agg() method here takes a function that is applied to all values of the groupby object.

Check if checkbox is NOT checked on click - jQuery

<script type="text/javascript">

 if(jQuery('input[id=input_id]').is(':checked')){
  // Your Statment
 }else{
  // Your Statment
 }

 OR

 if(jQuery('input[name=input_name]').is(':checked')){
  // Your Statment
 }else{
  // Your Statment
 }

</script>

Code taken from here : http://chandreshrana.blogspot.in/2015/10/how-to-check-if-checkbox-is-checked-or.html

How to add custom validation to an AngularJS form?

I extended @Ben Lesh's answer with an ability to specify whether the validation is case sensitive or not (default)

use:

<input type="text" name="fruitName" ng-model="data.fruitName" blacklist="Coconuts,Bananas,Pears" caseSensitive="true" required/>

code:

angular.module('crm.directives', []).
directive('blacklist', [
    function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: {
                'blacklist': '=',
            },
            link: function ($scope, $elem, $attrs, modelCtrl) {

                var check = function (value) {
                    if (!$attrs.casesensitive) {
                        value = (value && value.toUpperCase) ? value.toUpperCase() : value;

                        $scope.blacklist = _.map($scope.blacklist, function (item) {
                            return (item.toUpperCase) ? item.toUpperCase() : item
                        })
                    }

                    return !_.isArray($scope.blacklist) || $scope.blacklist.indexOf(value) === -1;
                }

                //For DOM -> model validation
                modelCtrl.$parsers.unshift(function (value) {
                    var valid = check(value);
                    modelCtrl.$setValidity('blacklist', valid);

                    return value;
                });
                //For model -> DOM validation
                modelCtrl.$formatters.unshift(function (value) {
                    modelCtrl.$setValidity('blacklist', check(value));
                    return value;
                });
            }
        };
    }
]);

How to sum the values of one column of a dataframe in spark/scala

Using spark sql query..just incase if it helps anyone!

import org.apache.spark.sql.SparkSession 
import org.apache.spark.SparkConf 
import org.apache.spark.sql.functions._ 
import org.apache.spark.SparkContext 
import java.util.stream.Collectors

val conf = new SparkConf().setMaster("local[2]").setAppName("test")
val spark = SparkSession.builder.config(conf).getOrCreate()
val df = spark.sparkContext.parallelize(Seq(1, 2, 3, 4, 5, 6, 7)).toDF()

df.createOrReplaceTempView("steps")
val sum = spark.sql("select  sum(steps) as stepsSum from steps").map(row => row.getAs("stepsSum").asInstanceOf[Long]).collect()(0)
println("steps sum = " + sum) //prints 28

Leap year calculation

You really should try to google first.

Wikipedia has a explanation of leap years. The algorithm your describing is for the Proleptic Gregorian calendar.

More about the math around it can be found in the article Calendar Algorithms.

Font.createFont(..) set color and size (java.awt.Font)

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

Returning data from Axios API

You can use Async - Await:

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

Drop data frame columns by name

Here is a dplyr way to go about it:

#df[ -c(1,3:6, 12) ]  # original
df.cut <- df %>% select(-col.to.drop.1, -col.to.drop.2, ..., -col.to.drop.6)  # with dplyr::select()

I like this because it's intuitive to read & understand without annotation and robust to columns changing position within the data frame. It also follows the vectorized idiom using - to remove elements.

How to get text and a variable in a messagebox

Why not use:

Dim msg as String = String.Format("Variable = {0}", variable)

More info on String.Format

How to make sure that string is valid JSON using JSON.NET

I'm using this one:

  internal static bool IsValidJson(string data)
  {
     data = data.Trim();
     try
     {
        if (data.StartsWith("{") && data.EndsWith("}"))
        {
           JToken.Parse(data);
        }
        else if (data.StartsWith("[") && data.EndsWith("]"))
        {
           JArray.Parse(data);
        }
        else
        {
           return false;
        }
        return true;
     }
     catch
     {
        return false;
     }
  }

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

After Xcode 6.1 Beta the code below works, slight edit on Tom S code that stopped working with the 6.1 beta (worked with previous beta):

   if UIApplication.sharedApplication().respondsToSelector("registerUserNotificationSettings:") {
        // It's iOS 8
        var types = UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert
       var settings = UIUserNotificationSettings(forTypes: types, categories: nil)
       UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    } else {
        // It's older
        var types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert
        UIApplication.sharedApplication().registerForRemoteNotificationTypes(types)
    }

Close application and launch home screen on Android

Start the second activity with startActivityForResult and in the second activity return a value, that once in the onActivityResult method of the first activity closes the main application. I think this is the correct way Android does it.

Session 'app': Error Installing APK

A bit late to the party, but be sure that you are trying to build a proper build variant. It sometimes happens to me that when I update AS, the build variants are totally messed up, so instead of building the "debug" variant I am actually building the "release" variant, which outputs apk to a different location (not to app/build directory, but to app directly) and I get the following error:

The APK file /path/to/file/app.apk does not exist on disk.
Error while Installing APK

To fix this just open the menu in left bottom corner, click on "Build Variants" and select the debug variant (it might have a different name, depending on how many modules/flavors or custom gradle build types you have).

How do you detect/avoid Memory leaks in your (Unmanaged) code?

I’m amazed no one mentioned DebugDiag for Windows OS.
It works on release builds, and even at the customer site.
(You just need to keep your release version PDBs, and configure DebugDiag to use Microsoft public symbol server)

How to retrieve GET parameters from JavaScript

You can use the search function available in the location object. The search function gives the parameter part of the URL. Details can be found in Location Object.

You will have to parse the resulting string for getting the variables and their values, e.g. splitting them on '='.

PHP replacing special characters like à->a, è->e

CodeIgniter way:

$this->load->helper('text');

$string = convert_accented_characters($string);

This function uses a companion config file application/config/foreign_chars.php to define the to and from array for transliteration.

https://www.codeigniter.com/user_guide/helpers/text_helper.html#ascii_to_entities

Compiler error: "class, interface, or enum expected"

You forgot your class declaration:

public class MyClass {
...

How to compress an image via Javascript in the browser?

In short:

  • Read the files using the HTML5 FileReader API with .readAsArrayBuffer
  • Create a Blob with the file data and get its url with window.URL.createObjectURL(blob)
  • Create new Image element and set it's src to the file blob url
  • Send the image to the canvas. The canvas size is set to desired output size
  • Get the scaled-down data back from canvas via canvas.toDataURL("image/jpeg",0.7) (set your own output format and quality)
  • Attach new hidden inputs to the original form and transfer the dataURI images basically as normal text
  • On backend, read the dataURI, decode from Base64, and save it

Source: code.

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

The most likely explanations for that error are:

  1. The file you are attempting to load is not an executable file. CreateProcess requires you to provide an executable file. If you wish to be able to open any file with its associated application then you need ShellExecute rather than CreateProcess.
  2. There is a problem loading one of the dependencies of the executable, i.e. the DLLs that are linked to the executable. The most common reason for that is a mismatch between a 32 bit executable and a 64 bit DLL, or vice versa. To investigate, use Dependency Walker's profile mode to check exactly what is going wrong.

Reading down to the bottom of the code, I can see that the problem is number 1.

How to change the color of the axis, ticks and labels for a plot in matplotlib

motivated by previous contributors, this is an example of three axes.

import matplotlib.pyplot as plt

x_values1=[1,2,3,4,5]
y_values1=[1,2,2,4,1]

x_values2=[-1000,-800,-600,-400,-200]
y_values2=[10,20,39,40,50]

x_values3=[150,200,250,300,350]
y_values3=[-10,-20,-30,-40,-50]


fig=plt.figure()
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax3=fig.add_subplot(111, label="3", frame_on=False)

ax.plot(x_values1, y_values1, color="C0")
ax.set_xlabel("x label 1", color="C0")
ax.set_ylabel("y label 1", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")

ax2.scatter(x_values2, y_values2, color="C1")
ax2.set_xlabel('x label 2', color="C1") 
ax2.xaxis.set_label_position('bottom') # set the position of the second x-axis to bottom
ax2.spines['bottom'].set_position(('outward', 36))
ax2.tick_params(axis='x', colors="C1")
ax2.set_ylabel('y label 2', color="C1")       
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right') 
ax2.tick_params(axis='y', colors="C1")

ax3.plot(x_values3, y_values3, color="C2")
ax3.set_xlabel('x label 3', color='C2')
ax3.xaxis.set_label_position('bottom')
ax3.spines['bottom'].set_position(('outward', 72))
ax3.tick_params(axis='x', colors='C2')
ax3.set_ylabel('y label 3', color='C2')
ax3.yaxis.tick_right()
ax3.yaxis.set_label_position('right') 
ax3.spines['right'].set_position(('outward', 36))
ax3.tick_params(axis='y', colors='C2')


plt.show()

Copy entire directory contents to another directory?

This is my piece of Groovy code for that. Tested.

private static void copyLargeDir(File dirFrom, File dirTo){
    // creation the target dir
    if (!dirTo.exists()){
        dirTo.mkdir();
    }
    // copying the daughter files
    dirFrom.eachFile(FILES){File source ->
        File target = new File(dirTo,source.getName());
        target.bytes = source.bytes;
    }
    // copying the daughter dirs - recursion
    dirFrom.eachFile(DIRECTORIES){File source ->
        File target = new File(dirTo,source.getName());
        copyLargeDir(source, target)
    }
}

How to change the text on the action bar

You can define the label for each activity in your manifest file.

A normal definition of a activity looks like this:

<activity
     android:name=".ui.myactivity"
     android:label="@string/Title Text" />

Where title text should be replaced by the id of a string resource for this activity.

You can also set the title text from code if you want to set it dynamically.

setTitle(address.getCity());

with this line the title is set to the city of a specific adress in the oncreate method of my activity.

How to discover number of *logical* cores on Mac OS X?

As jkp said in a comment, that doesn't show the actual number of physical cores. to get the number of physical cores you can use the following command:

system_profiler SPHardwareDataType

How to initialize a dict with keys from a list and empty value in Python?

You could use dict.fromkeys as follows:

dict.fromkeys([1, 2, 3, 4], list())

This will create a list object for each key. If you change value for any specific key it won't affect other keys (as most people would want, I presume).

Location of my.cnf file on macOS

Open Terminal and use below command:

sudo find / -name my.cnf

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

  • ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column of the first row. An example might be SELECT @@IDENTITY AS 'Identity'.
  • ExecuteReader is used for any result set with multiple rows/columns (e.g., SELECT col1, col2 from sometable).
  • ExecuteNonQuery is typically used for SQL statements without results (e.g., UPDATE, INSERT, etc.).

How to set thousands separator in Java?

As mentioned above, the following link gives you the specific country code to allow Java to localize the number. Every country has its own style.

In the link above you will find the country code which should be placed in here:

...(new Locale(<COUNTRY CODE HERE>));

Switzerland for example formats the numbers as follows:

1000.00 --> 1'000.00

country code

To achieve this, following codes works for me:

NumberFormat nf = NumberFormat.getNumberInstance(new Locale("de","CH"));
nf.setMaximumFractionDigits(2);
DecimalFormat df = (DecimalFormat)nf;
System.out.println(df.format(1000.00));

Result is as expected:

1'000.00

Remove all child elements of a DOM node in JavaScript

Simplest way of removing the child nodes of a node via Javascript

var myNode = document.getElementById("foo");
while(myNode.hasChildNodes())
{
   myNode.removeChild(myNode.lastChild);
}

Count indexes using "for" in Python

This?

for i in range(0,5): 
 print(i)

Simplest way to restart service on a remote computer

I recommend the method given by doofledorfer.

If you really want to do it via a direct API call, then look at the OpenSCManager function. Below are sample functions to take a machine name and service, and stop or start them.

function ServiceStart(sMachine, sService : string) : boolean;  //start service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    psTemp     : PChar;
    dwChkP     : DWord;
begin
  ss.dwCurrentState := 0;
  schm := OpenSCManager(PChar(sMachine),Nil,SC_MANAGER_CONNECT);  //connect to the service control manager

  if(schm > 0)then begin // if successful...
    schs := OpenService( schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS);    // open service handle, start and query status
    if(schs > 0)then begin     // if successful...
      psTemp := nil;
      if (StartService(schs,0,psTemp)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_RUNNING <> ss.dwCurrentState)do begin
          dwChkP := ss.dwCheckPoint;  //dwCheckPoint contains a value incremented periodically to report progress of a long operation.  Store it.
          Sleep(ss.dwWaitHint);  //Sleep for recommended time before checking status again
          if(not QueryServiceStatus(schs,ss))then
            break;  //couldn't check status
          if(ss.dwCheckPoint < dwChkP)then
            Break;  //if QueryServiceStatus didn't work for some reason, avoid infinite loop
        end;  //while not running
      CloseServiceHandle(schs);
    end;  //if able to get service handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_RUNNING = ss.dwCurrentState;  //if we were able to start it, return true
end;

function ServiceStop(sMachine, sService : string) : boolean;  //stop service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    dwChkP     : DWord;
begin
  schm := OpenSCManager(PChar(sMachine),nil,SC_MANAGER_CONNECT);

  if(schm > 0)then begin
    schs := OpenService(schm,PChar(sService),SERVICE_STOP or SERVICE_QUERY_STATUS);
    if(schs > 0)then begin
      if (ControlService(schs,SERVICE_CONTROL_STOP,ss)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_STOPPED <> ss.dwCurrentState) do begin
          dwChkP := ss.dwCheckPoint;
          Sleep(ss.dwWaitHint);
          if(not QueryServiceStatus(schs,ss))then
            Break;

          if(ss.dwCheckPoint < dwChkP)then
            Break;
        end;  //while
      CloseServiceHandle(schs);
    end;  //if able to get svc handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_STOPPED = ss.dwCurrentState;
end;

Adding timestamp to a filename with mv in BASH

Well, it's not a direct answer to your question, but there's a tool in GNU/Linux whose job is to rotate log files on regular basis, keeping old ones zipped up to a certain limit. It's logrotate

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

ubuntu users try this

apt-get install php7.2 libapache2-mod-php7.2 php7.2-common php7.2-gd php7.2-mysql php7.2-curl php7.2-intl php7.2-xsl php7.2-mbstring php7.2-zip php7.2-bcmath php7.2-soap php-xdebug php-imagick

this is work for php 7.2 but you can change this 7.2 to 5.2 and run this command it is work.

Default SecurityProtocol in .NET 4.5

The default System.Net.ServicePointManager.SecurityProtocol in both .NET 4.0/4.5 is SecurityProtocolType.Tls|SecurityProtocolType.Ssl3.

.NET 4.0 supports up to TLS 1.0 while .NET 4.5 supports up to TLS 1.2

However, an application targeting .NET 4.0 can still support up to TLS 1.2 if .NET 4.5 is installed in the same environment. .NET 4.5 installs on top of .NET 4.0, replacing System.dll.

I've verified this by observing the correct security protocol set in traffic with fiddler4 and by manually setting the enumerated values in a .NET 4.0 project:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 |
(SecurityProtocolType)768 | (SecurityProtocolType)3072;

Reference:

namespace System.Net
{
    [System.Flags]
    public enum SecurityProtocolType
    {
       Ssl3 = 48,
       Tls = 192,
       Tls11 = 768,
       Tls12 = 3072,
    }
}

If you attempt the hack on an environment with ONLY .NET 4.0 installed, you will get the exception:

Unhandled Exception: System.NotSupportedException: The requested security protocol is not supported. at System.Net.ServicePointManager.set_SecurityProtocol(SecurityProtocolType v alue)

However, I wouldn't recommend this "hack" since a future patch, etc. may break it.*

Therefore, I've decided the best route to remove support for SSLv3 is to:

  1. Upgrade all applications to .NET 4.5
  2. Add the following to boostrapping code to override the default and future proof it:

    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

*Someone correct me if this hack is wrong, but initial tests I see it works

Calling a Fragment method from a parent Activity

  1. If you're not using a support library Fragment, then do the following:

((FragmentName) getFragmentManager().findFragmentById(R.id.fragment_id)).methodName();


2. If you're using a support library Fragment, then do the following:

((FragmentName) getSupportFragmentManager().findFragmentById(R.id.fragment_id)).methodName();

Smooth scrolling when clicking an anchor link

Never forget that offset() function is giving your element's position to document. So when you need scroll your element relative to its parent you should use this;

    $('.a-parent-div').find('a').click(function(event){
        event.preventDefault();
        $('.scroll-div').animate({
     scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
     }, 500);       
  });

The key point is getting scrollTop of scroll-div and add it to scrollTop. If you won't do that position() function always gives you different position values.

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

Here's a start.. Open to suggestions/improvements.

Server

public class ChatHub : Hub
{
    public void SendChatMessage(string who, string message)
    {
        string name = Context.User.Identity.Name;
        Clients.Group(name).addChatMessage(name, message);
        Clients.Group("[email protected]").addChatMessage(name, message);
    }

    public override Task OnConnected()
    {
        string name = Context.User.Identity.Name;
        Groups.Add(Context.ConnectionId, name);

        return base.OnConnected();
    }
}

JavaScript

(Notice how addChatMessage and sendChatMessage are also methods in the server code above)

    $(function () {
    // Declare a proxy to reference the hub.
    var chat = $.connection.chatHub;
    // Create a function that the hub can call to broadcast messages.
    chat.client.addChatMessage = function (who, message) {
        // Html encode display name and message.
        var encodedName = $('<div />').text(who).html();
        var encodedMsg = $('<div />').text(message).html();
        // Add the message to the page.
        $('#chat').append('<li><strong>' + encodedName
            + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
    };

    // Start the connection.
    $.connection.hub.start().done(function () {
        $('#sendmessage').click(function () {
            // Call the Send method on the hub.
            chat.server.sendChatMessage($('#displayname').val(), $('#message').val());
            // Clear text box and reset focus for next comment.
            $('#message').val('').focus();
        });
    });
});

Testing enter image description here

Javascript Print iframe contents only

I would not expect that to work

try instead

window.frames["printf"].focus();
window.frames["printf"].print();

and use

<iframe id="printf" name="printf"></iframe>

Alternatively try good old

var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();

if jQuery cannot hack it

Live Demo

Convert object string to JSON

There's a much simpler way to accomplish this feat, just hijack the onclick attribute of a dummy element to force a return of your string as a JavaScript object:

var jsonify = (function(div){
  return function(json){
    div.setAttribute('onclick', 'this.__json__ = ' + json);
    div.click();
    return div.__json__;
  }
})(document.createElement('div'));

// Let's say you had a string like '{ one: 1 }' (malformed, a key without quotes)
// jsonify('{ one: 1 }') will output a good ol' JS object ;)

Here's a demo: http://codepen.io/csuwldcat/pen/dfzsu (open your console)

How to run Unix shell script from Java code?

It is possible, just exec it as any other program. Just make sure your script has the proper #! (she-bang) line as the first line of the script, and make sure there are execute permissions on the file.

For example, if it is a bash script put #!/bin/bash at the top of the script, also chmod +x .

Also as for if it's good practice, no it's not, especially for Java, but if it saves you a lot of time porting a large script over, and you're not getting paid extra to do it ;) save your time, exec the script, and put the porting to Java on your long-term todo list.

bootstrap responsive table content wrapping

EDIT

I think the reason that your table is not responsive to start with was you did not wrap in .container, .row and .col-md-x classes like this one

<div class="container">
   <div class="row">
     <div class="col-md-12">
     <!-- or use any other number .col-md- -->
         <div class="table-responsive">
             <div class="table">
             </div>
         </div>
     </div>
   </div>
</div>

With this, you can still use <p> tags and even make it responsive.

Please see the Bootply example here

Find out who is locking a file on a network share

Partial answer: With Process Explorer, you can view handles on a network share opened from your machine.

Use the Menu "Find Handle" and then you can type a path like this

\Device\LanmanRedirector\server\share\

Swift Bridging Header import issue

Add a temporary Objective-C file to your project. You may give it any name you like.

Select Yes to configure an Objective-C bridging header.

Delete the temporary Objective-C file you just created.

In the projectName-Bridging-Header.h file just created, add this line:

'#import < GoogleMaps/GoogleMaps.h >'

Edit the AppDelegate.swift file:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    GMSServices.provideAPIKey("AIza....") //iOS API key

    return true
}

Follow the link for full sample

Getting checkbox values on submit

It's very simple.

The checkbox field is like an input text. If you don't write anything in the field, it will say the field doesn't exist.

<form method="post">
    <input type="checkbox" name="check">This is how it works!<br>
    <button type="submit" name="submit">Submit</button>
</form>
<?php
if(isset($_POST['submit'])) {
    if(!isset($_POST['check'])) {
        echo "Not selected!";
    }else{
        echo "Selected!";
    }
}
?>

Today's Date in Perl in MM/DD/YYYY format

You can use Time::Piece, which shouldn't need installing as it is a core module and has been distributed with Perl 5 since version 10.

use Time::Piece;

my $date = localtime->strftime('%m/%d/%Y');
print $date;

output

06/13/2012


Update

You may prefer to use the dmy method, which takes a single parameter which is the separator to be used between the fields of the result, and avoids having to specify a full date/time format

my $date = localtime->dmy('/');

This produces an identical result to that of my original solution

How to call getResources() from a class which has no context?

Example: Getting app_name string:

Resources.getSystem().getString( R.string.app_name )

Importing PNG files into Numpy?

This can also be done with the Image class of the PIL library:

from PIL import Image
import numpy as np

im_frame = Image.open(path_to_file + 'file.png')
np_frame = np.array(im_frame.getdata())

Note: The .getdata() might not be needed - np.array(im_frame) should also work

selectOneMenu ajax events

I'd rather use more convenient itemSelect event. With this event you can use org.primefaces.event.SelectEvent objects in your listener.

<p:selectOneMenu ...>
    <p:ajax event="itemSelect" 
        update="messages"
        listener="#{beanMB.onItemSelectedListener}"/>
</p:selectOneMenu>

With such listener:

public void onItemSelectedListener(SelectEvent event){
    MyItem selectedItem = (MyItem) event.getObject();
    //do something with selected value
}

Is it possible to change the content HTML5 alert messages?

Thank you guys for the help,

When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:

http://blog.thomaslebrun.net/2011/11/html-5-how-to-customize-the-error-message-for-a-required-field/#.UsNN1BYrh2M

How to completely uninstall kubernetes

use kubeadm reset command. this will un-configure the kubernetes cluster.

What's the meaning of exception code "EXC_I386_GPFLT"?

For me it issue related to storyboard there is option of ViewController build for set iOS 9.0 and later previously set for iOS 10.0 and later. Actually i want to downgrade the ver from 10 to iOS 9.3.

How to do a for loop in windows command line?

This may help you find what you're looking for... Batch script loop

My answer is as follows:

@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start

:end
echo var has reached %var%.
pause
exit

The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.

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

I had the same problem and executing npm config delete prefix did not help me.

But this did:

After installing nvm using brew, create ~/.nvm directory:
$ mkdir ~/.nvm

and add following lines into ~/.bash_profile:

export NVM_DIR=~/.nvm
. $(brew --prefix nvm)/nvm.sh

(Check that you have no other nvm related command in any ~/.bashrc or ~/.profile or ~/.bash_profile)

Open a new terminal and this time it should not print any warning message.
Check that nvm is working by executing nvm --version command.
After that, install/reinstall NodeJS using nvm install node && nvm alias default node.

More Info

I installed nvm using homebrew and after that I got this notification:

Please note that upstream has asked us to make explicit managing nvm via Homebrew is unsupported by them and you should check any problems against the standard nvm install method prior to reporting.

You should create NVM's working directory if it doesn't exist:

 mkdir ~/.nvm

Add the following to ~/.bash_profile or your desired shell configuration file:

 export NVM_DIR=~/.nvm
 . $(brew --prefix nvm)/nvm.sh

You can set $NVM_DIR to any location, but leaving it unchanged from /usr/local/Cellar/nvm/0.31.0 will destroy any nvm-installed Node installations upon upgrade/reinstall.

Ignoring it brought me to this error message:

nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local/Cellar/nvm/0.31.0/versions/node/v5.7.1"
Run nvm use --delete-prefix v5.7.1 --silent to unset it.

I followed an earlier guide (from homebrew/nvm) and after that I found that I needed to reinstall NodeJS. So I did:

nvm install node && nvm alias default node

and it was fixed.

Update: Using brew to install NVM causes slow startup of the Terminal. You can follow this instruction to resolve it.

HTTP response code for POST when resource already exists

It's all about context, and also who is responsible for handling duplicates in requests (server or client or both)


If server just point the duplicate, look at 4xx:

  • 400 Bad Request - when the server will not process a request because it's obvious client fault
  • 409 Conflict - if the server will not process a request, but the reason for that is not the client's fault
  • ...

For implicit handling of duplicates, look at 2XX:

  • 200 OK
  • 201 Created
  • ...

if the server is expected to return something, look at 3XX:

  • 302 Found
  • 303 See Other
  • ...

when the server is able to point the existing resource, it implies a redirection.


If the above is not enough, it's always a good practice to prepare some error message in the body of the response.

How to write a full path in a batch file having a folder name with space?

CD E:\Documents and Settings\All Users\Application Data

E:\Documents and Settings\All Users\Application Data>REGSVR32 xyz.dll

How to return value from function which has Observable subscription inside?

In the single-threaded,asynchronous,promise-oriented,reactive-trending world of javascript async/await is the imperative-style programmer's best friend:

(async()=>{

    const store = of("someValue");
    function getValueFromObservable () {
        return store.toPromise();
    }
    console.log(await getValueFromObservable())

})();

And in case store is a sequence of multiple values:

  const aiFrom = require('ix/asynciterable').from;
  (async function() {

     const store = from(["someValue","someOtherValue"]);
     function getValuesFromObservable () {
        return aiFrom(store);
     }
     for await (let num of getValuesFromObservable()) {
       console.log(num);
     }
  })();

How to make an android app to always run in background?

In mi and vivo - Using the above solution is not enough. You must also tell the user to add permission manually. You can help them by opening the right location inside phone settings. Varies for different phone models.

Node Version Manager (NVM) on Windows

The first thing that we need to do is install NVM.

  1. Uninstall existing version of node since we won’t be using it anymore
  2. Delete any existing nodejs installation directories. e.g. “C:\Program Files\nodejs”) that might remain. NVM’s generated symlink will not overwrite an existing (even empty) installation directory.
  3. Delete the npm install directory at C:\Users[Your User]\AppData\Roaming\npm We are now ready to install nvm. Download the installer from https://github.com/coreybutler/nvm/releases

To upgrade, run the new installer. It will safely overwrite the files it needs to update without touching your node.js installations. Make sure you use the same installation and symlink folder. If you originally installed to the default locations, you just need to click “next” on each window until it finishes.

Credits Directly copied from : https://digitaldrummerj.me/windows-running-multiple-versions-of-node/

Convert dictionary to list collection in C#

Alternatively:

var keys = new List<string>(dicNumber.Keys);

Shorter syntax for casting from a List<X> to a List<Y>?

This is not quite the answer to this question, but it may be useful for some: as @SWeko said, thanks to covariance and contravariance, List<X> can not be cast in List<Y>, but List<X> can be cast into IEnumerable<Y>, and even with implicit cast.

Example:

List<Y> ListOfY = new List<Y>();
List<X> ListOfX = (List<X>)ListOfY; // Compile error

but

List<Y> ListOfY = new List<Y>();
IEnumerable<X> EnumerableOfX = ListOfY;  // No issue

The big advantage is that it does not create a new list in memory.

QED symbol in latex

I think you are looking for this:

\newcommand*{\QEDA}{\hfill\ensuremath{\blacksquare}}

Usage:

\begin{example}
  blah blah blah \QEDA
\end{example}

javax.naming.NameNotFoundException

I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound

This means that nothing is bound to the jndi name greetJndi, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.

Is there any specific directory structure to deploy in JBoss?

The internal structure of the ejb-jar is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):

.
+-- greetBean.java
+-- greetHome.java
+-- greetRemote.java
+-- META-INF
    +-- ejb-jar.xml
    +-- jboss.xml

But as already mentioned, this tutorial is full of mistakes:

  • there is an extra character (<enterprise-beans>] <-- HERE) in the ejb-jar.xml (!)
  • a space is missing after PUBLIC in the ejb-jar.xml and jboss.xml (!!)
  • the jboss.xml is incorrect, it should contain a session element instead of entity (!!!)

Here is a "fixed" version of the ejb-jar.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <home>greetHome</home>
      <remote>greetRemote</remote>
      <ejb-class>greetBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
</ejb-jar>

And of the jboss.xml:

<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <jndi-name>greetJndi</jndi-name>
    </session>
  </enterprise-beans>
</jboss>

After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:

21:48:06,512 INFO  [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/}
21:48:06,534 INFO  [EjbDeployer] installing bean: ejb/#greetBean,uid19981448
21:48:06,534 INFO  [EjbDeployer]   with dependencies:
21:48:06,534 INFO  [EjbDeployer]   and supplies:
21:48:06,534 INFO  [EjbDeployer]    jndi:greetJndi
21:48:06,624 INFO  [EjbModule] Deploying greetBean
21:48:06,661 WARN  [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/
21:48:06,805 INFO  [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'

That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.

Remove insignificant trailing zeros from a number?

If you use toFixed(n) where n > 0, a more simple and stable (no more float operations) solution can be:

(+n).toFixed(2).replace(/(\.0+|0+)$/, '')


// 0 => 0
// 0.1234 => 0.12
// 0.1001 => 0.1

// 1 => 1
// 1.1234 => 1.12
// 1.1001 => 1.1

// 100 => 100
// 100.1234 => 100.12
// 100.1001 => 100.1

PS: if you use toFixed(0), then no replace is needed.

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

I had the same problem when modifying a ListBox using JavaScript on the client. It occurs when you add new items to the ListBox from the client that were not there when the page was rendered.

The fix that I found is to inform the event validation system of all the possible valid items that can be added from the client. You do this by overriding Page.Render and calling Page.ClientScript.RegisterForEventValidation for each value that your JavaScript could add to the list box:

protected override void Render(HtmlTextWriter writer)
{
    foreach (string val in allPossibleListBoxValues)
    {
        Page.ClientScript.RegisterForEventValidation(myListBox.UniqueID, val);
    }
    base.Render(writer);
}

This can be kind of a pain if you have a large number of potentially valid values for the list box. In my case I was moving items between two ListBoxes - one that that has all the possible values and another that is initially empty but gets filled in with a subset of the values from the first one in JavaScript when the user clicks a button. In this case you just need to iterate through the items in the first ListBoxand register each one with the second list box:

protected override void Render(HtmlTextWriter writer)
{
    foreach (ListItem i in listBoxAll.Items)
    {
        Page.ClientScript.RegisterForEventValidation(listBoxSelected.UniqueID, i.Value);
    }
    base.Render(writer);
}

"Find next" in Vim

As discussed, there are several ways to search:

/pattern
?pattern
* (and g*, which I sometimes use in macros)
# (and g#)

plus, navigating prev/next with N and n.

You can also edit/recall your search history by pulling up the search prompt with / and then cycle with C-p/C-n. Even more useful is q/, which takes you to a window where you can navigate the search history.

Also for consideration is the all-important 'hlsearch' (type :hls to enable). This makes it much easier to find multiple instances of your pattern. You might even want make your matches extra bright with something like:

hi Search ctermfg=yellow ctermbg=red guifg=...

But then you might go crazy with constant yellow matches all over your screen. So you’ll often find yourself using :noh. This is so common that a mapping is in order:

nmap <leader>z :noh<CR>

I easily remember this one as z since I used to constantly type /zz<CR> (which is a fast-to-type uncommon occurrence) to clear my highlighting. But the :noh mapping is way better.

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

Reading a file line by line in Go

Another method is to use the io/ioutil and strings libraries to read the entire file's bytes, convert them into a string and split them using a "\n" (newline) character as the delimiter, for example:

import (
    "io/ioutil"
    "strings"
)

func main() {
    bytesRead, _ := ioutil.ReadFile("something.txt")
    file_content := string(bytesRead)
    lines := strings.Split(file_content, "\n")
}

Technically you're not reading the file line-by-line, however you are able to parse each line using this technique. This method is applicable to smaller files. If you're attempting to parse a massive file use one of the techniques that reads line-by-line.

ssl.SSLError: tlsv1 alert protocol version

I got this problem too. In macos, here is the solution:

  • Step 1: brew restall python. now you got python3.7 instead of the old python

  • Step 2: build the new env base on python3.7. my path is /usr/local/Cellar/python/3.7.2/bin/python3.7

now, you'll not being disturbed by this problem.

Filter Java Stream to 1 and only 1 element

I am using those two collectors:

public static <T> Collector<T, ?, Optional<T>> zeroOrOne() {
    return Collectors.reducing((a, b) -> {
        throw new IllegalStateException("More than one value was returned");
    });
}

public static <T> Collector<T, ?, T> onlyOne() {
    return Collectors.collectingAndThen(zeroOrOne(), Optional::get);
}

Eclipse will not open due to environment variables

You should install both 32bit & 64bit java (At least JRE), that in case you're using 64bit OS.

Joining three tables using MySQL

For normalize form

select e1.name as 'Manager', e2.name as 'Staff'
from employee e1 
left join manage m on m.mid = e1.id
left join employee e2 on m.eid = e2.id

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

Ok found out the Tomcat file server.xml must be configured as well for the data source to work. So just add:

<Resource 
auth="Container" 
driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
maxActive="20" 
maxIdle="10" 
maxWait="-1" 
name="ds/flexeraDS" 
type="javax.sql.DataSource" 
url="jdbc:derby:flexeraDB;create=true" 
  />

Git push error: "origin does not appear to be a git repository"

May be you forgot to run "git --bare init" on the remote? That was my problem

Function pointer to member function

Building on @IllidanS4 's answer, I have created a template class that allows virtually any member function with predefined arguments and class instance to be passed by reference for later calling.



template<class RET, class... RArgs> class Callback_t {
public:
    virtual RET call(RArgs&&... rargs) = 0;
    //virtual RET call() = 0;
};

template<class T, class RET, class... RArgs> class CallbackCalltimeArgs : public Callback_t<RET, RArgs...> {
public:
    T * owner;
    RET(T::*x)(RArgs...);
    RET call(RArgs&&... rargs) {
        return (*owner.*(x))(std::forward<RArgs>(rargs)...);
    };
    CallbackCalltimeArgs(T* t, RET(T::*x)(RArgs...)) : owner(t), x(x) {}
};

template<class T, class RET, class... Args> class CallbackCreattimeArgs : public Callback_t<RET> {
public:
    T* owner;
    RET(T::*x)(Args...);
    RET call() {
        return (*owner.*(x))(std::get<Args&&>(args)...);
    };
    std::tuple<Args&&...> args;
    CallbackCreattimeArgs(T* t, RET(T::*x)(Args...), Args&&... args) : owner(t), x(x),
        args(std::tuple<Args&&...>(std::forward<Args>(args)...)) {}
};

Test / example:

class container {
public:
    static void printFrom(container* c) { c->print(); };
    container(int data) : data(data) {};
    ~container() {};
    void print() { printf("%d\n", data); };
    void printTo(FILE* f) { fprintf(f, "%d\n", data); };
    void printWith(int arg) { printf("%d:%d\n", data, arg); };
private:
    int data;
};

int main() {
    container c1(1), c2(20);
    CallbackCreattimeArgs<container, void> f1(&c1, &container::print);
    Callback_t<void>* fp1 = &f1;
    fp1->call();//1
    CallbackCreattimeArgs<container, void, FILE*> f2(&c2, &container::printTo, stdout);
    Callback_t<void>* fp2 = &f2;
    fp2->call();//20
    CallbackCalltimeArgs<container, void, int> f3(&c2, &container::printWith);
    Callback_t<void, int>* fp3 = &f3;
    fp3->call(15);//20:15
}

Obviously, this will only work if the given arguments and owner class are still valid. As far as readability... please forgive me.

Edit: removed unnecessary malloc by making the tuple normal storage. Added inherited type for the reference. Added option to provide all arguments at calltime instead. Now working on having both....

Edit 2: As promised, both. Only restriction (that I see) is that the predefined arguments must come before the runtime supplied arguments in the callback function. Thanks to @Chipster for some help with gcc compliance. This works on gcc on ubuntu and visual studio on windows.

#ifdef _WIN32
#define wintypename typename
#else
#define wintypename
#endif

template<class RET, class... RArgs> class Callback_t {
public:
    virtual RET call(RArgs... rargs) = 0;
    virtual ~Callback_t() = default;
};

template<class RET, class... RArgs> class CallbackFactory {
private:
    template<class T, class... CArgs> class Callback : public Callback_t<RET, RArgs...> {
    private:
        T * owner;
        RET(T::*x)(CArgs..., RArgs...);
        std::tuple<CArgs...> cargs;
        RET call(RArgs... rargs) {
            return (*owner.*(x))(std::get<CArgs>(cargs)..., rargs...);
        };
    public:
        Callback(T* t, RET(T::*x)(CArgs..., RArgs...), CArgs... pda);
        ~Callback() {};
    };
public:
    template<class U, class... CArgs> static Callback_t<RET, RArgs...>* make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...));
};
template<class RET2, class... RArgs2> template<class T2, class... CArgs2> CallbackFactory<RET2, RArgs2...>::Callback<T2, CArgs2...>::Callback(T2* t, RET2(T2::*x)(CArgs2..., RArgs2...), CArgs2... pda) : x(x), owner(t), cargs(std::forward<CArgs2>(pda)...) {}
template<class RET, class... RArgs> template<class U, class... CArgs> Callback_t<RET, RArgs...>* CallbackFactory<RET, RArgs...>::make(U* owner, CArgs... cargs, RET(U::*func)(CArgs..., RArgs...)) {
    return new wintypename CallbackFactory<RET, RArgs...>::Callback<U, CArgs...>(owner, func, std::forward<CArgs>(cargs)...);
}

Trigger Change event when the Input value changed programmatically?

You are using jQuery, right? Separate JavaScript from HTML.

You can use trigger or triggerHandler.

var $myInput = $('#changeProgramatic').on('change', ChangeValue);

var anotherFunction = function() {
  $myInput.val('Another value');
  $myInput.trigger('change');
};

Animation fade in and out

Here is my solution. It uses AnimatorSet. AnimationSet library was too buggy to get working. This provides seamless and infinite transitions between fade in and out.

public static void setAlphaAnimation(View v) {
    ObjectAnimator fadeOut = ObjectAnimator.ofFloat(v, "alpha",  1f, .3f);
    fadeOut.setDuration(2000);
    ObjectAnimator fadeIn = ObjectAnimator.ofFloat(v, "alpha", .3f, 1f);
    fadeIn.setDuration(2000);

    final AnimatorSet mAnimationSet = new AnimatorSet();

    mAnimationSet.play(fadeIn).after(fadeOut);

    mAnimationSet.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            mAnimationSet.start();
        }
    });
    mAnimationSet.start();
}

jQuery prevent change for select

Another option to consider is disabling it when you do not want it to be able to be changed and enabling it:

//When select should be disabled:
{
    $('#my_select').attr('disabled', 'disabled');
}

//When select should not be disabled
{
    $('#my_select').removeAttr('disabled');
}

Update since your comment (if I understand the functionality you want):

$("#dropdown").change(function()
{
    var answer = confirm("Are you sure you want to change your selection?")
    {
        if(answer)
        {
            //Update dropdown (Perform update logic)
        }
        else
        {
            //Allow Change (Do nothing - allow change)
        } 
    }            
}); 

Demo

Child inside parent with min-height: 100% not inheriting height

This is a reported webkit (chrome/safari) bug, children of parents with min-height can't inherit the height property: https://bugs.webkit.org/show_bug.cgi?id=26559

Apparently Firefox is affected too (can't test in IE at the moment)

Possible workaround:

  • add position:relative to #containment
  • add position:absolute to #containment-shadow-left

The bug doesn't show when the inner element has absolute positioning.

See http://jsfiddle.net/xrebB/

Edit on April 10, 2014

Since I'm currently working on a project for which I really need parent containers with min-height, and child elements inheriting the height of the container, I did some more research.

First: I'm not so sure anymore whether the current browser behaviour really is a bug. CSS2.1 specs say:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

If I put a min-height on my container, I'm not explicitly specifying its height - so my element should get an auto height. And that's exactly what Webkit - and all other browsers - do.

Second, the workaround I found:

If I set my container element to display:table with height:inherit it acts exactly the same way as if I'd give it a min-height of 100%. And - more importantly - if I set the child element to display:table-cell it will perfectly inherit the height of the container element - whether it's 100% or more.

Full CSS:

html, body {
  height: 100%;
  margin: 0;
}

#container {
  background: green;
  display: table;
  height: inherit;
  width: 100%;
}

#content {
  background: red;
  display: table-cell;
}

The markup:

<div id="container">
  <div id="content">
      <p>content</p>
  </div>
</div>

See http://jsfiddle.net/xrebB/54/.

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

Print raw string from variable? (not getting the answers)

You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

How to make a radio button look like a toggle button

Inspired by Michal B. answer. If you use bootstrap..

_x000D_
_x000D_
label.btn {_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
label.btn input {_x000D_
  opacity: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
label.btn span {_x000D_
  text-align: center;_x000D_
  padding: 6px 12px;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
label.btn input:checked+span {_x000D_
  background-color: rgb(80, 110, 228);_x000D_
  color: #fff;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
<div>_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>One</span></label>_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Two</span></label>_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Three</span></label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get a list of all git commits, including the 'lost' ones

git log --reflog

saved me! I lost mine while merging HEAD and could not find my lates commit! Not showing in source tree but git log --reflog show all my local commits before

Where are the python modules stored?

1) Using the help function

Get into the python prompt and type the following command:

>>>help("modules")

This will list all the modules installed in the system. You don't need to install any additional packages to list them, but you need to manually search or filter the required module from the list.

2) Using pip freeze

sudo apt-get install python-pip
pip freeze

Even though you need to install additional packages to use this, this method allows you to easily search or filter the result with grep command. e.g. pip freeze | grep feed.

You can use whichever method is convenient for you.

Relative imports in Python 3

For PyCharm users:

I also was getting ImportError: attempted relative import with no known parent package because I was adding the . notation to silence a PyCharm parsing error. PyCharm innaccurately reports not being able to find:

lib.thing import function

If you change it to:

.lib.thing import function

it silences the error but then you get the aforementioned ImportError: attempted relative import with no known parent package. Just ignore PyCharm's parser. It's wrong and the code runs fine despite what it says.

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

Managing SSH keys within Jenkins for Git

It looks like the github.com host which jenkins tries to connect to is not listed under the Jenkins user's $HOME/.ssh/known_hosts. Jenkins runs on most distros as the user jenkins and hence has its own .ssh directory to store the list of public keys and known_hosts.

The easiest solution I can think of to fix this problem is:

# Login as the jenkins user and specify shell explicity,
# since the default shell is /bin/false for most
# jenkins installations.
sudo su jenkins -s /bin/bash

cd SOME_TMP_DIR
# git clone YOUR_GITHUB_URL

# Allow adding the SSH host key to your known_hosts

# Exit from su
exit

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

Jquery UI Datepicker not displaying

* html .ui-helper-hidden-accessible 
{
 position: absolute !important; 
 clip: rect(1px 1px 1px 1px); 
 clip: rect(1px,1px,1px,1px); 
}

This just works for IE, so I apply this hack and works fine on FF, Safari and others.

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

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

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

echo Pete > my_name
tar -cf my_data.tar my_name 

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

tar -xvf my_data_now.tar -O

It shows:

my_name
Fool  

Even if you execute

echo $?

tar said that there was no error:

0

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

How to clean up R memory (without the need to restart my PC)?

I came under the same problem with R. I dig a bit and come with a solution, that we need to restart R session to fully clean the memory/RAM. For this, you can use a simple code after removing everything from your workspace. the code is as follows :

rm(list = ls())

.rs.restartR()

Fastest check if row exists in PostgreSQL

Use the EXISTS key word for TRUE / FALSE return:

select exists(select 1 from contact where id=12)

replace \n and \r\n with <br /> in java

For me, this worked:

rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "\\\n");

Tip: use regex tester for quick testing without compiling in your environment

Adding values to an array in java

  • First line : array created.
  • Third line loop started from j = 1 to j = 28123
  • Fourth line you give the variable x value (0) each time the loop is accessed.
  • Fifth line you put the value of j in the index 0.
  • Sixth line you do increment to the value x by 1.(but it will be reset to 0 at line 4)

What is the difference between method overloading and overriding?

Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)
void foo(int a, float b)

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {
    void foo(double d) {
        // do something
    }
}

class Child extends Parent {

    @Override
    void foo(double d){
        // this method is overridden.  
    }
}

Create instance of generic type in Java?

You are correct. You can't do new E(). But you can change it to

private static class SomeContainer<E> {
    E createContents(Class<E> clazz) {
        return clazz.newInstance();
    }
}

It's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.

How to pass command line argument to gnuplot?

You may use trick in unix/linux environment:

  1. in gnuplot program: plot "/dev/stdin" ...

  2. In command line: gnuplot program.plot < data.dat

Eclipse Workspaces: What for and why?

The whole point of a workspace is to group a set of related projects together that usually make up an application. The workspace framework comes down to the eclipse.core.resources plugin and it naturally by design makes sense.

Projects have natures, builders are attached to specific projects and as you change resources in one project you can see in real time compile or other issues in projects that are in the same workspace. So the strategy I suggest is have different workspaces for different projects you work on but without a workspace in eclipse there would be no concept of a collection of projects and configurations and after all it's an IDE tool.

If that does not make sense ask how Net Beans or Visual Studio addresses this? It's the same theme. Maven is a good example, checking out a group of related maven projects into a workspace lets you develop and see errors in real time. If not a workspace what else would you suggest? An RCP application can be a different beast depending on what its used for but in the true IDE sense I don't know what would be a better solution than a workspace or context of projects. Just my thoughts. - Duncan

How to save .xlsx data to file as a blob

Solution for me.

Step: 1

<a onclick="exportAsExcel()">Export to excel</a>

Step: 2

I'm using file-saver lib.

Read more: https://www.npmjs.com/package/file-saver

npm i file-saver

Step: 3

let FileSaver = require('file-saver'); // path to file-saver

function exportAsExcel() {
    let dataBlob = '...kAAAAFAAIcmtzaGVldHMvc2hlZXQxLnhtbFBLBQYAAAAACQAJAD8CAADdGAAAAAA='; // If have ; You should be split get blob data only
    this.downloadFile(dataBlob);
}

function downloadFile(blobContent){
    let blob = new Blob([base64toBlob(blobContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')], {});
    FileSaver.saveAs(blob, 'report.xlsx');
}

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    let sliceSize = 1024;
    let byteCharacters = atob(base64Data);
    let bytesLength = byteCharacters.length;
    let slicesCount = Math.ceil(bytesLength / sliceSize);
    let byteArrays = new Array(slicesCount);
    for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        let begin = sliceIndex * sliceSize;
        let end = Math.min(begin + sliceSize, bytesLength);

        let bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Work for me. ^^

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

On many devices (such as the iPhone), it prevents the user from using the browser's zoom. If you have a map and the browser does the zooming, then the user will see a big ol' pixelated image with huge pixelated labels. The idea is that the user should use the zooming provided by Google Maps. Not sure about any interaction with your plugin, but that's what it's there for.

More recently, as @ehfeng notes in his answer, Chrome for Android (and perhaps others) have taken advantage of the fact that there's no native browser zooming on pages with a viewport tag set like that. This allows them to get rid of the dreaded 300ms delay on touch events that the browser takes to wait and see if your single touch will end up being a double touch. (Think "single click" and "double click".) However, when this question was originally asked (in 2011), this wasn't true in any mobile browser. It's just added awesomeness that fortuitously arose more recently.

Sending multipart/formdata with jQuery.ajax

If the file input name indicates an array and flags multiple, and you parse the entire form with FormData, it is not necessary to iteratively append() the input files. FormData will automatically handle multiple files.

_x000D_
_x000D_
$('#submit_1').on('click', function() {_x000D_
  let data = new FormData($("#my_form")[0]);_x000D_
_x000D_
  $.ajax({_x000D_
    url: '/path/to/php_file',_x000D_
    type: 'POST',_x000D_
    data: data,_x000D_
    processData: false,_x000D_
    contentType: false,_x000D_
    success: function(r) {_x000D_
      console.log('success', r);_x000D_
    },_x000D_
    error: function(r) {_x000D_
      console.log('error', r);_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="my_form">_x000D_
  <input type="file" name="multi_img_file[]" id="multi_img_file" accept=".gif,.jpg,.jpeg,.png,.svg" multiple="multiple" />_x000D_
  <button type="button" name="submit_1" id="submit_1">Not type='submit'</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Note that a regular button type="button" is used, not type="submit". This shows there is no dependency on using submit to get this functionality.

The resulting $_FILES entry is like this in Chrome dev tools:

multi_img_file:
  error: (2) [0, 0]
  name: (2) ["pic1.jpg", "pic2.jpg"]
  size: (2) [1978036, 2446180]
  tmp_name: (2) ["/tmp/phphnrdPz", "/tmp/phpBrGSZN"]
  type: (2) ["image/jpeg", "image/jpeg"]

Note: There are cases where some images will upload just fine when uploaded as a single file, but they will fail when uploaded in a set of multiple files. The symptom is that PHP reports empty $_POST and $_FILES without AJAX throwing any errors. Issue occurs with Chrome 75.0.3770.100 and PHP 7.0. Only seems to happen with 1 out of several dozen images in my test set.

get unique machine id

The following site uses System.Management to accomplish the same is a very sleek way in a console application

How to update the constant height constraint of a UIView programmatically?

If you have a view with multiple constrains, a much easier way without having to create multiple outlets would be:

In interface builder, give each constraint you wish to modify an identifier:

enter image description here

Then in code you can modify multiple constraints like so:

for constraint in self.view.constraints {
    if constraint.identifier == "myConstraint" {
       constraint.constant = 50
    }
}
myView.layoutIfNeeded()

You can give multiple constrains the same identifier thus allowing you to group together constrains and modify all at once.

SQL: Alias Column Name for Use in CASE Statement

Yes, you just need to add a parenthesis :

SELECT col1 as a, (CASE WHEN a = 'test' THEN 'yes' END) as value FROM table;

Incrementing a date in JavaScript

Get the string value of the date using the dateObj.toJSON() method Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON Slice the date from the returned value and then increment by the number of days you want.

var currentdate = new Date();
currentdate.setDate(currentdate.getDate() + 1);
var tomorrow = currentdate.toJSON().slice(0,10);

Using margin:auto to vertically-align a div

Since this question was asked in 2012 and we have come a long way with browser support for flexboxes, I felt as though this answer was obligatory.

If the display of your parent container is flex, then yes, margin: auto auto (also known as margin: auto) will work to center it both horizontally and vertically, regardless if it is an inline or block element.

_x000D_
_x000D_
#parent {
    width: 50vw;
    height: 50vh;
    background-color: gray;
    display: flex;
}
#child {
    margin: auto auto;
}
_x000D_
<div id="parent">
    <div id="child">hello world</div>
</div>
_x000D_
_x000D_
_x000D_

Note that the width/height do not have to be specified absolutely, as in this example jfiddle which uses sizing relative to the viewport.

Although browser support for flexboxes is at an all-time high at time of posting, many browsers still do not support it or require vendor prefixes. Refer to http://caniuse.com/flexbox for updated browser support information.

Update

Since this answer received a bit of attention, I would also like to point out that you don't need to specify margin at all if you're using display: flex and would like to center all of the elements in the container:

_x000D_
_x000D_
#parent {
    width: 50vw;
    height: 50vh;
    background-color: gray;
    display: flex;
    align-items: center; /* vertical */
    justify-content: center; /* horizontal */
}
_x000D_
<div id="parent">
    <div>hello world</div>
</div>
_x000D_
_x000D_
_x000D_

UITapGestureRecognizer - single tap and double tap

I implemented UIGestureRecognizerDelegate methods to detect both singleTap and doubleTap.

Just do this .

 UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTapGesture:)];
    [doubleTap setDelegate:self];
    doubleTap.numberOfTapsRequired = 2;
    [self.headerView addGestureRecognizer:doubleTap];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTapGesture:)];
    singleTap.numberOfTapsRequired = 1;
    [singleTap setDelegate:self];
    [doubleTap setDelaysTouchesBegan:YES];
    [singleTap setDelaysTouchesBegan:YES];
    [singleTap requireGestureRecognizerToFail:doubleTap];
    [self.headerView addGestureRecognizer:singleTap];

Then implement these delegate methods.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    return  YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

How can I style a PHP echo text?

You cannot style a variable such as $ip['countryName']

You can only style elements like p,div, etc, or classes and ids.

If you want to style $ip['countryName'] there are several ways.

You can echo it within an element:

echo '<p id="style">'.$ip['countryName'].'</p>';
echo '<span id="style">'.$ip['countryName'].'</span>';
echo '<div id="style">'.$ip['countryName'].'</div>';

If you want to style both the variables the same style, then set a class like:

echo '<p class="style">'.$ip['cityName'].'</p>';
echo '<p class="style">'.$ip['countryName'].'</p>';

You could also embed the variables within your actual html rather than echoing them out within the code.

$city = $ip['cityName'];  
$country = $ip['countryName'];
?>
<div class="style"><?php echo $city ?></div>
<div class="style"><?php echo $country?></div>

How to create a zip archive of a directory in Python?

To give more flexibility, e.g. select directory/file by name use:

import os
import zipfile

def zipall(ob, path, rel=""):
    basename = os.path.basename(path)
    if os.path.isdir(path):
        if rel == "":
            rel = basename
        ob.write(path, os.path.join(rel))
        for root, dirs, files in os.walk(path):
            for d in dirs:
                zipall(ob, os.path.join(root, d), os.path.join(rel, d))
            for f in files:
                ob.write(os.path.join(root, f), os.path.join(rel, f))
            break
    elif os.path.isfile(path):
        ob.write(path, os.path.join(rel, basename))
    else:
        pass

For a file tree:

.
+-- dir
¦   +-- dir2
¦   ¦   +-- file2.txt
¦   +-- dir3
¦   ¦   +-- file3.txt
¦   +-- file.txt
+-- dir4
¦   +-- dir5
¦   +-- file4.txt
+-- listdir.zip
+-- main.py
+-- root.txt
+-- selective.zip

You can e.g. select only dir4 and root.txt:

cwd = os.getcwd()
files = [os.path.join(cwd, f) for f in ['dir4', 'root.txt']]

with zipfile.ZipFile("selective.zip", "w" ) as myzip:
    for f in files:
        zipall(myzip, f)

Or just listdir in script invocation directory and add everything from there:

with zipfile.ZipFile("listdir.zip", "w" ) as myzip:
    for f in os.listdir():
        if f == "listdir.zip":
            # Creating a listdir.zip in the same directory
            # will include listdir.zip inside itself, beware of this
            continue
        zipall(myzip, f)

How do I use a custom deleter with a std::unique_ptr member?

You just need to create a deleter class:

struct BarDeleter {
  void operator()(Bar* b) { destroy(b); }
};

and provide it as the template argument of unique_ptr. You'll still have to initialize the unique_ptr in your constructors:

class Foo {
  public:
    Foo() : bar(create()), ... { ... }

  private:
    std::unique_ptr<Bar, BarDeleter> bar;
    ...
};

As far as I know, all the popular c++ libraries implement this correctly; since BarDeleter doesn't actually have any state, it does not need to occupy any space in the unique_ptr.

How do I use a pipe to redirect the output of one command to the input of another?

Try this. Copy this into a batch file - such as send.bat - and then simply run send.bat to send the message from the temperature program to the prismcom program.

temperature.exe > msg.txt
set /p msg= < msg.txt
prismcom.exe usb "%msg%"