Programs & Examples On #Stress

Angular get object from array by Id

getDimensions(id) {
    var obj = questions.filter(function(node) {
        return node.id==id;
    });

    return obj;   
}

how to wait for first command to finish?

Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait, and wait short time in every loop. This will result in something like

max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
   if [ -f /tmp/st_new.tmp ]; then
      break # call results.sh outside loop
   else
      (( retry = retry + 1 ))
      sleep 1
   fi
done
if [ -f /tmp/st_new.tmp ]; then
   source ../../results.sh 
   rm -f /tmp/st_new.tmp
else
   echo Something wrong with st_new.sh
fi

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

These are the ways :

1. /proc/meminfo

MemTotal: 8152200 kB

MemFree: 760808 kB

You can write a code or script to parse it.

2. Use sysconf by using below macros

sysconf (_SC_PHYS_PAGES) * sysconf (_SC_PAGESIZE);

3. By using sysinfo system call

int sysinfo(struct sysinfo *info);

struct sysinfo { .

   .

   unsigned long totalram;  /*Total memory size to use */

   unsigned long freeram;   /* Available memory size*/

   .

   . 

  }; 

Best practice for localization and globalization of strings and labels

When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:

  • Conceptualize the specific problem as a set of smaller sub-problems.
  • Solve each smaller problem.
  • Combine the results into a solution of the specific problem.

But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:

  • Conceptualize the specific problem as a special case of a more general problem.
  • Somehow solve the general problem.
  • Adapt the solution of the general problem to the specific problem.

- Eric Lippert

I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.

I've outlined some of the major aspects of the problem

  • Issue: We need to load data only for the desired language

    Solution: For this purpose we save data to a separate files for each language

ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)

  • Issue: Resource files for each page should be separated so we only get the data we need

    Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload

  • Issue: We need a key/value pair structure to save our data

    Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE

  • Issue: General members should be stored in a public file and all pages should access them

    Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'

  • Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope

    Solution: I considered a file for each

Application Structure

root/
    Global_Resources/
        default.js
        default.fr.js
    UserManagementSystem/
        Local_Resources/
            default.js
            default.fr.js
            createUser.js
        Login.htm
        CreateUser.htm

The corresponding code for the files:

Global_Resources/default.js

var res = {
    Create : "Create",
    Update : "Save Changes",
    Delete : "Delete"
};

Global_Resources/default.fr.js

var res = {
    Create : "créer",
    Update : "Enregistrer les modifications",
    Delete : "effacer"
};

The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.

UserManagementSystem/Local_Resources/default.js

res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";

UserManagementSystem/Local_Resources/default.fr.js

res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";

UserManagementSystem/Local_Resources/createUser.js

// Override res.Create on Global_Resources/default.js
res.Create = "Create User"; 

UserManagementSystem/Local_Resources/createUser.fr.js

// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";

manager.js file (this file should be load last)

res.lang = "fr";

var globalResourcePath = "Global_Resources";
var resourceFiles = [];

var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;

if(!IsFileExist(currentFile))
    currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");

resourceFiles.push(currentFile);

// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
    currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";

    if(!IsExist(currentFile))
        currentFile = folder + "\\Local_Resource\\default.js";
    if(!IsExist(currentFile)) throw new Exception("File Not Found");

    resourceFiles.push(currentFile);
}

for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }

// Get current page name
var pageNameWithoutExtension = "SomePage";

currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;

if(!IsExist(currentFile))
    currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");

Hope it helps :)

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

I would detect red rectangles: RGB -> HSV, filter red -> binary image, close (dilate then erode, known as imclose in matlab)

Then look through rectangles from largest to smallest. Rectangles that have smaller rectangles in a known position/scale can both be removed (assuming bottle proportions are constant, the smaller rectangle would be a bottle cap).

This would leave you with red rectangles, then you'll need to somehow detect the logos to tell if they're a red rectangle or a coke can. Like OCR, but with a known logo?

Load vs. Stress testing

The terms "stress testing" and "load testing" are often used interchangeably by software test engineers but they are really quite different.

Stress testing

In Stress testing we tries to break the system under test by overwhelming its resources or by taking resources away from it (in which case it is sometimes called negative testing). The main purpose behind this madness is to make sure that the system fails and recovers gracefully -- this quality is known as recoverability. OR Stress testing is the process of subjecting your program/system under test (SUT) to reduced resources and then examining the SUT’s behavior by running standard functional tests. The idea of this is to expose problems that do not appear under normal conditions.For example, a multi-threaded program may work fine under normal conditions but under conditions of reduced CPU availability, timing issues will be different and the SUT will crash. The most common types of system resources reduced in stress testing are CPU, internal memory, and external disk space. When performing stress testing, it is common to call the tools which reduce these three resources EatCPU, EatMem, and EatDisk respectively.

While on the other hand Load Testing

In case of Load testing Load testing is the process of subjecting your SUT to heavy loads, typically by simulating multiple users( Using Load runner), where "users" can mean human users or virtual/programmatic users. The most common example of load testing involves subjecting a Web-based or network-based application to simultaneous hits by thousands of users. This is generally accomplished by a program which simulates the users. There are two main purposes of load testing: to determine performance characteristics of the SUT, and to determine if the SUT "breaks" gracefully or not.

In the case of a Web site, you would use load testing to determine how many users your system can handle and still have adequate performance, and to determine what happens with an extreme load — will the Web site generate a "too busy" message for users, or will the Web server crash in flames?

Why does modern Perl avoid UTF-8 by default?

We're all in agreement that it is a difficult problem for many reasons, but that's precisely the reason to try to make it easier on everybody.

There is a recent module on CPAN, utf8::all, that attempts to "turn on Unicode. All of it".

As has been pointed out, you can't magically make the entire system (outside programs, external web requests, etc.) use Unicode as well, but we can work together to make sensible tools that make doing common problems easier. That's the reason that we're programmers.

If utf8::all doesn't do something you think it should, let's improve it to make it better. Or let's make additional tools that together can suit people's varying needs as well as possible.

