Programs & Examples On #Pascal

Pascal is an imperative language from the Wirthian family created in 1969. It was widely used in engineering and teaching in the 1970s and 1980s. It lives on in compilers as Free Pascal and Delphi.

How to install latest version of openssl Mac OS X El Capitan

Only

export PATH=$(brew --prefix openssl)/bin:$PATH in ~/.bash_profile

has worked for me! Thank you mipadi.

Exception is never thrown in body of corresponding try statement

Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.

Correct use for angular-translate in controllers

What is happening is that Angular-translate is watching the expression with an event-based system, and just as in any other case of binding or two-way binding, an event is fired when the data is retrieved, and the value changed, which obviously doesn't work for translation. Translation data, unlike other dynamic data on the page, must, of course, show up immediately to the user. It can't pop in after the page loads.

Even if you can successfully debug this issue, the bigger problem is that the development work involved is huge. A developer has to manually extract every string on the site, put it in a .json file, manually reference it by string code (ie 'pageTitle' in this case). Most commercial sites have thousands of strings for which this needs to happen. And that is just the beginning. You now need a system of keeping the translations in synch when the underlying text changes in some of them, a system for sending the translation files out to the various translators, of reintegrating them into the build, of redeploying the site so the translators can see their changes in context, and on and on.

Also, as this is a 'binding', event-based system, an event is being fired for every single string on the page, which not only is a slower way to transform the page but can slow down all the actions on the page, if you start adding large numbers of events to it.

Anyway, using a post-processing translation platform makes more sense to me. Using GlobalizeIt for example, a translator can just go to a page on the site and start editing the text directly on the page for their language, and that's it: https://www.globalizeit.com/HowItWorks. No programming needed (though it can be programmatically extensible), it integrates easily with Angular: https://www.globalizeit.com/Translate/Angular, the transformation of the page happens in one go, and it always displays the translated text with the initial render of the page.

Full disclosure: I'm a co-founder :)

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

Add Json NamingStrategy property to your class definition.

_x000D_
_x000D_
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
_x000D_
_x000D_
_x000D_

Is there a concise way to iterate over a stream with indices in Java 8?

With https://github.com/poetix/protonpack u can do that zip:

String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};

List<String> nameList;
Stream<Integer> indices = IntStream.range(0, names.length).boxed(); 

nameList = StreamUtils.zip(indices, stream(names),SimpleEntry::new)
        .filter(e -> e.getValue().length() <= e.getKey()).map(Entry::getValue).collect(toList());                   

System.out.println(nameList);

What is the perfect counterpart in Python for "while not EOF"

While there are suggestions above for "doing it the python way", if one wants to really have a logic based on EOF, then I suppose using exception handling is the way to do it --

try:
    line = raw_input()
    ... whatever needs to be done incase of no EOF ...
except EOFError:
    ... whatever needs to be done incase of EOF ...

Example:

$ echo test | python -c "while True: print raw_input()"
test
Traceback (most recent call last):
  File "<string>", line 1, in <module> 
EOFError: EOF when reading a line

Or press Ctrl-Z at a raw_input() prompt (Windows, Ctrl-Z Linux)

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

DEPLOYABLE SOLUTION (Alpine Linux)

To be able to fix this issue in our application environments, we have prepared Linux terminal commands as follows:

cd ~

Will generate cert file in home directory.

apk add openssl

This command installs openssl in alpine Linux. You can find proper commands for other Linux distributions.

openssl s_client -connect <host-dns-ssl-belongs> < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > public.crt

Generated the needed cert file.

sudo $JAVA_HOME/bin/keytool -import -alias server_name -keystore $JAVA_HOME/lib/security/cacerts -file public.crt -storepass changeit -noprompt

Applied the generated file to the JRE with the program 'keytool'.

Note: Please replace your DNS with <host-dns-ssl-belongs>

Note2: Please gently note that -noprompt will not prompt the verification message (yes/no) and -storepass changeit parameter will disable password prompt and provide the needed password (default is 'changeit'). These two properties will let you use those scripts in your application environments like building a Docker image.

Note3 If you are deploying your app via Docker, you can generate the secret file once and put it in your application project files. You won't need to generate it again and again.

Find object in list that has attribute equal to some value (that meets any condition)

You could do something like this

dict = [{
   "id": 1,
   "name": "Doom Hammer"
 },
 {
    "id": 2,
    "name": "Rings ov Saturn"
 }
]

for x in dict:
  if x["id"] == 2:
    print(x["name"])

Thats what i use to find the objects in a long array of objects.

JSON Naming Convention (snake_case, camelCase or PascalCase)

Premise

There is no standard naming of keys in JSON. According to the Objects section of the spec:

The JSON syntax does not impose any restrictions on the strings used as names,...

Which means camelCase or snake_case should work fine.

Driving factors

Imposing a JSON naming convention is very confusing. However, this can easily be figured out if you break it down into components.

  1. Programming language for generating JSON

    • Python - snake_case
    • PHP - snake_case
    • Java - camelCase
    • JavaScript - camelCase
  2. JSON itself has no standard naming of keys

  3. Programming language for parsing JSON

    • Python - snake_case
    • PHP - snake_case
    • Java - camelCase
    • JavaScript - camelCase

Mix-match the components

  1. Python » JSON » Python - snake_case - unanimous
  2. Python » JSON » PHP - snake_case - unanimous
  3. Python » JSON » Java - snake_case - please see the Java problem below
  4. Python » JSON » JavaScript - snake_case will make sense; screw the front-end anyways
  5. Python » JSON » you do not know - snake_case will make sense; screw the parser anyways
  6. PHP » JSON » Python - snake_case - unanimous
  7. PHP » JSON » PHP - snake_case - unanimous
  8. PHP » JSON » Java - snake_case - please see the Java problem below
  9. PHP » JSON » JavaScript - snake_case will make sense; screw the front-end anyways
  10. PHP » JSON » you do not know - snake_case will make sense; screw the parser anyways
  11. Java » JSON » Python - snake_case - please see the Java problem below
  12. Java » JSON » PHP - snake_case - please see the Java problem below
  13. Java » JSON » Java - camelCase - unanimous
  14. Java » JSON » JavaScript - camelCase - unanimous
  15. Java » JSON » you do not know - camelCase will make sense; screw the parser anyways
  16. JavaScript » JSON » Python - snake_case will make sense; screw the front-end anyways
  17. JavaScript » JSON » PHP - snake_case will make sense; screw the front-end anyways
  18. JavaScript » JSON » Java - camelCase - unanimous
  19. JavaScript » JSON » JavaScript - camelCase - Original

Java problem

snake_case will still make sense for those with Java entries because the existing JSON libraries for Java are using only methods to access the keys instead of using the standard dot.syntax. This means that it wouldn't hurt that much for Java to access the snake_cased keys in comparison to the other programming language which can do the dot.syntax.

Example for Java's org.json package

JsonObject.getString("snake_cased_key")

Example for Java's com.google.gson package

JsonElement.getAsString("snake_cased_key")

Some actual implementations

Conclusions

Choosing the right JSON naming convention for your JSON implementation depends on your technology stack. There are cases where one can use snake_case, camelCase, or any other naming convention.

Another thing to consider is the weight to be put on the JSON-generator vs the JSON-parser and/or the front-end JavaScript. In general, more weight should be put on the JSON-generator side rather than the JSON-parser side. This is because business logic usually resides on the JSON-generator side.

Also, if the JSON-parser side is unknown then you can declare what ever can work for you.

What is the convention for word separator in Java package names?

Underscores look ugly in package names. For what is worth, in case of names compound of three or more words I use initials (for example: com.company.app.ingresoegresofijo (ingreso/egreso fijo) -> com.company.app.iefijo) and then document the package purpose in package-info.java.

Purpose of Unions in C and C++

Others have mentioned the architecture differences (little - big endian).

I read the problem that since the memory for the variables is shared, then by writing to one, the others change and, depending on their type, the value could be meaningless.

eg. union{ float f; int i; } x;

Writing to x.i would be meaningless if you then read from x.f - unless that is what you intended in order to look at the sign, exponent or mantissa components of the float.

I think there is also an issue of alignment: If some variables must be word aligned then you might not get the expected result.

eg. union{ char c[4]; int i; } x;

If, hypothetically, on some machine a char had to be word aligned then c[0] and c[1] would share storage with i but not c[2] and c[3].

How can I use Ruby to colorize the text output to a terminal?

While the other answers will do the job fine for most people, the "correct" Unix way of doing this should be mentioned. Since all types of text terminals do not support these sequences, you can query the terminfo database, an abstraction over the capabilites of various text terminals. This might seem mostly of historical interest – software terminals in use today generally support the ANSI sequences – but it does have (at least) one practical effect: it is sometimes useful to be able to set the environment variable TERM to dumb to avoid all such styling, for example when saving the output to a text file. Also, it feels good to do things right. :-)

You can use the ruby-terminfo gem. It needs some C compiling to install; I was able to install it under my Ubuntu 14.10 system with:

$ sudo apt-get install libncurses5-dev
$ gem install ruby-terminfo --user-install

Then you can query the database like this (see the terminfo man page for a list of what codes are available):

require 'terminfo' 
TermInfo.control("bold")
puts "Bold text"
TermInfo.control("sgr0")
puts "Back to normal."
puts "And now some " + TermInfo.control_string("setaf", 1) + 
     "red" + TermInfo.control_string("sgr0") + " text."

Here's a little wrapper class I put together to make things a little more simple to use.

require 'terminfo'

class Style
  def self.style() 
    @@singleton ||= Style.new
  end

  colors = %w{black red green yellow blue magenta cyan white}
  colors.each_with_index do |color, index|
    define_method(color) { get("setaf", index) }
    define_method("bg_" + color) { get("setab", index) }
  end

  def bold()  get("bold")  end
  def under() get("smul")  end
  def dim()   get("dim")   end
  def clear() get("sgr0")  end

  def get(*args)
    begin
      TermInfo.control_string(*args)
    rescue TermInfo::TermInfoError
      ""
    end
  end
end

Usage:

c = Style.style
C = c.clear
puts "#{c.red}Warning:#{C} this is #{c.bold}way#{C} #{c.bg_red}too much #{c.cyan + c.under}styling#{C}!"
puts "#{c.dim}(Don't you think?)#{C}"

Output of above Ruby script

(edit) Finally, if you'd rather not require a gem, you can rely on the tput program, as described here – Ruby example:

puts "Hi! " + `tput setaf 1` + "This is red!" + `tput sgr0`

Is "else if" faster than "switch() case"?

I'm not sure, but i believe the speed of one or the other changes depending on the programming language you're using.

I usually prefer to use switch. That way the code is simplear to read.

LaTeX source code listing like in professional books

It seems to me that what you really want, is to customize the look of the captions. This is most easily done using the caption package. For instructions how to use this package, see the manual (PDF). You would probably need to create your own custom caption format, as described in chapter 4 in the manual.

Edit: Tested with MikTex:

\documentclass{report}

\usepackage{color}
\usepackage{xcolor}
\usepackage{listings}

\usepackage{caption}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}

% This concludes the preamble

\begin{document}

\begin{lstlisting}[label=some-code,caption=Some Code]
public void here() {
    goes().the().code()
}
\end{lstlisting}

\end{document}

Result:

Preview

Is there a program to decompile Delphi?

Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.

So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.

What is the naming convention in Python for variable and function names?

There is PEP 8, as other answers show, but PEP 8 is only the styleguide for the standard library, and it's only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There is no single predominate style, although considering the volume of code that uses mixedCase, if one were to make a strict census one would probably end up with a version of PEP 8 with mixedCase. There is little other deviation from PEP 8 that is quite as common.

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).

Can you delete data from influxdb?

With influx, you can only delete by time

For example, the following are invalid:

#Wrong
DELETE FROM foo WHERE time < '2014-06-30' and duration > 1000 #Can't delete if where clause has non time entity

This is how I was able to delete the data

DELETE FROM foo WHERE time > '2014-06-30' and time < '2014-06-30 15:16:01'

Update: this worked on influx 8. Supposedly it doesn't work on influx 9

How to clear a chart from a canvas so that hover events cannot be triggered?

Since destroy kind of destroys "everything", a cheap and simple solution when all you really want is to just "reset the data". Resetting your datasets to an empty array will work perfectly fine as well. So, if you have a dataset with labels, and an axis on each side:

window.myLine2.data.labels = [];
window.myLine2.data.datasets[0].data = [];
window.myLine2.data.datasets[1].data = [];

After this, you can simply call:

window.myLine2.data.labels.push(x);
window.myLine2.data.datasets[0].data.push(y);

or, depending whether you're using a 2d dataset:

window.myLine2.data.datasets[0].data.push({ x: x, y: y});

It'll be a lot more lightweight than completely destroying your whole chart/dataset, and rebuilding everything.

How to set custom favicon in Express?

You must install middleware to serve the favicon.

I tried this just now:

app.use(express.favicon(path.join(__dirname, 'public','images','favicon.ico'))); 

and got this error message back:

Error: Most middleware (like favicon) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.

I think we can take that as being definitive.

What determines the monitor my app runs on?

It's not exactly the answer to this question but I dealt with this problem with the Shift + Win + [left,right] arrow keys shortcut. You can move the currently active window to another monitor with it.

How can I search sub-folders using glob.glob module?

To find files in immediate subdirectories:

configfiles = glob.glob(r'C:\Users\sam\Desktop\*\*.txt')

For a recursive version that traverse all subdirectories, you could use ** and pass recursive=True since Python 3.5:

configfiles = glob.glob(r'C:\Users\sam\Desktop\**\*.txt', recursive=True)