`

How to implement the factory method pattern in C++ correctly

You can read a very good solution in: http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus

The best solution is on the "comments and discussions", see the "No need for static Create methods".

From this idea, I've done a factory. Note that I'm using Qt, but you can change QMap and QString for std equivalents.

#ifndef FACTORY_H
#define FACTORY_H

#include <QMap>
#include <QString>

template <typename T>
class Factory
{
public:
    template <typename TDerived>
    void registerType(QString name)
    {
        static_assert(std::is_base_of<T, TDerived>::value, "Factory::registerType doesn't accept this type because doesn't derive from base class");
        _createFuncs[name] = &createFunc<TDerived>;
    }

    T* create(QString name) {
        typename QMap<QString,PCreateFunc>::const_iterator it = _createFuncs.find(name);
        if (it != _createFuncs.end()) {
            return it.value()();
        }
        return nullptr;
    }

private:
    template <typename TDerived>
    static T* createFunc()
    {
        return new TDerived();
    }

    typedef T* (*PCreateFunc)();
    QMap<QString,PCreateFunc> _createFuncs;
};

#endif // FACTORY_H

Sample usage:

Factory<BaseClass> f;
f.registerType<Descendant1>("Descendant1");
f.registerType<Descendant2>("Descendant2");
Descendant1* d1 = static_cast<Descendant1*>(f.create("Descendant1"));
Descendant2* d2 = static_cast<Descendant2*>(f.create("Descendant2"));
BaseClass *b1 = f.create("Descendant1");
BaseClass *b2 = f.create("Descendant2");

How do I remove the "extended attributes" on a file in Mac OS X?

Removing a Single Attribute on a Single File

See Bavarious's answer.


To Remove All Extended Attributes On a Single File

Use xattr with the -c flag to "clear" the attributes:

xattr -c yourfile.txt



To Remove All Extended Attributes On Many Files

To recursively remove extended attributes on all files in a directory, combine the -c "clear" flag with the -r recursive flag:

xattr -rc /path/to/directory



A Tip for Mac OS X Users

Have a long path with spaces or special characters?

Open Terminal.app and start typing xattr -rc, include a trailing space, and then then drag the file or folder to the Terminal.app window and it will automatically add the full path with proper escaping.

long long int vs. long int vs. int64_t in C++

You don't need to go to 64-bit to see something like this. Consider int32_t on common 32-bit platforms. It might be typedef'ed as int or as a long, but obviously only one of the two at a time. int and long are of course distinct types.

It's not hard to see that there is no workaround which makes int == int32_t == long on 32-bit systems. For the same reason, there's no way to make long == int64_t == long long on 64-bit systems.

If you could, the possible consequences would be rather painful for code that overloaded foo(int), foo(long) and foo(long long) - suddenly they'd have two definitions for the same overload?!

The correct solution is that your template code usually should not be relying on a precise type, but on the properties of that type. The whole same_type logic could still be OK for specific cases:

long foo(long x);
std::tr1::disable_if(same_type(int64_t, long), int64_t)::type foo(int64_t);

I.e., the overload foo(int64_t) is not defined when it's exactly the same as foo(long).

[edit] With C++11, we now have a standard way to write this:

long foo(long x);
std::enable_if<!std::is_same<int64_t, long>::value, int64_t>::type foo(int64_t);

[edit] Or C++20

long foo(long x);
int64_t foo(int64_t) requires (!std::is_same_v<int64_t, long>);

In plain English, what does "git reset" do?

TL;DR

git reset resets Staging to the last commit. Use --hard to also reset files in your Working directory to the last commit.

LONGER VERSION

But that's obviously simplistic hence the many rather verbose answers. It made more sense for me to read up on git reset in the context of undoing changes. E.g. see this:

If git revert is a “safe” way to undo changes, you can think of git reset as the dangerous method. When you undo with git reset(and the commits are no longer referenced by any ref or the reflog), there is no way to retrieve the original copy—it is a permanent undo. Care must be taken when using this tool, as it’s one of the only Git commands that has the potential to lose your work.

From https://www.atlassian.com/git/tutorials/undoing-changes/git-reset

and this

On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.

From https://www.atlassian.com/git/tutorials/resetting-checking-out-and-reverting/commit-level-operations

How should you diagnose the error SEHException - External component has thrown an exception

My machine configurations :

Operating System : Windows 10 Version 1703 (x64)

I faced this error while debugging my C# .Net project in Visual Studio 2017 Community edition. I was calling a native method by performing p/invoke on a C++ assembly loaded at run-time. I encountered the very same error reported by OP.

I realized that Visual Studio was launched with a user account which was not an administrator on the machine. Then I relaunched Visual Studio under a different user account which was an administrator on the machine. That's all. My problem got resolved and I didn't face the issue again.

One thing to note is that the method which was being invoked on C++ assembly was supposed to write few things in registry. I didn't go debugging the C++ code to do some RCA but I see a possibility that the whole thing was failing as administrative privileges are required to write registry in Windows 10 operating system. So earlier when Visual Studio was running under a user account which didn't have administrative privileges on the machine, then the native calls were failing.

Best way to stress test a website

Try http://loadimpact.com the best I have found so far, but no alternative to it I can find.

How to find good looking font color if background color is known?

This is an interesting question, but I don't think this is actually possible. Whether or not two colors "fit" as background and foreground colors is dependent upon display technology and physiological characteristics of human vision, but most importantly on upon personal tastes shaped by experience. A quick run through MySpace shows pretty clearly that not all human beings perceive colors in the same way. I don't think this is a problem that can be solved algorithmically, although there may be a huge database somewhere of acceptable matching colors.

Performing a Stress Test on Web Application?

Trying all mentioned here, I found curl-loader as best for my purposes. very easy interface, real-time monitoring, useful statistics, from which I build graphs of performance. All features of libcurl are included.

WinError 2 The system cannot find the file specified (Python)

Popen expect a list of strings for non-shell calls and a string for shell calls.

Call subprocess.Popen with shell=True:

process = subprocess.Popen(command, stdout=tempFile, shell=True)

Hopefully this solves your issue.

This issue is listed here: https://bugs.python.org/issue17023

Java Spring - How to use classpath to specify a file location?

From an answer of @NimChimpsky in similar question:

Resource resource = new ClassPathResource("storedProcedures.sql");
InputStream resourceInputStream = resource.getInputStream();

Using ClassPathResource and interface Resource. And make sure you are adding the resources directory correctly (adding /src/main/resources/ into the classpath).

Note that Resource have a method to get a java.io.File so you can also use:

Resource resource = new ClassPathResource("storedProcedures.sql");
FileReader fr = new FileReader(resource.getFile());

Connect to SQL Server Database from PowerShell

The answer are as below for Window authentication

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SQLServer;Database=$SQLDBName;Integrated Security=True;"

HTML5 phone number validation with pattern

How about

<input type="text" pattern="[789][0-9]{9}">

Split string on whitespace in Python

The str.split() method without an argument splits on whitespace:

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']

How to resolve symbolic links in a shell script

Here's how one can get the actual path to the file in MacOS/Unix using an inline Perl script:

FILE=$(perl -e "use Cwd qw(abs_path); print abs_path('$0')")

Similarly, to get the directory of a symlinked file:

DIR=$(perl -e "use Cwd qw(abs_path); use File::Basename; print dirname(abs_path('$0'))")

php: loop through json array

First you have to decode your json :

$array = json_decode($the_json_code);

Then after the json decoded you have to do the foreach

foreach ($array as $key => $jsons) { // This will search in the 2 jsons
     foreach($jsons as $key => $value) {
         echo $value; // This will show jsut the value f each key like "var1" will print 9
                       // And then goes print 16,16,8 ...
    }
}

If you want something specific just ask for a key like this. Put this between the last foreach.

if($key == 'var1'){
 echo $value;
}

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

Most efficient T-SQL way to pad a varchar on the left to a certain length?

This is simply an inefficient use of SQL, no matter how you do it.

perhaps something like

right('XXXXXXXXXXXX'+ rtrim(@str), @n)

where X is your padding character and @n is the number of characters in the resulting string (assuming you need the padding because you are dealing with a fixed length).

But as I said you should really avoid doing this in your database.

Is it possible to dynamically compile and execute C# code fragments?

The best solution in C#/all static .NET languages is to use the CodeDOM for such things. (As a note, its other main purpose is for dynamically constructing bits of code, or even whole classes.)

Here's a nice short example take from LukeH's blog, which uses some LINQ too just for fun.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

class Program
{
    static void Main(string[] args)
    {
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
        parameters.GenerateExecutable = true;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class Program {
              public static void Main(string[] args) {
                var q = from i in Enumerable.Range(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }
}

The class of primary importance here is the CSharpCodeProvider which utilises the compiler to compile code on the fly. If you want to then run the code, you just need to use a bit of reflection to dynamically load the assembly and execute it.

Here is another example in C# that (although slightly less concise) additionally shows you precisely how to run the runtime-compiled code using the System.Reflection namespace.

Array versus linked-list

Besides convenience in insertions and deletions, the memory representation of linked list is different than the arrays. There is no restriction on the number of elements in a linked list, while in the arrays, you have to specify the total number of elements. Check this article.

Difference between JSON.stringify and JSON.parse

Firstly, JSON.stringify() function converts a JavaScript value to a JavaScript Object Notation (JSON) string. JSON.parse() function converts a JavaScript Object Notation (JSON) string into an object. For more information about these two functions, please refer to the following links.

https://msdn.microsoft.com/library/cc836459(v=vs.94).aspx https://msdn.microsoft.com/library/cc836466(v=vs.94).aspx

Secondly, the following sample will be helpful for you to understand these two functions.

<form id="form1" runat="server">
    <div>
        <div id="result"></div>
    </div>
</form>

<script>
    $(function () {
        //define a json object
        var employee = { "name": "John Johnson", "street": "Oslo West 16", "phone": "555 1234567" };

        //use JSON.stringify to convert it to json string
        var jsonstring = JSON.stringify(employee);
        $("#result").append('<p>json string: ' + jsonstring + '</p>');

        //convert json string to json object using JSON.parse function
        var jsonobject = JSON.parse(jsonstring);
        var info = '<ul><li>Name:' + jsonobject.name + '</li><li>Street:' + jsonobject.street + '</li><li>Phone:' + jsonobject.phone + '</li></ul>';

        $("#result").append('<p>json object:</p>');
        $("#result").append(info);
    });
</script>

How to delete columns in numpy.array

Another way is to use masked arrays:

import numpy as np
a = np.array([[ np.nan,   2.,   3., np.nan], [  1.,   2.,   3., 9]])
print(a)
# [[ NaN   2.   3.  NaN]
#  [  1.   2.   3.   9.]]

The np.ma.masked_invalid method returns a masked array with nans and infs masked out:

print(np.ma.masked_invalid(a))
[[-- 2.0 3.0 --]
 [1.0 2.0 3.0 9.0]]

The np.ma.compress_cols method returns a 2-D array with any column containing a masked value suppressed:

a=np.ma.compress_cols(np.ma.masked_invalid(a))
print(a)
# [[ 2.  3.]
#  [ 2.  3.]]

See manipulating-a-maskedarray

Compare two columns using pandas

Use np.select if you have multiple conditions to be checked from the dataframe and output a specific choice in a different column

conditions=[(condition1),(condition2)]
choices=["choice1","chocie2"]

df["new column"]=np.select=(condtion,choice,default=)

Note: No of conditions and no of choices should match, repeat text in choice if for two different conditions you have same choices

Where is Python language used?

Python started as a scripting language for Linux like Perl but less cryptic. Now it is used for both web and desktop applications and is available on Windows too. Desktop GUI APIs like GTK have their Python implementations and Python based web frameworks like Django are preferred by many over PHP et al. for web applications.

And by the way,

  • What can you do with PHP that you can't do with ASP or JSP?
  • What can you do with Java that you can't do with C++?

How do I correctly clean up a Python object?

It seems that the idiomatic way to do this is to provide a close() method (or similar), and call it explicitely.

SQL Server - INNER JOIN WITH DISTINCT

I think you actually provided a good start for the correct answer right in your question (you just need the correct syntax). I had this exact same problem, and putting DISTINCT in a sub-query was indeed less costly than what other answers here have proposed.

select a.FirstName, a.LastName, v.District
from AddTbl a 
inner join (select distinct LastName, District 
    from ValTbl) v
   on a.LastName = v.LastName
order by Firstname   

How do I change an HTML selected option using JavaScript?

You can use JQuery also

$(document).ready(function () {
  $('#personlist').val("10");
}

How to use shell commands in Makefile

Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.

If you're on GNU Make, use the := assignment instead of =. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.

FILES := $(shell ...)  # expand now; FILES is now the result of $(shell ...)

FILES = $(shell ...)   # expand later: FILES holds the syntax $(shell ...)

If you use the = assignment, it means that every single occurrence of $(FILES) will be expanding the $(shell ...) syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.

python numpy ValueError: operands could not be broadcast together with shapes

You are looking for np.matmul(X, y). In Python 3.5+ you can use X @ y.

Inserting Image Into BLOB Oracle 10g

You should do something like this:

1) create directory object what would point to server-side accessible folder

CREATE DIRECTORY image_files AS '/data/images'
/

2) Place your file into OS folder directory object points to

3) Give required access privileges to Oracle schema what will load data from file into table:

GRANT READ ON DIRECTORY image_files TO scott
/

4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:

DECLARE
  l_blob BLOB; 
  v_src_loc  BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
  v_amount   INTEGER;
BEGIN
  INSERT INTO esignatures  
  VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob; 
  DBMS_LOB.OPEN(v_src_loc, DBMS_LOB.LOB_READONLY);
  v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
  DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);
  DBMS_LOB.CLOSE(v_src_loc);
  COMMIT;
END;
/

After this you get the content of your file in BLOB column and can get it back using Java for example.

edit: One letter left missing: it should be LOADFROMFILE.

Allowed memory size of X bytes exhausted

If by increasing the memory limit you have gotten rid of the error and your code now works, you'll need to take measures to decrease that memory usage. Here are a few things you could do to decrease it:

If you're reading files, read them line-by-line instead of reading in the complete file into memory. Look at fgets and SplFileObject::fgets. Upgrade to a new version of PHP if you're using PHP 5.3. PHP 5.4 and 5.5 use much less memory.

Avoid loading large datasets into in an array. Instead, go for processing smaller subsets of the larger dataset and, if necessary, persist your data into a database to relieve memory use.

Try the latest version or minor version of a third-party library (1.9.3 vs. your 1.8.2, for instance) and use whichever is more stable. Sometimes newer versions of libraries are written more efficiently.

If you have an uncommon or unstable PHP extension, try upgrading it. It might have a memory leak.

If you're dealing with large files and you simply can't read it line-by-line, try breaking the file into many smaller files and process those individually. Disable PHP extensions that you don't need.

In the problem area, unset variables which contain large amounts of data and aren't required later in the code.

FROM: https://www.airpair.com/php/fatal-error-allowed-memory-size

is of a type that is invalid for use as a key column in an index

Noting klaisbyskov's comment about your key length needing to be gigabytes in size, and assuming that you do in fact need this, then I think your only options are:

  1. use a hash of the key value
    • Create a column on nchar(40) (for a sha1 hash, for example),
    • put a unique key on the hash column.
    • generate the hash when saving or updating the record
  2. triggers to query the table for an existing match on insert or update.

Hashing comes with the caveat that one day, you might get a collision.

Triggers will scan the entire table.

Over to you...

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

I also faced this problem because I just only installed JRE not with JDK. So , adding dependency for jdk.tools can't fix for me because tools.jar was not exist at my ${JAVA_HOME}/lib/ directory.

Now I downloaded and installed JDK to fix it.

Input and Output binary streams using JERSEY?

Here's another example. I'm creating a QRCode as a PNG via a ByteArrayOutputStream. The resource returns a Response object, and the stream's data is the entity.

To illustrate the response code handling, I've added handling of cache headers (If-modified-since, If-none-matches, etc).

@Path("{externalId}.png")
@GET
@Produces({"image/png"})
public Response getAsImage(@PathParam("externalId") String externalId, 
        @Context Request request) throws WebApplicationException {

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    // do something with externalId, maybe retrieve an object from the
    // db, then calculate data, size, expirationTimestamp, etc

    try {
        // create a QRCode as PNG from data     
        BitMatrix bitMatrix = new QRCodeWriter().encode(
                data, 
                BarcodeFormat.QR_CODE, 
                size, 
                size
        );
        MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);

    } catch (Exception e) {
        // ExceptionMapper will return HTTP 500 
        throw new WebApplicationException("Something went wrong …")
    }

    CacheControl cc = new CacheControl();
    cc.setNoTransform(true);
    cc.setMustRevalidate(false);
    cc.setNoCache(false);
    cc.setMaxAge(3600);

    EntityTag etag = new EntityTag(HelperBean.md5(data));

    Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(
            updateTimestamp,
            etag
    );
    if (responseBuilder != null) {
        // Preconditions are not met, returning HTTP 304 'not-modified'
        return responseBuilder
                .cacheControl(cc)
                .build();
    }

    Response response = Response
            .ok()
            .cacheControl(cc)
            .tag(etag)
            .lastModified(updateTimestamp)
            .expires(expirationTimestamp)
            .type("image/png")
            .entity(stream.toByteArray())
            .build();
    return response;
}   

Please don't beat me up in case stream.toByteArray() is a no-no memory wise :) It works for my <1KB PNG files...

Batch file script to zip files

This is the correct syntax for archiving individual; folders in a batch as individual zipped files...

for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a -mx "%%X.zip" "%%X\*"

How do I get the browser scroll position in jQuery?

Since it appears you are using jQuery, here is a jQuery solution.

$(function() {
    $('#Eframe').on("mousewheel", function() {
        alert($(document).scrollTop());
    });
});

Not much to explain here. If you want, here is the jQuery documentation.

Deserialize JSON with C#

Newtonsoft.JSON is a good solution for these kind of situations. Also Newtonsof.JSON is faster than others, such as JavaScriptSerializer, DataContractJsonSerializer.

In this sample, you can the following:

var jsonData = JObject.Parse("your JSON data here");

Then you can cast jsonData to JArray, and you can use a for loop to get data at each iteration.

Also, I want to add something:

for (int i = 0; (JArray)jsonData["data"].Count; i++)
{
    var data = jsonData[i - 1];
}

Working with dynamic object and using Newtonsoft serialize is a good choice.

Git commit date

If you like to have the timestamp without the timezone but local timezone do

git log -1 --format=%cd --date=local

Which gives this depending on your location

Mon Sep 28 12:07:37 2015

Get my phone number in android

Method 1:

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

With below permission

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

Method 2:

There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

Try below code:

String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
        main_data, "mimetype=?",
        new String[]{"vnd.android.cursor.item/phone_v2"},
        "is_primary DESC");
if (object != null) {
    do {
        if (!((Cursor) (object)).moveToNext())
            break;
        String s1 = ((Cursor) (object)).getString(4);
    } while (true);
    ((Cursor) (object)).close();
}

You will need to add these two permissions.

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />

Hope this helps, Thanks!

How do I pass a datetime value as a URI parameter in asp.net mvc?

Since MVC 5 you can use the built in Attribute Routing package which supports a datetime type, which will accept anything that can be parsed to a DateTime.

e.g.

[GET("Orders/{orderDate:datetime}")]

More info here.

jquery data selector

At the moment I'm selecting like this:

$('a[data-attribute=true]')

Which seems to work just fine, but it would be nice if jQuery was able to select by that attribute without the 'data-' prefix.

I haven't tested this with data added to elements via jQuery dynamically, so that could be the downfall of this method.

JSON.stringify doesn't work with normal Javascript array

Json has to have key-value pairs. Tho you can still have an array as the value part. Thus add a "key" of your chousing:

var json = JSON.stringify({whatver: test});

How to delete all files and folders in a folder by cmd call

If the subfolder names may contain spaces you need to surround them in escaped quotes. The following example shows this for commands used in a batch file.

set targetdir=c:\example
del /q %targetdir%\*
for /d %%x in (%targetdir%\*) do @rd /s /q ^"%%x^"

How to convert map to url query string?

Update June 2016

Felt compelled to add an answer having seen far too many SOF answers with dated or inadequate answers to very common problem - a good library and some solid example usage for both parse and format operations.

Use org.apache.httpcomponents.httpclient library. The library contains this org.apache.http.client.utils.URLEncodedUtils class utility.

For example, it is easy to download this dependency from Maven:

 <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5</version>
 </dependency>

For my purposes I only needed to parse (read from query string to name-value pairs) and format (read from name-value pairs to query string) query strings. However, there are equivalents for doing the same with a URI (see commented out line below).

// Required imports

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

// code snippet

public static void parseAndFormatExample() throws UnsupportedEncodingException {
        final String queryString = "nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk";
        System.out.println(queryString);
        // => nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk

        final List<NameValuePair> params =
                URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);
        // List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), "UTF-8");

        for (final NameValuePair param : params) {
            System.out.println(param.getName() + " : " + param.getValue());
            // => nonce : 12345
            // => redirectCallbackUrl : http://www.bbc.co.uk
        }

        final String newQueryStringEncoded =
                URLEncodedUtils.format(params, StandardCharsets.UTF_8);


        // decode when printing to screen
        final String newQueryStringDecoded =
                URLDecoder.decode(newQueryStringEncoded, StandardCharsets.UTF_8.toString());
        System.out.println(newQueryStringDecoded);
        // => nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk
    }

This library did exactly what I needed and was able to replace some hacked custom code.

How can I convert integer into float in Java?

Sameer:

float l = new Float(x/y)

will not work, as it will compute integer division of x and y first, then construct a float from it.

float result = (float) x / (float) y;

Is semantically the best candidate.

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

Uninstall the apk(app that you are working) from your android device and then run again.

Can't load IA 32-bit .dll on a AMD 64-bit platform

I had the same issue with a Java application using tibco dll originally intended to run on Win XP. To get it to work on Windows 7, I made the application point to 32-bit JRE. Waiting to see if there is another solution.

Making PHP var_dump() values display one line per value

I really love var_export(). If you like copy/paste-able code, try:

echo '<pre>' . var_export($data, true) . '</pre>';

Or even something like this for color syntax highlighting:

highlight_string("<?php\n\$data =\n" . var_export($data, true) . ";\n?>");

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

apache not accepting incoming connections from outside of localhost

SELinux prevents Apache (and therefore all Apache modules) from making remote connections by default.

# setsebool -P httpd_can_network_connect=1

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

I got this error:

System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

when the port was used by another program.

How do I clear the content of a div using JavaScript?

You can do it the DOM way as well:

var div = document.getElementById('cart_item');
while(div.firstChild){
    div.removeChild(div.firstChild);
}

How to close Browser Tab After Submitting a Form?

Window.close( ) does not work as it used to. Can be seen here:

window.close and self.close do not close the window in Chrome

In my case, I realized that I didn't need to close the page. So you can redirect the user to another page with:

window.location.replace("https://stackoverflow.com/");

C++ equivalent of StringBuffer/StringBuilder?

The Rope container may be worth if have to insert/delete string into the random place of destination string or for a long char sequences. Here is an example from SGI's implementation:

crope r(1000000, 'x');          // crope is rope<char>. wrope is rope<wchar_t>
                                // Builds a rope containing a million 'x's.
                                // Takes much less than a MB, since the
                                // different pieces are shared.
crope r2 = r + "abc" + r;       // concatenation; takes on the order of 100s
                                // of machine instructions; fast
crope r3 = r2.substr(1000000, 3);       // yields "abc"; fast.
crope r4 = r2.substr(1000000, 1000000); // also fast.
reverse(r2.mutable_begin(), r2.mutable_end());
                                // correct, but slow; may take a
                                // minute or more.

Convert varchar into datetime in SQL Server

SQL Server can implicitly cast strings in the form of 'YYYYMMDD' to a datetime - all other strings must be explicitly cast. here are two quick code blocks which will do the conversion from the form you are talking about:

version 1 uses unit variables:

BEGIN 
DECLARE @input VARCHAR(8), @mon CHAR(2), 
@day char(2), @year char(4), @output DATETIME

SET @input = '10022009'   --today's date


SELECT @mon = LEFT(@input, 2), @day = SUBSTRING(@input, 3,2), @year = RIGHT(@input,4)

SELECT @output = @year+@mon+@day 
SELECT @output 
END

version 2 does not use unit variables:

BEGIN 
DECLARE @input CHAR(8), @output DATETIME
SET @input = '10022009' --today's date 

SELECT @output = RIGHT(@input,4) + SUBSTRING(@input, 3,2) + LEFT(@input, 2)

SELECT @output
END

Both cases rely on sql server's ability to do that implicit conversion.

Conditional logic in AngularJS template

You can use ng-show on every div element in the loop. Is this what you've wanted: http://jsfiddle.net/pGwRu/2/ ?

<div class="from" ng-show="message.from">From: {{message.from.name}}</div>

std::queue iteration

I use something like this. Not very sophisticated but should work.

    queue<int> tem; 

    while(!q1.empty()) // q1 is your initial queue. 
    {
        int u = q1.front(); 

        // do what you need to do with this value.  

        q1.pop(); 
        tem.push(u); 
    }


    while(!tem.empty())
    {
        int u = tem.front(); 
        tem.pop(); 
        q1.push(u); // putting it back in our original queue. 
    }

It will work because when you pop something from q1, and push it into tem, it becomes the first element of tem. So, in the end tem becomes a replica of q1.

How to remove empty cells in UITableView?

override func viewWillAppear(animated: Bool) {
    self.tableView.tableFooterView = UIView(frame: CGRect.zeroRect)

/// OR 

    self.tableView.tableFooterView = UIView()
}

You must add a reference to assembly 'netstandard, Version=2.0.0.0

This issue is based on your installed version of visual studio and Windows, you can follow the following steps:-

  1. Go to Command Window
  2. downgraded your PCL by the following command

    Install-Package Xamarin.Forms -Version 2.5.1.527436
    
  3. Rebuild Your Project.
  4. Now You will able to see the required output

Add Items to ListView - Android

Try this one it will work

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}

How to access Winform textbox control from another class?

I would recommend that you don't. Do you really want to have a class that is dependent on how the text editing is implemented in the form, or do you want a mechanism allowing you to get and set the text?

I would suggest the latter. So in your form, create a property that wraps the Text property of the TextBox control in question:

public string FirstName
{
    get { return firstNameTextBox.Text; }
    set { firstNameTextBox.Text = value; }
}

Next, create some mechanism through which you class can get a reference to the form (through the contructor for instance). Then that class can use the property to access and modify the text:

class SomeClass
{
    private readonly YourFormClass form;
    public SomeClass(YourFormClass form)
    {
        this.form = form;
    }

    private void SomeMethodDoingStuffWithText()
    {
        string firstName = form.FirstName;
        form.FirstName = "some name";
    }
}

An even better solution would be to define the possible interactions in an interface, and let that interface be the contract between your form and the other class. That way the class is completely decoupled from the form, and can use anyting implementing the interface (which opens the door for far easier testing):

interface IYourForm
{
    string FirstName { get; set; }
}

In your form class:

class YourFormClass : Form, IYourForm
{
    // lots of other code here

    public string FirstName
    {
        get { return firstNameTextBox.Text; }
        set { firstNameTextBox.Text = value; }
    }
}

...and the class:

class SomeClass
{
    private readonly IYourForm form;
    public SomeClass(IYourForm form)
    {
        this.form = form;
    }

    // and so on

}

Media Queries - In between two widths

@Jonathan Sampson i think your solution is wrong if you use multiple @media.

You should use (min-width first):

@media screen and (min-width:400px) and (max-width:900px){
   ...
}

DateTime "null" value

You can use a nullable class.

DateTime? date = new DateTime?();

Getting the last n elements of a vector. Is there a better way than using the length() function?

I just add here something related. I was wanted to access a vector with backend indices, ie writting something like tail(x, i) but to return x[length(x) - i + 1] and not the whole tail.

Following commentaries I benchmarked two solutions:

accessRevTail <- function(x, n) {
    tail(x,n)[1]
}

accessRevLen <- function(x, n) {
  x[length(x) - n + 1]
}

microbenchmark::microbenchmark(accessRevLen(1:100, 87), accessRevTail(1:100, 87))
Unit: microseconds
                     expr    min      lq     mean median      uq     max neval
  accessRevLen(1:100, 87)  1.860  2.3775  2.84976  2.803  3.2740   6.755   100
 accessRevTail(1:100, 87) 22.214 23.5295 28.54027 25.112 28.4705 110.833   100

So it appears in this case that even for small vectors, tail is very slow comparing to direct access

Authentication failed to bitbucket

If you made an account using google/ other oauth, then you need to set a bitbucket password for your account first. The URL for that is : https://bitbucket.org/account/user// or look for Bitbucket settings under the menu.

Then can login from git (I tried via command line). I use the built in manager for credentials :

credential.helper=manager

Now, after I set the password on the bitbucket site (email verified too), and tried to push again, it prompted me for the password, then pushed the code.

Menu location image on bitbucket web page -> http://ctrlv.in/747291 as of May 2016.

Adding the "Clear" Button to an iPhone UITextField

Swift 4+:

textField.clearButtonMode = UITextField.ViewMode.whileEditing

or even shorter:

textField.clearButtonMode = .whileEditing

how to get a list of dates between two dates in java

You can also look at the Date.getTime() API. That gives a long to which you can add your increment. Then create a new Date.

List<Date> dates = new ArrayList<Date>();
long interval = 1000 * 60 * 60; // 1 hour in millis
long endtime = ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
  dates.add(new Date(curTime));
  curTime += interval;
}

and maybe apache commons has something like this in DateUtils, or perhaps they have a CalendarUtils too :)

EDIT

including the start and enddate may not be possible if your interval is not perfect :)

Java - How to find the redirected url of a url?

@balusC I did as you wrote . In my case , I've added cookie information to be able to reuse the session .

   // get the cookie if need
    String cookies = conn.getHeaderField("Set-Cookie");

    // open the new connnection again
    conn = (HttpURLConnection) new URL(newUrl).openConnection();
    conn.setRequestProperty("Cookie", cookies);

Switching to landscape mode in Android Emulator

On iMac with long keyboard (keyboard with numeric keypad at the right):

(1) Cmd + 7 (on numeric part of keyboard)
(2) Cmd + 9 (on numeric part of keyboard)

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

make sure you download the x86 SDK instead of only the x64 SDK for visual studio.

How to give a Blob uploaded as FormData a file name?

Adding this here as it doesn't seem to be here.

Aside from the excellent solution of form.append("blob",blob, filename); you can also turn the blob into a File instance:

var blob = new Blob([JSON.stringify([0,1,2])], {type : 'application/json'});
var fileOfBlob = new File([blob], 'aFileName.json');
form.append("upload", fileOfBlob);

Instantly detect client disconnection from server socket

i had same problem , try this :

void client_handler(Socket client) // set 'KeepAlive' true
{
    while (true)
    {
        try
        {
            if (client.Connected)
            {

            }
            else
            { // client disconnected
                break;
            }
        }
        catch (Exception)
        {
            client.Poll(4000, SelectMode.SelectRead);// try to get state
        }
    }
}

"You may need an appropriate loader to handle this file type" with Webpack and Babel

If you are using Webpack > 3 then you only need to install babel-preset-env, since this preset accounts for es2015, es2016 and es2017.

var path = require('path');
let webpack = require("webpack");

module.exports = {
    entry: {
        app: './app/App.js',
        vendor: ["react","react-dom"]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, '../public')
    },
    module: {
        rules: [{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader?cacheDirectory=true',
            }
        }]
    }
};

This picks up its configuration from my .babelrc file:

{
    "presets": [
        [
            "env",
            {
                "targets": {
                    "browsers":["last 2 versions"],
                    "node":"current"
                }
            }
        ],["react"]
    ]
}

How do I get logs/details of ansible-playbook module executions?

If you pass the -v flag to ansible-playbook on the command line, you'll see the stdout and stderr for each task executed:

$ ansible-playbook -v playbook.yaml

Ansible also has built-in support for logging. Add the following lines to your ansible configuration file:

[defaults] 
log_path=/path/to/logfile

Ansible will look in several places for the config file:

  • ansible.cfg in the current directory where you ran ansible-playbook
  • ~/.ansible.cfg
  • /etc/ansible/ansible.cfg

What happens if you don't commit a transaction to a database (say, SQL Server)?

As long as you don't COMMIT or ROLLBACK a transaction, it's still "running" and potentially holding locks.

If your client (application or user) closes the connection to the database before committing, any still running transactions will be rolled back and terminated.

Removing duplicates from a SQL query (not just "use distinct")

If I understand you correctly, you want to list to exclude duplicates on one column only, inner join to a sub-select

select u.* [whatever joined values]
from users u
inner join
(select name from users group by name having count(*)=1) uniquenames
on uniquenames.name = u.name

How to generate UML diagrams (especially sequence diagrams) from Java code?

EDIT: If you're a designer then Papyrus is your best choice it's very advanced and full of features, but if you just want to sketch out some UML diagrams and easy installation then ObjectAid is pretty cool and it doesn't require any plugins I just installed it over Eclipse-Java EE and works great !.


UPDATE Oct 11th, 2013

My original post was in June 2012 a lot of things have changed many tools has grown and others didn't. Since I'm going back to do some modeling and also getting some replies to the post I decided to install papyrus again and will investigate other possible UML modeling solutions again. UML generation (with synchronization feature) is really important not to software designer but to the average developer.

I wish papyrus had straightforward way to Reverse Engineer classes into UML class diagram and It would be super cool if that reverse engineering had a synchronization feature, but unfortunately papyrus project is full of features and I think developers there have already much at hand since also many actions you do over papyrus might not give you any response and just nothing happens but that's out of this question scope anyway.

The Answer (Oct 11th, 2013)

Tools

  1. Download Papyrus
  2. Go to Help -> Install New Software...
  3. In the Work with: drop-down, select --All Available Sites--
  4. In the filter, type in Papyrus
  5. After installation finishes restart Eclipse
  6. Repeat steps 1-3 and this time, install Modisco

Steps

  1. In your java project (assume it's called MyProject) create a folder e.g UML
  2. Right click over the project name -> Discovery -> Discoverer -> Discover Java and inventory model from java project, a file called MyProject_kdm.xmi will be generated. enter image description here
  3. Right click project name file --> new --> papyrus model -> and call it MyProject.
  4. Move the three generated files MyProject.di , MyProject.notation, MyProject.uml to the UML folder
  5. Right click on MyProject_kdm.xmi -> Discovery -> Discoverer -> Discover UML model from KDM code again you'll get a property dialog set the serialization prop to TRUE to generate a file named MyProject.uml enter image description here

  6. Move generated MyProject.uml which was generated at root, to UML folder, Eclipse will ask you If you wanted to replace it click yes. What we did in here was that we replaced an empty model with a generated one.

  7. ALT+W -> show view -> papyrus -> model explorer

  8. In that view, you'll find your classes like in the picture enter image description here

  9. In the view Right click root model -> New diagram enter image description here

  10. Then start grabbing classes to the diagram from the view

Some features

  • To show the class elements (variables, functions etc) Right click on any class -> Filters -> show/hide contents Voila !!

  • You can have default friendly color settings from Window -> pereferences -> papyrus -> class diagram

  • one very important setting is Arrange when you drop the classes they get a cramped right click on any empty space at a class diagram and click Arrange All

  • Arrows in the model explorer view can be grabbed to the diagram to show generalization, realization etc

  • After all of that your settings will show diagrams like enter image description here

  • Synchronization isn't available as far as I know you'll need to manually import any new classes.

That's all, And don't buy commercial products unless you really need it, papyrus is actually great and sophisticated instead donate or something.

Disclaimer: I've no relation to the papyrus people, in fact, I didn't like papyrus at first until I did lots of research and experienced it with some patience. And will get back to this post again when I try other free tools.

Is there a CSS parent selector?

There is currently no way to select the parent of an element in CSS.

If there was a way to do it, it would be in either of the current CSS selectors specs:

That said, the Selectors Level 4 Working Draft includes a :has() pseudo-class that will provide this capability. It will be similar to the jQuery implementation.

li:has(> a.active) { /* styles to apply to the li tag */ }

However, as of 2020, this is still not supported by any browser.

In the meantime, you'll have to resort to JavaScript if you need to select a parent element.

CSS: Background image and padding

Use background-position: calc(100% - 20px) center, For pixel perfection calc() is the best solution.

_x000D_
_x000D_
ul {_x000D_
  width: 100px;_x000D_
}_x000D_
ul li {_x000D_
  border: 1px solid orange;_x000D_
  background: url("http://placehold.it/30x15") no-repeat calc(100% - 10px) center;_x000D_
}_x000D_
ul li:hover {_x000D_
  background-position: calc(100% - 20px) center;_x000D_
}
_x000D_
<ul>_x000D_
  <li>Hello</li>_x000D_
  <li>Hello world</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

VSCode cannot find module '@angular/core' or any other modules

The fix for me was to import the entire project. For those who have this problem in 2019 please check if you have imported the entire project not a part of the project.

How do I encode/decode HTML entities in Ruby?

To encode the characters, you can use CGI.escapeHTML:

string = CGI.escapeHTML('test "escaping" <characters>')

To decode them, there is CGI.unescapeHTML:

CGI.unescapeHTML("test &quot;unescaping&quot; &lt;characters&gt;")

Of course, before that you need to include the CGI library:

require 'cgi'

And if you're in Rails, you don't need to use CGI to encode the string. There's the h method.

<%= h 'escaping <html>' %>

Specified cast is not valid?

From your comment:

this line DateTime Date = reader.GetDateTime(0); was throwing the exception

The first column is not a valid DateTime. Most likely, you have multiple columns in your table, and you're retrieving them all by running this query:

SELECT * from INFO

Replace it with a query that retrieves only the two columns you're interested in:

SELECT YOUR_DATE_COLUMN, YOUR_TIME_COLUMN from INFO

Then try reading the values again:

var Date = reader.GetDateTime(0);
var Time = reader.GetTimeSpan(1);  // equivalent to time(7) from your database

Or:

var Date = Convert.ToDateTime(reader["YOUR_DATE_COLUMN"]);
var Time = (TimeSpan)reader["YOUR_TIME_COLUMN"];

How can I remove specific rules from iptables?

First list all iptables rules with this command:

iptables -S

it lists like:

-A XYZ -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

Then copy the desired line, and just replace -A with -D to delete that:

iptables -D XYZ -p ...

how does Array.prototype.slice.call() work?

The arguments object is not actually an instance of an Array, and does not have any of the Array methods. So, arguments.slice(...) will not work because the arguments object does not have the slice method.

Arrays do have this method, and because the arguments object is very similar to an array, the two are compatible. This means that we can use array methods with the arguments object. And since array methods were built with arrays in mind, they will return arrays rather than other argument objects.

So why use Array.prototype? The Array is the object which we create new arrays from (new Array()), and these new arrays are passed methods and properties, like slice. These methods are stored in the [Class].prototype object. So, for efficiency sake, instead of accessing the slice method by (new Array()).slice.call() or [].slice.call(), we just get it straight from the prototype. This is so we don't have to initialise a new array.

But why do we have to do this in the first place? Well, as you said, it converts an arguments object into an Array instance. The reason why we use slice, however, is more of a "hack" than anything. The slice method will take a, you guessed it, slice of an array and return that slice as a new array. Passing no arguments to it (besides the arguments object as its context) causes the slice method to take a complete chunk of the passed "array" (in this case, the arguments object) and return it as a new array.

UL list style not applying

My reset.css was margin: 0, padding: 0. After several hours of looking and troubleshooting this worked:

li {
    list-style: disc outside none;
    margin-left: 1em;
}

ul {
    margin: 1em;
}

Resize jqGrid when browser is resized?

this seems to be working nicely for me

$(window).bind('resize', function() {
    jQuery("#grid").setGridWidth($('#parentDiv').width()-30, true);
}).trigger('resize');

PostgreSQL: role is not permitted to log in

The role you have created is not allowed to log in. You have to give the role permission to log in.

One way to do this is to log in as the postgres user and update the role:

psql -U postgres

Once you are logged in, type:

ALTER ROLE "asunotest" WITH LOGIN;

Here's the documentation http://www.postgresql.org/docs/9.0/static/sql-alterrole.html

keyCode values for numeric keypad?

You can use this to figure out keyCodes easily:

$(document).keyup(function(e) {
    // Displays the keycode of the last pressed key in the body
    $(document.body).html(e.keyCode);
});

http://jsfiddle.net/vecvc4fr/

How to declare an array in Python?

I would normally just do a = [1,2,3] which is actually a list but for arrays look at this formal definition

How do I git rm a file without deleting it from disk?

I tried experimenting with the answers given. My personal finding came out to be:

git rm -r --cached .

And then

git add .

This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

That is okay for removing of data connections by using VBA as follows:

Sub deleteConn()
    Dim xlBook As Workbook
    Dim Cn As WorkbookConnection
    Dim xlSheet As Worksheet
    Dim Qt As QueryTable
    Set xlBook = ActiveWorkbook
    For Each Cn In xlBook.Connections
        Debug.Print VarType(Cn)
        Cn.Delete
    Next Cn
    For Each xlSheet In xlBook.Worksheets
        For Each Qt In xlSheet.QueryTables
            Debug.Print Qt.Name
            Qt.Delete
        Next Qt
    Next xlSheet
End Sub

Creating a JavaScript cookie on a domain and reading it across sub domains

Just set the domain and path attributes on your cookie, like:

<script type="text/javascript">
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate 
                  + ";domain=.example.com;path=/";
</script>

How to redirect a page using onclick event in php?

Please try this

    <input type="button" value="Home" class="homebutton" id="btnHome" onClick="Javascript:window.location.href = 'http://www.website.com/index.php';" />

window.location.href example:

 window.location.href = 'http://www.google.com'; //Will take you to Google.

window.open() example:

     window.open('http://www.google.com'); //This will open Google in a new window.

Eliminating NAs from a ggplot

Just an update to the answer of @rafa.pereira. Since ggplot2 is part of tidyverse, it makes sense to use the convenient tidyverse functions to get rid of NAs.

library(tidyverse)
airquality %>% 
        drop_na(Ozone) %>%
        ggplot(aes(x = Ozone))+
        geom_bar(stat="bin")

Note that you can also use drop_na() without columns specification; then all the rows with NAs in any column will be removed.

What is the meaning of the prefix N in T-SQL statements and when should I use it?

It's declaring the string as nvarchar data type, rather than varchar

You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.

To quote from Microsoft:

Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.


If you want to know the difference between these two data types, see this SO post:

What is the difference between varchar and nvarchar?

Add colorbar to existing axis

Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
    for col in row:
        im = col.imshow(data, cmap='bone')
        divider = make_axes_locatable(col)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()

How to convert a char array back to a string?

This will convert char array back to string:

char[] charArray = {'a', 'b', 'c'};
String str = String.valueOf(charArray);

Verify External Script Is Loaded

Create the script tag with a specific ID and then check if that ID exists?

Alternatively, loop through script tags checking for the script 'src' and make sure those are not already loaded with the same value as the one you want to avoid ?

Edit: following feedback that a code example would be useful:

(function(){
    var desiredSource = 'https://sitename.com/js/script.js';
    var scripts       = document.getElementsByTagName('script');
    var alreadyLoaded = false;

    if(scripts.length){
        for(var scriptIndex in scripts) {
            if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
                alreadyLoaded = true;
            }
        }
    }
    if(!alreadyLoaded){
        // Run your code in this block?
    }
})();

As mentioned in the comments (https://stackoverflow.com/users/1358777/alwin-kesler), this may be an alternative (not benchmarked):

(function(){
    var desiredSource = 'https://sitename.com/js/script.js';
    var scripts = document.getElementsByTagName('script');
    var alreadyLoaded = false;

    for(var scriptIndex in document.scripts) {
        if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
            alreadyLoaded = true;
        }
    }
    if(!alreadyLoaded){
        // Run your code in this block?
    }
})();

How to write data to a text file without overwriting the current data

Best thing is

File.AppendAllText("c:\\file.txt","Your Text");

How to get calendar Quarter from a date in TSQL

Try the following:

CONCAT(datepart(yyyy,DATE),'-', DATEPART(qq,DATE))

It returns:

yyyy-q

Example: 2017-3 for 2017-07-11

C# Dictionary get item by index

you can easily access elements by index , by use System.Linq

Here is the sample

First add using in your class file

using System.Linq;

Then

yourDictionaryData.ElementAt(i).Key
yourDictionaryData.ElementAt(i).Value

Hope this helps.

How do you write multiline strings in Go?

You have to be very careful on formatting and line spacing in go, everything counts and here is a working sample, try it https://play.golang.org/p/c0zeXKYlmF

package main

import "fmt"

func main() {
    testLine := `This is a test line 1