Both function calls return lists. You could use glob.iglob() to return paths one by one. Or use pathlib:

from pathlib import Path

path = Path(r'C:\Users\sam\Desktop')
txt_files_only_subdirs = path.glob('*/*.txt')
txt_files_all_recursively = path.rglob('*.txt') # including the current dir

Both methods return iterators (you can get paths one by one).

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

Below command worked for me docker build -t docker-whale -f Dockerfile.txt .

Parse JSON String to JSON Object in C#.NET

use new JavaScriptSerializer().Deserialize<object>(jsonString)

You need System.Web.Extensions dll and import the following namespace.

Namespace: System.Web.Script.Serialization

for more info MSDN

How to use environment variables in docker compose

Use .env file to define dynamic values in docker-compse.yml. Be it port or any other value.

Sample docker-compose:

testcore.web:
       image: xxxxxxxxxxxxxxx.dkr.ecr.ap-northeast-2.amazonaws.com/testcore:latest
       volumes: 
            - c:/logs:c:/logs
       ports:
            - ${TEST_CORE_PORT}:80
       environment:
            - CONSUL_URL=http://${CONSUL_IP}:8500 
            - HOST=${HOST_ADDRESS}:${TEST_CORE_PORT}

Inside .env file you can define the value of these variables:

CONSUL_IP=172.31.28.151
HOST_ADDRESS=172.31.16.221
TEST_CORE_PORT=10002

Singleton design pattern vs Singleton beans in Spring container

Let's take the simplest example: you have an application and you just use the default classloader. You have a class which, for whatever reason, you decide that it should not have more than one instance in the application. (Think of a scenario where several people work on pieces of the application).

If you are not using the Spring framework, the Singleton pattern ensures that there will not be more than one instance of a class in your application. That is because you cannot instantiate instances of the class by doing 'new' because the constructor is private. The only way to get an instance of the class is to call some static method of the class (usually called 'getInstance') which always returns the same instance.

Saying that you are using the Spring framework in your application, just means that in addition to the regular ways of obtaining an instance of the class (new or static methods that return an instance of the class), you can also ask Spring to get you an instance of that class and Spring will ensure that whenever you ask it for an instance of that class it will always return the same instance, even if you didn't write the class using the Singleton pattern. In other words, even if the class has a public constructor, if you always ask Spring for an instance of that class, Spring will only call that constructor once during the life of your application.

Normally if you are using Spring, you should only use Spring to create instances, and you can have a public constructor for the class. But if your constructor is not private you are not really preventing anyone from creating new instances of the class directly, by bypassing Spring.

If you truly want a single instance of the class, even if you use Spring in your application and define the class in Spring to be a singleton, the only way to ensure that is also implement the class using the Singleton pattern. That ensures that there will be a single instance, whether people use Spring to get an instance or bypass Spring.

rotating axis labels in R

First, create the data for the chart

H <- c(1.964138757, 1.729143013,    1.713273714,    1.706771799,    1.67977205)
M <- c("SP105", "SP30", "SP244", "SP31",    "SP147")

Second, give the name for a chart file

png(file = "Bargraph.jpeg", width = 500, height = 300)

Third, Plot the bar chart

barplot(H,names.arg=M,ylab="Degree ", col= rainbow(5), las=2, border = 0, cex.lab=1, cex.axis=1, font=1,col.axis="black")
title(xlab="Service Providers", line=4, cex.lab=1)

Finally, save the file

dev.off()

Output:

enter image description here

Add & delete view from Layout

This is the best way

LinearLayout lp = new LinearLayout(this);
lp.addView(new Button(this));
lp.addView(new ImageButton(this));
// Now remove them 
lp.removeViewAt(0); // and so on

If you have xml layout then no need to add dynamically.just call

lp.removeViewAt(0);

PL/SQL, how to escape single quote in a string?

EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'; worked for me. closing the varchar/string with two pairs of single quotes did the trick. Other option could be to use using keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'; Remember using keyword will not work, if you are using EXECUTE IMMEDIATE to execute DDL's with parameters, however, using quotes will work for DDL's.

Waiting until two async blocks are executed before starting another block

Not to say other answers are not great for certain circumstances, but this is one snippet I always user from Google:

- (void)runSigninThenInvokeSelector:(SEL)signInDoneSel {


    if (signInDoneSel) {
        [self performSelector:signInDoneSel];
    }

}

How to draw a graph in LaTeX?

In my experience, I always just use an external program to generate the graph (mathematica, gnuplot, matlab, etc.) and export the graph as a pdf or eps file. Then I include it into the document with includegraphics.

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

Old thread but for me it started working (after following all advise above) when i renamed int main(void) to int wmain(void) and removed WIN23 from cmake's add_executable().

How to import and use image in a Vue single file component?

As simple as:

<template>
    <div id="app">
        <img src="./assets/logo.png">
    </div>
</template>
    
<script>
    export default {
    }
</script>
    
<style lang="css">
</style> 

Taken from the project generated by vue cli.

If you want to use your image as a module, do not forget to bind data to your Vuejs component:

<template>
    <div id="app">
        <img :src="image"/>
    </div>
</template>
    
<script>
    import image from "./assets/logo.png"
    
    export default {
        data: function () {
            return {
                image: image
            }
        }
    }
</script>
    
<style lang="css">
</style>

And a shorter version:

<template>
    <div id="app">
        <img :src="require('./assets/logo.png')"/>
    </div>
</template>
    
<script>
    export default {
    }
</script>
    
<style lang="css">
</style> 

What is the best way to delete a value from an array in Perl?

splice will remove array element(s) by index. Use grep, as in your example, to search and remove.

How can I see which Git branches are tracking which remote / upstream branch?

If you look at the man page for git-rev-parse, you'll see the following syntax is described:

<branchname>@{upstream}, e.g. master@{upstream}, @{u}

The suffix @{upstream} to a branchname (short form <branchname>@{u}) refers to the branch that the branch specified by branchname is set to build on top of. A missing branchname defaults to the current one.

Hence to find the upstream of the branch master, you would do:

git rev-parse --abbrev-ref master@{upstream}
# => origin/master

To print out the information for each branch, you could do something like:

while read branch; do
  upstream=$(git rev-parse --abbrev-ref $branch@{upstream} 2>/dev/null)
  if [[ $? == 0 ]]; then
    echo $branch tracks $upstream
  else
    echo $branch has no upstream configured
  fi
done < <(git for-each-ref --format='%(refname:short)' refs/heads/*)

# Output:
# master tracks origin/master
# ...

This is cleaner than parsing refs and config manually.

JavaScript: Get image dimensions

Following code add image attribute height and width to each image on the page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function addImgAttributes()
{
    for( i=0; i < document.images.length; i++)
    { 
        width = document.images[i].width;
        height = document.images[i].height;
        window.document.images[i].setAttribute("width",width);
        window.document.images[i].setAttribute("height",height);

    }
}
</script>
</head>
<body onload="addImgAttributes();">
<img src="2_01.jpg"/>
<img src="2_01.jpg"/>
</body>
</html>

Better way to find control in ASP.NET

If you're looking for a specific type of control you could use a recursive loop like this one - http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx

Here's an example I made that returns all controls of the given type

/// <summary>
/// Finds all controls of type T stores them in FoundControls
/// </summary>
/// <typeparam name="T"></typeparam>
private class ControlFinder<T> where T : Control 
{
    private readonly List<T> _foundControls = new List<T>();
    public IEnumerable<T> FoundControls
    {
        get { return _foundControls; }
    }    

    public void FindChildControlsRecursive(Control control)
    {
        foreach (Control childControl in control.Controls)
        {
            if (childControl.GetType() == typeof(T))
            {
                _foundControls.Add((T)childControl);
            }
            else
            {
                FindChildControlsRecursive(childControl);
            }
        }
    }
}

jQuery: How can I create a simple overlay?

Here is a simple javascript only solution

function displayOverlay(text) {
    $("<table id='overlay'><tbody><tr><td>" + text + "</td></tr></tbody></table>").css({
        "position": "fixed",
        "top": 0,
        "left": 0,
        "width": "100%",
        "height": "100%",
        "background-color": "rgba(0,0,0,.5)",
        "z-index": 10000,
        "vertical-align": "middle",
        "text-align": "center",
        "color": "#fff",
        "font-size": "30px",
        "font-weight": "bold",
        "cursor": "wait"
    }).appendTo("body");
}

function removeOverlay() {
    $("#overlay").remove();
}

Demo:

http://jsfiddle.net/UziTech/9g0pko97/

Gist:

https://gist.github.com/UziTech/7edcaef02afa9734e8f2

Full-screen responsive background image

Simple fullscreen and centered image https://jsfiddle.net/maestro888/3a9Lrmho

_x000D_
_x000D_
jQuery(function($) {_x000D_
    function resizeImage() {_x000D_
        $('.img-fullscreen').each(function () {_x000D_
            var $imgWrp = $(this);_x000D_
_x000D_
            $('img', this).each(function () {_x000D_
                var imgW = $(this)[0].width,_x000D_
                    imgH = $(this)[0].height;_x000D_
_x000D_
                $(this).removeClass();_x000D_
_x000D_
                $imgWrp.css({_x000D_
                    width: $(window).width(),_x000D_
                    height: $(window).height()_x000D_
                });_x000D_
_x000D_
                imgW / imgH < $(window).width() / $(window).height() ?_x000D_
                    $(this).addClass('full-width') : $(this).addClass('full-height');_x000D_
            });_x000D_
        });_x000D_
    }_x000D_
_x000D_
    window.onload = function () {_x000D_
        resizeImage();_x000D_
    };_x000D_
_x000D_
    window.onresize = function () {_x000D_
        setTimeout(resizeImage, 300);_x000D_
    };_x000D_
 _x000D_
    resizeImage();_x000D_
});
_x000D_
/*_x000D_
 * Hide scrollbars_x000D_
 */_x000D_
_x000D_
#wrapper {_x000D_
    overflow: hidden;_x000D_
}_x000D_
_x000D_
/*_x000D_
 * Basic styles_x000D_
 */_x000D_
_x000D_
.img-fullscreen {_x000D_
    position: relative;_x000D_
    overflow: hidden;_x000D_
}_x000D_
_x000D_
.img-fullscreen img {_x000D_
    vertical-align: middle;_x000D_
    position: absolute;_x000D_
    display: table;_x000D_
    margin: auto;_x000D_
    height: auto;_x000D_
    width: auto;_x000D_
    bottom: -100%;_x000D_
    right: -100%;_x000D_
    left: -100%;_x000D_
    top: -100%;_x000D_
}_x000D_
_x000D_
.img-fullscreen .full-width {_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
.img-fullscreen .full-height {_x000D_
    height: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="wrapper">_x000D_
    <div class="img-fullscreen">_x000D_
        <img src="https://static.pexels.com/photos/33688/delicate-arch-night-stars-landscape.jpg" alt=""/>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to copy files across computers using SSH and MAC OS X Terminal

You can do this with the scp command, which uses the ssh protocol to copy files across machines. It extends the syntax of cp to allow references to other systems:

scp username1@hostname1:/path/to/file username2@hostname2:/path/to/other/file

Copy something from this machine to some other machine:

scp /path/to/local/file username@hostname:/path/to/remote/file

Copy something from another machine to this machine:

scp username@hostname:/path/to/remote/file /path/to/local/file

Copy with a port number specified:

scp -P 1234 username@hostname:/path/to/remote/file /path/to/local/file

How to install sklearn?

pip install numpy scipy scikit-learn

if you don't have pip, install it using

python get-pip.py

Download get-pip.py from the following link. or use curl to download it.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Find UNC path of a network drive?

In Windows, if you have mapped network drives and you don't know the UNC path for them, you can start a command prompt (Start ? Run ? cmd.exe) and use the net use command to list your mapped drives and their UNC paths:

C:\>net use
New connections will be remembered.

Status       Local     Remote                    Network

-------------------------------------------------------------------------------
OK           Q:        \\server1\foo             Microsoft Windows Network
OK           X:        \\server2\bar             Microsoft Windows Network
The command completed successfully.

Note that this shows the list of mapped and connected network file shares for the user context the command is run under. If you run cmd.exe under your own user account, the results shown are the network file shares for yourself. If you run cmd.exe under another user account, such as the local Administrator, you will instead see the network file shares for that user.

hibernate: LazyInitializationException: could not initialize proxy

I think Piko means in his response that there is the hbm file. I have a file called Tax.java. The mapping information are saved in the hbm (=hibernate mapping) file. In the class tag there is a property called lazy. Set that property to true. The following hbm example shows a way to set the lazy property to false.

` id ...'

If you are using Annotations instead look in the hibernate documenation. http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/

I hope that helped.

Oracle: how to UPSERT (update or insert into a table?)

Another alternative without the exception check:

UPDATE tablename
    SET val1 = in_val1,
        val2 = in_val2
    WHERE val3 = in_val3;

IF ( sql%rowcount = 0 )
    THEN
    INSERT INTO tablename
        VALUES (in_val1, in_val2, in_val3);
END IF;

Undefined variable: $_SESSION

You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION superglobal. Like this:

<?php
  session_start();
  echo $_SESSION['youritem'];
?>

You forgot the Session HELPER.

Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html

How to set up default schema name in JPA configuration?

If you are using (org.springframework.jdbc.datasource.DriverManagerDataSource) in ApplicationContext.xml to specify Database details then use below simple property to specify the schema.

<property name="schema" value="schemaName" />

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

How do you create a Distinct query in HQL

If you need to use new keyword for a custom DTO in your select statement and need distinct elements, use new outside of new like as follows-

select distinct new com.org.AssetDTO(a.id, a.address, a.status) from Asset as a where ...

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

You can convert a string to a date easily by:

CAST(YourDate AS DATE)

How to load image files with webpack file-loader

webpack.config.js

{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
    options: {
        name: '[name].[ext]',
    },
}

anyfile.html

<img src={image_name.jpg} />

How to display Woocommerce Category image?

To prevent full size category images slowing page down, you can use smaller images with wp_get_attachment_image_src():

<?php 

$thumbnail_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );

// get the medium-sized image url
$image = wp_get_attachment_image_src( $thumbnail_id, 'medium' );

// Output in img tag
echo '<img src="' . $image[0] . '" alt="" />'; 

// Or as a background for a div
echo '<div class="image" style="background-image: url("' . $image[0] .'")"></div>';

?>

EDIT: Fixed variable name and missing quote

How to get Top 5 records in SqLite?

select price from mobile_sales_details order by price desc limit 5

Note: i have mobile_sales_details table

syntax

select column_name from table_name order by column_name desc limit size.  

if you need top low price just remove the keyword desc from order by

How to center an unordered list?

To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element.

Now, add the style to the div class and use the text-align property with center as its value.

See the below example.

<style>
.myDivElement{
    text-align:center;
}
.myDivElement ul li{
   display:inline;

 }
</style>
<div class="myDivElement">
<ul>
    <li>Home</li>
    <li>About</li>
    <li>Gallery</li>
    <li>Contact</li>
</ul>
</div>

Here is the reference website Center Align Unordered List

Android: Getting a file URI from a content URI?

Well I am bit late to answer,but my code is tested

check scheme from uri:

 byte[] videoBytes;

if (uri.getScheme().equals("content")){
        InputStream iStream =   context.getContentResolver().openInputStream(uri);
            videoBytes = getBytes(iStream);
        }else{
            File file = new File(uri.getPath());
            FileInputStream fileInputStream = new FileInputStream(file);     
            videoBytes = getBytes(fileInputStream);
        }

In the above answer I converted the video uri to bytes array , but that's not related to question, I just copied my full code to show the usage of FileInputStream and InputStream as both are working same in my code.

I used the variable context which is getActivity() in my Fragment and in Activity it simply be ActivityName.this

context=getActivity(); //in Fragment

context=ActivityName.this;// in activity

How can I fix "Design editor is unavailable until a successful build" error?

I had tried to change SDK Version:

Check below image: In that I changed 27 from Android P

Image

How can I create an observable with a delay

import * as Rx from 'rxjs/Rx';

We should add the above import to make the blow code to work

Let obs = Rx.Observable
    .interval(1000).take(3);

obs.subscribe(value => console.log('Subscriber: ' + value));

Can dplyr package be used for conditional mutating?

dplyr now has a function case_when that offers a vectorised if. The syntax is a little strange compared to mosaic:::derivedFactor as you cannot access variables in the standard dplyr way, and need to declare the mode of NA, but it is considerably faster than mosaic:::derivedFactor.

df %>%
mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L, 
                     a %in% c(0,1,3,4) | c == 4 ~ 3L, 
                     TRUE~as.integer(NA)))

EDIT: If you're using dplyr::case_when() from before version 0.7.0 of the package, then you need to precede variable names with '.$' (e.g. write .$a == 1 inside case_when).

Benchmark: For the benchmark (reusing functions from Arun 's post) and reducing sample size:

require(data.table) 
require(mosaic) 
require(dplyr)
require(microbenchmark)

set.seed(42) # To recreate the dataframe
DT <- setDT(lapply(1:6, function(x) sample(7, 10000, TRUE)))
setnames(DT, letters[1:6])
DF <- as.data.frame(DT)

DPLYR_case_when <- function(DF) {
  DF %>%
  mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L, 
                       a %in% c(0,1,3,4) | c==4 ~ 3L, 
                       TRUE~as.integer(NA)))
}

DT_fun <- function(DT) {
  DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
  DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}

DPLYR_fun <- function(DF) {
  mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
                    ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

mosa_fun <- function(DF) {
  mutate(DF, g = derivedFactor(
    "2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
    "3" = (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
    .method = "first",
    .default = NA
  ))
}

perf_results <- microbenchmark(
  dt_fun <- DT_fun(copy(DT)),
  dplyr_ifelse <- DPLYR_fun(copy(DF)),
  dplyr_case_when <- DPLYR_case_when(copy(DF)),
  mosa <- mosa_fun(copy(DF)),
  times = 100L
)

This gives:

print(perf_results)
Unit: milliseconds
           expr        min         lq       mean     median         uq        max neval
         dt_fun   1.391402    1.560751   1.658337   1.651201   1.716851   2.383801   100
   dplyr_ifelse   1.172601    1.230351   1.331538   1.294851   1.390351   1.995701   100
dplyr_case_when   1.648201    1.768002   1.860968   1.844101   1.958801   2.207001   100
           mosa 255.591301  281.158350 291.391586 286.549802 292.101601 545.880702   100

Node.js - EJS - including a partial

In Express 4.x I used the following to load ejs:

  var path = require('path');

  // Set the default templating engine to ejs
  app.set('view engine', 'ejs');
  app.set('views', path.join(__dirname, 'views'));

  // The views/index.ejs exists in the app directory
  app.get('/hello', function (req, res) {
    res.render('index', {title: 'title'});
  });

Then you just need two files to make it work - views/index.ejs:

<%- include partials/navigation.ejs %>

And the views/partials/navigation.ejs:

<ul><li class="active">...</li>...</ul>

You can also tell Express to use ejs for html templates:

var path = require('path');
var EJS  = require('ejs');

app.engine('html', EJS.renderFile);

// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// The views/index.html exists in the app directory
app.get('/hello', function (req, res) {
  res.render('index.html', {title: 'title'});
});

Finally you can also use the ejs layout module:

var EJSLayout = require('express-ejs-layouts');
app.use(EJSLayout);

This will use the views/layout.ejs as your layout.

My Routes are Returning a 404, How can I Fix Them?

Have you tried adding this to your routes file instead Route::get('user', "user@index")?

The piece of text before the @, user in this case, will direct the page to the user controller and the piece of text after the @, index, will direct the script to the user function public function get_index().

I see you're using $restful, in which case you could set your Route to Route::any('user', 'user@index'). This will handle both POST and GET, instead of writing them both out separately.

Check variable equality against a list of values

Using the answers provided, I ended up with the following:

Object.prototype.in = function() {
    for(var i=0; i<arguments.length; i++)
       if(arguments[i] == this) return true;
    return false;
}

It can be called like:

if(foo.in(1, 3, 12)) {
    // ...
}

Edit: I came across this 'trick' lately which is useful if the values are strings and do not contain special characters. For special characters is becomes ugly due to escaping and is also more error-prone due to that.

/foo|bar|something/.test(str);

To be more precise, this will check the exact string, but then again is more complicated for a simple equality test:

/^(foo|bar|something)$/.test(str);

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

jQuery Validate Required Select

You only need to put validate[required] as class of this select and then put a option with value=""

for example:

<select class="validate[required]">
  <option value="">Choose...</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

Meaning of end='' in the statement print("\t",end='')?

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

Eg: - print ("hello",end=" +") will print hello +

Displaying one div on top of another

Here is the jsFiddle

#backdrop{
    border: 2px solid red;
    width: 400px;
    height: 200px;
    position: absolute;
}

#curtain {
    border: 1px solid blue;
    width: 400px;
    height: 200px;
    position: absolute;
}

Use Z-index to move the one you want on top.

Create local maven repository

Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.

To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source

Add a file to your repository like this:

mvn install:install-file \
  -Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID 
  -DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
  -Dpackaging=jar \
  -DlocalRepositoryPath=/var/www/html/mavenRepository

If your domain is example.com and the root directory of the web server is located at /var/www/html/, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>.

while-else-loop

This while else statement should only execute the else code when the condition is false, this means it will always execute it. But, there is a catch, when you use the break keyword within the while loop, the else statement should not execute.

The code that satisfies does condition is only:

boolean entered = false;
while (condition) {
   entered = true; // Set it to true stright away
   // While loop code


   // If you want to break out of this loop
   if (condition) {
      entered = false;
      break;
   }
} if (!entered) {
   // else code
}

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

What is @ModelAttribute in Spring MVC?

@ModelAttribute simply binds the value from jsp fields to Pojo calss to perform our logic in controller class. If you are familiar with struts, then this is like populating the formbean object upon submission.

HTML-Tooltip position relative to mouse pointer

This CAN be done with pure html and css. It may not be the best way but we all have different limitations. There are 3 ways that could be useful depending on what your specific circumstances are.

  1. The first involves overlaying an invisible table over top of your link with a hover action on each cell that displays an image.

_x000D_
_x000D_
#imagehover td:hover::after{_x000D_
  content: "             ";_x000D_
  white-space: pre;_x000D_
  background-image: url("http://www.google.com/images/srpr/logo4w.png");_x000D_
  position: relative;_x000D_
  left: 5px;_x000D_
  top: 5px;_x000D_
  font-size: 20px;_x000D_
  background-color: transparent;_x000D_
  background-position: 0px 0px;_x000D_
  background-size: 60px 20px;_x000D_
  background-repeat: no-repeat;_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
#imagehover table, #imagehover th, #imagehover td {_x000D_
  border: 0px;_x000D_
  border-spacing: 0px;_x000D_
}
_x000D_
<a href="https://www.google.com">_x000D_
<table id="imagehover" style="width:50px;height:10px;z-index:9999;position:absolute" cellspacing="0">_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
_x000D_
</table>_x000D_
Google</a>
_x000D_
_x000D_
_x000D_

  1. The second relies on being able to create your own cursor image

_x000D_
_x000D_
#googleLink{_x000D_
_x000D_
cursor: url(https://winter-bush-d06c.sto.workers.dev/cursor-extern.php?id=98272),url(https://9dc1a5c00e8109665645209c2d036b1c.cloudflareworkers.com/cursor-extern.php?id=98272),auto;_x000D_
_x000D_
}
_x000D_
<a href="https://www.google.com" id="googleLink">Google</a>
_x000D_
_x000D_
_x000D_

  1. While the normal title tooltip doesn't technically allow images it does allow any unicode characters including block letters and emojis which may suite your needs.

_x000D_
_x000D_
<a href="https://www.google.com" title="??" alt="??">Google</a>
_x000D_
_x000D_
_x000D_

Difference between <context:annotation-config> and <context:component-scan>

you can find more information in spring context schema file. following is in spring-context-4.3.xsd

<conxtext:annotation-config />
Activates various annotations to be detected in bean classes: Spring's @Required and
@Autowired, as well as JSR 250's @PostConstruct, @PreDestroy and @Resource (if available),
JAX-WS's @WebServiceRef (if available), EJB 3's @EJB (if available), and JPA's
@PersistenceContext and @PersistenceUnit (if available). Alternatively, you may
choose to activate the individual BeanPostProcessors for those annotations.

Note: This tag does not activate processing of Spring's @Transactional or EJB 3's
@TransactionAttribute annotation. Consider the use of the <tx:annotation-driven>
tag for that purpose.
<context:component-scan>
Scans the classpath for annotated components that will be auto-registered as
Spring beans. By default, the Spring-provided @Component, @Repository, @Service, @Controller, @RestController, @ControllerAdvice, and @Configuration stereotypes    will be detected.

Note: This tag implies the effects of the 'annotation-config' tag, activating @Required,
@Autowired, @PostConstruct, @PreDestroy, @Resource, @PersistenceContext and @PersistenceUnit
annotations in the component classes, which is usually desired for autodetected components
(without external configuration). Turn off the 'annotation-config' attribute to deactivate
this default behavior, for example in order to use custom BeanPostProcessor definitions
for handling those annotations.

Note: You may use placeholders in package paths, but only resolved against system
properties (analogous to resource paths). A component scan results in new bean definitions
being registered; Spring's PropertySourcesPlaceholderConfigurer will apply to those bean
definitions just like to regular bean definitions, but it won't apply to the component
scan settings themselves.

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

Maybe Eclipse WTP plugin has been accidently removed. Have you tried re-installing WTP using this location ? If I were you I would have reinstall Eclipse from strach or even better try Spring ToolSuite which integrates with Google Plugin for Eclipse seamlessly (usign Extenstions tab on STS Dashboard)

How do I close an Android alertdialog

final AlertDialog.Builder alert = new AlertDialog.Builder(mcontext);
alert.setTitle(title);
alert.setMessage(description);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
  @Override                                 
  public void onClick(DialogInterface dialog,int which) {
        cancelDialog(); //Implement method for canceling dialog
         }
   });
alert.show();
void cancelDialog()
{
   //Now you can either use  
   dialog.cancel();
    //or dialog.dismiss();
}

where is gacutil.exe?

  1. Open Developer Command prompt.
  2. type

where gacutil

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

Try this solution

PUT THESE PERMISSIONS IN MANIFEST

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

INTENT TO CAPTURE IMAGE

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                }

GET CAPTURED IMAGE IN ONACTIVITYRESULT

@Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
                    Bundle extras = data.getExtras();
                    Bitmap imageBitmap = (Bitmap) extras.get("data");
                    // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
                    Uri tempUri = getImageUri(getApplicationContext(), imageBitmap);
                    //DO SOMETHING WITH URI
                }
            } 

METHOD TO GET IMAGE URI

public Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

Precision String Format Specifier In Swift

Also with rounding:

extension Float
{
    func format(f: String) -> String
    {
        return NSString(format: "%\(f)f", self)
    }
    mutating func roundTo(f: String)
    {
        self = NSString(format: "%\(f)f", self).floatValue
    }
}

extension Double
{
    func format(f: String) -> String
    {
        return NSString(format: "%\(f)f", self)
    }
    mutating func roundTo(f: String)
    {
        self = NSString(format: "%\(f)f", self).doubleValue
    }
}

x = 0.90695652173913
x.roundTo(".2")
println(x) //0.91

How to add pandas data to an existing csv file?

A bit late to the party but you can also use a context manager, if you're opening and closing your file multiple times, or logging data, statistics, etc.

from contextlib import contextmanager
import pandas as pd
@contextmanager
def open_file(path, mode):
     file_to=open(path,mode)
     yield file_to
     file_to.close()


##later
saved_df=pd.DataFrame(data)
with open_file('yourcsv.csv','r') as infile:
      saved_df.to_csv('yourcsv.csv',mode='a',header=False)`

Fetch: POST json data

Had the same issue - no body was sent from a client to a server.

Adding Content-Type header solved it for me:

var headers = new Headers();

headers.append('Accept', 'application/json'); // This one is enough for GET requests
headers.append('Content-Type', 'application/json'); // This one sends body

return fetch('/some/endpoint', {
    method: 'POST',
    mode: 'same-origin',
    credentials: 'include',
    redirect: 'follow',
    headers: headers,
    body: JSON.stringify({
        name: 'John',
        surname: 'Doe'
    }),
}).then(resp => {
    ...
}).catch(err => {
   ...
})

How to force JS to do math instead of putting two strings together

I'm adding this answer because I don't see it here.

One way is to put a '+' character in front of the value

example:

var x = +'11.5' + +'3.5'

x === 15

I have found this to be the simplest way

In this case, the line:

dots = document.getElementById("txt").value;

could be changed to

dots = +(document.getElementById("txt").value);

to force it to a number

NOTE:

+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5

finding and replacing elements in a list

I know this is a very old question and there's a myriad of ways to do it. The simpler one I found is using numpy package.

import numpy

arr = numpy.asarray([1, 6, 1, 9, 8])
arr[ arr == 8 ] = 0 # change all occurrences of 8 by 0
print(arr)

notifyDataSetChange not working from custom adapter

As I have already explained the reasons behind this issue and also how to handle it in a different answer thread Here. Still i am sharing the solution summary here.

One of the main reasons notifyDataSetChanged() won't work for you - is,

Your adapter loses reference to your list.

When creating and adding a new list to the Adapter. Always follow these guidelines:

  1. Initialise the arrayList while declaring it globally.
  2. Add the List to the adapter directly with out checking for null and empty values . Set the adapter to the list directly (don't check for any condition). Adapter guarantees you that wherever you make changes to the data of the arrayList it will take care of it, but never loose the reference.
  3. Always modify the data in the arrayList itself (if your data is completely new than you can call adapter.clear() and arrayList.clear() before actually adding data to the list) but don't set the adapter i.e If the new data is populated in the arrayList than just adapter.notifyDataSetChanged()

Hope this helps.

Read line with Scanner

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.io.File;
import java.util.Scanner;

/**
 *
 * @author zsagga
 */
class openFile {
        private Scanner x ; 
        int count = 0 ; 
        String path = "C:\\Users\\zsagga\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\Readthis.txt"; 


    public void openFile() {
//                System.out.println("I'm Here");
        try {
            x = new Scanner(new File(path)); 

        } 
        catch (Exception e) {
            System.out.println("Could not find a file");
        }
    }

    public void readFile() {

        while (x.hasNextLine()){
            count ++ ;
            x.nextLine();     
        }
        System.out.println(count);
    }

    public void closeFile() {
        x.close();
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

/**
 *
 * @author zsagga
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        // TODO code application logic here
        openFile r =  new openFile(); 
        r.openFile(); 
        r.readFile();
        r.closeFile(); 

    }
}

ImportError: No module named pythoncom

You should be using pip to install packages, since it gives you uninstall capabilities.

Also, look into virtualenv. It works well with pip and gives you a sandbox so you can explore new stuff without accidentally hosing your system-wide install.

How do I make a C++ macro behave like a function?

There is a rather clever solution:

#define MACRO(X,Y)                         \
do {                                       \
  cout << "1st arg is:" << (X) << endl;    \
  cout << "2nd arg is:" << (Y) << endl;    \
  cout << "Sum is:" << ((X)+(Y)) << endl;  \
} while (0)

Now you have a single block-level statement, which must be followed by a semicolon. This behaves as expected and desired in all three examples.

Credit card expiration dates - Inclusive or exclusive?

If you are writing a site which takes credit card numbers for payment:

  1. You should probably be as permissive as possible, so that if it does expire, you allow the credit card company to catch it. So, allow it until the last second of the last day of the month.
  2. Don't write your own credit card processing code. If^H^HWhen you write a bug, someone will lose real money. We all make mistakes, just don't make decisions that turn your mistakes into catastrophes.

What to return if Spring MVC controller method doesn't return value?

You can simply return a ResponseEntity with the appropriate header:

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
public ResponseEntity updateDataThatDoesntRequireClientToBeNotified(...){
....
return new ResponseEntity(HttpStatus.OK)
}

Substitute multiple whitespace with single whitespace in Python

For completeness, you can also use:

mystring = mystring.strip()  # the while loop will leave a trailing space, 
                  # so the trailing whitespace must be dealt with
                  # before or after the while loop
while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

which will work quickly on strings with relatively few spaces (faster than re in these situations).

In any scenario, Alex Martelli's split/join solution performs at least as quickly (usually significantly more so).

In your example, using the default values of timeit.Timer.repeat(), I get the following times:

str.replace: [1.4317800167340238, 1.4174888149192384, 1.4163512401715934]
re.sub:      [3.741931446594549,  3.8389395858970374, 3.973777672860706]
split/join:  [0.6530919432498195, 0.6252146571700905, 0.6346594329726258]


EDIT:

Just came across this post which provides a rather long comparison of the speeds of these methods.

How do I find a particular value in an array and return its index?

int arr[5] = {4, 1, 3, 2, 6};
vector<int> vec;
int i =0;
int no_to_be_found;

cin >> no_to_be_found;

while(i != 4)
{
    vec.push_back(arr[i]);
    i++;
}

cout << find(vec.begin(),vec.end(),no_to_be_found) - vec.begin();

Batch files : How to leave the console window open

If that is really all the batch file is doing, remove the cmd /K and add PAUSE.

start /B /LOW /WAIT make package
PAUSE

Then, just point your shortcut to "My Batch File.bat"...no need to run it with CMD /K.

UPDATE

Ah, some new info...you're trying to do it from a pinned shortcut on the taskbar.

I found this, Adding Batch Files to Windows 7 Taskbar like the Vista/XP Quick Launch, with the relevant part below.

  1. First, pin a shortcut for CMD.EXE to the taskbar by hitting the start button, then type "cmd" in the search box, right-click the result and chose "Pin to Taskbar".
  2. Right-click the shortcut on the taskbar.
  3. You will see a list that includes "Command Prompt" and "Unpin this program from the taskbar".
  4. Right-click the icon for CMD.EXE and select Properties.
  5. In the box for Target, go to the end of "%SystemRoot%\system32\cmd.exe" and type " /C " and the path and name of the batch file.

For your purposes, you can either:

  1. Use /C and put a PAUSE at the end of your batch file.

    OR

  2. Change the command line to use /K and remove the PAUSE from your batch file.

Combining CSS Pseudo-elements, ":after" the ":last-child"

To have something like One, two and three you should add one more css style

li:nth-last-child(2):after {
    content: ' ';
}

This would remove the comma from the second last element.

Complete Code

_x000D_
_x000D_
li {_x000D_
  display: inline;_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
li:after {_x000D_
  content: ", ";_x000D_
}_x000D_
_x000D_
li:nth-last-child(2):after {_x000D_
  content: '';_x000D_
}_x000D_
_x000D_
li:last-child:before {_x000D_
  content: " and ";_x000D_
}_x000D_
_x000D_
li:last-child:after {_x000D_
  content: ".";_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <ul>_x000D_
    <li>One</li>_x000D_
    <li>Two</li>_x000D_
    <li>Three</li>_x000D_
  </ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Jenkins - How to access BUILD_NUMBER environment variable

Assuming I am understanding your question and setup correctly,

If you're trying to use the build number in your script, you have two options:

1) When calling ant, use: ant -Dbuild_parameter=${BUILD_NUMBER}

2) Change your script so that:

<property environment="env" />
<property name="build_parameter"  value="${env.BUILD_NUMBER}"/>

Dump a mysql database to a plaintext (CSV) backup from the command line

If you can cope with table-at-a-time, and your data is not binary, use the -B option to the mysql command. With this option it'll generate TSV (tab separated) files which can import into Excel, etc, quite easily:

% echo 'SELECT * FROM table' | mysql -B -uxxx -pyyy database

Alternatively, if you've got direct access to the server's file system, use SELECT INTO OUTFILE which can generate real CSV files:

SELECT * INTO OUTFILE 'table.csv'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
FROM table

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

I have a function which returns a CLOB and I was seeing the above error when I'd forgotten to declare the return value as an output parameter. Initially I had:

protected SimpleJdbcCall buildJdbcCall(JdbcTemplate jdbcTemplate)
{
    SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate)
        .withSchemaName(schema)
        .withCatalogName(catalog)
        .withFunctionName(functionName)
        .withReturnValue()          
        .declareParameters(buildSqlParameters());

    return call;
}

public SqlParameter[] buildSqlParameters() {
    return new SqlParameter[]{
        new SqlParameter("p_names", Types.VARCHAR),
        new SqlParameter("p_format", Types.VARCHAR),
        new SqlParameter("p_units", Types.VARCHAR),
        new SqlParameter("p_datums", Types.VARCHAR),
        new SqlParameter("p_start", Types.VARCHAR),
        new SqlParameter("p_end", Types.VARCHAR),
        new SqlParameter("p_timezone", Types.VARCHAR),
        new SqlParameter("p_office_id", Types.VARCHAR),
        };
}

The buildSqlParameters method should have included the SqlOutParameter:

public SqlParameter[] buildSqlParameters() {
    return new SqlParameter[]{
        new SqlParameter("p_names", Types.VARCHAR),
        new SqlParameter("p_format", Types.VARCHAR),
        new SqlParameter("p_units", Types.VARCHAR),
        new SqlParameter("p_datums", Types.VARCHAR),
        new SqlParameter("p_start", Types.VARCHAR),
        new SqlParameter("p_end", Types.VARCHAR),
        new SqlParameter("p_timezone", Types.VARCHAR),
        new SqlParameter("p_office_id", Types.VARCHAR),
        new SqlOutParameter("l_clob", Types.CLOB)  // <-- This was missing!
    }; 
}

How can I return the current action in an ASP.NET MVC view?

In MVC you should provide the View with all data, not let the View collect its own data so what you can do is to set the CSS class in your controller action.

ViewData["CssClass"] = "bold";

and pick out this value from your ViewData in your View

How to get all subsets of a set? (powerset)

I know this is too late

There are many other solutions already but still...

def power_set(lst):
    pw_set = [[]]

    for i in range(0,len(lst)):
        for j in range(0,len(pw_set)):
            ele = pw_set[j].copy()
            ele = ele + [lst[i]]
            pw_set = pw_set + [ele]

    return pw_set

How to Get Element By Class in JavaScript?

jQuery handles this easy.

let element = $(.myclass);
element.html("Some string");

It changes all the .myclass elements to that text.

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

What is the difference between a .cpp file and a .h file?

I know the difference between a declaration and a definition.

Whereas:

  • A CPP file includes the definitions from any header which it includes (because CPP and header file together become a single 'translation unit')
  • A header file might be included by more than one CPP file
  • The linker typically won't like anything defined in more than one CPP file

Therefore any definitions in a header file should be inline or static. Header files also contain declarations which are used by more than one CPP file.

Definitions that are neither static nor inline are placed in CPP files. Also, any declarations that are only needed within one CPP file are often placed within that CPP file itself, nstead of in any (sharable) header file.

Get file path of image on Android

In order to take a picture you have to determine a path where you would like the image saved and pass that as an extra in the intent, for example:

private void capture(){
    String directoryPath = Environment.getExternalStorageDirectory() + "/" + IMAGE_DIRECTORY + "/";
    String filePath = directoryPath+Long.toHexString(System.currentTimeMillis())+".jpg";
    File directory = new File(directoryPath);
    if (!directory.exists()) {
        directory.mkdirs();
    }
    this.capturePath = filePath; // you will process the image from this path if the capture goes well
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File(filePath) ) );
    startActivityForResult(intent, REQUEST_CAPTURE);                

}

I just copied the above portion from another answer I gave.

However to warn you there are a lot of inconsitencies with image capture behavior between devices that you should look out for.

Here is an issue I ran into on some HTC devices, where it would save in the location I passed and in it's default location resulting in duplicate images on the device: Deleting a gallery image after camera intent photo taken

How do I get an OAuth 2.0 authentication token in C#

https://github.com/IdentityModel/IdentityModel adds extensions to HttpClient to acquire tokens using different flows and the documentation is great too. It's very handy because you don't have to think how to implement it yourself. I'm not aware if any official MS implementation exists.

how to get curl to output only http response body (json) and no other headers etc

You are specifying the -i option:

-i, --include

(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...

Simply remove that option from your command line:

response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")

How to grey out a button?

Set Clickable as false and change the backgroung color as:

callButton.setClickable(false);
callButton.setBackgroundColor(Color.parseColor("#808080"));

Filter by Dates in SQL

WHERE dates BETWEEN (convert(datetime, '2012-12-12',110) AND (convert(datetime, '2012-12-12',110))

How can I issue a single command from the command line through sql plus?

For UNIX (AIX):

export ORACLE_HOME=/oracleClient/app/oracle/product/version
export DBUSER=fooUser
export DBPASSWD=fooPW
export DBNAME=fooSchema 

echo "select * from someTable;" | $ORACLE_HOME/bin/sqlplus $DBUSER/$DBPASSWD@$DBNAME

Simple calculations for working with lat/lon and km distance?

Why not use properly formulated geospatial queries???

Here is the SQL server reference page on the STContains geospatial function:

https://docs.microsoft.com/en-us/sql/t-sql/spatial-geography/stcontains-geography-data-type?view=sql-server-ver15

or if you do not waant to use box and radian conversion , you cna always use the distance function to find the points that you need:

DECLARE @CurrentLocation geography; 
SET @CurrentLocation  = geography::Point(12.822222, 80.222222, 4326)

SELECT * , Round (GeoLocation.STDistance(@CurrentLocation ),0) AS Distance FROM [Landmark]
WHERE GeoLocation.STDistance(@CurrentLocation )<= 2000 -- 2 Km

There should be similar functionality for almost any database out there.

If you have implemented geospatial indexing correctly your searches would be way faster than the approach you are using

Why is datetime.strptime not working in this simple example?

You should be using datetime.datetime.strptime. Note that very old versions of Python (2.4 and older) don't have datetime.datetime.strptime; use time.strptime in that case.

Border Radius of Table is not working

A note to this old question:

My reset.css had set border-spacing: 0, causing the corners to get cut off. I had to set it to 3px for my radius to work properly (value will depend on the radius in question).

Search for string and get count in vi editor

:%s/string/string/g will give the answer.

How to create a checkbox with a clickable label?

<label for="myInputID">myLabel</label><input type="checkbox" id="myInputID" name="myInputID />

ERROR 1148: The used command is not allowed with this MySQL version

Refer to MySQL 8.0 Reference Manual -- 6.1.6 Security Issues with LOAD DATA LOCAL

On the server side, run

mysql.server start --local-infile

On the client side, run

mysql --local-infile database_name -u username -p

How do I unbind "hover" in jQuery?

All hover is doing behind the scenes is binding to the mouseover and mouseout property. I would bind and unbind your functions from those events individually.

For example, say you have the following html:

<a href="#" class="myLink">Link</a>

then your jQuery would be:

$(document).ready(function() {

  function mouseOver()
  {
    $(this).css('color', 'red');
  }
  function mouseOut()
  {
    $(this).css('color', 'blue');
  }

  // either of these might work
  $('.myLink').hover(mouseOver, mouseOut); 
  $('.myLink').mouseover(mouseOver).mouseout(mouseOut); 
  // otherwise use this
  $('.myLink').bind('mouseover', mouseOver).bind('mouseout', mouseOut);


  // then to unbind
  $('.myLink').click(function(e) {
    e.preventDefault();
    $('.myLink').unbind('mouseover', mouseOver).unbind('mouseout', mouseOut);
  });

});

How to combine two lists in R

I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:

combineListsAsOne <-function(list1, list2){
  n <- c()
  for(x in list1){
    n<-c(n, x)
  }
  for(y in list2){
    n<-c(n, y)
  }
  return(n)
}

It just creates a new list and adds items from two supplied lists to create one.

How to search for an element in a golang slice

You can use sort.Slice() plus sort.Search()

type Person struct {
    Name string
}

func main() {
    crowd := []Person{{"Zoey"}, {"Anna"}, {"Benni"}, {"Chris"}}

    sort.Slice(crowd, func(i, j int) bool {
        return crowd[i].Name <= crowd[j].Name
    })

    needle := "Benni"
    idx := sort.Search(len(crowd), func(i int) bool {
        return string(crowd[i].Name) >= needle
    })

    if crowd[idx].Name == needle {
        fmt.Println("Found:", idx, crowd[idx])
    } else {
        fmt.Println("Found noting: ", idx)
    }
}

See: https://play.golang.org/p/47OPrjKb0g_c

how to call url of any other website in php

Check out the PHP cURL functions. They should do what you want.

Or if you just want a simple URL GET then:

$lines = file('http://www.example.com/');

Can an interface extend multiple interfaces in Java?

From the Oracle documentation page about multiple inheritance type,we can find the accurate answer here. Here we should first know the type of multiple inheritance in java:-

  1. Multiple inheritance of state.
  2. Multiple inheritance of implementation.
  3. Multiple inheritance of type.

Java "doesn't support the multiple inheritance of state, but it support multiple inheritance of implementation with default methods since java 8 release and multiple inheritance of type with interfaces.

Then here the question arises for "diamond problem" and how Java deal with that:-

  1. In case of multiple inheritance of implementation java compiler gives compilation error and asks the user to fix it by specifying the interface name. Example here:-

                interface A {
                    void method();
                }
    
                interface B extends A {
                    @Override
                    default void method() {
                        System.out.println("B");
                    }
                }
    
                interface C extends A { 
                    @Override
                    default void method() {
                        System.out.println("C");
                    }
                }
    
                interface D extends B, C {
    
                }
    

So here we will get error as:- interface D inherits unrelated defaults for method() from types B and C interface D extends B, C

You can fix it like:-

interface D extends B, C {
                @Override
                default void method() {
                    B.super.method();
                }
            }
  1. In multiple inheritance of type java allows it because interface doesn't contain mutable fields and only one implementation will belong to the class so java doesn't give any issue and it allows you to do so.

In Conclusion we can say that java doesn't support multiple inheritance of state but it does support multiple inheritance of implementation and multiple inheritance of type.

R - test if first occurrence of string1 is followed by string2

I think it's worth answering the generic question "R - test if string contains string" here.

For that, use the grep function.

# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"

Add space between cells (td) using css

Suppose cellspcing / cellpadding / border-spacing property did not worked, you can use the code as follow.

<div class="form-group">
  <table width="100%" cellspacing="2px" style="border-spacing: 10px;">
    <tr>                        
      <td width="47%">
        <input type="submit" class="form-control btn btn-info" id="submit" name="Submit" />
      </td>
      <td width="5%"></td>
      <td width="47%">
        <input type="reset" class="form-control btn btn-info" id="reset" name="Reset" />
      </td>
    </tr>
  </table>
</div>

I've tried and got succeed while seperate the button by using table-width and make an empty td as 2 or 1% it doesn't return more different.

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

You can reverse the logic. Instead of deleting an invalid row after it has been inserted, write an INSTEAD OF trigger to insert only if you verify the row is valid.

CREATE TRIGGER mytrigger ON sometable
INSTEAD OF INSERT
AS BEGIN
  DECLARE @isnum TINYINT;

  SELECT @isnum = ISNUMERIC(somefield) FROM inserted;

  IF (@isnum = 1)
    INSERT INTO sometable SELECT * FROM inserted;
  ELSE
    RAISERROR('somefield must be numeric', 16, 1)
      WITH SETERROR;
END

If your application doesn't want to handle errors (as Joel says is the case in his app), then don't RAISERROR. Just make the trigger silently not do an insert that isn't valid.

I ran this on SQL Server Express 2005 and it works. Note that INSTEAD OF triggers do not cause recursion if you insert into the same table for which the trigger is defined.

Can't update data-attribute value

This answer is for those seeking to just change the value of a data-attribute

The suggested will not change the value of your Jquery data-attr correctly as @adeneo has stated. For some reason though, I'm not seeing him (or any others) post the correct method for those seeking to update their data-attr. The answer that @Lucas Willems has posted may be the answer to problem Brian Tompsett - ??? is having, but it's not the answer to the inquiry that may be bringing other users here.

Quick answer in regards to original inquiry statement

-To update data-attr

$('#ElementId').attr('data-attributeTitle',newAttributeValue);

Easy mistakes* - there must be "data-" at the beginning of your attribute you're looking to change the value of.

Wait Until File Is Completely Written

So, having glanced quickly through some of these and other similar questions I went on a merry goose chase this afternoon trying to solve a problem with two separate programs using a file as a synchronization (and also file save) method. A bit of an unusual situation, but it definitely highlighted for me the problems with the 'check if the file is locked, then open it if it's not' approach.

The problem is this: the file can become locked between the time that you check it and the time you actually open the file. Its really hard to track down the sporadic Cannot copy the file, because it's used by another process error if you aren't looking for it too.

The basic resolution is to just try to open the file inside a catch block so that if its locked, you can try again. That way there is no elapsed time between the check and the opening, the OS does them at the same time.

The code here uses File.Copy, but it works just as well with any of the static methods of the File class: File.Open, File.ReadAllText, File.WriteAllText, etc.

/// <param name="timeout">how long to keep trying in milliseconds</param>
static void safeCopy(string src, string dst, int timeout)
{
    while (timeout > 0)
    {
        try
        {
            File.Copy(src, dst);

            //don't forget to either return from the function or break out fo the while loop
            break;
        }
        catch (IOException)
        {
            //you could do the sleep in here, but its probably a good idea to exit the error handler as soon as possible
        }
        Thread.Sleep(100);

        //if its a very long wait this will acumulate very small errors. 
        //For most things it's probably fine, but if you need precision over a long time span, consider
        //   using some sort of timer or DateTime.Now as a better alternative
        timeout -= 100;
    }
}

Another small note on parellelism: This is a synchronous method, which will block its thread both while waiting and while working on the thread. This is the simplest approach, but if the file remains locked for a long time your program may become unresponsive. Parellelism is too big a topic to go into in depth here, (and the number of ways you could set up asynchronous read/write is kind of preposterous) but here is one way it could be parellelized.

public class FileEx
{
    public static async void CopyWaitAsync(string src, string dst, int timeout, Action doWhenDone)
    {
        while (timeout > 0)
        {
            try
            {
                File.Copy(src, dst);
                doWhenDone();
                break;
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
    }

    public static async Task<string> ReadAllTextWaitAsync(string filePath, int timeout)
    {
        while (timeout > 0)
        {
            try {
                return File.ReadAllText(filePath);
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
        return "";
    }

    public static async void WriteAllTextWaitAsync(string filePath, string contents, int timeout)
    {
        while (timeout > 0)
        {
            try
            {
                File.WriteAllText(filePath, contents);
                return;
            }
            catch (IOException) { }

            await Task.Delay(100);
            timeout -= 100;
        }
    }
}

And here is how it could be used:

public static void Main()
{
    test_FileEx();
    Console.WriteLine("Me First!");
}    

public static async void test_FileEx()
{
    await Task.Delay(1);

    //you can do this, but it gives a compiler warning because it can potentially return immediately without finishing the copy
    //As a side note, if the file is not locked this will not return until the copy operation completes. Async functions run synchronously
    //until the first 'await'. See the documentation for async: https://msdn.microsoft.com/en-us/library/hh156513.aspx
    CopyWaitAsync("file1.txt", "file1.bat", 1000);

    //this is the normal way of using this kind of async function. Execution of the following lines will always occur AFTER the copy finishes
    await CopyWaitAsync("file1.txt", "file1.readme", 1000);
    Console.WriteLine("file1.txt copied to file1.readme");

    //The following line doesn't cause a compiler error, but it doesn't make any sense either.
    ReadAllTextWaitAsync("file1.readme", 1000);

    //To get the return value of the function, you have to use this function with the await keyword
    string text = await ReadAllTextWaitAsync("file1.readme", 1000);
    Console.WriteLine("file1.readme says: " + text);
}

//Output:
//Me First!
//file1.txt copied to file1.readme
//file1.readme says: Text to be duplicated!

How to get Locale from its String representation in Java?

Since Java 7 there is factory method Locale.forLanguageTag and instance method Locale.toLanguageTag using IETF language tags.

bash: pip: command not found

Installing using apt-get installs a system wide pip, not just a local one for your user. Try this command to get pip running on your system ...

$ sudo apt-get install python-pip python-dev build-essential

Then pip will be installed without any issues and you will be able to use "sudo pip...".

Month name as a string

The only one way on Android to get properly formatted stanalone month name for such languages as ukrainian, russian, czech

private String getMonthName(Calendar calendar, boolean short) {
    int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_NO_YEAR;
    if (short) {
        flags |= DateUtils.FORMAT_ABBREV_MONTH;
    }
    return DateUtils.formatDateTime(getContext(), calendar.getTimeInMillis(), flags);
}

Tested on API 15-25

Output for May is ??? but not ???

Comparing boxed Long values 127 and 128

Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.

This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127, whichever is bigger.(We can set top level value upto which Integer values should get cached by using java.lang.Integer.IntegerCache.high).

 For example:
    If we set java.lang.Integer.IntegerCache.high=500;
    then values from -128 to 500 will get cached and 

    Integer a=498;
    Integer b=499;
    System.out.println(a==b)

    Output will be "true".

Float and Double objects never gets cached.

Character will get cache from 0 to 127

You are comparing two objects. so == operator will check equality of object references. There are following ways to do it.

1) type cast both objects into primitive values and compare

    (long)val3 == (long)val4

2) read value of object and compare

    val3.longValue() == val4.longValue()

3) Use equals() method on object comparison.

    val3.equals(val4);  

"The import org.springframework cannot be resolved."

if you're sure that your pom.xml is pretty good, then you have just to update the poject. right click on the project - Maven - update project. or simply alt+F5.

Get docker container id from container name

I also need the container name or Id which a script requires to attach to the container. took some tweaking but this works perfectly well for me...

export svr=$(docker ps --format "table {{.ID}}"| sed 's/CONTAINER ID//g' | sed '/^[[:space:]]*$/d')
docker exec -it $svr bash

The sed command is needed to get rid of the fact that the words CONTAINER ID gets printed too ... but I just need the actual id stored in a var.

How to copy data from one table to another new table in MySQL?

You should create table2 first.

insert into table2(field1,field2,...)
select field1,field2,....
from table1
where condition;

How can I toggle word wrap in Visual Studio?

In latest version.

1.click the left bottom of the icon setting

2.select setting setting

3.select "text editor"> "word wrap" on word wrap

Getting data-* attribute for onclick event for an html element

User $() to get jQuery object from your link and data() to get your values

<a id="option1" 
   data-id="10" 
   data-option="21" 
   href="#" 
   onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
       Click to do something
</a>

CSS: styled a checkbox to look like a button, is there a hover?

Do this for a cool border and font effect:

#ck-button:hover {             /*ADD :hover */
    margin:4px;
    background-color:#EFEFEF;
    border-radius:4px;
    border:1px solid red;      /*change border color*/ 
    overflow:auto;
    float:left;
    color:red;                 /*add font color*/
}

Example: http://jsfiddle.net/zAFND/6/

jQuery, simple polling example

function make_call()
{
  // do the request

  setTimeout(function(){ 
    make_call();
  }, 5000);
}

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

PHP - Modify current object in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Adding text to a cell in Excel using VBA

You can also use the cell property.

Cells(1, 1).Value = "Hey, what's up?"

Make sure to use a . before Cells(1,1).Value as in .Cells(1,1).Value, if you are using it within With function. If you are selecting some sheet.

Check if string ends with certain pattern

You can test if a string ends with work followed by one character like this:

theString.matches(".*work.$");

If the trailing character is optional you can use this:

theString.matches(".*work.?$");

To make sure the last character is a period . or a slash / you can use this:

theString.matches(".*work[./]$");

To test for work followed by an optional period or slash you can use this:

theString.matches(".*work[./]?$");

To test for work surrounded by periods or slashes, you could do this:

theString.matches(".*[./]work[./]$");

If the tokens before and after work must match each other, you could do this:

theString.matches(".*([./])work\\1$");

Your exact requirement isn't precisely defined, but I think it would be something like this:

theString.matches(".*work[,./]?$");

In other words:

  • zero or more characters
  • followed by work
  • followed by zero or one , . OR /
  • followed by the end of the input

Explanation of various regex items:

.               --  any character
*               --  zero or more of the preceeding expression
$               --  the end of the line/input
?               --  zero or one of the preceeding expression
[./,]           --  either a period or a slash or a comma
[abc]           --  matches a, b, or c
[abc]*          --  zero or more of (a, b, or c)
[abc]?          --  zero or one of (a, b, or c)

enclosing a pattern in parentheses is called "grouping"

([abc])blah\\1  --  a, b, or c followed by blah followed by "the first group"

Here's a test harness to play with:

class TestStuff {

    public static void main (String[] args) {

        String[] testStrings = { 
                "work.",
                "work-",
                "workp",
                "/foo/work.",
                "/bar/work",
                "baz/work.",
                "baz.funk.work.",
                "funk.work",
                "jazz/junk/foo/work.",
                "funk/punk/work/",
                "/funk/foo/bar/work",
                "/funk/foo/bar/work/",
                ".funk.foo.bar.work.",
                ".funk.foo.bar.work",
                "goo/balls/work/",
                "goo/balls/work/funk"
        };

        for (String t : testStrings) {
            print("word: " + t + "  --->  " + matchesIt(t));
        }
    }

    public static boolean matchesIt(String s) {
        return s.matches(".*([./,])work\\1?$");
    }

    public static void print(Object o) {
        String s = (o == null) ? "null" : o.toString();
        System.out.println(o);
    }

}

AppendChild() is not a function javascript

Your div variable is a string, not a DOM element object:

var div = '<div>top div</div>';

Strings don't have an appendChild method. Instead of creating a raw HTML string, create the div as a DOM element and append a text node, then append the input element:

var div = document.createElement('div');
div.appendChild(document.createTextNode('top div'));

div.appendChild(element);

Read input numbers separated by spaces

int main() {
int sum = 0;
cout << "enter number" << endl;
int i = 0;
while (true) {
    cin >> i;
    sum += i;
    //cout << i << endl;
    if (cin.peek() == '\n') {
        break;
    }
    
}

cout << "result: " << sum << endl;
return 0;
}

I think this code works, you may enter any int numbers and spaces, it will calculate the sum of input ints

How to run a program in Atom Editor?

In order to get this working properly on Windows, you need to manually set the path to the JDK (...\jdk1.x.x_xx\bin) in the system environment variables.

Removing leading zeroes from a field in a SQL statement

select CASE
         WHEN TRY_CONVERT(bigint,Mtrl_Nbr) = 0
           THEN ''
           ELSE substring(Mtrl_Nbr, patindex('%[^0]%',Mtrl_Nbr), 18)
       END

SQL: sum 3 columns when one column has a null value?

looks like you want to SUM all the columns (I'm not sure where "sum 3 columns" comes from), not just TotalHoursM, so try this:

SELECT 
    SUM(    ISNULL(TotalHoursM  ,0)
          + ISNULL(TotalHoursT  ,0)
          + ISNULL(TotalHoursW  ,0)
          + ISNULL(TotalHoursTH ,0)
          + ISNULL(TotalHoursF  ,0) 
       ) AS TOTAL
    FROM LeaveRequest

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

Multiple IE http://tredosoft.com/Multiple_IE Will install ie up to 6, without disrupting current installation (i have 7 and it left it as it is). Now I need to find a way to run 8 on top of all that. 6 and 7 already run fine thanks to that little app above. (only tested on XP)

How to automate browsing using python?

You likely want urllib2. It can handle things like HTTPS, cookies, and authentication. You will probably also want BeautifulSoup to help parse the HTML pages.

JavaScript: SyntaxError: missing ) after argument list

just posting in case anyone else has the same error...

I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.

The solution was to make the function asynchronous

function functionName(args) {}

becomes

async function functionName(args) {}

Is there a macro to conditionally copy rows to another worksheet?

This is partially pseudocode, but you will want something like:

rows = ActiveSheet.UsedRange.Rows
n = 0

while n <= rows
  if ActiveSheet.Rows(n).Cells(DateColumnOrdinal).Value > '8/1/08' AND < '8/30/08' then
     ActiveSheet.Rows(n).CopyTo(DestinationSheet)
  endif
  n = n + 1
wend

How do I find the install time and date of Windows?

Windows 10 OS has yet another registry subkey, this one in the SYSTEM hive file:

Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\

The Install Date information here is the original computer OS install date/time. It also tells you when the update started, ie

 Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\Source OS (Updated on xxxxxx)."

This may of course not be when the update ends, the user may choose to turn off instead of rebooting when prompted, etc...

The update can actually complete on a different day, and

Computer\HKEY_LOCAL_MACHINE\SYSTEM\Setup\Source OS (Updated on xxxxxx)"

will reflect the date/time it started the update.

PuTTY scripting to log onto host

mputty can do that but it does not seem to work always. (if that wait period is too slow)

mputty uses putty and it extends putty. There is an option to run a script. If it does not work, make sure that wait period before typing is a high value or increase that value. See putty sessions , then name of session, right mouse button,properties/script page.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

Convert python datetime to epoch with strftime

If you want to convert a python datetime to seconds since epoch you could do it explicitly:

>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0

Why you should not use datetime.strftime('%s')

Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.

>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

Returning a value from callback function in Node.js

If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:

Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.

Basically, you can do something like this:

function doCall(urlToCall) {
  return co(function *(){
    var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.                             
    var statusCode = response.statusCode;
    finalData = getResponseJson(statusCode, data.toString());
    return finalData;
  });
}

Then,

var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.

By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.

How can I uninstall an application using PowerShell?

Here is the PowerShell script using msiexec:

echo "Getting product code"
$ProductCode = Get-WmiObject win32_product -Filter "Name='Name of my Software in Add Remove Program Window'" | Select-Object -Expand IdentifyingNumber
echo "removing Product"
# Out-Null argument is just for keeping the power shell command window waiting for msiexec command to finish else it moves to execute the next echo command
& msiexec /x $ProductCode | Out-Null
echo "uninstallation finished"

Add / Change parameter of URL and redirect to the new URL

I think something like this would work, upgrading the @Marc code:

//view-all parameter does NOT exist  
$params = $_GET;  
if(!isset($_GET['view-all'])){  
  //Adding view-all parameter  
  $params['view-all'] = 'Yes';  
}  
else{  
  //view-all parameter does exist!  
  $params['view-all'] = ($params['view-all'] == 'Yes' ? 'No' : 'Yes');  
}
$new_url = $_SERVER['PHP_SELF'].'?'.http_build_query($params);

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

Github: error cloning my private repository

I solved the problem installing the Git from: https://git-for-windows.github.io/ Locate the cert file path:

D:\Program Files\Git\mingw64\ssl\certs\ca-bundle.crt

Configure the Git path:

git config --system http.sslcainfo "D:\Program Files\Git\mingw64\ssl\certs\ca-bundle.crt"

Try again

Concatenating elements in an array to a string

Arrays.toString: (from the API, at least for the Object[] version of it)

public static String toString(Object[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(String.valueOf(a[i]));
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}

So that means it inserts the [ at the start, the ] at the end, and the , between elements.

If you want it without those characters: (StringBuilder is faster than the below, but it can't be the small amount of code)

String str = "";
for (String i:arr)
  str += i;
System.out.println(str);

Side note:

String[] arr[3]= [1,2,3] won't compile.

Presumably you wanted: String[] arr = {"1", "2", "3"};

Map to String in Java

You can also use google-collections (guava) Joiner class if you want to customize the print format

How can I delete Docker's images?

I found the answer in this command:

docker images --no-trunc | grep none | awk '{print $3}' | xargs docker rmi

I had your problem when I deleted some images that were being used, and I didn't realise (using docker ps -a).

Microsoft SQL Server 2005 service fails to start

solution for the microsoft sql server 2005 failed to start

  1. Read carefully all the tabs and icon name when you open it
  2. Don't be in a hurry be cool and do this procedure
  3. Start your sql and proceed further when u get this error than start with this solution . do not quit the installation
    start->control panel-->administrative tools-->services-->in services search for the sql server (sql express) -->click on logon (tab)--> check local system account & also check
    service to interact with desktop -->click on recovery tab -->first failure choose restart the service ;second failure --> run the program --> apply ok

Remove unused imports in Android Studio

Sorry for the late answer.. For mac users command + option + o Try this.. It is working for me..

Best practice for REST token-based authentication with JAX-RS and Jersey

This answer is all about authorization and it is a complement of my previous answer about authentication

Why another answer? I attempted to expand my previous answer by adding details on how to support JSR-250 annotations. However the original answer became the way too long and exceeded the maximum length of 30,000 characters. So I moved the whole authorization details to this answer, keeping the other answer focused on performing authentication and issuing tokens.


Supporting role-based authorization with the @Secured annotation

Besides authentication flow shown in the other answer, role-based authorization can be supported in the REST endpoints.

Create an enumeration and define the roles according to your needs:

public enum Role {
    ROLE_1,
    ROLE_2,
    ROLE_3
}

Change the @Secured name binding annotation created before to support roles:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
    Role[] value() default {};
}

And then annotate the resource classes and methods with @Secured to perform the authorization. The method annotations will override the class annotations:

@Path("/example")
@Secured({Role.ROLE_1})
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // But it's declared within a class annotated with @Secured({Role.ROLE_1})
        // So it only can be executed by the users who have the ROLE_1 role
        ...
    }

    @DELETE
    @Path("{id}")    
    @Produces(MediaType.APPLICATION_JSON)
    @Secured({Role.ROLE_1, Role.ROLE_2})
    public Response myOtherMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured({Role.ROLE_1, Role.ROLE_2})
        // The method annotation overrides the class annotation
        // So it only can be executed by the users who have the ROLE_1 or ROLE_2 roles
        ...
    }
}

Create a filter with the AUTHORIZATION priority, which is executed after the AUTHENTICATION priority filter defined previously.

The ResourceInfo can be used to get the resource Method and resource Class that will handle the request and then extract the @Secured annotations from them:

@Secured
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the resource class which matches with the requested URL
        // Extract the roles declared by it
        Class<?> resourceClass = resourceInfo.getResourceClass();
        List<Role> classRoles = extractRoles(resourceClass);

        // Get the resource method which matches with the requested URL
        // Extract the roles declared by it
        Method resourceMethod = resourceInfo.getResourceMethod();
        List<Role> methodRoles = extractRoles(resourceMethod);

        try {

            // Check if the user is allowed to execute the method
            // The method annotations override the class annotations
            if (methodRoles.isEmpty()) {
                checkPermissions(classRoles);
            } else {
                checkPermissions(methodRoles);
            }

        } catch (Exception e) {
            requestContext.abortWith(
                Response.status(Response.Status.FORBIDDEN).build());
        }
    }

    // Extract the roles from the annotated element
    private List<Role> extractRoles(AnnotatedElement annotatedElement) {
        if (annotatedElement == null) {
            return new ArrayList<Role>();
        } else {
            Secured secured = annotatedElement.getAnnotation(Secured.class);
            if (secured == null) {
                return new ArrayList<Role>();
            } else {
                Role[] allowedRoles = secured.value();
                return Arrays.asList(allowedRoles);
            }
        }
    }

    private void checkPermissions(List<Role> allowedRoles) throws Exception {
        // Check if the user contains one of the allowed roles
        // Throw an Exception if the user has not permission to execute the method
    }
}