This is a test line 2`
    fmt.Println(testLine)
}

Uploading a file in Rails

There is a nice gem especially for uploading files : carrierwave. If the wiki does not help , there is a nice RailsCast about the best way to use it . Summarizing , there is a field type file in Rails forms , which invokes the file upload dialog. You can use it , but the 'magic' is done by carrierwave gem .

I don't know what do you mean with "how to write to a file" , but I hope this is a nice start.

How can I get screen resolution in java?

This call will give you the information you want.

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

phpmailer - The following SMTP Error: Data not accepted

For AWS users who work with Amazon SES in conjunction with PHPMailer, this error also appears when your "from" mail sender isn't a verified sender.

To add a verified sender:

  1. Log in to your Amazon AWS console: https://console.aws.amazon.com

  2. Select "Amazon SES" from your list of available AWS applications

  3. Select, under "Verified Senders", the "Email Addresses" --> "Verify a new email address"

  4. Navigate to that new sender's email, click the confirmation e-mail's link.

And you're all set.

data.table vs dplyr: can one do something well the other can't or does poorly?

In direct response to the Question Title...

dplyr definitely does things that data.table can not.

Your point #3

dplyr abstracts (or will) potential DB interactions

is a direct answer to your own question but isn't elevated to a high enough level. dplyr is truly an extendable front-end to multiple data storage mechanisms where as data.table is an extension to a single one.

Look at dplyr as a back-end agnostic interface, with all of the targets using the same grammer, where you can extend the targets and handlers at will. data.table is, from the dplyr perspective, one of those targets.

You will never (I hope) see a day that data.table attempts to translate your queries to create SQL statements that operate with on-disk or networked data stores.

dplyr can possibly do things data.table will not or might not do as well.

Based on the design of working in-memory, data.table could have a much more difficult time extending itself into parallel processing of queries than dplyr.


In response to the in-body questions...

Usage

Are there analytical tasks that are a lot easier to code with one or the other package for people familiar with the packages (i.e. some combination of keystrokes required vs. required level of esotericism, where less of each is a good thing).

This may seem like a punt but the real answer is no. People familiar with tools seem to use the either the one most familiar to them or the one that is actually the right one for the job at hand. With that being said, sometimes you want to present a particular readability, sometimes a level of performance, and when you have need for a high enough level of both you may just need another tool to go along with what you already have to make clearer abstractions.

Performance

Are there analytical tasks that are performed substantially (i.e. more than 2x) more efficiently in one package vs. another.

Again, no. data.table excels at being efficient in everything it does where dplyr gets the burden of being limited in some respects to the underlying data store and registered handlers.

This means when you run into a performance issue with data.table you can be pretty sure it is in your query function and if it is actually a bottleneck with data.table then you've won yourself the joy of filing a report. This is also true when dplyr is using data.table as the back-end; you may see some overhead from dplyr but odds are it is your query.

When dplyr has performance issues with back-ends you can get around them by registering a function for hybrid evaluation or (in the case of databases) manipulating the generated query prior to execution.

Also see the accepted answer to when is plyr better than data.table?

Accessing an array out of bounds gives no error, why?

It's undefined behavior as far as I know. Run a larger program with that and it will crash somewhere along the way. Bounds checking is not a part of raw arrays (or even std::vector).

Use std::vector with std::vector::iterator's instead so you don't have to worry about it.

Edit:

Just for fun, run this and see how long until you crash:

int main()
{
   int array[1];

   for (int i = 0; i != 100000; i++)
   {
       array[i] = i;
   }

   return 0; //will be lucky to ever reach this
}

Edit2:

Don't run that.

Edit3:

OK, here is a quick lesson on arrays and their relationships with pointers:

When you use array indexing, you are really using a pointer in disguise (called a "reference"), that is automatically dereferenced. This is why instead of *(array[1]), array[1] automatically returns the value at that value.

When you have a pointer to an array, like this:

int array[5];
int *ptr = array;

Then the "array" in the second declaration is really decaying to a pointer to the first array. This is equivalent behavior to this:

int *ptr = &array[0];

When you try to access beyond what you allocated, you are really just using a pointer to other memory (which C++ won't complain about). Taking my example program above, that is equivalent to this:

int main()
{
   int array[1];
   int *ptr = array;

   for (int i = 0; i != 100000; i++, ptr++)
   {
       *ptr++ = i;
   }

   return 0; //will be lucky to ever reach this
}

The compiler won't complain because in programming, you often have to communicate with other programs, especially the operating system. This is done with pointers quite a bit.

Difference in make_shared and normal shared_ptr in C++

There is another case where the two possibilities differ, on top of those already mentioned: if you need to call a non-public constructor (protected or private), make_shared might not be able to access it, while the variant with the new works fine.

class A
{
public:

    A(): val(0){}

    std::shared_ptr<A> createNext(){ return std::make_shared<A>(val+1); }
    // Invalid because make_shared needs to call A(int) **internally**

    std::shared_ptr<A> createNext(){ return std::shared_ptr<A>(new A(val+1)); }
    // Works fine because A(int) is called explicitly

private:

    int val;

    A(int v): val(v){}
};

Singletons vs. Application Context in Android?

My 2 cents:

I did notice that some singleton / static fields were reseted when my activity was destroyed. I noticed this on some low end 2.3 devices.

My case was very simple : I just have a private filed "init_done" and a static method "init" that I called from activity.onCreate(). I notice that the method init was re-executing itself on some re-creation of the activity.

While I cannot prove my affirmation, It may be related to WHEN the singleton/class was created/used first. When the activity get destroyed/recycled, it seem that all class that only this activity refer are recycled too.

I moved my instance of singleton to a sub class of Application. I acces them from the application instance. and, since then, did not notice the problem again.

I hope this can help someone.

Twitter Bootstrap onclick event on buttons-radio

For Bootstrap 3 the default radio/button-group structure is :

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option1"> Option 1
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option2"> Option 2
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option3"> Option 3
    </label>
</div>

And you can select the active one like this:

$('.btn-primary').on('click', function(){
    alert($(this).find('input').attr('id'));
}); 

how to add picasso library in android studio

easiest way to add dependence

hope this help you or Ctrl + Alt + Shift + S => select Dependencies tab and find what you need ( see my image)

ipython notebook clear cell output in code

You can use IPython.display.clear_output to clear the output of a cell.

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print("Hello World!")

At the end of this loop you will only see one Hello World!.

Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

using nth-child in tables tr td

Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td> that have $ inside. Example: using nth-child in tables tr td

html

<tr>
    <td>&nbsp;</td>
    <td data-rel='$'>$</td>
    <td>&nbsp;</td>
</tr>

css

table tr td[data-rel='$'] {
    background-color: #333;
    color: white;
}

Please try these example.

_x000D_
_x000D_
table tr td[data-content='$'] {_x000D_
    background-color: #333;_x000D_
    color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
    <tr>_x000D_
        <td>A</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>B</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>C</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>D</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

git recover deleted file where no commit was made after the delete

Since you're doing a git checkout ., it looks like you are trying to restore your branch back to the last commit state.

You can achieve this with a git reset HEAD --hard

Warning

Doing this may remove all your latest modifications and unstage your modifications, e.g., you can lose work. It may be what you want, but check out the docs to make sure.

Finding row index containing maximum value using R

See ?which.max

> which.max( matrix[,2] )
[1] 2

Change an image with onclick()

You can try something like this:

CSS

div {
    width:200px;
    height:200px;
    background: url(img1.png) center center no-repeat;
}

.visited {
    background: url(img2.png) center center no-repeat;
}

HTML

<div href="#" onclick="this.className='visited'">
    <p>Content</p>
</div>

Fiddle

How to make custom dialog with rounded corners in android

Setting

dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

will prevent dialog to cast a shadow.

Solution is to use

dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_rounded_background);

where is R.drawable.dialog_rounded_background

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape android:shape="rectangle" android:padding="10dp">
            <solid
                android:color="@color/dialog_bg_color"/>
            <corners
                android:radius="30dp" />
        </shape>
    </item>

</layer-list>

How to change package name of an Android Application

Without Eclipse:

  1. Change package name and Activity names in AndroidManifext.xml and anywhere else it shows up in .xml files (custom view names, etc)

  2. Update package import statement across all source files

  3. Rename all folders to match the package name. Folder locations:
    a. bin/classes
    b. gen
    c. src

  4. Update the project name in build.xml (or your apk's name won't change)

  5. Delete all the .class files in bin/classes/com/example/myapp/ (if you skip this step the files don't get rewritten during build and dex give a bunch of trouble processing "class name does not match path" errors

  6. Delete gen/com/example/myapp/BuildConfig.java (I don't know why deleting BuildConfig.class in step 3a didn't cause dex to update it's path to this, but until I deleted BuildConfig.java it kept recreating gen/com/oldapp_example/oldapp and putting BuildConfig.class in there. I don't know why R.java from the same location doesn't have this problem. I suspect BuildConfig.java is auto-generated in pre-compile but R.java is not)

The above 6 steps are what I did to get my package name changed and get a successful* build. There may be a better way to handle steps 5 and 6 via dex commands to update paths, or perhaps by editing classes.dex.d in the root directory of the project. I'm not familiar with dex or if it's ok to delete/edit classes.dex.d so I went with the method of deleting .class files that I know will be regenerated in the build. I then checked classes.dex.d to see what still needed to be updated.

*No errors or warnings left in my build EXCEPT dex and apkbuilder both state "Found Deleted Target File" with no specifics about what that file is. Not sure if this shows up in every build, if it was there before I messed with my package name, or if it's a result of my deletions and I'm missing a step.

How do I include negative decimal numbers in this regular expression?

This will allow both positive and negative integers

ValidationExpression="^-?[0-9]\d*(\d+)?$"

Darkening an image with CSS (In any shape)

You could always change the opacity of the image, given the difficulty of any alternatives this might be the best approach.

CSS:

.tinted { opacity: 0.8; }

If you're interested in better browser compatability, I suggest reading this:

http://css-tricks.com/css-transparency-settings-for-all-broswers/

If you're determined enough you can get this working as far back as IE7 (who knew!)

Note: As JGonzalezD points out below, this only actually darkens the image if the background colour is generally darker than the image itself. Although this technique may still be useful if you don't specifically want to darken the image, but instead want to highlight it on hover/focus/other state for whatever reason.

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.

You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.

EDIT: Courtesy of @Laurynas, consider this:

TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat = 
       new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);

System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();

System.out.println("UTC:     " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

Sorry for the "diggy up", but i just encoured this issue with an symfony3.8 project deploiement on shared hosting (php 7.3.18)...

I solved this issue by set the php memory limit in the command line options, a stuff like this:

php -dmemory_limit=-1 /path/to/the/executable

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

When creating a foreign key constraint, MySQL requires a usable index on both the referencing table and also on the referenced table. The index on the referencing table is created automatically if one doesn't exist, but the one on the referenced table needs to be created manually (Source). Yours appears to be missing.

Test case:

CREATE TABLE tbl_a (
    id int PRIMARY KEY,
    some_other_id int,
    value int
) ENGINE=INNODB;
Query OK, 0 rows affected (0.10 sec)

CREATE TABLE tbl_b (
    id int PRIMARY KEY,
    a_id int,
    FOREIGN KEY (a_id) REFERENCES tbl_a (some_other_id)
) ENGINE=INNODB;
ERROR 1005 (HY000): Can't create table 'e.tbl_b' (errno: 150)

But if we add an index on some_other_id:

CREATE INDEX ix_some_id ON tbl_a (some_other_id);
Query OK, 0 rows affected (0.11 sec)
Records: 0  Duplicates: 0  Warnings: 0

CREATE TABLE tbl_b (
    id int PRIMARY KEY,
    a_id int,
    FOREIGN KEY (a_id) REFERENCES tbl_a (some_other_id)
) ENGINE=INNODB;
Query OK, 0 rows affected (0.06 sec)

This is often not an issue in most situations, since the referenced field is often the primary key of the referenced table, and the primary key is indexed automatically.

How to install ADB driver for any android device?

If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID instead of HardwareID in the driver's INF Models section

SQL Server Operating system error 5: "5(Access is denied.)"

The actual server permissions will not matter at this point; all looks ok. SQL Server itself needs folder permissions.
depending on your version, you can add SERVERNAME$MSSQLSERVER permissions to touch your folder. Othewise, it has to be in the default BACKUP directory (either where you installed it or default to c:\programfiles(x)\MSSQL\BACKUP.

How can I customize the tab-to-space conversion factor?

Menu File ? Preferences ? Settings

Add to user settings:

"editor.tabSize": 2,
"editor.detectIndentation": false

then right click your document if you have one opened already and click Format Document to have your existing document follow these new settings.

Link to a section of a webpage

Hashtags at the end of the URL bring a visitor to the element with the ID: e.g.

http://stackoverflow.com/questions/8424785/link-to-a-section-of-a-webpage#answers 

Would bring you to where the DIV with the ID 'answers' begins. Also, you can use the name attribute in anchor tags, to create the same effect.

Resource

How to top, left justify text in a <td> cell that spans multiple rows

try this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table, th, td {_x000D_
    border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:50%;">_x000D_
    <tr>_x000D_
      <th>Month</th>_x000D_
      <th>Savings</th>_x000D_
    </tr>_x000D_
    <tr style="height:100px">_x000D_
      <td valign="top">January</td>_x000D_
      <td valign="bottom">$100</td>_x000D_
    </tr>_x000D_
</table>_x000D_
_x000D_
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

use valign="top" for td style

Simple way to compare 2 ArrayLists

Convert Lists to Collection and use removeAll

    Collection<String> listOne = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));
    Collection<String> listTwo = new ArrayList(Arrays.asList("a","b",  "d", "e", "f", "gg", "h"));


    List<String> sourceList = new ArrayList<String>(listOne);
    List<String> destinationList = new ArrayList<String>(listTwo);


    sourceList.removeAll( listTwo );
    destinationList.removeAll( listOne );



    System.out.println( sourceList );
    System.out.println( destinationList );

Output:

[c, g]
[gg, h]

[EDIT]

other way (more clear)

  Collection<String> list = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));

    List<String> sourceList = new ArrayList<String>(list);
    List<String> destinationList = new ArrayList<String>(list);

    list.add("boo");
    list.remove("b");

    sourceList.removeAll( list );
    list.removeAll( destinationList );


    System.out.println( sourceList );
    System.out.println( list );

Output:

[b]
[boo]

#ifdef in C#

#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif

Make sure you have the checkbox to define DEBUG checked in your build properties.

Why doesn't TFS get latest get the latest?

In my case, Get specific version, even checking both check boxes and undoing all pending changes didn't work.

Checked the work spaces. Edit current workspace. Check all paths. The solution path was incorrect and was pointing to a deleted folder.

Fixed the path and get latest worked fine.

Make the current Git branch a master branch

The problem with the other two answers is that the new master doesn't have the old master as an ancestor, so when you push it, everyone else will get messed up. This is what you want to do:

git checkout better_branch
git merge --strategy=ours master    # keep the content of this branch, but record a merge
git checkout master
git merge better_branch             # fast-forward master up to the merge

If you want your history to be a little clearer, I'd recommend adding some information to the merge commit message to make it clear what you've done. Change the second line to:

git merge --strategy=ours --no-commit master
git commit          # add information to the template merge message

Generating unique random numbers (integers) between 0 and 'x'

These answers either don't give unique values, or are so long (one even adding an external library to do such a simple task).

1. generate a random number.
2. if we have this random already then goto 1, else keep it.
3. if we don't have desired quantity of randoms, then goto 1.

_x000D_
_x000D_
function uniqueRandoms(qty, min, max){_x000D_
  var rnd, arr=[];_x000D_
  do { do { rnd=Math.floor(Math.random()*max)+min }_x000D_
      while(arr.includes(rnd))_x000D_
      arr.push(rnd);_x000D_
  } while(arr.length<qty)_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
//generate 5 unique numbers between 1 and 10_x000D_
console.log( uniqueRandoms(5, 1, 10) );
_x000D_
_x000D_
_x000D_

...and a compressed version of the same function:

function uniqueRandoms(qty,min,max){var a=[];do{do{r=Math.floor(Math.random()*max)+min}while(a.includes(r));a.push(r)}while(a.length<qty);return a}

How can I convert an image into a Base64 string?

If you're doing this on Android, here's a helper copied from the React Native codebase:

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;

// You probably don't want to do this with large files
// (will allocate a large string and can cause an OOM crash).
private String readFileAsBase64String(String path) {
  try {
    InputStream is = new FileInputStream(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
    byte[] buffer = new byte[8192];
    int bytesRead;
    try {
      while ((bytesRead = is.read(buffer)) > -1) {
        b64os.write(buffer, 0, bytesRead);
      }
      return baos.toString();
    } catch (IOException e) {
      Log.e(TAG, "Cannot read file " + path, e);
      // Or throw if you prefer
      return "";
    } finally {
      closeQuietly(is);
      closeQuietly(b64os); // This also closes baos
    }
  } catch (FileNotFoundException e) {
    Log.e(TAG, "File not found " + path, e);
    // Or throw if you prefer
    return "";
  }
}

private static void closeQuietly(Closeable closeable) {
  try {
    closeable.close();
  } catch (IOException e) {
  }
}

How to modify a specified commit?

Use the awesome interactive rebase:

git rebase -i @~9   # Show the last 9 commits in a text editor

Find the commit you want, change pick to e (edit), and save and close the file. Git will rewind to that commit, allowing you to either:

  • use git commit --amend to make changes, or
  • use git reset @~ to discard the last commit, but not the changes to the files (i.e. take you to the point you were at when you'd edited the files, but hadn't committed yet).

The latter is useful for doing more complex stuff like splitting into multiple commits.

Then, run git rebase --continue, and Git will replay the subsequent changes on top of your modified commit. You may be asked to fix some merge conflicts.

Note: @ is shorthand for HEAD, and ~ is the commit before the specified commit.

Read more about rewriting history in the Git docs.


Don't be afraid to rebase

ProTip™:   Don't be afraid to experiment with "dangerous" commands that rewrite history* — Git doesn't delete your commits for 90 days by default; you can find them in the reflog:

$ git reset @~3   # go back 3 commits
$ git reflog
c4f708b HEAD@{0}: reset: moving to @~3
2c52489 HEAD@{1}: commit: more changes
4a5246d HEAD@{2}: commit: make important changes
e8571e4 HEAD@{3}: commit: make some changes
... earlier commits ...
$ git reset 2c52489
... and you're back where you started

* Watch out for options like --hard and --force though — they can discard data.
* Also, don't rewrite history on any branches you're collaborating on.



On many systems, git rebase -i will open up Vim by default. Vim doesn't work like most modern text editors, so take a look at how to rebase using Vim. If you'd rather use a different editor, change it with git config --global core.editor your-favorite-text-editor.

relative path to CSS file

Background

Absolute: The browser will always interpret / as the root of the hostname. For example, if my site was http://google.com/ and I specified /css/images.css then it would search for that at http://google.com/css/images.css. If your project root was actually at /myproject/ it would not find the css file. Therefore, you need to determine where your project folder root is relative to the hostname, and specify that in your href notation.

Relative: If you want to reference something you know is in the same path on the url - that is, if it is in the same folder, for example http://mysite.com/myUrlPath/index.html and http://mysite.com/myUrlPath/css/style.css, and you know that it will always be this way, you can go against convention and specify a relative path by not putting a leading / in front of your path, for example, css/style.css.

Filesystem Notations: Additionally, you can use standard filesystem notations like ... If you do http://google.com/images/../images/../images/myImage.png it would be the same as http://google.com/images/myImage.png. If you want to reference something that is one directory up from your file, use ../myFile.css.


Your Specific Case

In your case, you have two options:

  • <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
  • <link rel="stylesheet" type="text/css" href="css/styles.css"/>

The first will be more concrete and compatible if you move things around, however if you are planning to keep the file in the same location, and you are planning to remove the /ServletApp/ part of the URL, then the second solution is better.

How do I perform query filtering in django templates

I just add an extra template tag like this:

@register.filter
def in_category(things, category):
    return things.filter(category=category)

Then I can do:

{% for category in categories %}
  {% for thing in things|in_category:category %}
    {{ thing }}
  {% endfor %}
{% endfor %}

Working with INTERVAL and CURDATE in MySQL

As suggested by A Star, I always use something along the lines of:

DATE(NOW()) - INTERVAL 1 MONTH

Similarly you can do:

NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY

and so on. Much easier than typing DATE_ADD or DATE_SUB all the time :)!

Connection Java-MySql : Public Key Retrieval is not allowed

Give connection URL as jdbc:mysql://localhost:3306/hb_student_tracker?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC

jQuery UI Accordion Expand/Collapse All

This my solution:

Working in real project.

   $(function () {
    $("#accordion").accordion({collapsible:true, active:false});
    $('.open').click(function () {
        $('.ui-accordion-header').removeClass('ui-corner-all').addClass('ui-accordion-header-active ui-state-active ui-corner-top').attr({'aria-selected':'true','tabindex':'0'});
        $('.ui-accordion-header .ui-icon').removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
        $('.ui-accordion-content').addClass('ui-accordion-content-active').attr({'aria-expanded':'true','aria-hidden':'false'}).show();
        $(this).hide();
        $('.close').show();
    });
    $('.close').click(function () {
        $('.ui-accordion-header').removeClass('ui-accordion-header-active ui-state-active ui-corner-top').addClass('ui-corner-all').attr({'aria-selected':'false','tabindex':'-1'});
        $('.ui-accordion-header .ui-icon').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
        $('.ui-accordion-content').removeClass('ui-accordion-content-active').attr({'aria-expanded':'false','aria-hidden':'true'}).hide();
        $(this).hide();
        $('.open').show();
    });
    $('.ui-accordion-header').click(function () {
        $('.open').show();
        $('.close').show();
    });
});

http://jsfiddle.net/bigvax/hEApL/

Select last row in MySQL

You can combine two queries suggested by @spacepille into single query that looks like this:

SELECT * FROM `table_name` WHERE id=(SELECT MAX(id) FROM `table_name`);

It should work blazing fast, but on INNODB tables it's fraction of milisecond slower than ORDER+LIMIT.

Import/Index a JSON file into Elasticsearch

Adding to KenH's answer

$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests

You can replace @requests with @complete_path_to_json_file

Note: @is important before the file path

How to replace blank (null ) values with 0 for all records?

I used a two step process to change rows with "blank" values to "Null" values as place holders.

UPDATE [TableName] SET [TableName].[ColumnName] = "0"
WHERE ((([TableName].[ColumnName])=""));

UPDATE [TableName] SET [TableName].[ColumnName] = "Null"
WHERE ((([TableName].[ColumnName])="0"));

Excel "External table is not in the expected format."

Ran into the same issue and found this thread. None of the suggestions above helped except for @Smith's comment to the accepted answer on Apr 17 '13.

The background of my issue is close enough to @zhiyazw's - basically trying to set an exported Excel file (SSRS in my case) as the data source in the dtsx package. All I did, after some tinkering around, was renaming the worksheet. It doesn't have to be lowercase as @Smith has suggested.

I suppose ACE OLEDB expects the Excel file to follow a certain XML structure but somehow Reporting Services is not aware of that.

multiprocessing.Pool: When to use apply, apply_async or map?

Back in the old days of Python, to call a function with arbitrary arguments, you would use apply:

apply(f,args,kwargs)

apply still exists in Python2.7 though not in Python3, and is generally not used anymore. Nowadays,

f(*args,**kwargs)

is preferred. The multiprocessing.Pool modules tries to provide a similar interface.

Pool.apply is like Python apply, except that the function call is performed in a separate process. Pool.apply blocks until the function is completed.

Pool.apply_async is also like Python's built-in apply, except that the call returns immediately instead of waiting for the result. An AsyncResult object is returned. You call its get() method to retrieve the result of the function call. The get() method blocks until the function is completed. Thus, pool.apply(func, args, kwargs) is equivalent to pool.apply_async(func, args, kwargs).get().

In contrast to Pool.apply, the Pool.apply_async method also has a callback which, if supplied, is called when the function is complete. This can be used instead of calling get().

For example:

import multiprocessing as mp
import time

def foo_pool(x):
    time.sleep(2)
    return x*x

result_list = []
def log_result(result):
    # This is called whenever foo_pool(i) returns a result.
    # result_list is modified only by the main process, not the pool workers.
    result_list.append(result)

def apply_async_with_callback():
    pool = mp.Pool()
    for i in range(10):
        pool.apply_async(foo_pool, args = (i, ), callback = log_result)
    pool.close()
    pool.join()
    print(result_list)

if __name__ == '__main__':
    apply_async_with_callback()

may yield a result such as

[1, 0, 4, 9, 25, 16, 49, 36, 81, 64]

Notice, unlike pool.map, the order of the results may not correspond to the order in which the pool.apply_async calls were made.


So, if you need to run a function in a separate process, but want the current process to block until that function returns, use Pool.apply. Like Pool.apply, Pool.map blocks until the complete result is returned.

If you want the Pool of worker processes to perform many function calls asynchronously, use Pool.apply_async. The order of the results is not guaranteed to be the same as the order of the calls to Pool.apply_async.

Notice also that you could call a number of different functions with Pool.apply_async (not all calls need to use the same function).

In contrast, Pool.map applies the same function to many arguments. However, unlike Pool.apply_async, the results are returned in an order corresponding to the order of the arguments.

Visibility of global variables in imported modules

As a workaround, you could consider setting environment variables in the outer layer, like this.

main.py:

import os
os.environ['MYVAL'] = str(myintvariable)

mymodule.py:

import os

myval = None
if 'MYVAL' in os.environ:
    myval = os.environ['MYVAL']

As an extra precaution, handle the case when MYVAL is not defined inside the module.

How to get error message when ifstream open fails

You can also throw a std::system_error as shown in the test code below. This method seems to produce more readable output than f.exception(...).

#include <exception> // <-- requires this
#include <fstream>
#include <iostream>

void process(const std::string& fileName) {
    std::ifstream f;
    f.open(fileName);

    // after open, check f and throw std::system_error with the errno
    if (!f)
        throw std::system_error(errno, std::system_category(), "failed to open "+fileName);

    std::clog << "opened " << fileName << std::endl;
}

int main(int argc, char* argv[]) {
    try {
        process(argv[1]);
    } catch (const std::system_error& e) {
        std::clog << e.what() << " (" << e.code() << ")" << std::endl;
    }
    return 0;
}

Example output (Ubuntu w/clang):

$ ./test /root/.profile
failed to open /root/.profile: Permission denied (system:13)
$ ./test missing.txt
failed to open missing.txt: No such file or directory (system:2)
$ ./test ./test
opened ./test
$ ./test $(printf '%0999x')
failed to open 000...000: File name too long (system:36)

Jquery open popup on button click for bootstrap

The answer is on the example link you provided:

http://getbootstrap.com/javascript/#modals-usage

i.e.

Call a modal with id myModal with a single line of JavaScript:

$('#myModal').modal('show');

How do format a phone number as a String in Java?

To get your desired output:

long phoneFmt = 123456789L;
//get a 12 digits String, filling with left '0' (on the prefix)   
DecimalFormat phoneDecimalFmt = new DecimalFormat("0000000000");
String phoneRawString= phoneDecimalFmt.format(phoneFmt);

java.text.MessageFormat phoneMsgFmt=new java.text.MessageFormat("({0})-{1}-{2}");
    //suposing a grouping of 3-3-4
String[] phoneNumArr={phoneRawString.substring(0, 3),
          phoneRawString.substring(3,6),
          phoneRawString.substring(6)};

System.out.println(phoneMsgFmt.format(phoneNumArr));

The result at the Console looks like this:

(012)-345-6789

For storing phone numbers, you should consider using a data type other than numbers.

Is there a no-duplicate List implementation out there?

Why not encapsulate a set with a list, sort like:

new ArrayList( new LinkedHashSet() )

This leaves the other implementation for someone who is a real master of Collections ;-)

Get key from a HashMap using the value

You mixed the keys and the values.

Hashmap <Integer,String> hashmap = new HashMap<Integer, String>();

hashmap.put(100, "one");
hashmap.put(200, "two");

Afterwards a

hashmap.get(100);

will give you "one"

Calculating days between two dates with Java

Most / all answers caused issues for us when daylight savings time came around. Here's our working solution for all dates, without using JodaTime. It utilizes calendar objects:

public static int daysBetween(Calendar day1, Calendar day2){
    Calendar dayOne = (Calendar) day1.clone(),
            dayTwo = (Calendar) day2.clone();

    if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
        return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
    } else {
        if (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
            //swap them
            Calendar temp = dayOne;
            dayOne = dayTwo;
            dayTwo = temp;
        }
        int extraDays = 0;

        int dayOneOriginalYearDays = dayOne.get(Calendar.DAY_OF_YEAR);

        while (dayOne.get(Calendar.YEAR) > dayTwo.get(Calendar.YEAR)) {
            dayOne.add(Calendar.YEAR, -1);
            // getActualMaximum() important for leap years
            extraDays += dayOne.getActualMaximum(Calendar.DAY_OF_YEAR);
        }

        return extraDays - dayTwo.get(Calendar.DAY_OF_YEAR) + dayOneOriginalYearDays ;
    }
}

sql searching multiple words in a string

if you put all the searched words in a temporaray table say @tmp and column col1, then you could try this:

Select * from T where C like (Select '%'+col1+'%' from @temp);

Entity Framework The underlying provider failed on Open

Always check for Inner Exception if any. In my case Inner Exception turned out to be really helpful in figuring out the issue.

My site was working fine in Dev Environment. But after i deployed to production, it started giving out this exception, but the Inner Exception was saying that Login failed for the particular user.
So i figured out it was something to do with the connection itself. Hence tried logging in using SSMS and even that failed.

Eventually figured out that exception showed up for the simple reason that the SQL server had only Windows Authentication enabled and SQL Authentication was failing which was what i was using for Authentication.

In short, changing Authentication to Mixed(SQL and Windows), fixed the issue for me. :)

How can I view the contents of an ElasticSearch index?

You can view any existing index by using the below CURL. Please replace the index-name with your actual name before running and it will run as is.

View the index content

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name?pretty

And the output will include an index(see settings in output) and its mappings too and it will look like below output -

{
  "index_name": {
    "aliases": {},
    "mappings": {
      "collection_name": {
        "properties": {
          "test_field": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
       }
    },
    "settings": {
      "index": {
        "creation_date": "1527377274366",
        "number_of_shards": "5",
        "number_of_replicas": "1",
        "uuid": "6QfKqbbVQ0Gbsqkq7WZJ2g",
        "version": {
          "created": "6020299"
        },
        "provided_name": "index_name"
      }
    }
  }
}

View ALL the data under this index

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name/_search?pretty

Function to calculate distance between two coordinates

Try this. It is in VB.net and you need to convert it to Javascript. This function accepts parameters in decimal minutes.

    Private Function calculateDistance(ByVal long1 As String, ByVal lat1 As String, ByVal long2 As String, ByVal lat2 As String) As Double
    long1 = Double.Parse(long1)
    lat1 = Double.Parse(lat1)
    long2 = Double.Parse(long2)
    lat2 = Double.Parse(lat2)

    'conversion to radian
    lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0
    long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0
    lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0
    long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0

    ' use to different earth axis length
    Dim a As Double = 6378137.0        ' Earth Major Axis (WGS84)
    Dim b As Double = 6356752.3142     ' Minor Axis
    Dim f As Double = (a - b) / a        ' "Flattening"
    Dim e As Double = 2.0 * f - f * f      ' "Eccentricity"

    Dim beta As Double = (a / Math.Sqrt(1.0 - e * Math.Sin(lat1) * Math.Sin(lat1)))
    Dim cos As Double = Math.Cos(lat1)
    Dim x As Double = beta * cos * Math.Cos(long1)
    Dim y As Double = beta * cos * Math.Sin(long1)
    Dim z As Double = beta * (1 - e) * Math.Sin(lat1)

    beta = (a / Math.Sqrt(1.0 - e * Math.Sin(lat2) * Math.Sin(lat2)))
    cos = Math.Cos(lat2)
    x -= (beta * cos * Math.Cos(long2))
    y -= (beta * cos * Math.Sin(long2))
    z -= (beta * (1 - e) * Math.Sin(lat2))

    Return Math.Sqrt((x * x) + (y * y) + (z * z))
End Function

Edit The converted function in javascript

function calculateDistance(lat1, long1, lat2, long2)
  {    

      //radians
      lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0;      
      long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0;    
      lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0;   
      long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0;       


      // use to different earth axis length    
      var a = 6378137.0;        // Earth Major Axis (WGS84)    
      var b = 6356752.3142;     // Minor Axis    
      var f = (a-b) / a;        // "Flattening"    
      var e = 2.0*f - f*f;      // "Eccentricity"      

      var beta = (a / Math.sqrt( 1.0 - e * Math.sin( lat1 ) * Math.sin( lat1 )));    
      var cos = Math.cos( lat1 );    
      var x = beta * cos * Math.cos( long1 );    
      var y = beta * cos * Math.sin( long1 );    
      var z = beta * ( 1 - e ) * Math.sin( lat1 );      

      beta = ( a / Math.sqrt( 1.0 -  e * Math.sin( lat2 ) * Math.sin( lat2 )));    
      cos = Math.cos( lat2 );   
      x -= (beta * cos * Math.cos( long2 ));    
      y -= (beta * cos * Math.sin( long2 ));    
      z -= (beta * (1 - e) * Math.sin( lat2 ));       

      return (Math.sqrt( (x*x) + (y*y) + (z*z) )/1000);  
    }

Get UserDetails object from Security Context in Spring MVC controller

If you already know for sure that the user is logged in (in your example if /index.html is protected):

UserDetails userDetails =
 (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

To first check if the user is logged in, check that the current Authentication is not a AnonymousAuthenticationToken.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
        // userDetails = auth.getPrincipal()
}

How to compile and run C files from within Notepad++ using NppExec plugin?

Here is the code for compling and running java source code: - Open Notepadd++ - Hit F6 - Paste this code

npp_save <-- Saves the current document
CD $(CURRENT_DIRECTORY) <-- Moves to the current directory
javac "$(FILE_NAME)" <-- compiles your file named *.java
java "$(NAME_PART)" <-- executes the program

The Java Classpath variable has to be set for this...

Another useful site: http://www.scribd.com/doc/52238931/Notepad-Tutorial-Compile-and-Run-Java-Program

Generic List - moving an item within the list

Simplest way:

list[newIndex] = list[oldIndex];
list.RemoveAt(oldIndex);

EDIT

The question isn't very clear ... Since we don't care where the list[newIndex] item goes I think the simplest way of doing this is as follows (with or without an extension method):

    public static void Move<T>(this List<T> list, int oldIndex, int newIndex)
    {
        T aux = list[newIndex];
        list[newIndex] = list[oldIndex];
        list[oldIndex] = aux;
    }

This solution is the fastest because it doesn't involve list insertions/removals.

what's the correct way to send a file from REST web service to client?

If you want to return a File to be downloaded, specially if you want to integrate with some javascript libs of file upload/download, then the code bellow should do the job:

@GET
@Path("/{key}")
public Response download(@PathParam("key") String key,
                         @Context HttpServletResponse response) throws IOException {
    try {
        //Get your File or Object from wherever you want...
            //you can use the key parameter to indentify your file
            //otherwise it can be removed
        //let's say your file is called "object"
        response.setContentLength((int) object.getContentLength());
        response.setHeader("Content-Disposition", "attachment; filename="
                + object.getName());
        ServletOutputStream outStream = response.getOutputStream();
        byte[] bbuf = new byte[(int) object.getContentLength() + 1024];
        DataInputStream in = new DataInputStream(
                object.getDataInputStream());
        int length = 0;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            outStream.write(bbuf, 0, length);
        }
        in.close();
        outStream.flush();
    } catch (S3ServiceException e) {
        e.printStackTrace();
    } catch (ServiceException e) {
        e.printStackTrace();
    }
    return Response.ok().build();
}

cast a List to a Collection

List<T> already implements Collection<T> - why would you need to create a new one?

Collection<T> collection = myList;

The error message is absolutely right - you can't directly instantiate an interface. If you want to create a copy of the existing list, you could use something like:

Collection<T> collection = new ArrayList<T>(myList);

Where can I download an offline installer of Cygwin?

I'm not a big fan of Cygwin. It is good if you have some Unix code that requires a full POSIX system, I suppose. Even then, using it renders your programs GPL (due to the GPLed DLL), unless you pay Red Hat for a different license.

Most people should be using MinGW (and MSYS) instead. This gives you the Unix shell and utilities (even compilers, if you want them) without the purposely infectious DLL. Most of the folks using GNU compilers on Windows are using MinGW (although some don't realise it).

Just as importantly for your purposes, you can download the parts separately, rather than use the re-downloading installer.

The SourceForge download page is here. I'd suggest starting with the MSYS Base System package, which will give you the coreutils, Bash, make, tar, etc. If there's other stuff you need, you can pick and choose from the list of packages.

How to execute a java .class from the command line

If you have in your java source

package mypackage;

and your class is hello.java with

public class hello {

and in that hello.java you have

 public static void main(String[] args) {

Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then

java -cp . mypackage.hello

Mind the current directory and the package name before the class name. It works for my on linux mint and i hope on the other os's also

Thanks Stack overflow for a wealth of info.

Find out which remote branch a local branch is tracking

I use EasyGit (a.k.a. "eg") as a super lightweight wrapper on top of (or along side of) Git. EasyGit has an "info" subcommand that gives you all kinds of super useful information, including the current branches remote tracking branch. Here's an example (where the current branch name is "foo"):

pknotz@s883422: (foo) ~/workspace/bd
$ eg info
Total commits:      175
Local repository: .git
Named remote repositories: (name -> location)
  origin -> git://sahp7577/home/pknotz/bd.git
Current branch: foo
  Cryptographic checksum (sha1sum): bd248d1de7d759eb48e8b5ff3bfb3bb0eca4c5bf
  Default pull/push repository: origin
  Default pull/push options:
    branch.foo.remote = origin
    branch.foo.merge = refs/heads/aal_devel_1
  Number of contributors:        3
  Number of files:       28
  Number of directories:       20
  Biggest file size, in bytes: 32473 (pygooglechart-0.2.0/COPYING)
  Commits:       62

How do I bottom-align grid elements in bootstrap fluid layout

You can use flex:

@media (min-width: 768px) {
  .row-fluid {
    display: flex;
    align-items: flex-end;
  }
}

jquery find closest previous sibling with class

You can follow this code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $(".add").on("click", function () {
            var v = $(this).closest(".division").find("input[name='roll']").val();
            alert(v);
        });
    });
</script>
<?php

for ($i = 1; $i <= 5; $i++) {
    echo'<div class = "division">'
        . '<form method="POST" action="">'
        . '<p><input type="number" name="roll" placeholder="Enter Roll"></p>'
        . '<p><input type="button" class="add" name = "submit" value = "Click"></p>'
        . '</form></div>';
}
?>

You can get idea from this.

How to uninstall Apache with command line

Try this :

sc delete Apache2.4

or try this :

C:\Apache24\bin>httpd -k uninstall

hope this will be helpful

SimpleXml to string

Sometimes you can simply typecast:

// this is the value of my $xml
object(SimpleXMLElement)#10227 (1) {
  [0]=>
  string(2) "en"
}

$s = (string) $xml; // returns "en";

How to make a radio button unchecked by clicking it?

Most of the modern day browsers consider checked="anything" as checked="true".

You might have to remove the checked attribute if that makes sense in your case, one of which might be related to when you load the page.

$(this).removeAttr('checked')

This might help you in cases when you want your radio button to be checked adhering to some condition. You can simply remove the attribute to achieve that.

PS: Not helpful in all the cases.

Replace words in the body text

I ended up with this function to safely replace text without side effects (so far):

function replaceInText(element, pattern, replacement) {
    for (let node of element.childNodes) {
        switch (node.nodeType) {
            case Node.ELEMENT_NODE:
                replaceInText(node, pattern, replacement);
                break;
            case Node.TEXT_NODE:
                node.textContent = node.textContent.replace(pattern, replacement);
                break;
            case Node.DOCUMENT_NODE:
                replaceInText(node, pattern, replacement);
        }
    }
}

It's for cases where the 16kB of findAndReplaceDOMText are a bit too heavy.

How to wait for 2 seconds?

As mentioned in other answers, all of the following will work for the standard string-based syntax.

WAITFOR DELAY '02:00' --Two hours
WAITFOR DELAY '00:02' --Two minutes
WAITFOR DELAY '00:00:02' --Two seconds
WAITFOR DELAY '00:00:00.200' --Two tenths of a seconds

There is also an alternative method of passing it a DATETIME value. You might think I'm confusing this with WAITFOR TIME, but it also works for WAITFOR DELAY.

Considerations for passing DATETIME:

  • It must be passed as a variable, so it isn't a nice one-liner anymore.
  • The delay is measured as the time since the Epoch ('1900-01-01').
  • For situations that require a variable amount of delay, it is much easier to manipulate a DATETIME than to properly format a VARCHAR.

How to wait for 2 seconds:

--Example 1
DECLARE @Delay1 DATETIME
SELECT @Delay1 = '1900-01-01 00:00:02.000'
WAITFOR DELAY @Delay1

--Example 2
DECLARE @Delay2 DATETIME
SELECT @Delay2 = dateadd(SECOND, 2, convert(DATETIME, 0))
WAITFOR DELAY @Delay2

A note on waiting for TIME vs DELAY:

Have you ever noticed that if you accidentally pass WAITFOR TIME a date that already passed, even by just a second, it will never return? Check it out:

--Example 3
DECLARE @Time1 DATETIME
SELECT @Time1 = getdate()
WAITFOR DELAY '00:00:01'
WAITFOR TIME @Time1 --WILL HANG FOREVER

Unfortunately, WAITFOR DELAY will do the same thing if you pass it a negative DATETIME value (yes, that's a thing).

--Example 4
DECLARE @Delay3 DATETIME
SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0))
WAITFOR DELAY @Delay3 --WILL HANG FOREVER

However, I would still recommend using WAITFOR DELAY over a static time because you can always confirm your delay is positive and it will stay that way for however long it takes your code to reach the WAITFOR statement.

How do I split a string into an array of characters?

You can split on an empty string:

var chars = "overpopulation".split('');

If you just want to access a string in an array-like fashion, you can do that without split:

var s = "overpopulation";
for (var i = 0; i < s.length; i++) {
    console.log(s.charAt(i));
}

You can also access each character with its index using normal array syntax. Note, however, that strings are immutable, which means you can't set the value of a character using this method, and that it isn't supported by IE7 (if that still matters to you).

var s = "overpopulation";

console.log(s[3]); // logs 'r'

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Google Apps KitKat for Genymotion.

Download the Google Apps ZIP file from the link which contain the essential Google Apps such as Play Store, Gmail, YouTube, etc.

https://www.mediafire.com/?qbbt4lhyu9q10ix

After finishing booting, drag and drop the ZIP file we downloaded named update-gapps-4-4-2-signed.zip to the Genymotion Window. It starts installing the Google Apps, and it asks for your confirmation. Confirm it.

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

If you are using Sql Server (any edition, even express) then you can install Sql Server Reporting Services. This allows the creation of reports through a visual studio plugin, or through a browser control and can export the reports in a variety of formats, including PDF. You can view the reports through the winforms report viewer control which is included, or take advantage of all of the built in generated web content.

The learning curve is not very steep at all if you are used to using datasets in Visual Studio.

How to set background image in Java?

<script>
function SetBack(dir) {
    document.getElementById('body').style.backgroundImage=dir;
}
SetBack('url(myniftybg.gif)');
</script>

Sending data back to the Main Activity in Android

In first activity u can send intent using startActivityForResult() and then get result from second activity after it finished using setResult.

MainActivity.class

public class MainActivity extends AppCompatActivity {

    private static final int SECOND_ACTIVITY_RESULT_CODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // Start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        // send intent for result 
        startActivityForResult(intent, SECOND_ACTIVITY_RESULT_CODE);
    }

    // This method is called when the second activity finishes
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_RESULT_CODE) {
            if (resultCode == RESULT_OK) {

                // get String data from Intent
                String returnString = data.getStringExtra("keyName");

                // set text view with string
                TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText(returnString);
            }
        }
    }
}

SecondActivity.class

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    // "Send text back" button click
    public void onButtonClick(View view) {

        // get the text from the EditText
        EditText editText = (EditText) findViewById(R.id.editText);
        String stringToPassBack = editText.getText().toString();

        // put the String to pass back into an Intent and close this activity
        Intent intent = new Intent();
        intent.putExtra("keyName", stringToPassBack);
        setResult(RESULT_OK, intent);
        finish();
    }
}

How to make the web page height to fit screen height

As another guy described here, all you need to do is add

height: 100vh;

to the style of whatever you need to fill the screen

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

How do you beta test an iphone app?

In year 2011, there's a new service out called "Test Flight", and it addresses this issue directly.

Apple has since bought TestFlight in 2014 and has integrated it into iTunes Connect and App Store Connect.

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

The Gantt charts given by Hifzan and Raja are for FCFS algorithms.

With an SJF algorithm, processes can be interrupted. That is, every process doesn't necessarily execute straight through their given burst time.

P3|P2|P4|P3|P5|P1|P5

1|2|3|5|7|8|11|14

P3 arrives at 1ms, then is interrupted by P2 and P4 since they both have smaller burst times, and then P3 resumes. P5 starts executing next, then is interrupted by P1 since P1's burst time is smaller than P5's. You must note the arrival times and be careful. These problems can be trickier than how they appear at-first-glance.

EDIT: This applies only to Preemptive SJF algorithms. A plain SJF algorithm is non-preemptive, meaning it does not interrupt a process.

How do I return the response from an asynchronous call?

XMLHttpRequest 2 (first of all read the answers from Benjamin Gruenbaum & Felix Kling)

If you don't use jQuery and want a nice short XMLHttpRequest 2 which works on the modern browsers and also on the mobile browsers I suggest to use it this way:

function ajax(a, b, c){ // URL, callback, just a placeholder
  c = new XMLHttpRequest;
  c.open('GET', a);
  c.onload = b;
  c.send()
}

As you can see:

  1. It's shorter than all other functions Listed.
  2. The callback is set directly (so no extra unnecessary closures).
  3. It uses the new onload (so you don't have to check for readystate && status)
  4. There are some other situations which I don't remember that make the XMLHttpRequest 1 annoying.

There are two ways to get the response of this Ajax call (three using the XMLHttpRequest var name):

The simplest:

this.response

Or if for some reason you bind() the callback to a class:

e.target.response

Example:

function callback(e){
  console.log(this.response);
}
ajax('URL', callback);

Or (the above one is better anonymous functions are always a problem):

ajax('URL', function(e){console.log(this.response)});

Nothing easier.

Now some people will probably say that it's better to use onreadystatechange or the even the XMLHttpRequest variable name. That's wrong.

Check out XMLHttpRequest advanced features

It supported all *modern browsers. And I can confirm as I'm using this approach since XMLHttpRequest 2 exists. I never had any type of problem on all browsers I use.

onreadystatechange is only useful if you want to get the headers on state 2.

Using the XMLHttpRequest variable name is another big error as you need to execute the callback inside the onload/oreadystatechange closures else you lost it.


Now if you want something more complex using post and FormData you can easily extend this function:

function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val},placeholder
  c = new XMLHttpRequest;
  c.open(e||'get', a);
  c.onload = b;
  c.send(d||null)
}

Again ... it's a very short function, but it does get & post.

Examples of usage:

x(url, callback); // By default it's get so no need to set
x(url, callback, 'post', {'key': 'val'}); // No need to set post data

Or pass a full form element (document.getElementsByTagName('form')[0]):

var fd = new FormData(form);
x(url, callback, 'post', fd);

Or set some custom values:

var fd = new FormData();
fd.append('key', 'val')
x(url, callback, 'post', fd);

As you can see I didn't implement sync... it's a bad thing.

Having said that ... why don't do it the easy way?


As mentioned in the comment the use of error && synchronous does completely break the point of the answer. Which is a nice short way to use Ajax in the proper way?

Error handler

function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val}, placeholder
  c = new XMLHttpRequest;
  c.open(e||'get', a);
  c.onload = b;
  c.onerror = error;
  c.send(d||null)
}

function error(e){
  console.log('--Error--', this.type);
  console.log('this: ', this);
  console.log('Event: ', e)
}
function displayAjax(e){
  console.log(e, this);
}
x('WRONGURL', displayAjax);

In the above script, you have an error handler which is statically defined so it does not compromise the function. The error handler can be used for other functions too.

But to really get out an error the only way is to write a wrong URL in which case every browser throws an error.

Error handlers are maybe useful if you set custom headers, set the responseType to blob array buffer or whatever...

Even if you pass 'POSTAPAPAP' as the method it won't throw an error.

Even if you pass 'fdggdgilfdghfldj' as formdata it won't throw an error.

In the first case the error is inside the displayAjax() under this.statusText as Method not Allowed.

In the second case, it simply works. You have to check at the server side if you passed the right post data.

cross-domain not allowed throws error automatically.

In the error response, there are no error codes.

There is only the this.type which is set to error.

Why add an error handler if you totally have no control over errors? Most of the errors are returned inside this in the callback function displayAjax().

So: No need for error checks if you're able to copy and paste the URL properly. ;)

PS: As the first test I wrote x('x', displayAjax)..., and it totally got a response...??? So I checked the folder where the HTML is located, and there was a file called 'x.xml'. So even if you forget the extension of your file XMLHttpRequest 2 WILL FIND IT. I LOL'd


Read a file synchronous

Don't do that.

If you want to block the browser for a while load a nice big .txt file synchronous.

function omg(a, c){ // URL
  c = new XMLHttpRequest;
  c.open('GET', a, true);
  c.send();
  return c; // Or c.response
}

Now you can do

 var res = omg('thisIsGonnaBlockThePage.txt');

There is no other way to do this in a non-asynchronous way. (Yeah, with setTimeout loop... but seriously?)

Another point is... if you work with APIs or just your own list's files or whatever you always use different functions for each request...

Only if you have a page where you load always the same XML/JSON or whatever you need only one function. In that case, modify a little the Ajax function and replace b with your special function.


The functions above are for basic use.

If you want to EXTEND the function...

Yes, you can.

I'm using a lot of APIs and one of the first functions I integrate into every HTML page is the first Ajax function in this answer, with GET only...

But you can do a lot of stuff with XMLHttpRequest 2:

I made a download manager (using ranges on both sides with resume, filereader, filesystem), various image resizers converters using canvas, populate web SQL databases with base64images and much more... But in these cases you should create a function only for that purpose... sometimes you need a blob, array buffers, you can set headers, override mimetype and there is a lot more...

But the question here is how to return an Ajax response... (I added an easy way.)

How to insert values into the database table using VBA in MS access

You can't run two SQL statements into one like you are doing.

You can't "execute" a select query.

db is an object and you haven't set it to anything: (e.g. set db = currentdb)

In VBA integer types can hold up to max of 32767 - I would be tempted to use Long.

You might want to be a bit more specific about the date you are inserting:

INSERT INTO Test (Start_Date) VALUES ('#" & format(InDate, "mm/dd/yyyy") & "#' );"

PHP CURL & HTTPS

Another option like Gavin Palmer answer is to use the .pem file but with a curl option

  1. download the last updated .pem file from https://curl.haxx.se/docs/caextract.html and save it somewhere on your server(outside the public folder)

  2. set the option in your code instead of the php.ini file.

In your code

curl_setopt($ch, CURLOPT_CAINFO, $_SERVER['DOCUMENT_ROOT'] .  "/../cacert-2017-09-20.pem");

NOTE: setting the cainfo in the php.ini like @Gavin Palmer did is better than setting it in your code like I did, because it will save a disk IO every time the function is called, I just make it like this in case you want to test the cainfo file on the fly instead of changing the php.ini while testing your function.

WPF Button with Image

Another way to Stretch image to full button. Can try the below code.

<Grid.Resources>
  <ImageBrush x:Key="AddButtonImageBrush" ImageSource="/Demoapp;component/Resources/AddButton.png" Stretch="UniformToFill"/>
</Grid.Resources>

<Button Content="Load Inventory 1" Background="{StaticResource AddButtonImageBrush}"/> 

Referred from Here

Also it might helps other. I posted the same with MouseOver Option here.

Check if a string contains a string in C++

You can also use the System namespace. Then you can use the contains method.

#include <iostream>
using namespace System;

int main(){
    String ^ wholeString = "My name is Malindu";

    if(wholeString->ToLower()->Contains("malindu")){
        std::cout<<"Found";
    }
    else{
        std::cout<<"Not Found";
    }
}

JQuery / JavaScript - trigger button click from another button click event

If it does not work by using the click() method like suggested in the accepted answer, then you can try this:

//trigger second button
$("#second").mousedown();
$("#second").mouseup();

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

Spring CORS No 'Access-Control-Allow-Origin' header is present

Following on Omar's answer, I created a new class file in my REST API project called WebConfig.java with this configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedOrigins("*");
  }
} 

This allows any origin to access the API and applies it to all controllers in the Spring project.

How to install SignTool.exe for Windows 10

If you only want SignTool and really want to minimize the install, here is a way that I just reverse-engineered my way to:

  1. Download the .iso file from https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk (current download link is http://go.microsoft.com/fwlink/p/?LinkID=2022797) The .exe download will not work, since it's an online installer that pulls down its dependencies at runtime.
  2. Unpack the .iso with a tool such as 7-zip.
  3. Install the Installers/Windows SDK Signing Tools-x86_en-us.msi file - it's only 388 KiB large. For reference, it pulls in its files from the following .cab files, so these are also needed for a standalone install:
    • 4c3ef4b2b1dc72149f979f4243d2accf.cab (339 KiB)
    • 685f3d4691f444bc382762d603a99afc.cab (1002 KiB)
    • e5c4b31ff9997ac5603f4f28cd7df602.cab (389 KiB)
    • e98fa5eb5fee6ce17a7a69d585870b7c.cab (1.2 MiB)

There we go - you will now have the signtool.exe file and companions in C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x64 (replace x64 with x86, arm or arm64 if you need it for another CPU architecture.)


It is also possible to commit signtool.exe and the other files from this folder into your version control repository if want to use it in e.g. CI scenarios. I have tried it and it seems to work fine.

(All files are probably not necessary since there are also some other .exe tools in this folder that might be responsible for these dependencies, but I am not sure which ones could be removed to make the set of files even smaller. Someone else is free to investigate further in this area. :) I tried to just copy signtool.* and that didn't work, so at least some of the other files are needed.)

Commit only part of a file in Git

You can use git add --interactive or git add -p <file>, and then git commit (not git commit -a); see Interactive mode in git-add manpage, or simply follow instructions.

Modern Git has also git commit --interactive (and git commit --patch, which is shortcut to patch option in interactive commit).

If you prefer doing it from GUI, you can use git-gui. You can simply mark chunks which you want to have included in commit. I personally find it easier than using git add -i. Other git GUIs, like QGit or GitX, might also have this functionality as well.

adding classpath in linux

I don't like setting CLASSPATH. CLASSPATH is a global variable and as such it is evil:

  • If you modify it in one script, suddenly some java programs will stop working.
  • If you put there the libraries for all the things which you run, and it gets cluttered.
  • You get conflicts if two different applications use different versions of the same library.
  • There is no performance gain as libraries in the CLASSPATH are not shared - just their name is shared.
  • If you put the dot (.) or any other relative path in the CLASSPATH that means a different thing in each place - that will cause confusion, for sure.

Therefore the preferred way is to set the classpath per each run of the jvm, for example:

java -Xmx500m -cp ".:../somejar.jar:../mysql-connector-java-5.1.6-bin.jar"    "folder.subfolder../dit1/some.xml

If it gets long the standard procedure is to wrap it in a bash or batch script to save typing.

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

I've found a solution by creating the following function:

CREATE FUNCTION [dbo].[JoinTexts]
(
  @delimiter VARCHAR(20) ,
  @whereClause VARCHAR(1)
)
RETURNS VARCHAR(MAX)
AS 
BEGIN
    DECLARE @Texts VARCHAR(MAX)

    SELECT  @Texts = COALESCE(@Texts + @delimiter, '') + T.Texto
    FROM    SomeTable AS T
    WHERE   T.SomeOtherColumn = @whereClause

    RETURN @Texts
END
GO

Usage:

SELECT dbo.JoinTexts(' , ', 'Y')

MVC Calling a view from a different controller

I'm not really sure if I got your question right. Maybe something like

public class CommentsController : Controller
{
    [HttpPost]
    public ActionResult WriteComment(CommentModel comment)
    {
        // Do the basic model validation and other stuff
        try
        {
            if (ModelState.IsValid )
            {
                 // Insert the model to database like:
                 db.Comments.Add(comment);
                 db.SaveChanges();

                 // Pass the comment's article id to the read action
                 return RedirectToAction("Read", "Articles", new {id = comment.ArticleID});
            }
        }
        catch ( Exception e )
        {
             throw e;
        }
        // Something went wrong
        return View(comment);

    }
}


public class ArticlesController : Controller
{
    // id is the id of the article
    public ActionResult Read(int id)
    {
        // Get the article from database by id
        var model = db.Articles.Find(id);
        // Return the view
        return View(model);
    }
}

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

It sounds like you hit the "Insert" key .. in most applications this results in a fat (solid rectangle) cursor being displayed, as your screenshot suggests. This indicates that you are in overwrite mode rather than the default insert mode.

Just hit the "insert" key on your keyboard once more... it's usually near the 'delete' (not backspace), scroll lock and 'Print Screen' (often above the cursor keys in a full size keyboard.) This will switch back to insert mode and turn your cursor into a vertical line rather than a rectangle.

Checking if a number is a prime number in Python

There are many efficient ways to test primality (and this isn't one of them), but the loop you wrote can be concisely rewritten in Python:

def is_prime(a):
    return all(a % i for i in xrange(2, a))

That is, a is prime if all numbers between 2 and a (not inclusive) give non-zero remainder when divided into a.

HTML5 video - show/hide controls programmatically

<video id="myvideo">
  <source src="path/to/movie.mp4" />
</video>

<p onclick="toggleControls();">Toggle</p>

<script>
var video = document.getElementById("myvideo");

function toggleControls() {
  if (video.hasAttribute("controls")) {
     video.removeAttribute("controls")   
  } else {
     video.setAttribute("controls","controls")   
  }
}
</script>

See it working on jsFiddle: http://jsfiddle.net/dgLds/

Ruby: Easiest Way to Filter Hash Keys?

As for bonus question:

  1. If you have output from #select method like this (list of 2-element arrays):

    [[:choice1, "Oh look, another one"], [:choice2, "Even more strings"], [:choice3, "But wait"]]
    

    then simply take this result and execute:

    filtered_params.join("\t")
    # or if you want only values instead of pairs key-value
    filtered_params.map(&:last).join("\t")
    
  2. If you have output from #delete_if method like this (hash):

    {:choice1=>"Oh look, another one", :choice2=>"Even more strings", :choice3=>"But wait"}
    

    then:

    filtered_params.to_a.join("\t")
    # or
    filtered_params.values.join("\t")
    

How do I sort a list of dictionaries by a value of the dictionary?

Sometimes we need to use lower(). For example,

lists = [{'name':'Homer', 'age':39},
  {'name':'Bart', 'age':10},
  {'name':'abby', 'age':9}]

lists = sorted(lists, key=lambda k: k['name'])
print(lists)
# [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}, {'name':'abby', 'age':9}]

lists = sorted(lists, key=lambda k: k['name'].lower())
print(lists)
# [ {'name':'abby', 'age':9}, {'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]

How can I get Docker Linux container information from within the container itself?

I believe that the "problem" with all of the above is that it depends upon a certain implementation convention either of docker itself or its implementation and how that interacts with cgroups and /proc, and not via a committed, public, API, protocol or convention as part of the OCI specs.

Hence these solutions are "brittle" and likely to break when least expected when implementations change, or conventions are overridden by user configuration.

container and image ids should be injected into the r/t environment by the component that initiated the container instance, if for no other reason than to permit code running therein to use that information to uniquely identify themselves for logging/tracing etc...

just my $0.02, YMMV...

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

If you are trying to run Google android sample code, try to import the entire repository instead of an individual sample.

Here is instructions.html, included with the Google Calendar API sample code.

  • Import calendar-android-sample project
  • Select "Import Project..." or File > Import Project...
  • Select [someDirectory]/google-api-java-client-samples/build.gradle and click OK.
    • Note: it will not work if you try to import [someDirectory]/google-api-java-client-samples/calendar-android-sample/build.gradle
  • Select "Use local gradle distribution" with "Gradle home" of [someDirectory]/gradle-2.2.1 and click OK.

Get selected value from combo box in C# WPF

It depends what you bound to your ComboBox. If you have bound an object called MyObject, and have, let's say, a property called Name do the following:

MyObject mo = myListBox.SelectedItem as MyObject;
return mo.Name;

How do I use 'git reset --hard HEAD' to revert to a previous commit?

WARNING: git clean -f will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.


Try this and see git clean -f.

git reset --hard will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under Git tracking.

Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)

  • git clean -df
  • git clean -xdf CAUTION! This will also delete ignored files

How to get an object's properties in JavaScript / jQuery?

I hope this doesn't count as spam. I humbly ended up writing a function after endless debug sessions: http://github.com/halilim/Javascript-Simple-Object-Inspect

function simpleObjInspect(oObj, key, tabLvl)
{
    key = key || "";
    tabLvl = tabLvl || 1;
    var tabs = "";
    for(var i = 1; i < tabLvl; i++){
        tabs += "\t";
    }
    var keyTypeStr = " (" + typeof key + ")";
    if (tabLvl == 1) {
        keyTypeStr = "(self)";
    }
    var s = tabs + key + keyTypeStr + " : ";
    if (typeof oObj == "object" && oObj !== null) {
        s += typeof oObj + "\n";
        for (var k in oObj) {
            if (oObj.hasOwnProperty(k)) {
                s += simpleObjInspect(oObj[k], k, tabLvl + 1);
            }
        }
    } else {
        s += "" + oObj + " (" + typeof oObj + ") \n";
    }
    return s;
}

Usage

alert(simpleObjInspect(anyObject));

or

console.log(simpleObjInspect(anyObject));

How to return multiple values in one column (T-SQL)?

You can either loop through the rows with a cursor and append to a field in a temp table, or you could use the COALESCE function to concatenate the fields.

Angular2 *ngIf check object array length in template

<div class="row" *ngIf="teamMembers?.length > 0">

This checks first if teamMembers has a value and if teamMembers doesn't have a value, it doesn't try to access length of undefined because the first part of the condition already fails.