If the user has no permission to execute the operation, the request is aborted with a 403 (Forbidden).

To know the user who is performing the request, see my previous answer. You can get it from the SecurityContext (which should be already set in the ContainerRequestContext) or inject it using CDI, depending on the approach you go for.

If a @Secured annotation has no roles declared, you can assume all authenticated users can access that endpoint, disregarding the roles the users have.

Supporting role-based authorization with JSR-250 annotations

Alternatively to defining the roles in the @Secured annotation as shown above, you could consider JSR-250 annotations such as @RolesAllowed, @PermitAll and @DenyAll.

JAX-RS doesn't support such annotations out-of-the-box, but it could be achieved with a filter. Here are a few considerations to keep in mind if you want to support all of them:

So an authorization filter that checks JSR-250 annotations could be like:

@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        Method method = resourceInfo.getResourceMethod();

        // @DenyAll on the method takes precedence over @RolesAllowed and @PermitAll
        if (method.isAnnotationPresent(DenyAll.class)) {
            refuseRequest();
        }

        // @RolesAllowed on the method takes precedence over @PermitAll
        RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
            return;
        }

        // @PermitAll on the method takes precedence over @RolesAllowed on the class
        if (method.isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // @DenyAll can't be attached to classes

        // @RolesAllowed on the class takes precedence over @PermitAll on the class
        rolesAllowed = 
            resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
        }

        // @PermitAll on the class
        if (resourceInfo.getResourceClass().isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // Authentication is required for non-annotated methods
        if (!isAuthenticated(requestContext)) {
            refuseRequest();
        }
    }

    /**
     * Perform authorization based on roles.
     *
     * @param rolesAllowed
     * @param requestContext
     */
    private void performAuthorization(String[] rolesAllowed, 
                                      ContainerRequestContext requestContext) {

        if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
            refuseRequest();
        }

        for (final String role : rolesAllowed) {
            if (requestContext.getSecurityContext().isUserInRole(role)) {
                return;
            }
        }

        refuseRequest();
    }

    /**
     * Check if the user is authenticated.
     *
     * @param requestContext
     * @return
     */
    private boolean isAuthenticated(final ContainerRequestContext requestContext) {
        // Return true if the user is authenticated or false otherwise
        // An implementation could be like:
        // return requestContext.getSecurityContext().getUserPrincipal() != null;
    }

    /**
     * Refuse the request.
     */
    private void refuseRequest() {
        throw new AccessDeniedException(
            "You don't have permissions to perform this action.");
    }
}

Note: The above implementation is based on the Jersey RolesAllowedDynamicFeature. If you use Jersey, you don't need to write your own filter, just use the existing implementation.

How can I remove a key and its value from an associative array?

You may need two or more loops depending on your array:

$arr[$key1][$key2][$key3]=$value1; // ....etc

foreach ($arr as $key1 => $values) {
  foreach ($key1 as $key2 => $value) {
  unset($arr[$key1][$key2]);
  }
}

How to master AngularJS?

Please keep an eye on the mailing list for problems/solutions discussed by community members. https://groups.google.com/forum/?fromgroups#!forum/angular . It's been really useful to me.

Find all CSV files in a directory using Python

This solution uses the python function filter. This function creates a list of elements for which a function returns true. In this case, the anonymous function used is partial matching '.csv' on every element of the directory files list obtained with os.listdir('the path i want to look in')

import os

filepath= 'filepath_to_my_CSVs'  # for example: './my_data/'

list(filter(lambda x: '.csv' in x, os.listdir('filepath_to_my_CSVs')))

How to decrypt an encrypted Apple iTunes iPhone backup?

You should grab a copy of Erica Sadun's mdhelper command line utility (OS X binary & source). It supports listing and extracting the contents of iPhone/iPod Touch backups, including address book & SMS databases, and other application metadata and settings.

Passing an array/list into a Python function

When you define your function using this syntax:

def someFunc(*args):
    for x in args
        print x

You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:

def someFunc(myList = [], *args):
    for x in myList:
        print x

Then you can call it with this:

items = [1,2,3,4,5]

someFunc(items)

You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:

def someFunc(arg1, arg2, arg3, *args, **kwargs):
    for x in args
        print x

Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.

Conditionally ignoring tests in JUnit 4

A quick note: Assume.assumeTrue(condition) ignores rest of the steps but passes the test. To fail the test, use org.junit.Assert.fail() inside the conditional statement. Works same like Assume.assumeTrue() but fails the test.

How can I add comments in MySQL?

You can use single line comments:

-- this is a comment
# this is also a comment

Or a multiline comment:

/*
   multiline
   comment
*/

Refused to execute script, strict MIME type checking is enabled?

i had the same issue and the problem was that i was missing a slash in my path.

i had

and to fix it i only needed to add the slash in between jquery-ui and jquery-ui.min:

  <script type="text/javascript" src="js/jquery-ui/jquery-ui.min.js"></script>

hope this helps :D

svn : how to create a branch from certain revision of trunk

append the revision using an "@" character:

svn copy http://src@REV http://dev

Or, use the -r [--revision] command line argument.

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

Kushagra Gour's solution does work (at least in Chrome and IE) and solves the original problem without having to use display: table; and display: table-cell;. See plunker: http://plnkr.co/edit/ULEgY1FDCsk8yiRTfOWU

Setting min-height: 100%; height: 1px; on the outer div causes its actual height to be at least 100%, as required. It also allows the inner div to correctly inherit the height.

Python `if x is not None` or `if not x is None`?

Code should be written to be understandable to the programmer first, and the compiler or interpreter second. The "is not" construct resembles English more closely than "not is".

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

I commented all the lines start with SET in the *.sql file and it worked.

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Below code will work ,but first install cors by:

npm install --save cors

Then:

module.exports = function(app) { 
var express = require("express");
var cors = require('cors');
var router = express.Router();
app.use(cors());

app.post("/movies",cors(), function(req, res) { 
res.send("test");
});

How can I check MySQL engine type for a specific table?

SHOW TABLE STATUS WHERE Name = 'xxx'

This will give you (among other things) an Engine column, which is what you want.

Change language of Visual Studio 2017 RC

I didn't find a complete answer here

Firstly

You should install your preferred language

  1. Open the Visual Studio Installer.
  2. In installed products click on plus Dropdown menu
  3. click edit
  4. then click on language packs
  5. choose you preferred language and finally click on install

Secondly

  1. Go to Tools -> Options

    2.Select International Settings in Environment

    3.click on Menu and select you preferred language

    4.Click on Ok

    5.restart visual studio

Excel is not updating cells, options > formula > workbook calculation set to automatic

Add this to your macro and it will recalculate all the cells and formulae.

Call Application.CalculateFullRebuild

Hope it has been already fixed.

PS The above code is for the people looking for a macro to solve the issue.

Reference: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-calculatefullrebuild-method-excel/

SQL select only rows with max value on a column

I think, You want this?

select * from docs where (id, rev) IN (select id, max(rev) as rev from docs group by id order by id)  

SQL Fiddle : Check here

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

I use this method and it works well:

1- Copy And paste the .jar files under the libs folder.

2- Add compile fileTree(dir: 'libs', include: '*.jar') to dependencies in build.gradle then all the jars in the libs folder will be included..

3- Right click on libs folder and select 'Add as library' option from the list.

clientHeight/clientWidth returning different values on different browsers

It may be caused by IE's box model bug. To fix this, you can use the Box Model Hack.

Changing CSS Values with Javascript

Gathering the code in the answers, I wrote this function that seems running well on my FF 25.

function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
  /* returns the value of the element style of the rule in the stylesheet
  *  If no value is given, reads the value
  *  If value is given, the value is changed and returned
  *  If '' (empty string) is given, erases the value.
  *  The browser will apply the default one
  *
  * string stylesheet: part of the .css name to be recognized, e.g. 'default'
  * string selectorText: css selector, e.g. '#myId', '.myClass', 'thead td'
  * string style: camelCase element style, e.g. 'fontSize'
  * string value optionnal : the new value
  */
  var CCSstyle = undefined, rules;
  for(var m in document.styleSheets){
    if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
     rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
     for(var n in rules){
       if(rules[n].selectorText == selectorText){
         CCSstyle = rules[n].style;
         break;
       }
     }
     break;
    }
  }
  if(value == undefined)
    return CCSstyle[style]
  else
    return CCSstyle[style] = value
}

This is a way to put values in the css that will be used in JS even if not understood by the browser. e.g. maxHeight for a tbody in a scrolled table.

Call :

CCSStylesheetRuleStyle('default', "#mydiv", "height");

CCSStylesheetRuleStyle('default', "#mydiv", "color", "#EEE");

How to secure RESTful web services?

There's another, very secure method. It's client certificates. Know how servers present an SSL Cert when you contact them on https? Well servers can request a cert from a client so they know the client is who they say they are. Clients generate certs and give them to you over a secure channel (like coming into your office with a USB key - preferably a non-trojaned USB key).

You load the public key of the cert client certificates (and their signer's certificate(s), if necessary) into your web server, and the web server won't accept connections from anyone except the people who have the corresponding private keys for the certs it knows about. It runs on the HTTPS layer, so you may even be able to completely skip application-level authentication like OAuth (depending on your requirements). You can abstract a layer away and create a local Certificate Authority and sign Cert Requests from clients, allowing you to skip the 'make them come into the office' and 'load certs onto the server' steps.

Pain the neck? Absolutely. Good for everything? Nope. Very secure? Yup.

It does rely on clients keeping their certificates safe however (they can't post their private keys online), and it's usually used when you sell a service to clients rather then letting anyone register and connect.

Anyway, it may not be the solution you're looking for (it probably isn't to be honest), but it's another option.

How can I disable selected attribute from select2() dropdown Jquery?

The below code also works fine for Select2 3.x

For Enable Select Box:

$('#foo').select2('enable');

For Disable Select Box:

$('#foo').select2('disable');

jsfiddle: http://jsfiddle.net/DcunN/

How to remove listview all items

An other approach after trying the solutions below. When you need it clear, just initialise your list to new clear new list.

List<ModelData> dataLists = new ArrayList<>();
                RaporAdapter adapter = new RaporAdapter(AyrintiliRapor.this, dataLists);
                listview.setAdapter(adapter);

Or set visibility to Gone / Invisible up to need

img_pdf.setVisibility(View.INVISIBLE);

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

Use HH for 24 hour hours format:

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

Or the tt format specifier for the AM/PM part:

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")

Take a look at the custom Date and Time format strings documentation.

Prevent flicker on webkit-transition of webkit-transform

Both of the above two answers work for me with a similar problem.

However, the body {-webkit-transform} approach causes all elements on the page to effectively be rendered in 3D. This isn't the worst thing, but it slightly changes the rendering of text and other CSS-styled elements.

It may be an effect you want. It may be useful if you're doing a lot of transform on your page. Otherwise, -webkit-backface-visibility:hidden on the element your transforming is the least invasive option.

Why do I get "MismatchSenderId" from GCM server side?

Your android app needs to correct 12-digit number id (aka GCM Project Number). If this 12-digit number is incorrect, then you will also get this error.

This 12-digit number is found in your Google Play Console under your specific app, 'Service & API' -> 'LINKED SENDER IDS'

How to get the cell value by column name not by index in GridView in asp.net

Although its a long time but this relatively small piece of code seems easy to read and get:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
   int index;
   string cellContent;

    foreach (TableCell tc in ((GridView)sender).HeaderRow.Cells)
    {
       if( tc.Text.Equals("yourColumnName") )
       {
         index = ((GridView)sender).HeaderRow.Cells.GetCellIndex(tc);
         cellContent = ((GridView)sender).SelectedRow.Cells[index].Text;
         break;
       }
    }
}

VBA check if file exists

I'll throw this out there and then duck. The usual reason to check if a file exists is to avoid an error when attempting to open it. How about using the error handler to deal with that:

Function openFileTest(filePathName As String, ByRef wkBook As Workbook, _
                      errorHandlingMethod As Long) As Boolean
'Returns True if filePathName is successfully opened,
'        False otherwise.
   Dim errorNum As Long

'***************************************************************************
'  Open the file or determine that it doesn't exist.
   On Error Resume Next:
   Set wkBook = Workbooks.Open(fileName:=filePathName)
   If Err.Number <> 0 Then
      errorNum = Err.Number
      'Error while attempting to open the file. Maybe it doesn't exist?
      If Err.Number = 1004 Then
'***************************************************************************
      'File doesn't exist.
         'Better clear the error and point to the error handler before moving on.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         '[Clever code here to cope with non-existant file]
         '...
         'If the problem could not be resolved, invoke the error handler.
         Err.Raise errorNum
      Else
         'No idea what the error is, but it's not due to a non-existant file
         'Invoke the error handler.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         Err.Raise errorNum
      End If
   End If

   'Either the file was successfully opened or the problem was resolved.
   openFileTest = True
   Exit Function

OPENFILETEST_FAIL:
   errorNum = Err.Number
   'Presumabley the problem is not a non-existant file, so it's
   'some other error. Not sure what this would be, so...
   If errorHandlingMethod < 2 Then
      'The easy out is to clear the error, reset to the default error handler,
      'and raise the error number again.
      'This will immediately cause the code to terminate with VBA's standard
      'run time error Message box:
      errorNum = Err.Number
      Err.Clear
      On Error GoTo 0
      Err.Raise errorNum
      Exit Function

   ElseIf errorHandlingMethod = 2 Then
      'Easier debugging, generate a more informative message box, then terminate:
      MsgBox "" _
           & "Error while opening workbook." _
           & "PathName: " & filePathName & vbCrLf _
           & "Error " & errorNum & ": " & Err.Description & vbCrLf _
           , vbExclamation _
           , "Failure in function OpenFile(), IO Module"
      End

   Else
      'The calling function is ok with a false result. That is the point
      'of returning a boolean, after all.
      openFileTest = False
      Exit Function
   End If

End Function 'openFileTest()

How to get and set the current web page scroll position?

You're looking for the document.documentElement.scrollTop property.

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

Supported by SQL Server 2005 and later versions

SELECT CONVERT(VARCHAR(10), GETDATE(), 101) 
       + ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)

* See Microsoft's documentation to understand what the 101 and 108 style codes above mean.

Supported by SQL Server 2012 and later versions

SELECT FORMAT(GETDATE() , 'MM/dd/yyyy HH:mm:ss')

Result

Both of the above methods will return:

10/16/2013 17:00:20

Printing without newline (print 'a',) prints a space, how to remove?

this is really simple

for python 3+ versions you only have to write the following codes

for i in range(20):
      print('a',end='')

just convert the loop to the following codes, you don't have to worry about other things

Xcode doesn't see my iOS device but iTunes does

The error I had in XCode was "iOS version lower than deployment target", which I didn't know how to fix. The error was displayed where the iPhone should have been indicated as a Device (upper left). I selected the project in Project Navigator and noticed that the iOS Deployment Target was set to 11.3 but when I checked my iPhone it was set to 11.2.1 (or something lower than 11.3). So I opened Settings on the phone, scrolled down to General and tapped Software Update. Since the update said it was scheduled but didn't start, I decided to take the SIM card out of my other phone and put it in the iPhone I was using for testing. Then the upgrade started quickly. After the Update finished on the phone, however, XCode still didn't recognize the phone. I unplugged the USB cable but didn't hear any sound, so I plugged it into another USB port on the computer and then heard a sound. Then XCode noticed the phone. So the problems were that the iPhone didn't inform me that I had an Update (or I ignored it and forgot about it) and it may have needed the SIM card, and I had a bad USB connection.

How to present popover properly in iOS 8

Swift 2.0

Well I worked out. Have a look. Made a ViewController in StoryBoard. Associated with PopOverViewController class.

import UIKit

class PopOverViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()    
        self.preferredContentSize = CGSizeMake(200, 200)    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss:")    
    }    
    func dismiss(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}      

See ViewController:

//  ViewController.swift

import UIKit

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate
{
    func showPopover(base: UIView)
    {
        if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("popover") as? PopOverViewController {    

            let navController = UINavigationController(rootViewController: viewController)
            navController.modalPresentationStyle = .Popover

            if let pctrl = navController.popoverPresentationController {
                pctrl.delegate = self

                pctrl.sourceView = base
                pctrl.sourceRect = base.bounds

                self.presentViewController(navController, animated: true, completion: nil)
            }
        }
    }    
    override func viewDidLoad(){
        super.viewDidLoad()
    }    
    @IBAction func onShow(sender: UIButton)
    {
        self.showPopover(sender)
    }    
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return .None
    }
}  

Note: The func showPopover(base: UIView) method should be placed before ViewDidLoad. Hope it helps !

Python: print a generator expression?

You can just wrap the expression in a call to list:

>>> list(x for x in string.letters if x in (y for y in "BigMan on campus"))
['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']

DateDiff to output hours and minutes

Very simply:

CONVERT(TIME,Date2 - Date1)

For example:

Declare @Date2 DATETIME = '2016-01-01 10:01:10.022'
Declare @Date1 DATETIME = '2016-01-01 10:00:00.000'
Select CONVERT(TIME,@Date2 - @Date1) as ElapsedTime

Yelds:

ElapsedTime
----------------
00:01:10.0233333

(1 row(s) affected)

How to access a mobile's camera from a web app?

well, there's a new HTML5 features for accessing the native device camera - "getUserMedia API"

NOTE: HTML5 can handle photo capture from a web page on Android devices (at least on the latest versions, run by the Honeycomb OS; but it can’t handle it on iPhones but iOS 6 ).

How to extract base URL from a string in JavaScript?

function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}

You then can use it like this...

var str = 'http://en.wikipedia.org/wiki/Knopf?q=1&t=2';
var url = str.toUrl();

The value of url will be...

{
"original":"http://en.wikipedia.org/wiki/Knopf?q=1&t=2",<br/>"protocol":"http:",
"domain":"wikipedia.org",<br/>"host":"en.wikipedia.org",<br/>"relativePath":"wiki"
}

The "var url" also contains two methods.

var paramQ = url.getParameter('q');

In this case the value of paramQ will be 1.

var allParameters = url.getParameters();

The value of allParameters will be the parameter names only.

["q","t"]

Tested on IE,chrome and firefox.

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

None of the answers here worked for me. This was what worked.

Test_y = np.nan_to_num(Test_y)

It replaces the infinity values with high finite values and the nan values with numbers

Paste Excel range in Outlook

First off, RangeToHTML. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.

On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.

For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.

Sub Mail_Selection_Range_Outlook_Body()

Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object

Set rng = Nothing
' Only send the visible cells in the selection.

Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected. " & _
           vbNewLine & "Please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)


With OutMail
    .To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .HTMLBody = RangetoHTML(rng)
    ' In place of the following statement, you can use ".Display" to
    ' display the e-mail message.
    .Display
End With
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub


Function RangetoHTML(rng As Range)
' By Ron de Bruin.
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.ReadAll
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

FileNotFoundException..Classpath resource not found in spring?

Looking at your classpath you exclude src/main/resources and src/test/resources:

    <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"/>
    <classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources"/>

Is there a reason for it? Try not to exclude a classpath to spring-config.xml :)

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

2019: Use AppCompatActivity

At the time of this writing (check the link to confirm it is still true), the Android Documentation recommends using AppCompatActivity if you are using an App Bar.

This is the rational given:

Beginning with Android 3.0 (API level 11), all activities that use the default theme have an ActionBar as an app bar. However, app bar features have gradually been added to the native ActionBar over various Android releases. As a result, the native ActionBar behaves differently depending on what version of the Android system a device may be using. By contrast, the most recent features are added to the support library's version of Toolbar, and they are available on any device that can use the support library.

For this reason, you should use the support library's Toolbar class to implement your activities' app bars. Using the support library's toolbar helps ensure that your app will have consistent behavior across the widest range of devices. For example, the Toolbar widget provides a material design experience on devices running Android 2.1 (API level 7) or later, but the native action bar doesn't support material design unless the device is running Android 5.0 (API level 21) or later.

The general directions for adding a ToolBar are

  1. Add the v7 appcompat support library
  2. Make all your activities extend AppCompatActivity
  3. In the Manifest declare that you want NoActionBar.
  4. Add a ToolBar to each activity's xml layout.
  5. Get the ToolBar in each activity's onCreate.

See the documentation directions for more details. They are quite clear and helpful.

Image resizing in React Native

This worked for me:

image: {
  flex: 1,
  width: 900,
  height: 900,
  resizeMode: 'contain'
}

Just need to make sure that the width and height are bigger than you need as it is limited to what you set.

Setting up and using Meld as your git difftool and mergetool

It can be complicated to compute a diff in your head from the different sections in $MERGED and apply that. In my setup, meld helps by showing you these diffs visually, using:

[merge]
    tool = mymeld
    conflictstyle = diff3

[mergetool "mymeld"]
    cmd = meld --diff $BASE $REMOTE --diff $REMOTE $LOCAL --diff $LOCAL $MERGED

It looks strange but offers a very convenient work-flow, using three tabs:

  1. in tab 1 you see (from left to right) the change that you should make in tab 2 to solve the merge conflict.

  2. in the right side of tab 2 you apply the "change that you should make" and copy the entire file contents to the clipboard (using ctrl-a and ctrl-c).

  3. in tab 3 replace the right side with the clipboard contents. If everything is correct, you will now see - from left to right - the same change as shown in tab 1 (but with different contexts). Save the changes made in this tab.

Notes:

  • don't edit anything in tab 1
  • don't save anything in tab 2 because that will produce annoying popups in tab 3

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

Another thing to try is to re-install ca-certificates as detailed here.

# yum reinstall ca-certificates
...
# update-ca-trust force-enable 
# update-ca-trust extract

And another thing to try is to explicitly allow the one site's certificate in question as described here (especially if the one site is your own server and you already have the .pem in reach).

# cp /your/site.pem /etc/pki/ca-trust/source/anchors/
# update-ca-trust extract

I was running into this exact SO error after upgrading to PHP 5.6 on CentOS 6 trying to access the server itself which has a cheapsslsecurity certificate which maybe it needed to be updated, but instead I installed a letsencrypt certificate and with these two steps above it did the trick. I don't know why the second step was necessary.


Useful Commands

View openssl version:

# openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013

View PHP cli ssl current settings:

# php -i | grep ssl
openssl
Openssl default config => /etc/pki/tls/openssl.cnf
openssl.cafile => no value => no value
openssl.capath => no value => no value

How to convert integer to decimal in SQL Server query?

SELECT height/10.0 AS HeightDecimal FROM dbo.whatever;

If you want a specific precision scale, then say so:

SELECT CONVERT(DECIMAL(16,4), height/10.0) AS HeightDecimal
  FROM dbo.whatever;

What is the best free SQL GUI for Linux for various DBMS systems

I use SQLite Database Browser for SQLite3 currently and it's pretty useful. Works across Windows/OS X/Linux and is lightweight and fast. Slightly unstable with executing SQL on the DB if it's incorrectly formatted.

Edit: I have recently discovered SQLite Manager, a plugin for Firefox. Obviously you need to run Firefox, but you can close all windows and just run it "standalone". It's very feature complete, amazingly stable and it remembers your databases! It has tonnes of features so I've moved away from SQLite Database Browser as the instability and lack of features is too much to bear.

How do I check to see if my array includes an object?

#include? should work, it works for general objects, not only strings. Your problem in example code is this test:

unless @suggested_horses.exists?(horse.id)
  @suggested_horses<< horse
end

(even assuming using #include?). You try to search for specific object, not for id. So it should be like this:

unless @suggested_horses.include?(horse)
  @suggested_horses << horse
end

ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id

How to trigger a click on a link using jQuery

Sorry, but the event handler is really not needed. What you do need is another element within the tag to click on.

<a id="test1" href="javascript:alert('test1')">TEST1</a>
<a id="test2" href="javascript:alert('test2')"><span>TEST2</span></a>

Jquery:

$('#test1').trigger('click'); // Nothing
$('#test2').find('span').trigger('click'); // Works
$('#test2 span').trigger('click'); // Also Works

This is all about what you are clicking and it is not the tag but the thing within it. Unfortunately, bare text does not seem to be recognised by JQuery, but it is by vanilla javascript:

document.getElementById('test1').click(); // Works!

Or by accessing the jQuery object as an array

$('#test1')[0].click(); // Works too!!!

PL/SQL print out ref cursor returned by a stored procedure

You can use a bind variable at the SQLPlus level to do this. Of course you have little control over the formatting of the output.

VAR x REFCURSOR;
EXEC GetGrantListByPI(args, :x);
PRINT x;

How can I send the "&" (ampersand) character via AJAX?

You need to url-escape the ampersand. Use:

var wysiwyg_clean = wysiwyg.replace('&', '%26');

As Wolfram points out, this is nicely handled (along with all the other special characters) by encodeURIComponent.

Easily measure elapsed time

From what is see, tv_sec stores the seconds elapsed while tv_usec stored the microseconds elapsed separately. And they aren't the conversions of each other. Hence, they must be changed to proper unit and added to get the total time elapsed.

struct timeval startTV, endTV;

gettimeofday(&startTV, NULL); 

doSomething();
doSomethingLong();

gettimeofday(&endTV, NULL); 

printf("**time taken in microseconds = %ld\n",
    (endTV.tv_sec * 1e6 + endTV.tv_usec - (startTV.tv_sec * 1e6 + startTV.tv_usec))
    );

Remove characters from NSString?

You could use:

NSString *stringWithoutSpaces = [myString 
   stringByReplacingOccurrencesOfString:@" " withString:@""];

How to download excel (.xls) file from API in postman?

If the endpoint really is a direct link to the .xls file, you can try the following code to handle downloading:

public static boolean download(final File output, final String source) {
    try {
        if (!output.createNewFile()) {
            throw new RuntimeException("Could not create new file!");
        }
        URL url = new URL(source);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // Comment in the code in the following line in case the endpoint redirects instead of it being a direct link
        // connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("AUTH-KEY-PROPERTY-NAME", "yourAuthKey");
        final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        final FileOutputStream fos = new FileOutputStream(output);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        fos.close();
        return true;
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return false;
}

All you should need to do is set the proper name for the auth token and fill it in.

Example usage:

download(new File("C:\\output.xls"), "http://www.website.com/endpoint");

Resolving a Git conflict with binary files

I came across a similar problem (wanting to pull a commit that included some binary files which caused conflicts when merged), but came across a different solution that can be done entirely using git (i.e. not having to manually copy files over). I figured I'd include it here so at the very least I can remember it the next time I need it. :) The steps look like this:

% git fetch

This fetches the latest commit(s) from the remote repository (you may need to specify a remote branch name, depending on your setup), but doesn't try to merge them. It records the the commit in FETCH_HEAD

% git checkout FETCH_HEAD stuff/to/update

This takes the copy of the binary files I want and overwrites what's in the working tree with the version fetched from the remote branch. git doesn't try to do any merging, so you just end up with an exact copy of the binary file from the remote branch. Once that's done, you can add/commit the new copy just like normal.

How to convert std::string to lower case?

Boost provides a string algorithm for this:

#include <boost/algorithm/string.hpp>

std::string str = "HELLO, WORLD!";
boost::algorithm::to_lower(str); // modifies str

Or, for non-in-place:

#include <boost/algorithm/string.hpp>

const std::string str = "HELLO, WORLD!";
const std::string lower_str = boost::algorithm::to_lower_copy(str);