Programs & Examples On #Aec

Acoustic Echo Cancellation, a feature of Adobe Flash.

npm install Error: rollbackFailedOptional

use sudo before your command as


sudo npm install

try/catch blocks with async/await

catching in this fashion, in my experience, is dangerous. Any error thrown in the entire stack will be caught, not just an error from this promise (which is probably not what you want).

The second argument to a promise is already a rejection/failure callback. It's better and safer to use that instead.

Here's a typescript typesafe one-liner I wrote to handle this:

function wait<R, E>(promise: Promise<R>): [R | null, E | null] {
  return (promise.then((data: R) => [data, null], (err: E) => [null, err]) as any) as [R, E];
}

// Usage
const [currUser, currUserError] = await wait<GetCurrentUser_user, GetCurrentUser_errors>(
  apiClient.getCurrentUser()
);

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

The simple answer:

  • doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice

  • ADD 1 is probably faster than INC here

  • MOV 2 and DIV is very expensive; just shift right

  • 64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code

If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.

How to configure CORS in a Spring Boot + Spring Security application?

If you are using Spring Security, you can do the following to ensure that CORS requests are handled first:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // by default uses a Bean by the name of corsConfigurationSource
            .cors().and()
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

See Spring 4.2.x CORS for more information.

Without Spring Security this will work:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS");
        }
    };
}

Docker is in volume in use, but there aren't any Docker containers

A one liner to give you just the needed details:

docker inspect `docker ps -aq` | jq '.[] | {Name: .Name, Mounts: .Mounts}' | less

search for the volume of complaint, you have the container name as well.

Applying an ellipsis to multiline text

You can achieve this by a few lines of CSS and JS.

CSS:

        div.clip-context {
          max-height: 95px;
          word-break: break-all;
          white-space: normal;
          word-wrap: break-word; //Breaking unicode line for MS-Edge works with this property;
        }

JS:

        $(document).ready(function(){
             for(let c of $("div.clip-context")){
                    //If each of element content exceeds 95px its css height, extract some first 
                    //lines by specifying first length of its text content. 
                   if($(c).innerHeight() >= 95){
                        //Define text length for extracting, here 170.
                        $(c).text($(c).text().substr(0, 170)); 
                        $(c).append(" ...");
                   }
             }

        });

HTML:

        <div class="clip-context">
            (Here some text)
        </div>

Docker error : no space left on device

As already mentioned,

docker system prune

helps, but with Docker 17.06.1 and later without pruning unused volumes. Since Docker 17.06.1, the following command prunes volumes, too:

docker system prune --volumes

From the Docker documentation: https://docs.docker.com/config/pruning/

The docker system prune command is a shortcut that prunes images, containers, and networks. In Docker 17.06.0 and earlier, volumes are also pruned. In Docker 17.06.1 and higher, you must specify the --volumes flag for docker system prune to prune volumes.

If you want to prune volumes and keep images and containers:

docker volume prune

Make div 100% Width of Browser Window

Try to give it a postion: absolute;

Bootstrap Accordion button toggle "data-parent" not working

Bootstrap 4

Use the data-parent="" attribute on the collapse element (instead of the trigger element)

<div id="accordion">
  <div class="card">
    <div class="card-header">
      <h5>
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne">
          Collapsible #1 trigger
        </button>
      </h5>
    </div>
    <div id="collapseOne" class="collapse show" data-parent="#accordion">
      <div class="card-body">
        Collapsible #1 element
      </div>
    </div>
  </div>
  ... (more cards/collapsibles inside #accordion parent)
</div>

Bootstrap 3

See this issue on GitHub: https://github.com/twbs/bootstrap/issues/10966

There is a "bug" that makes the accordion dependent on the .panel class when using the data-parent attribute. To workaround it, you can wrap each accordion group in a 'panel' div..

http://bootply.com/88288

<div class="accordion" id="myAccordion">
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
        <div id="collapsible-1" class="collapse">
            ..
        </div>
    </div>
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
        <div id="collapsible-2" class="collapse">
            ..
        </div>
    </div>
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
        <div id="collapsible-3" class="collapse">
           ...
        </div>
    </div>
</div>

Edit

As mentioned in the comments, each section doesn't have to be a .panel. However...

  • .panel must be a direct child of the element used as data-parent=
  • each accordion section (data-toggle=) must be a direct child of the .panel (http://www.bootply.com/AbiRW7BdD6#)

draw diagonal lines in div background with CSS

If you'd like the cross to be partially transparent, the naive approach would be to make linear-gradient colors semi-transparent. But that doesn't work out good due to the alpha blending at the intersection, producing a differently colored diamond. The solution to this is to leave the colors solid but add transparency to the gradient container instead:

_x000D_
_x000D_
.cross {_x000D_
  position: relative;_x000D_
}_x000D_
.cross::after {_x000D_
  pointer-events: none;_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0; bottom: 0; left: 0; right: 0;_x000D_
}_x000D_
_x000D_
.cross1::after {_x000D_
  background:_x000D_
    linear-gradient(to top left, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%),_x000D_
    linear-gradient(to top right, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%);_x000D_
}_x000D_
_x000D_
.cross2::after {_x000D_
  background:_x000D_
    linear-gradient(to top left, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%),_x000D_
    linear-gradient(to top right, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%);_x000D_
  opacity: 0.35;_x000D_
}_x000D_
_x000D_
div { width: 180px; text-align: justify; display: inline-block; margin: 20px; }
_x000D_
<div class="cross cross1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>_x000D_
_x000D_
<div class="cross cross2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>
_x000D_
_x000D_
_x000D_

Can't install via pip because of egg_info error

See this : What Python version can I use with Django?¶ https://docs.djangoproject.com/en/2.0/faq/install/

if you are using python27 you must to set django version :

try: $pip install django==1.9

Position Absolute + Scrolling

So gaiour is right, but if you're looking for a full height item that doesn't scroll with the content, but is actually the height of the container, here's the fix. Have a parent with a height that causes overflow, a content container that has a 100% height and overflow: scroll, and a sibling then can be positioned according to the parent size, not the scroll element size. Here is the fiddle: http://jsfiddle.net/M5cTN/196/

and the relevant code:

html:

<div class="container">
  <div class="inner">
    Lorem ipsum ...
  </div>
  <div class="full-height"></div>
</div>

css:

.container{
  height: 256px;
  position: relative;
}
.inner{
  height: 100%;
  overflow: scroll;
}
.full-height{
  position: absolute;
  left: 0;
  width: 20%;
  top: 0;
  height: 100%;
}

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

I got similar error while using in-app-purchase in android. My mistake is I used wrong purchase id while instantiating the purchases.

public static final String PRODUCT_ID_ASTRO_Match = "android.test.product";//wrong id not in play store dev console

Replaced it with:

public static final String PRODUCT_ID_ASTRO_Match = "android.test.purchased";

and it worked.

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

To solve this problem (RPC:S-5:AEC-0):

  1. Go to settings
  2. Go to backup and reset
  3. Go down to recovery mode
  4. Reboot the system

This seemed to fix the problem for my tab. Now I can use Google Play store and download any app I want.

How to display the first few characters of a string in Python?

Since there is a delimiter, you should use that instead of worrying about how long the md5 is.

>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f"
>>> md5sum, delim, rest = s.partition('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'

Alternatively

>>> md5sum, sha1sum, sha5sum = s.split('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
>>> sha1sum
'd4f656ee006e248f2f3a8a93a8aec5868788b927'
>>> sha5sum
'12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f'

How do I wrap text in a span?

Try

_x000D_
_x000D_
.test {
white-space:pre-wrap;
}
_x000D_
<a class="test" href="#">
    Notes

    <span>
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.
    </span>
</a>
_x000D_
_x000D_
_x000D_

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:

 <?php 
    require_once('mylib.php');
    session_start();
 ?>

In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending.

HTH

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

Scroll part of content in fixed position container

Set the scrollable div to have a max-size and add overflow-y: scroll; to it's properties.

Edit: trying to get the jsfiddle to work, but it's not scrolling properly. This will take some time to figure out.

Regex to match any character including new lines

Yeap, you just need to make . match newline :

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

Python base64 data decode

Interesting if maddening puzzle...but here's the best I could get:

The data seems to repeat every 8 bytes or so.

import struct
import base64

target = \
r'''Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YH 
[snip.]
ZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA''' 

data = base64.b64decode(target)

cleaned_data = []
struct_format = ">ff"
for i in range(len(data) // 8):
   cleaned_data.append(struct.unpack_from(struct_format, data, 8*i))

That gives output like the following (a sampling of lines from the first 100 or so):

(300.00030517578125, 0.0)
(300.05975341796875, 241.93943786621094)
(301.05612182617187, 0.0)
(301.05667114257812, 8.7439727783203125)
(326.9617919921875, 0.0)
(326.96826171875, 0.0)
(328.34432983398438, 280.55218505859375)

That first number does seem to monotonically increase through the entire set. If you plot it:

import matplotlib.pyplot as plt
f, ax = plt.subplots()
ax.plot(*zip(*cleaned_data))

enter image description here

format = 'hhhh' (possibly with various paddings/directions (e.g. '<hhhh', '<xhhhh') also might be worth a look (again, random lines):

(-27069, 2560, 0, 0)
(-27069, 8968, 0, 0)
(-27069, 13576, 3139, -18487)
(-27069, 18184, 31043, -5184)
(-27069, -25721, -25533, -8601)
(-27069, -7289, 0, 0)
(-25533, 31066, 0, 0)
(-25533, -29350, 0, 0)
(-25533, 25179, 0, 0)
(-24509, -1888, 0, 0)
(-24509, -4447, 0, 0)
(-23741, -14725, 32067, 27475)
(-23741, -3973, 0, 0)
(-23485, 4908, -29629, -20922)

Scroll to a div using jquery

First, your code does not contain a contact div, it has a contacts div!

In sidebar you have contact in the div at the bottom of the page you have contacts. I removed the final s for the code sample. (you also misspelled the projectslink id in the sidebar).

Second, take a look at some of the examples for click on the jQuery reference page. You have to use click like, object.click( function() { // Your code here } ); in order to bind a click event handler to the object.... Like in my example below. As an aside, you can also just trigger a click on an object by using it without arguments, like object.click().

Third, scrollTo is a plugin in jQuery. I don't know if you have the plugin installed. You can't use scrollTo() without the plugin. In this case, the functionality you desire is only 2 lines of code, so I see no reason to use the plugin.

Ok, now on to a solution.

The code below will scroll to the correct div if you click a link in the sidebar. The window does have to be big enough to allow scrolling:

// This is a functions that scrolls to #{blah}link
function goToByScroll(id) {
    // Remove "link" from the ID
    id = id.replace("link", "");
    // Scroll
    $('html,body').animate({
        scrollTop: $("#" + id).offset().top
    }, 'slow');
}

$("#sidebar > ul > li > a").click(function(e) {
    // Prevent a page reload when a link is pressed
    e.preventDefault();
    // Call the scroll function
    goToByScroll(this.id);
});

Live Example

( Scroll to function taken from here )


PS: Obviously you should have a compelling reason to go this route instead of using anchor tags <a href="#gohere">blah</a> ... <a name="gohere">blah title</a>

Generating a SHA-256 hash from the Linux command line

For the sha256 hash in base64, use:

echo -n foo | openssl dgst -binary -sha1 | openssl base64

Example

echo -n foo | openssl dgst -binary -sha1 | openssl base64
C+7Hteo/D9vJXQ3UfzxbwnXaijM=

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

In my xml file, the header looked like this:

<?xml version="1.0" encoding="utf-16"? />

In a test file, I was reading the file bytes and decoding the data as UTF-8 (not realizing the header in this file was utf-16) to create a string.

byte[] data = Files.readAllBytes(Paths.get(path));
String dataString = new String(data, "UTF-8");

When I tried to deserialize this string into an object, I was seeing the same error:

javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Content is not allowed in prolog.

When I updated the second line to

String dataString = new String(data, "UTF-16");

I was able to deserialize the object just fine. So as Romain had noted above, the encodings need to match.

How do I vertically align text in a div?

If you need to use with the min-height property you must add this CSS on:

.outerContainer .innerContainer {
    height: 0;
    min-height: 100px;
}

"No such file or directory" error when executing a binary

Well another possible cause of this can be simple line break at end of each line and shebang line If you have been coding in windows IDE its possible that windows has added its own line break at the end of each line and when you try to run it on linux the line break cause problems

How to detect page zoom level in all modern browsers?

On Chrome

var ratio = (screen.availWidth / document.documentElement.clientWidth);
var zoomLevel = Number(ratio.toFixed(1).replace(".", "") + "0");

JQUERY ajax passing value from MVC View to Controller

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatu`enter code here`s) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

How can I find the method that called the current method?

In general, you can use the System.Diagnostics.StackTrace class to get a System.Diagnostics.StackFrame, and then use the GetMethod() method to get a System.Reflection.MethodBase object. However, there are some caveats to this approach:

  1. It represents the runtime stack -- optimizations could inline a method, and you will not see that method in the stack trace.
  2. It will not show any native frames, so if there's even a chance your method is being called by a native method, this will not work, and there is in-fact no currently available way to do it.

(NOTE: I am just expanding on the answer provided by Firas Assad.)

Nginx location priority

From the HTTP core module docs:

  1. Directives with the "=" prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings. If this match used the "^~" prefix, searching stops.
  3. Regular expressions, in the order they are defined in the configuration file.
  4. If #3 yielded a match, that result is used. Otherwise, the match from #2 is used.

Example from the documentation:

location  = / {
  # matches the query / only.
  [ configuration A ] 
}
location  / {
  # matches any query, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
  [ configuration B ] 
}
location /documents/ {
  # matches any query beginning with /documents/ and continues searching,
  # so regular expressions will be checked. This will be matched only if
  # regular expressions don't find a match.
  [ configuration C ] 
}
location ^~ /images/ {
  # matches any query beginning with /images/ and halts searching,
  # so regular expressions will not be checked.
  [ configuration D ] 
}
location ~* \.(gif|jpg|jpeg)$ {
  # matches any request ending in gif, jpg, or jpeg. However, all
  # requests to the /images/ directory will be handled by
  # Configuration D.   
  [ configuration E ] 
}

If it's still confusing, here's a longer explanation.

Image inside div has extra space below the image

You can use several methods for this issue like

  1. Using line-height

    #wrapper {  line-height: 0px;  }
    
  2. Using display: flex

    #wrapper {  display: flex;         }
    #wrapper {  display: inline-flex;  }
    
  3. Using display: block, table, flex and inherit

    #wrapper img {  display: block;    }
    #wrapper img {  display: table;    }
    #wrapper img {  display: flex;     }
    #wrapper img {  display: inherit;  }
    

Embed image in a <button> element

The topic is 'Embed image in a button element', and the question using plain HTML. I do this using the span tag in the same way that glyphicons are used in bootstrap. My image is 16 x 16px and can be any format.

Here's the plain HTML that answers the question:

<button type="button"><span><img src="images/xxx.png" /></span>&nbsp;Click Me</button>

How do I compare strings in Java?

.equals() compares the data in a class (assuming the function is implemented). == compares pointer locations (location of the object in memory).

== returns true if both objects (NOT TALKING ABOUT PRIMITIVES) point to the SAME object instance. .equals() returns true if the two objects contain the same data equals() Versus == in Java

That may help you.

How to create a user in Django?

Have you confirmed that you are passing actual values and not None?

from django.shortcuts import render

def createUser(request):
    userName = request.REQUEST.get('username', None)
    userPass = request.REQUEST.get('password', None)
    userMail = request.REQUEST.get('email', None)

    # TODO: check if already existed
    if userName and userPass and userMail:
       u,created = User.objects.get_or_create(userName, userMail)
       if created:
          # user was created
          # set the password here
       else:
          # user was retrieved
    else:
       # request was empty

    return render(request,'home.html')

Image comparison - fast algorithm

I believe that dropping the size of the image down to an almost icon size, say 48x48, then converting to greyscale, then taking the difference between pixels, or Delta, should work well. Because we're comparing the change in pixel color, rather than the actual pixel color, it won't matter if the image is slightly lighter or darker. Large changes will matter since pixels getting too light/dark will be lost. You can apply this across one row, or as many as you like to increase the accuracy. At most you'd have 47x47=2,209 subtractions to make in order to form a comparable Key.

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

Store output of subprocess.Popen call in a string

subprocess.Popen: http://docs.python.org/2/library/subprocess.html#subprocess.Popen

import subprocess

command = "ntpq -p"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)

#Launch the shell command:
output = process.communicate()

print output[0]

In the Popen constructor, if shell is True, you should pass the command as a string rather than as a sequence. Otherwise, just split the command into a list:

command = ["ntpq", "-p"]  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)

If you need to read also the standard error, into the Popen initialization, you can set stderr to subprocess.PIPE or to subprocess.STDOUT:

import subprocess

command = "ntpq -p"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

#Launch the shell command:
output, error = process.communicate()

Why does Date.parse give incorrect results?

During recent experience writing a JS interpreter I wrestled plenty with the inner workings of ECMA/JS dates. So, I figure I'll throw in my 2 cents here. Hopefully sharing this stuff will help others with any questions about the differences among browsers in how they handle dates.

The Input Side

All implementations store their date values internally as 64-bit numbers that represent the number of milliseconds (ms) since 1970-01-01 UTC (GMT is the same thing as UTC). This date is the ECMAScript epoch that is also used by other languages such as Java and POSIX systems such as UNIX. Dates occurring after the epoch are positive numbers and dates prior are negative.

The following code is interpreted as the same date in all current browsers, but with the local timezone offset:

Date.parse('1/1/1970'); // 1 January, 1970

In my timezone (EST, which is -05:00), the result is 18000000 because that's how many ms are in 5 hours (it's only 4 hours during daylight savings months). The value will be different in different time zones. This behaviour is specified in ECMA-262 so all browsers do it the same way.

While there is some variance in the input string formats that the major browsers will parse as dates, they essentially interpret them the same as far as time zones and daylight saving is concerned even though parsing is largely implementation dependent.

However, the ISO 8601 format is different. It's one of only two formats outlined in ECMAScript 2015 (ed 6) specifically that must be parsed the same way by all implementations (the other is the format specified for Date.prototype.toString).

But, even for ISO 8601 format strings, some implementations get it wrong. Here is a comparison output of Chrome and Firefox when this answer was originally written for 1/1/1970 (the epoch) on my machine using ISO 8601 format strings that should be parsed to exactly the same value in all implementations:

Date.parse('1970-01-01T00:00:00Z');       // Chrome: 0         FF: 0
Date.parse('1970-01-01T00:00:00-0500');   // Chrome: 18000000  FF: 18000000
Date.parse('1970-01-01T00:00:00');        // Chrome: 0         FF: 18000000
  • In the first case, the "Z" specifier indicates that the input is in UTC time so is not offset from the epoch and the result is 0
  • In the second case, the "-0500" specifier indicates that the input is in GMT-05:00 and both browsers interpret the input as being in the -05:00 timezone. That means that the UTC value is offset from the epoch, which means adding 18000000ms to the date's internal time value.
  • The third case, where there is no specifier, should be treated as local for the host system. FF correctly treats the input as local time while Chrome treats it as UTC, so producing different time values. For me this creates a 5 hour difference in the stored value, which is problematic. Other systems with different offsets will get different results.

This difference has been fixed as of 2020, but other quirks exist between browsers when parsing ISO 8601 format strings.

But it gets worse. A quirk of ECMA-262 is that the ISO 8601 date–only format (YYYY-MM-DD) is required to be parsed as UTC, whereas ISO 8601 requires it to be parsed as local. Here is the output from FF with the long and short ISO date formats with no time zone specifier.

Date.parse('1970-01-01T00:00:00');       // 18000000
Date.parse('1970-01-01');                // 0

So the first is parsed as local because it's ISO 8601 date and time with no timezone, and the second is parsed as UTC because it's ISO 8601 date only.

So, to answer the original question directly, "YYYY-MM-DD" is required by ECMA-262 to be interpreted as UTC, while the other is interpreted as local. That's why:

This doesn't produce equivalent results:

console.log(new Date(Date.parse("Jul 8, 2005")).toString()); // Local
console.log(new Date(Date.parse("2005-07-08")).toString());  // UTC

This does:

console.log(new Date(Date.parse("Jul 8, 2005")).toString());
console.log(new Date(Date.parse("2005-07-08T00:00:00")).toString());

The bottom line is this for parsing date strings. The ONLY ISO 8601 string that you can safely parse across browsers is the long form with an offset (either ±HH:mm or "Z"). If you do that you can safely go back and forth between local and UTC time.

This works across browsers (after IE9):

console.log(new Date(Date.parse("2005-07-08T00:00:00Z")).toString());

Most current browsers do treat the other input formats equally, including the frequently used '1/1/1970' (M/D/YYYY) and '1/1/1970 00:00:00 AM' (M/D/YYYY hh:mm:ss ap) formats. All of the following formats (except the last) are treated as local time input in all browsers. The output of this code is the same in all browsers in my timezone. The last one is treated as -05:00 regardless of the host timezone because the offset is set in the timestamp:

console.log(Date.parse("1/1/1970"));
console.log(Date.parse("1/1/1970 12:00:00 AM"));
console.log(Date.parse("Thu Jan 01 1970"));
console.log(Date.parse("Thu Jan 01 1970 00:00:00"));
console.log(Date.parse("Thu Jan 01 1970 00:00:00 GMT-0500"));

However, since parsing of even the formats specified in ECMA-262 is not consistent, it is recommended to never rely on the built–in parser and to always manually parse strings, say using a library and provide the format to the parser.

E.g. in moment.js you might write:

let m = moment('1/1/1970', 'M/D/YYYY'); 

The Output Side

On the output side, all browsers translate time zones the same way but they handle the string formats differently. Here are the toString functions and what they output. Notice the toUTCString and toISOString functions output 5:00 AM on my machine. Also, the timezone name may be an abbreviation and may be different in different implementations.

Converts from UTC to Local time before printing

 - toString
 - toDateString
 - toTimeString
 - toLocaleString
 - toLocaleDateString
 - toLocaleTimeString

Prints the stored UTC time directly

 - toUTCString
 - toISOString 

In Chrome
toString            Thu Jan 01 1970 00:00:00 GMT-05:00 (Eastern Standard Time)
toDateString        Thu Jan 01 1970
toTimeString        00:00:00 GMT-05:00 (Eastern Standard Time)
toLocaleString      1/1/1970 12:00:00 AM
toLocaleDateString  1/1/1970
toLocaleTimeString  00:00:00 AM

toUTCString         Thu, 01 Jan 1970 05:00:00 GMT
toISOString         1970-01-01T05:00:00.000Z

In Firefox
toString            Thu Jan 01 1970 00:00:00 GMT-05:00 (Eastern Standard Time)
toDateString        Thu Jan 01 1970
toTimeString        00:00:00 GMT-0500 (Eastern Standard Time)
toLocaleString      Thursday, January 01, 1970 12:00:00 AM
toLocaleDateString  Thursday, January 01, 1970
toLocaleTimeString  12:00:00 AM

toUTCString         Thu, 01 Jan 1970 05:00:00 GMT
toISOString         1970-01-01T05:00:00.000Z

I normally don't use the ISO format for string input. The only time that using that format is beneficial to me is when dates need to be sorted as strings. The ISO format is sortable as-is while the others are not. If you have to have cross-browser compatibility, either specify the timezone or use a compatible string format.

The code new Date('12/4/2013').toString() goes through the following internal pseudo-transformation:

  "12/4/2013" -> toUCT -> [storage] -> toLocal -> print "12/4/2013"

I hope this answer was helpful.

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

To avoid having "pod install" reset only_active_arch for debug each time it's run, you can add the following to your pod file

# Append to your Podfile
post_install do |installer_representation|
    installer_representation.project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
        end
    end
end

Save internal file in my own internal folder in Android

The answer of Mintir4 is fine, I would also do the following to load the file.

FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";

while ((s = r.readLine()) != null) {
    txt += s;
}

r.close();

Passing command line arguments in Visual Studio 2010?

Visual Studio 2015:

Project => Your Application Properties. Each argument can be separated using space. If you have a space in between for the same argument, put double quotes as shown in the example below.

enter image description here

        static void Main(string[] args)
        {
            if(args == null || args.Length == 0)
            {
                Console.WriteLine("Please specify arguments!");
            }
            else
            {
                Console.WriteLine(args[0]);     // First
                Console.WriteLine(args[1]);     // Second Argument
            }
        }

How to convert datetime to integer in python

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))

General Function

To avoid that doing manually use below function

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))

How to convert List<string> to List<int>?

yourEnumList.Select(s => (int)s).ToList()

What is (x & 1) and (x >>= 1)?

These are Bitwise Operators (reference).

x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation.

x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift.

Note: The value of the most significant bit after the shift is zero for values of unsigned type. For values of signed type the most significant bit is copied from the sign bit of the value prior to shifting as part of sign extension, so the loop will never finish if x is a signed type, and the initial value is negative.

import httplib ImportError: No module named httplib

You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client.

You could try to run the 2to3 tool on your code, and try to have it translated automatically. References to httplib will automatically be rewritten to use http.client instead.

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

Communication between tabs or windows

I created a module that works equal to the official Broadcastchannel but has fallbacks based on localstorage, indexeddb and unix-sockets. This makes sure it always works even with Webworkers or NodeJS. See pubkey:BroadcastChannel

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

function setDate(){
    var now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    var timeToSet = now.toISOString().slice(0,16);

    /*
        If you have an element called "eventDate" like the following:

        <input type="datetime-local" name="eventdate" id="eventdate" />

        and you would like to  set the current and minimum time then use the following:
    */

    var elem = document.getElementById("eventDate");
    elem.value = timeToSet;
    elem.min = timeToSet;
}

Generating random integer from a range

If your compiler supports C++0x and using it is an option for you, then the new standard <random> header is likely to meet your needs. It has a high quality uniform_int_distribution which will accept minimum and maximum bounds (inclusive as you need), and you can choose among various random number generators to plug into that distribution.

Here is code that generates a million random ints uniformly distributed in [-57, 365]. I've used the new std <chrono> facilities to time it as you mentioned performance is a major concern for you.

#include <iostream>
#include <random>
#include <chrono>

int main()
{
    typedef std::chrono::high_resolution_clock Clock;
    typedef std::chrono::duration<double> sec;
    Clock::time_point t0 = Clock::now();
    const int N = 10000000;
    typedef std::minstd_rand G;
    G g;
    typedef std::uniform_int_distribution<> D;
    D d(-57, 365);
    int c = 0;
    for (int i = 0; i < N; ++i) 
        c += d(g);
    Clock::time_point t1 = Clock::now();
    std::cout << N/sec(t1-t0).count() << " random numbers per second.\n";
    return c;
}

For me (2.8 GHz Intel Core i5) this prints out:

2.10268e+07 random numbers per second.

You can seed the generator by passing in an int to its constructor:

    G g(seed);

If you later find that int doesn't cover the range you need for your distribution, this can be remedied by changing the uniform_int_distribution like so (e.g. to long long):

    typedef std::uniform_int_distribution<long long> D;

If you later find that the minstd_rand isn't a high enough quality generator, that can also easily be swapped out. E.g.:

    typedef std::mt19937 G;  // Now using mersenne_twister_engine

Having separate control over the random number generator, and the random distribution can be quite liberating.

I've also computed (not shown) the first 4 "moments" of this distribution (using minstd_rand) and compared them to the theoretical values in an attempt to quantify the quality of the distribution:

min = -57
max = 365
mean = 154.131
x_mean = 154
var = 14931.9
x_var = 14910.7
skew = -0.00197375
x_skew = 0
kurtosis = -1.20129
x_kurtosis = -1.20001

(The x_ prefix refers to "expected")

Global npm install location on windows?

These are typical npm paths if you install a package globally:

Windows XP -             %USERPROFILE%\Application Data\npm\node_modules
Newer Windows Versions - %AppData%\npm\node_modules
or -                     %AppData%\roaming\npm\node_modules

Java: Check the date format of current string is according to required format or not

For your case, you may use regex:

boolean checkFormat;

if (input.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))
    checkFormat=true;
else
   checkFormat=false;

For a larger scope or if you want a flexible solution, refer to MadProgrammer's answer.

Edit

Almost 5 years after posting this answer, I realize that this is a stupid way to validate a date format. But i'll just leave this here to tell people that using regex to validate a date is unacceptable

How to delete row based on cell value

if you want to delete rows based on some specific cell value. let suppose we have a file containing 10000 rows, and a fields having value of NULL. and based on that null value want to delete all those rows and records.

here are some simple tip. First open up Find Replace dialog, and on Replace tab, make all those cell containing NULL values with Blank. then press F5 and select the Blank option, now right click on the active sheet, and select delete, then option for Entire row.

it will delete all those rows based on cell value of containing word NULL.

php check if array contains all array values from another array

How about this:

function array_keys_exist($searchForKeys = array(), $searchableArray) {
    $searchableArrayKeys = array_keys($searchableArray);

    return count(array_intersect($searchForKeys, $searchableArrayKeys)) == count($searchForKeys); 
}

How to automatically update your docker containers, if base-images are updated

Another approach could be to assume that your base image gets behind quite quickly (and that's very likely to happen), and force another image build of your application periodically (e.g. every week) and then re-deploy it if it has changed.

As far as I can tell, popular base images like the official Debian or Java update their tags to cater for security fixes, so tags are not immutable (if you want a stronger guarantee of that you need to use the reference [image:@digest], available in more recent Docker versions). Therefore, if you were to build your image with docker build --pull, then your application should get the latest and greatest of the base image tag you're referencing.

Since mutable tags can be confusing, it's best to increment the version number of your application every time you do this so that at least on your side things are cleaner.

So I'm not sure that the script suggested in one of the previous answers does the job, since it doesn't rebuild you application's image - it just updates the base image tag and then it restarts the container, but the new container still references the old base image hash.

I wouldn't advocate for running cron-type jobs in containers (or any other processes, unless really necessary) as this goes against the mantra of running only one process per container (there are various arguments about why this is better, so I'm not going to go into it here).

How can I convert a hex string to a byte array?

Here's a nice fun LINQ example.

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

What is the largest TCP/IP network port number allowable for IPv4?

According to RFC 793, the port is a 16 bit unsigned int.

This means the range is 0 - 65535.

However, within that range, ports 0 - 1023 are generally reserved for specific purposes. I say generally because, apart from port 0, there is usually no enforcement of the 0-1023 reservation. TCP/UDP implementations usually don't enforce reservations apart from 0. You can, if you want to, run up a web server's TLS port on port 80, or 25, or 65535 instead of the standard 443. Likewise, even tho it is the standard that SMTP servers listen on port 25, you can run it on 80, 443, or others.

Most implementations reserve 0 for a specific purpose - random port assignment. So in most implementations, saying "listen on port 0" actually means "I don't care what port I use, just give me some random unassigned port to listen on".

So any limitation on using a port in the 0-65535 range, including 0, ephemeral reservation range etc, is implementation (i.e. OS/driver) specific, however all, including 0, are valid ports in the RFC 793.

Python: Get HTTP headers from urllib2.urlopen call?

urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).

Is returning out of a switch statement considered a better practice than using break?

A break will allow you continue processing in the function. Just returning out of the switch is fine if that's all you want to do in the function.

Changing nav-bar color after scrolling?

Slight variation to the above answers, but with Vanilla JS:

var nav = document.querySelector('nav'); // Identify target

window.addEventListener('scroll', function(event) { // To listen for event
    event.preventDefault();

    if (window.scrollY <= 150) { // Just an example
        nav.style.backgroundColor = '#000'; // or default color
    } else {
        nav.style.backgroundColor = 'transparent';
    }
});

DataTables fixed headers misaligned with columns in wide tables

Trigger DataTable search function after initializing DataTable with a blank string in it. It will automatically adjust misalignment of thead with tbody.

$( document ).ready(function()
{

    $('#monitor_data_voyage').DataTable( {
        scrollY:150,
        bSort:false,
        bPaginate:false,
        sScrollX: "100%",
        scrollX: true,
    } );

    setTimeout( function(){
       $('#monitor_data_voyage').DataTable().search( '' ).draw();
    }, 10 );

});

How do I install cURL on Windows?

You can also use CygWin and install the cURL package. It works very well and flawlessly!!

Renaming branches remotely in Git

I don't know why but @Sylvain Defresne's answer does not work for me.

git branch new-branch-name origin/old-branch-name
git push origin --set-upstream new-branch-name
git push origin :old-branch-name

I have to unset the upstream and then I can set the stream again. The following is how I did it.

git checkout -b new-branch-name
git branch --unset-upstream
git push origin new-branch-name -u
git branch origin :old-branch-name

Abort a Git Merge

Truth be told there are many, many resources explaining how to do this already out on the web:

Git: how to reverse-merge a commit?

Git: how to reverse-merge a commit?

Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)

So I guess I'll just summarize some of these:

  1. git revert <merge commit hash>
    This creates an extra "revert" commit saying you undid a merge

  2. git reset --hard <commit hash *before* the merge>
    This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick them on to afterwards.

But honestly this guide here is better than anything I can explain, with diagrams! :)

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

How can I export the schema of a database in PostgreSQL?

In Linux you can do like this

pg_dump -U postgres -s postgres > exportFile.dmp

Maybe it can work in Windows too, if not try the same with pg_dump.exe

pg_dump.exe -U postgres -s postgres > exportFile.dmp

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

Check whether the jars are imported properly. I imported them using build path. But it didn't recognise the jar in WAR/lib folder. Later, I copied the same jar to war/lib folder. It works fine now. You can refresh / clean your project.

How to get all properties values of a JavaScript Object (without knowing the keys)?

Depending on which browsers you have to support, this can be done in a number of ways. The overwhelming majority of browsers in the wild support ECMAScript 5 (ES5), but be warned that many of the examples below use Object.keys, which is not available in IE < 9. See the compatibility table.

ECMAScript 3+

If you have to support older versions of IE, then this is the option for you:

for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
        var val = obj[key];
        // use val
    }
}

The nested if makes sure that you don't enumerate over properties in the prototype chain of the object (which is the behaviour you almost certainly want). You must use

Object.prototype.hasOwnProperty.call(obj, key) // ok

rather than

obj.hasOwnProperty(key) // bad

because ECMAScript 5+ allows you to create prototypeless objects with Object.create(null), and these objects will not have the hasOwnProperty method. Naughty code might also produce objects which override the hasOwnProperty method.

ECMAScript 5+

You can use these methods in any browser that supports ECMAScript 5 and above. These get values from an object and avoid enumerating over the prototype chain. Where obj is your object:

var keys = Object.keys(obj);

for (var i = 0; i < keys.length; i++) {
    var val = obj[keys[i]];
    // use val
}

If you want something a little more compact or you want to be careful with functions in loops, then Array.prototype.forEach is your friend:

Object.keys(obj).forEach(function (key) {
    var val = obj[key];
    // use val
});

The next method builds an array containing the values of an object. This is convenient for looping over.

var vals = Object.keys(obj).map(function (key) {
    return obj[key];
});

// use vals array

If you want to make those using Object.keys safe against null (as for-in is), then you can do Object.keys(obj || {})....

Object.keys returns enumerable properties. For iterating over simple objects, this is usually sufficient. If you have something with non-enumerable properties that you need to work with, you may use Object.getOwnPropertyNames in place of Object.keys.

ECMAScript 2015+ (A.K.A. ES6)

Arrays are easier to iterate with ECMAScript 2015. You can use this to your advantage when working with values one-by–one in a loop:

for (const key of Object.keys(obj)) {
    const val = obj[key];
    // use val
}

Using ECMAScript 2015 fat-arrow functions, mapping the object to an array of values becomes a one-liner:

const vals = Object.keys(obj).map(key => obj[key]);

// use vals array

ECMAScript 2015 introduces Symbol, instances of which may be used as property names. To get the symbols of an object to enumerate over, use Object.getOwnPropertySymbols (this function is why Symbol can't be used to make private properties). The new Reflect API from ECMAScript 2015 provides Reflect.ownKeys, which returns a list of property names (including non-enumerable ones) and symbols.

Array comprehensions (do not attempt to use)

Array comprehensions were removed from ECMAScript 6 before publication. Prior to their removal, a solution would have looked like:

const vals = [for (key of Object.keys(obj)) obj[key]];

// use vals array

ECMAScript 2017+

ECMAScript 2016 adds features which do not impact this subject. The ECMAScript 2017 specification adds Object.values and Object.entries. Both return arrays (which will be surprising to some given the analogy with Array.entries). Object.values can be used as is or with a for-of loop.

const values = Object.values(obj);

// use values array or:

for (const val of Object.values(obj)) {
    // use val
}

If you want to use both the key and the value, then Object.entries is for you. It produces an array filled with [key, value] pairs. You can use this as is, or (note also the ECMAScript 2015 destructuring assignment) in a for-of loop:

for (const [key, val] of Object.entries(obj)) {
    // use key and val
}

Object.values shim

Finally, as noted in the comments and by teh_senaus in another answer, it may be worth using one of these as a shim. Don't worry, the following does not change the prototype, it just adds a method to Object (which is much less dangerous). Using fat-arrow functions, this can be done in one line too:

Object.values = obj => Object.keys(obj).map(key => obj[key]);

which you can now use like

// ['one', 'two', 'three']
var values = Object.values({ a: 'one', b: 'two', c: 'three' });

If you want to avoid shimming when a native Object.values exists, then you can do:

Object.values = Object.values || (obj => Object.keys(obj).map(key => obj[key]));

Finally...

Be aware of the browsers/versions you need to support. The above are correct where the methods or language features are implemented. For example, support for ECMAScript 2015 was switched off by default in V8 until recently, which powered browsers such as Chrome. Features from ECMAScript 2015 should be be avoided until the browsers you intend to support implement the features that you need. If you use babel to compile your code to ECMAScript 5, then you have access to all the features in this answer.

Make cross-domain ajax JSONP request with jQuery

You need to use the ajax-cross-origin plugin: http://www.ajax-cross-origin.com/

Just add the option crossOrigin: true

$.ajax({
    crossOrigin: true,
    url: url,
    success: function(data) {
        console.log(data);
    }
});

How do I pass the this context to a function?

Use function.call:

var f = function () { console.log(this); }
f.call(that, arg1, arg2, etc);

Where that is the object which you want this in the function to be.

How to draw circle in html page?

There is not technically a way to draw a circle with HTML (there isn’t a <circle> HTML tag), but a circle can be drawn.

The best way to draw one is to add border-radius: 50% to a tag such as div. Here’s an example:

<div style="width: 50px; height: 50px; border-radius: 50%;">You can put text in here.....</div>

What is the memory consumption of an object in Java?

Each object has a certain overhead for its associated monitor and type information, as well as the fields themselves. Beyond that, fields can be laid out pretty much however the JVM sees fit (I believe) - but as shown in another answer, at least some JVMs will pack fairly tightly. Consider a class like this:

public class SingleByte
{
    private byte b;
}

vs

public class OneHundredBytes
{
    private byte b00, b01, ..., b99;
}

On a 32-bit JVM, I'd expect 100 instances of SingleByte to take 1200 bytes (8 bytes of overhead + 4 bytes for the field due to padding/alignment). I'd expect one instance of OneHundredBytes to take 108 bytes - the overhead, and then 100 bytes, packed. It can certainly vary by JVM though - one implementation may decide not to pack the fields in OneHundredBytes, leading to it taking 408 bytes (= 8 bytes overhead + 4 * 100 aligned/padded bytes). On a 64 bit JVM the overhead may well be bigger too (not sure).

EDIT: See the comment below; apparently HotSpot pads to 8 byte boundaries instead of 32, so each instance of SingleByte would take 16 bytes.

Either way, the "single large object" will be at least as efficient as multiple small objects - for simple cases like this.

How to set margin of ImageView using code, not xml

You can use this method, in case you want to specify margins in dp:

private void addMarginsInDp(View view, int leftInDp, int topInDp, int rightInDp, int bottomInDp) {
    DisplayMetrics dm = view.getResources().getDisplayMetrics();
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    lp.setMargins(convertDpToPx(leftInDp, dm), convertDpToPx(topInDp, dm), convertDpToPx(rightInDp, dm), convertDpToPx(bottomInDp, dm));
    view.setLayoutParams(lp);
}

private int convertDpToPx(int dp, DisplayMetrics displayMetrics) {
    float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, displayMetrics);
    return Math.round(pixels);
}

How do I create a comma-separated list from an array in PHP?

I prefer to use an IF statement in the FOR loop that checks to make sure the current iteration isn't the last value in the array. If not, add a comma

$fruit = array("apple", "banana", "pear", "grape");

for($i = 0; $i < count($fruit); $i++){
    echo "$fruit[$i]";
    if($i < (count($fruit) -1)){
      echo ", ";
    }
}

Set Canvas size using javascript

Try this:

var setCanvasSize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}

JavaScript alert not working in Android WebView

As others indicated, setting the WebChromeClient is needed to get alert() to work. It's sufficient to just set the default WebChromeClient():

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient());

Thanks for all the comments below. Including John Smith's who indicated that you needed to enable JavaScript.

How to debug Google Apps Script (aka where does Logger.log log to?)

A little hacky, but I created an array called "console", and anytime I wanted to output to console I pushed to the array. Then whenever I wanted to see the actual output, I just returned console instead of whatever I was returning before.

    //return 'console' //uncomment to output console
    return "actual output";
}

How to get back Lost phpMyAdmin Password, XAMPP

You want to edit this file: "\xampp\phpMyAdmin\config.inc.php"

change this line:

$cfg['Servers'][$i]['password'] = 'WhateverPassword';

to whatever your password is. If you don't remember your password, then run this command in the Shell:

mysqladmin.exe -u root password WhateverPassword

where 'WhateverPassword' is your new password.

SQL Server: Query fast, but slow from procedure

I found the problem, here's the script of the slow and fast versions of the stored procedure:

dbo.ViewOpener__RenamedForCruachan__Slow.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
    @SessionGUID uniqueidentifier
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

dbo.ViewOpener__RenamedForCruachan__Fast.PRC

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
    @SessionGUID uniqueidentifier 
AS

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:

Slow: SET ANSI_NULLS OFF

Fast: SET ANSI_NULLS ON


This answer also could be made to make sense, since the view does have a join clause that says:

(table.column IS NOT NULL)

So there is some NULLs involved.


The explanation is further proved by returning to Query Analizer, and running

SET ANSI_NULLS OFF

.

DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'

.

SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank

And the query is slow.


So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off, rather than ANSI_NULLS on, which is QA's default.

Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS option in the stored procedure dialog:

Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....

What are the "standard unambiguous date" formats for string-to-date conversion in R?

Converting the date without specifying the current format can bring this error to you easily.

Here is an example:

sdate <- "2015.10.10"

Convert without specifying the Format:

date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".

Convert with specified Format:

date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.

How can I view the Git history in Visual Studio Code?

If you need to know the Commit history only, So don't use much Meshed up and bulky plugins,

I will recommend you a Basic simple plugin like "Git Commits"

I use it too :

https://marketplace.visualstudio.com/items?itemName=exelord.git-commits

Enjoy

How do I catch a numpy warning like it's an exception (not just for testing)?

To add a little to @Bakuriu's answer:

If you already know where the warning is likely to occur then it's often cleaner to use the numpy.errstate context manager, rather than numpy.seterr which treats all subsequent warnings of the same type the same regardless of where they occur within your code:

import numpy as np

a = np.r_[1.]
with np.errstate(divide='raise'):
    try:
        a / 0   # this gets caught and handled as an exception
    except FloatingPointError:
        print('oh no!')
a / 0           # this prints a RuntimeWarning as usual

Edit:

In my original example I had a = np.r_[0], but apparently there was a change in numpy's behaviour such that division-by-zero is handled differently in cases where the numerator is all-zeros. For example, in numpy 1.16.4:

all_zeros = np.array([0., 0.])
not_all_zeros = np.array([1., 0.])

with np.errstate(divide='raise'):
    not_all_zeros / 0.  # Raises FloatingPointError

with np.errstate(divide='raise'):
    all_zeros / 0.  # No exception raised

with np.errstate(invalid='raise'):
    all_zeros / 0.  # Raises FloatingPointError

The corresponding warning messages are also different: 1. / 0. is logged as RuntimeWarning: divide by zero encountered in true_divide, whereas 0. / 0. is logged as RuntimeWarning: invalid value encountered in true_divide. I'm not sure why exactly this change was made, but I suspect it has to do with the fact that the result of 0. / 0. is not representable as a number (numpy returns a NaN in this case) whereas 1. / 0. and -1. / 0. return +Inf and -Inf respectively, per the IEE 754 standard.

If you want to catch both types of error you can always pass np.errstate(divide='raise', invalid='raise'), or all='raise' if you want to raise an exception on any kind of floating point error.

How can I remove or replace SVG content?

I had two charts.

<div id="barChart"></div>
<div id="bubbleChart"></div>

This removed all charts.

d3.select("svg").remove(); 

This worked for removing the existing bar chart, but then I couldn't re-add the bar chart after

d3.select("#barChart").remove();

Tried this. It not only let me remove the existing bar chart, but also let me re-add a new bar chart.

d3.select("#barChart").select("svg").remove();

var svg = d3.select('#barChart')
       .append('svg')
       .attr('width', width + margins.left + margins.right)
       .attr('height', height + margins.top + margins.bottom)
       .append('g')
       .attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');

Not sure if this is the correct way to remove, and re-add a chart in d3. It worked in Chrome, but have not tested in IE.

IF statement: how to leave cell blank if condition is false ("" does not work)

To Validate data in column A for Blanks

Step 1: Step 1: B1=isblank(A1)

Step 2: Drag the formula for the entire column say B1:B100; This returns Ture or False from B1 to B100 depending on the data in column A

Step 3: CTRL+A (Selct all), CTRL+C (Copy All) , CRTL+V (Paste all as values)

Step4: Ctrl+F ; Find and replace function Find "False", Replace "leave this blank field" ; Find and Replace ALL

There you go Dude!

Jackson enum Serializing and DeSerializer

Actual Answer:

The default deserializer for enums uses .name() to deserialize, so it's not using the @JsonValue. So as @OldCurmudgeon pointed out, you'd need to pass in {"event": "FORGOT_PASSWORD"} to match the .name() value.

An other option (assuming you want the write and read json values to be the same)...

More Info:

There is (yet) another way to manage the serialization and deserialization process with Jackson. You can specify these annotations to use your own custom serializer and deserializer:

@JsonSerialize(using = MySerializer.class)
@JsonDeserialize(using = MyDeserializer.class)
public final class MyClass {
    ...
}

Then you have to write MySerializer and MyDeserializer which look like this:

MySerializer

public final class MySerializer extends JsonSerializer<MyClass>
{
    @Override
    public void serialize(final MyClass yourClassHere, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException
    {
        // here you'd write data to the stream with gen.write...() methods
    }

}

MyDeserializer

public final class MyDeserializer extends org.codehaus.jackson.map.JsonDeserializer<MyClass>
{
    @Override
    public MyClass deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException
    {
        // then you'd do something like parser.getInt() or whatever to pull data off the parser
        return null;
    }

}

Last little bit, particularly for doing this to an enum JsonEnum that serializes with the method getYourValue(), your serializer and deserializer might look like this:

public void serialize(final JsonEnum enumValue, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException
{
    gen.writeString(enumValue.getYourValue());
}

public JsonEnum deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException
{
    final String jsonValue = parser.getText();
    for (final JsonEnum enumValue : JsonEnum.values())
    {
        if (enumValue.getYourValue().equals(jsonValue))
        {
            return enumValue;
        }
    }
    return null;
}

Cannot find name 'require' after upgrading to Angular4

I added

"types": [ 
   "node"
]

in my tsconfig file and its worked for me tsconfig.json file look like

  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "es2015",
    "types": [ 
      "node",
      "underscore"
    ]
  },  

Check if argparse optional argument is set or not

A custom action can handle this problem. And I found that it is not so complicated.

is_set = set() #global set reference
class IsStored(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        is_set.add(self.dest) # save to global reference
        setattr(namespace, self.dest + '_set', True) # or you may inject directly to namespace
        setattr(namespace, self.dest, values) # implementation of store_action
        # You cannot inject directly to self.dest until you have a custom class


parser.add_argument("--myarg", type=int, default=1, action=IsStored)
params = parser.parse_args()
print(params.myarg, 'myarg' in is_set)
print(hasattr(params, 'myarg_set'))

How to activate "Share" button in android app?

in kotlin :

val sharingIntent = Intent(android.content.Intent.ACTION_SEND)
sharingIntent.type = "text/plain"
val shareBody = "Application Link : https://play.google.com/store/apps/details?id=${App.context.getPackageName()}"
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "App link")
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody)
startActivity(Intent.createChooser(sharingIntent, "Share App Link Via :"))

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

Well if you have given

@ManyToOne ()
   @JoinColumn (name = "countryId")
   private Country country;

then object of that class i mean Country need to be save first.

because it will only allow User to get saved into the database if there is key available for the Country of that user for the same. means it will allow user to be saved if and only if that country is exist into the Country table.

So for that you need to save that Country first into the table.

How to use LINQ to select object with minimum or maximum property value

I was looking for something similar myself, preferably without using a library or sorting the entire list. My solution ended up similar to the question itself, just simplified a bit.

var firstBorn = People.FirstOrDefault(p => p.DateOfBirth == People.Min(p2 => p2.DateOfBirth));

Security of REST authentication schemes

In fact, the original S3 auth does allow for the content to be signed, albeit with a weak MD5 signature. You can simply enforce their optional practice of including a Content-MD5 header in the HMAC (string to be signed).

http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html

Their new v4 authentication scheme is more secure.

http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html

Can Android Studio be used to run standard Java projects?

Tested in Android Studio 0.8.14:
I was able to get a standard project running with minimal steps in this way:

  • In an open Android Studio project, click File > New Module.
  • Click More Modules > Java Library > Next, then fill in whatever you prefer for the names.
  • A new module will appear as a folder on the same level as your "app" folder in the Project Structure. Open it and open the new Java class file.

    You can then add your code, and choose Build > Run 'YourClassName'. Presto, your code is running with no Android device!

  • Best way to format integer as string with leading zeros?

    You most likely just need to format your integer:

    '%0*d' % (fill, your_int)
    

    For example,

    >>> '%0*d' % (3, 4)
    '004'
    

    Two decimal places using printf( )

    What you want is %.2f, not 2%f.

    Also, you might want to replace your %d with a %f ;)

    #include <cstdio>
    int main()
    {
    printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
    return 0;
    }
    

    This will output:

    When this number: 94.945600 is assigned to 2 dp, it will be: 94.95

    See here for a full description of the printf formatting options: printf

    Can a CSV file have a comment?

    No, CSV doesn't specify any way of tagging comments - they will just be loaded by programs like Excel as additional cells containing text.

    The closest you can manage (with CSV being imported into a specific application such as Excel) is to define a special way of tagging comments that Excel will ignore. For Excel, you can "hide" the comment (to a limited degree) by embedding it into a formula. For example, try importing the following csv file into Excel:

    =N("This is a comment and will appear as a simple zero value in excel")
    John, Doe, 24
    

    You still end up with a cell in the spreadsheet that displays the number 0, but the comment is hidden.

    Alternatively, you can hide the text by simply padding it out with spaces so that it isn't displayed in the visible part of cell:

                                  This is a sort-of hidden comment!,
    John, Doe, 24
    

    Note that you need to follow the comment text with a comma so that Excel fills the following cell and thus hides any part of the text that doesn't fit in the cell.

    Nasty hacks, which will only work with Excel, but they may suffice to make your output look a little bit tidier after importing.

    CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

    Those error messages

    CMake Error at ... (project):
        No CMAKE_C_COMPILER could be found.
    -- Configuring incomplete, errors occurred!
    See also ".../CMakeFiles/CMakeOutput.log".
    See also ".../CMakeFiles/CMakeError.log".
    

    or

    CMake Error: your CXX compiler: "CMAKE_CXX_COMPILER-NOTFOUND" was not found.
    Please set CMAKE_CXX_COMPILER to a valid compiler path or name.
    ...
    -- Configuring incomplete, errors occurred!
    

    just mean that CMake was unable to find your C/CXX compiler to compile a simple test program (one of the first things CMake tries while detecting your build environment).

    The steps to find your problem are dependent on the build environment you want to generate. The following tutorials are a collection of answers here on Stack Overflow and some of my own experiences with CMake on Microsoft Windows 7/8/10 and Ubuntu 14.04.

    Preconditions

    • You have installed the compiler/IDE and it was able to once compile any other program (directly without CMake)
    • You have the latest CMake version
    • You have access rights on the drive you want CMake to generate your build environment
    • You have a clean build directory (because CMake does cache things from the last try) e.g. as sub-directory of your source tree

      Windows cmd.exe

      > rmdir /s /q VS2015
      > mkdir VS2015
      > cd VS2015
      

      Bash shell

      $ rm -rf MSYS
      $ mkdir MSYS
      $ cd MSYS
      

      and make sure your command shell points to your newly created binary output directory.

    General things you can/should try

    1. Is CMake able find and run with any/your default compiler? Run without giving a generator

      > cmake ..
      -- Building for: Visual Studio 14 2015
      ...
      

      Perfect if it correctly determined the generator to use - like here Visual Studio 14 2015

    2. What was it that actually failed?

      In the previous build output directory look at CMakeFiles\CMakeError.log for any error message that make sense to you or try to open/compile the test project generated at CMakeFiles\[Version]\CompilerIdC|CompilerIdCXX directly from the command line (as found in the error log).

    CMake can't find Visual Studio

    1. Try to select the correct generator version:

      > cmake --help
      > cmake -G "Visual Studio 14 2015" ..
      
    2. If that doesn't help, try to set the Visual Studio environment variables first (the path could vary):

      > "c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat"
      > cmake ..
      

      or use the Developer Command Prompt for VS2015 short-cut in your Windows Start Menu under All Programs/Visual Studio 2015/Visual Studio Tools (thanks at @Antwane for the hint).

    Background: CMake does support all Visual Studio releases and flavors (Express, Community, Professional, Premium, Test, Team, Enterprise, Ultimate, etc.). To determine the location of the compiler it uses a combination of searching the registry (e.g. at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[Version];InstallDir), system environment variables and - if none of the others did come up with something - plainly try to call the compiler.

    CMake can't find GCC (MinGW/MSys)

    1. You start the MSys bash shell with msys.bat and just try to directly call gcc

      $ gcc
      gcc.exe: fatal error: no input files
      compilation terminated.
      

      Here it did find gcc and is complaining that I didn't gave it any parameters to work with.

      So the following should work:

      $ cmake -G "MSYS Makefiles" ..
      -- The CXX compiler identification is GNU 4.8.1
      ...
      $ make
      

      If GCC was not found call export PATH=... to add your compilers path (see How to set PATH environment variable in CMake script?) and try again.

    2. If it's still not working, try to set the CXX compiler path directly by exporting it (path may vary)

      $ export CC=/c/MinGW/bin/gcc.exe
      $ export CXX=/c/MinGW/bin/g++.exe
      $ cmake -G "MinGW Makefiles" ..
      -- The CXX compiler identification is GNU 4.8.1
      ...
      $ mingw32-make
      

      For more details see How to specify new GCC path for CMake

      Note: When using the "MinGW Makefiles" generator you have to use the mingw32-make program distributed with MinGW

    3. Still not working? That's weird. Please make sure that the compiler is there and it has executable rights (see also preconditions chapter above).

      Otherwise the last resort of CMake is to not try any compiler search itself and set CMake's internal variables directly by

      $ cmake -DCMAKE_C_COMPILER=/c/MinGW/bin/gcc.exe -DCMAKE_CXX_COMPILER=/c/MinGW/bin/g++.exe ..
      

      For more details see Cmake doesn't honour -D CMAKE_CXX_COMPILER=g++ and Cmake error setting compiler

      Alternatively those variables can also be set via cmake-gui.exe on Windows. See Cmake cannot find compiler

    Background: Much the same as with Visual Studio. CMake supports all sorts of GCC flavors. It searches the environment variables (CC, CXX, etc.) or simply tries to call the compiler. In addition it will detect any prefixes (when cross-compiling) and tries to add it to all binutils of the GNU compiler toolchain (ar, ranlib, strip, ld, nm, objdump, and objcopy).

    Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

    There's a property that enables/disables in line media playback in the iOS web browser (if you were writing a native app, it would be the allowsInlineMediaPlayback property of a UIWebView). By default on iPhone this is set to NO, but on iPad it's set to YES.

    Fortunately for you, you can also adjust this behaviour in HTML as follows:

    <video id="myVideo" width="280" height="140" webkit-playsinline>

    ...that should hopefully sort it out for you. I don't know if it will work on your Android devices. It's a webkit property, so it might. Worth a go, anyway.

    Saving and loading objects and using pickle

    You can use anycache to do the job for you. Assuming you have a function myfunc which creates the instance:

    from anycache import anycache
    
    class Fruits:pass
    
    @anycache(cachedir='/path/to/your/cache')    
    def myfunc()
        banana = Fruits()
        banana.color = 'yellow'
        banana.value = 30
    return banana
    

    Anycache calls myfunc at the first time and pickles the result to a file in cachedir using an unique identifier (depending on the the function name and the arguments) as filename. On any consecutive run, the pickled object is loaded.

    If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.

    The function arguments are also taken into account. A refactored implementation works likewise:

    from anycache import anycache
    
    class Fruits:pass
    
    @anycache(cachedir='/path/to/your/cache')    
    def myfunc(color, value)
        fruit = Fruits()
        fruit.color = color
        fruit.value = value
    return fruit
    

    Find a string by searching all tables in SQL Server Management Studio 2008

    A bit late but hopefully useful.

    Why not try some of the third party tools that can be integrated into SSMS.

    I’ve worked with ApexSQL Search (100% free) with good success for both schema and data search and there is also SSMS tools pack that has this feature (not free for SQL 2012 but quite affordable).

    Stored procedure above is really great; it’s just that this is way more convenient in my opinion. Also, it would require some slight modifications if you want to search for datetime columns or GUID columns and such…

    How to check permissions of a specific directory?

    In GNU/Linux, try to use ls, namei, getfacl, stat.

    For Dir

    [flying@lempstacker ~]$ ls -ldh /tmp
    drwxrwxrwt. 23 root root 4.0K Nov  8 15:41 /tmp
    [flying@lempstacker ~]$ namei -l /tmp
    f: /tmp
    dr-xr-xr-x root root /
    drwxrwxrwt root root tmp
    [flying@lempstacker ~]$ getfacl /tmp
    getfacl: Removing leading '/' from absolute path names
    # file: tmp
    # owner: root
    # group: root
    # flags: --t
    user::rwx
    group::rwx
    other::rwx
    
    [flying@lempstacker ~]$ 
    

    or

    [flying@lempstacker ~]$ stat -c "%a" /tmp
    1777
    [flying@lempstacker ~]$ stat -c "%n %a" /tmp
    /tmp 1777
    [flying@lempstacker ~]$ stat -c "%A" /tmp
    drwxrwxrwt
    [flying@lempstacker ~]$ stat -c "%n %A" /tmp
    /tmp drwxrwxrwt
    [flying@lempstacker ~]$
    

    For file

    [flying@lempstacker ~]$ ls -lh /tmp/anaconda.log
    -rw-r--r-- 1 root root 0 Nov  8 08:31 /tmp/anaconda.log
    [flying@lempstacker ~]$ namei -l /tmp/anaconda.log
    f: /tmp/anaconda.log
    dr-xr-xr-x root root /
    drwxrwxrwt root root tmp
    -rw-r--r-- root root anaconda.log
    [flying@lempstacker ~]$ getfacl /tmp/anaconda.log
    getfacl: Removing leading '/' from absolute path names
    # file: tmp/anaconda.log
    # owner: root
    # group: root
    user::rw-
    group::r--
    other::r--
    
    [flying@lempstacker ~]$
    

    or

    [flying@lempstacker ~]$ stat -c "%a" /tmp/anaconda.log
    644
    [flying@lempstacker ~]$ stat -c "%n %a" /tmp/anaconda.log
    /tmp/anaconda.log 644
    [flying@lempstacker ~]$ stat -c "%A" /tmp/anaconda.log
    -rw-r--r--
    [flying@lempstacker ~]$ stat -c "%n %A" /tmp/anaconda.log
    /tmp/anaconda.log -rw-r--r--
    [flying@lempstacker ~]$
    

    Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

    It has to do with how much memory is available for AS to create a VM environment for your app to populate. The thing is that ever since the update to 2.2 I've had the same problem every time I try to create a new project in AS.

    How I solve it is by going into Project (on the left hand side) > Gradle Scripts > gradle.properties. When it opens the file go to the line under "(Line 10)# Specifies the JVM arguments used for the daemon process. (Line 11)# The setting is particularly useful for tweaking memory settings." You're looking for the line that starts with "org.gradle.jvmargs". This should be line 12. Change line 12 to this

    org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
    

    After changing this line you can either sync the gradle with the project by clicking Try again on the notification telling you the gradle sync failed (it'll be at the top of the file you opened). Or you can simply close and restart the AS and it should sync.

    Essentially what this is saying is for AS to allocate more memory to the app initialization. I know it's not a permanent fix but it should get you through actually starting your app.

    What is a singleton in C#?

    A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. The singleton premise is a pattern across software development.

    There is a C# implementation "Implementing the Singleton Pattern in C#" covering most of what you need to know - including some good advice regarding thread safety.

    To be honest, It's very rare that you need to implement a singleton - in my opinion it should be one of those things you should be aware of, even if it's not used too often.

    parsing a tab-separated file in Python

    Like this:

    >>> s='1\t2\t3\t4\t5'
    >>> [x for x in s.split('\t')]
    ['1', '2', '3', '4', '5']
    

    For a file:

    # create test file:
    >>> with open('tabs.txt','w') as o:
    ...    s='\n'.join(['\t'.join(map(str,range(i,i+10))) for i in [0,10,20,30]])
    ...    print >>o, s
    
    #read that file:
    >>> with open('tabs.txt','r') as f:
    ...    LoL=[x.strip().split('\t') for x in f]
    ... 
    >>> LoL
    [['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 
     ['10', '11', '12', '13', '14', '15', '16', '17', '18', '19'], 
     ['20', '21', '22', '23', '24', '25', '26', '27', '28', '29'], 
     ['30', '31', '32', '33', '34', '35', '36', '37', '38', '39']]
    >>> LoL[2][3]
    23
    

    If you want the input transposed:

    >>> with open('tabs.txt','r') as f:
    ...    LoT=zip(*(line.strip().split('\t') for line in f))
    ... 
    >>> LoT[2][3]
    '32'
    

    Or (better still) use the csv module in the default distribution...

    How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

    Another great option is the free V-Tools addin for Microsoft Access. Among other helpful tools it has a form to edit and save the Import/Export specifications.

    enter image description here

    enter image description here

    Note: As of version 1.83, there is a bug in enumerating the code pages on Windows 10. (Apparently due to a missing/changed API function in Windows 10) The tools still works great, you just need to comment out a few lines of code or step past it in the debug window.

    This has been a real life-saver for me in editing a complex import spec for our online orders.

    How to use opencv in using Gradle?

    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:0.5.+'
        }
    }
    apply plugin: 'android'
    
    repositories {
        mavenCentral()
        maven {
            url 'http://maven2.javacv.googlecode.com/git/'
        }
    }
    
    dependencies {
        compile 'com.android.support:support-v4:13.0.+'
        compile 'com.googlecode.javacv:javacv:0.5'
        instrumentTestCompile 'junit:junit:4.4'
    }
    
    android {
        compileSdkVersion 14
        buildToolsVersion "17.0.0"
    
        defaultConfig {
            minSdkVersion 7
            targetSdkVersion 14
        }
    }
    

    This is worked for me :)

    Getting number of days in a month

    You want DateTime.DaysInMonth:

    int days = DateTime.DaysInMonth(year, month);
    

    Obviously it varies by year, as sometimes February has 28 days and sometimes 29. You could always pick a particular year (leap or not) if you want to "fix" it to one value or other.

    what is the use of xsi:schemaLocation?

    The Java XML parser that spring uses will read the schemaLocation values and try to load them from the internet, in order to validate the XML file. Spring, in turn, intercepts those load requests and serves up versions from inside its own JAR files.

    If you omit the schemaLocation, then the XML parser won't know where to get the schema in order to validate the config.

    GCC fatal error: stdio.h: No such file or directory

    ubuntu users:

    sudo apt-get install libc6-dev

    specially ruby developers that have problem installing gem install json -v '1.8.2' on their VMs

    Convert Pandas Column to DateTime

    You can use the DataFrame method .apply() to operate on the values in Mycol:

    >>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
    >>> df
                        Mycol
    0  05SEP2014:00:00:00.000
    >>> import datetime as dt
    >>> df['Mycol'] = df['Mycol'].apply(lambda x: 
                                        dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
    >>> df
           Mycol
    0 2014-09-05
    

    Case-Insensitive List Search

    Below is the example of searching for a keyword in the whole list and remove that item:

    public class Book
    {
      public int BookId { get; set; }
      public DateTime CreatedDate { get; set; }
      public string Text { get; set; }
      public string Autor { get; set; }
      public string Source { get; set; }
    }
    

    If you want to remove a book that contains some keyword in the Text property, you can create a list of keywords and remove it from list of books:

    List<Book> listToSearch = new List<Book>()
       {
            new Book(){
                BookId = 1,
                CreatedDate = new DateTime(2014, 5, 27),
                Text = " test voprivreda...",
                Autor = "abc",
                Source = "SSSS"
    
            },
            new Book(){
                BookId = 2,
                CreatedDate = new DateTime(2014, 5, 27),
                Text = "here you go...",
                Autor = "bcd",
                Source = "SSSS"
    
    
            }
        };
    
    var blackList = new List<string>()
                {
                    "test", "b"
                }; 
    
    foreach (var itemtoremove in blackList)
        {
            listToSearch.RemoveAll(p => p.Source.ToLower().Contains(itemtoremove.ToLower()) || p.Source.ToLower().Contains(itemtoremove.ToLower()));
        }
    
    
    return listToSearch.ToList();
    

    Exit/save edit to sudoers file? Putty SSH

    Be careful to type exactly :wq as Wouter Verleur said at step 7. After type enter, you will save the changes and exit the visudo editor to bash.

    Check if a string is a date value

    I know it's an old question but I faced the same problem and saw that none of the answers worked properly - specifically weeding out numbers (1,200,345,etc..) from dates, which is the original question. Here is a rather unorthodox method I could think of and it seems to work. Please point out if there are cases where it will fail.

    if(sDate.toString() == parseInt(sDate).toString()) return false;
    

    This is the line to weed out numbers. Thus, the entire function could look like:

    _x000D_
    _x000D_
    function isDate(sDate) {  _x000D_
      if(sDate.toString() == parseInt(sDate).toString()) return false; _x000D_
      var tryDate = new Date(sDate);_x000D_
      return (tryDate && tryDate.toString() != "NaN" && tryDate != "Invalid Date");  _x000D_
    }_x000D_
    _x000D_
    console.log("100", isDate(100));_x000D_
    console.log("234", isDate("234"));_x000D_
    console.log("hello", isDate("hello"));_x000D_
    console.log("25 Feb 2018", isDate("25 Feb 2018"));_x000D_
    console.log("2009-11-10T07:00:00+0000", isDate("2009-11-10T07:00:00+0000"));
    _x000D_
    _x000D_
    _x000D_

    String comparison technique used by Python

    Take a look also at How do I sort unicode strings alphabetically in Python? where the discussion is about sorting rules given by the Unicode Collation Algorithm (http://www.unicode.org/reports/tr10/).

    To reply to the comment

    What? How else can ordering be defined other than left-to-right?

    by S.Lott, there is a famous counter-example when sorting French language. It involves accents: indeed, one could say that, in French, letters are sorted left-to-right and accents right-to-left. Here is the counter-example: we have e < é and o < ô, so you would expect the words cote, coté, côte, côté to be sorted as cote < coté < côte < côté. Well, this is not what happens, in fact you have: cote < côte < coté < côté, i.e., if we remove "c" and "t", we get oe < ôe < oé < ôé, which is exactly right-to-left ordering.

    And a last remark: you shouldn't be talking about left-to-right and right-to-left sorting but rather about forward and backward sorting.

    Indeed there are languages written from right to left and if you think Arabic and Hebrew are sorted right-to-left you may be right from a graphical point of view, but you are wrong on the logical level!

    Indeed, Unicode considers character strings encoded in logical order, and writing direction is a phenomenon occurring on the glyph level. In other words, even if in the word ???? the letter shin appears on the right of the lamed, logically it occurs before it. To sort this word one will first consider the shin, then the lamed, then the vav, then the mem, and this is forward ordering (although Hebrew is written right-to-left), while French accents are sorted backwards (although French is written left-to-right).

    How To Change DataType of a DataColumn in a DataTable?

    Puedes agregar una columna con tipo de dato distinto , luego copiar los datos y eliminar la columna anterior

    TB.Columns.Add("columna1", GetType(Integer))    
    TB.Select("id=id").ToList().ForEach(Sub(row) row("columna1") = row("columna2"))    
    TB.Columns.Remove("columna2")
    

    How to add an Access-Control-Allow-Origin header

    In your file.php of request ajax, can set value header.

    <?php header('Access-Control-Allow-Origin: *'); //for all ?>
    

    How do I get the name of the current executable in C#?

    Try this:

    System.Reflection.Assembly.GetExecutingAssembly()
    

    This returns you a System.Reflection.Assembly instance that has all the data you could ever want to know about the current application. I think that the Location property might get what you are after specifically.

    How do I compare strings in GoLang?

    == is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString do not contain "a", but "a\n" (if you look closely, you'll see the extra line break in your example output).

    You can use the strings.TrimRight function to remove trailing whitespaces from your input:

    if strings.TrimRight(input, "\n") == "a" {
        // ...
    }
    

    How to execute a function when page has fully loaded?

    The onload property of the GlobalEventHandlers mixin is an event handler for the load event of a Window, XMLHttpRequest, element, etc., which fires when the resource has loaded.

    So basically javascript already has onload method on window which get executed which page fully loaded including images...

    You can do something:

    var spinner = true;
    
    window.onload = function() {
      //whatever you like to do now, for example hide the spinner in this case
      spinner = false;
    };
    

    How to open a txt file and read numbers in Java

       try{
    
        BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
        String strLine;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
          // Print the content on the console
          System.out.println (strLine);
        }
        //Close the input stream
        in.close();
        }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
        }finally{
         in.close();
        }
    

    This will read line by line,

    If your no. are saperated by newline char. then in place of

     System.out.println (strLine);
    

    You can have

    try{
    int i = Integer.parseInt(strLine);
    }catch(NumberFormatException npe){
    //do something
    }  
    

    If it is separated by spaces then

    try{
        String noInStringArr[] = strLine.split(" ");
    //then you can parse it to Int as above
        }catch(NumberFormatException npe){
        //do something
        }  
    

    Find JavaScript function definition in Chrome

    You can print the function by evaluating the name of it in the console, like so

    > unknownFunc
    function unknownFunc(unknown) {
        alert('unknown seems to be ' + unknown);
    }
    

    this won't work for built-in functions, they will only display [native code] instead of the source code.

    EDIT: this implies that the function has been defined within the current scope.

    Changing SVG image color with javascript

    Your SVG must be inline in your document in order to be styled with CSS. This can be done by writing the SVG markup directly into your HTML code, or by using SVG injection, which replaces the img element with the content from and SVG file with Javascript.

    There is an open source library called SVGInject that does this for you. All you have to do is to add the attribute onload="SVGInject(this)" to you <img> tag.

    A simple example using SVGInject looks like this:

    <html>
      <head>
        <script src="svg-inject.min.js"></script>
      </head>
      <body>
        <img src="image.svg" onload="SVGInject(this)" />
      </body>
    </html>
    

    After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the SVG file provided in the src attribute.

    Passing a variable to a powershell script via command line

    Declare the parameter in test.ps1:

     Param(
                    [Parameter(Mandatory=$True,Position=1)]
                    [string]$input_dir,
                    [Parameter(Mandatory=$True)]
                    [string]$output_dir,
                    [switch]$force = $false
                    )
    

    Run the script from Run OR Windows Task Scheduler:

    powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"
    

    or,

     powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"
    

    How to do vlookup and fill down (like in Excel) in R?

    Solution #2 of @Ben's answer is not reproducible in other more generic examples. It happens to give the correct lookup in the example because the unique HouseType in houses appear in increasing order. Try this:

    hous <- read.table(header = TRUE,   stringsAsFactors = FALSE,   text="HouseType HouseTypeNo
      Semi            1
      ECIIsHome       17
      Single          2
      Row             3
      Single          2
      Apartment       4
      Apartment       4
      Row             3")
    
    largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)
    lookup <- unique(hous)
    

    Bens solution#2 gives

    housenames <- as.numeric(1:length(unique(hous$HouseType)))
    names(housenames) <- unique(hous$HouseType)
    base2 <- data.frame(HouseType = largetable$HouseType,
                        HouseTypeNo = (housenames[largetable$HouseType]))
    

    which when

    unique(base2$HouseTypeNo[ base2$HouseType=="ECIIsHome" ])
    [1] 2
    

    when the correct answer is 17 from the lookup table

    The correct way to do it is

     hous <- read.table(header = TRUE,   stringsAsFactors = FALSE,   text="HouseType HouseTypeNo
          Semi            1
          ECIIsHome       17
          Single          2
          Row             3
          Single          2
          Apartment       4
          Apartment       4
          Row             3")
    
    largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)
    
    housenames <- tapply(hous$HouseTypeNo, hous$HouseType, unique)
    base2 <- data.frame(HouseType = largetable$HouseType,
      HouseTypeNo = (housenames[largetable$HouseType]))
    

    Now the lookups are performed correctly

    unique(base2$HouseTypeNo[ base2$HouseType=="ECIIsHome" ])
    ECIIsHome 
           17
    

    I tried to edit Bens answer but it gets rejected for reasons I cannot understand.

    How to get JSON objects value if its name contains dots?

    What you want is:

    var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
    

    In JavaScript, any field you can access using the . operator, you can access using [] with a string version of the field name.

    Why shouldn't `&apos;` be used to escape single quotes?

    &apos; is not part of the HTML 4 standard.

    &quot; is, though, so is fine to use.

    Getting an object array from an Angular service

    Take a look at your code :

     getUsers(): Observable<User[]> {
            return Observable.create(observer => {
                this.http.get('http://users.org').map(response => response.json();
            })
        }
    

    and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

     getHeroes(): Promise<Hero[]> {
        return this.http.get(this.heroesUrl)
                   .toPromise()
                   .then(response => response.json().data as Hero[])
                   .catch(this.handleError);
      }
    

    The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

       return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json()
    

    Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

    ---EDIT----

    First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

    Try to do it like this:

      getUsers(): void {
            this.userService.getUsers()
                .then(users => {
                   this.users = users
                   console.log('this.users=' + this.users);
                });
    
    
        }
    

    See where the console.log(...) is!

    Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

    Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

    How do I directly modify a Google Chrome Extension File? (.CRX)

    I searched it in Google and I found this:

    The Google Chrome Extension file type is CRX. It is essentially a compression format. So if you want to see what is behind an extension, the scripts and the code, just change the file-type from “CRX” to “ZIP” .

    Unzip the file and you will get all the info you need. This way you can see the guts, learn how to write an extension yourself, or modify it for your own needs.

    Then you can pack it back up with Chrome’s internal tools which automatically create the file back into CRX. Installing it just requires a click.

    What is the syntax for adding an element to a scala.collection.mutable.Map?

    var map:Map[String, String] = Map()

    var map1 = map + ("red" -> "#FF0000")

    println(map1)

    Read pdf files with php

    your initial request is "I have a large PDF file that is a floor map for a building. "

    I am afraid to tell you this might be harder than you guess.

    Cause the last known lib everyones use to parse pdf is smalot, and this one is known to encounter issue regarding large file.

    Here too, Lookig for a real php lib to parse pdf, without any memory peak that need a php configuration to disable memory limit as lot of "developers" does (which I guess is really not advisable).

    see this post for more details about smalot performance : https://github.com/smalot/pdfparser/issues/163

    How to Query Database Name in Oracle SQL Developer?

    Edit: Whoops, didn't check your question tags before answering.

    Check that you can actually connect to DB (have the driver placed? tested the conn when creating it?).

    If so, try runnung those queries with F5

    Removing spaces from a variable input using PowerShell 4.0

    You also have the Trim, TrimEnd and TrimStart methods of the System.String class. The trim method will strip whitespace (with a couple of Unicode quirks) from the leading and trailing portion of the string while allowing you to optionally specify the characters to remove.

    #Note there are spaces at the beginning and end
    Write-Host " ! This is a test string !%^ "
     ! This is a test string !%^
    #Strips standard whitespace
    Write-Host " ! This is a test string !%^ ".Trim()
    ! This is a test string !%^
    #Strips the characters I specified
    Write-Host " ! This is a test string !%^ ".Trim('!',' ')
    This is a test string !%^
    #Now removing ^ as well
    Write-Host " ! This is a test string !%^ ".Trim('!',' ','^')
    This is a test string !%
    Write-Host " ! This is a test string !%^ ".Trim('!',' ','^','%')
    This is a test string
    #Powershell even casts strings to character arrays for you
    Write-Host " ! This is a test string !%^ ".Trim('! ^%')
    This is a test string
    

    TrimStart and TrimEnd work the same way just only trimming the start or end of the string.

    Add comma to numbers every three digits

    You can also look at the jquery FormatCurrency plugin (of which I am the author); it has support for multiple locales as well, but may have the overhead of the currency support that you don't need.

    $(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });
    

    PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

    I had this problem. Reinstalling the latest version of Adobe Reader did nothing. Adobe Reader worked in Chrome but not in IE. This worked for me ...

    1) Go to IE's Tools-->Compatibility View menu.
    2) Enter a website that has the PDF you wish to see. Click OK.
    3) Restart IE 4) Go to the website you entered and select the PDF. It should come up.
    5) Go back to Compatibility View and delete the entry you made.
    6) Adobe Reader works OK now in IE on all websites.

    It's a strange fix, but it worked for me. I needed to go through an Adobe acceptance screen after reinstall that only appeared after I did the Compatibility View trick. Once accepted, it seemed to work everywhere. Pretty flaky stuff. Hope this helps someone.

    Pass form data to another page with php

    The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

    index.php

    <html>
    <body>
    
    <form action="site2.php" method="post">
    Name: <input type="text" name="name">
    Email: <input type="text" name="email">
    <input type="submit">
    </form>
    
    </body>
    </html> 
    

    site2.php

     <html>
     <body>
    
     Hello <?php echo $_POST["name"]; ?>!<br>
     Your mail is <?php echo $_POST["mail"]; ?>.
    
     </body>
     </html> 
    

    output

    Hello "name" !

    Your email is "[email protected]" .

    Gradle: How to Display Test Results in the Console in Real Time?

    For those using Kotlin DSL, you can do:

    tasks {
      named<Test>("test") {
        testLogging.showStandardStreams = true
      }
    }
    

    Convert string to title case with JavaScript

    I think you should try with this function.

    var toTitleCase = function (str) {
        str = str.toLowerCase().split(' ');
        for (var i = 0; i < str.length; i++) {
            str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
        }
        return str.join(' ');
    };
    

    How to create a TextArea in Android

    Use TextView inside a ScrollView to display messages with any no.of lines. User can't edit the text in this view as in EditText.

    I think this is good for your requirement. Try it once.

    You can change the default color and text size in XML file only if you want to fix them as below:

    <TextView 
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="100px"
        android:textColor="#f00"
        android:textSize="25px"
        android:typeface="serif"
        android:textStyle="italic"/>
    

    or if you want to change dynamically whenever you want use as below:

    TextView textarea = (TextView)findViewById(R.id.tv);  // tv is id in XML file for TextView
    textarea.setTextSize(20);
    textarea.setTextColor(Color.rgb(0xff, 0, 0));
    textarea.setTypeface(Typeface.SERIF, Typeface.ITALIC);
    

    Extract first and last row of a dataframe in pandas

    The accepted answer duplicates the first row if the frame only contains a single row. If that's a concern

    df[0::len(df)-1 if len(df) > 1 else 1]

    works even for single row-dataframes.

    Example: For the following dataframe this will not create a duplicate:

    df = pd.DataFrame({'a': [1], 'b':['a']})
    df2 = df[0::len(df)-1 if len(df) > 1  else 1]
    
    print df2
    
       a  b
    0  1  a
    

    whereas this does:

    df3 = df.iloc[[0, -1]]
    
    print df3 
    
       a  b
    0  1  a
    0  1  a
    

    because the single row is the first AND last row at the same time.

    MySQL Fire Trigger for both Insert and Update

    unfortunately we can't use in MySQL after INSERT or UPDATE description, like in Oracle

    cannot call member function without object

    You are right - you declared a new use defined type (Name_pairs) and you need variable of that type to use it.

    The code should go like this:

    Name_pairs np;
    np.read_names()
    

    SyntaxError: missing ) after argument list

    For me, once there was a mistake in spelling of function

    For e.g. instead of

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

    I wrote

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

    So keep that also in check

    mysqli_fetch_array while loop columns

    Try this :

       $i = 0;    
        while($row = mysqli_fetch_array($result)) {  
    
                $posts['post_id'] = $row[$i]['post_id'];
                $posts['post_title'] = $row[$i]['post_title'];
                $posts['type'] = $row[$i]['type'];
                $posts['author'] = $row[$i]['author'];  
    
            }   
        $i++;
        }
    
    print_r($posts);
    

    SQL/mysql - Select distinct/UNIQUE but return all columns?

    You're looking for a group by:

    select *
    from table
    group by field1
    

    Which can occasionally be written with a distinct on statement:

    select distinct on field1 *
    from table
    

    On most platforms, however, neither of the above will work because the behavior on the other columns is unspecified. (The first works in MySQL, if that's what you're using.)

    You could fetch the distinct fields and stick to picking a single arbitrary row each time.

    On some platforms (e.g. PostgreSQL, Oracle, T-SQL) this can be done directly using window functions:

    select *
    from (
       select *,
              row_number() over (partition by field1 order by field2) as row_number
       from table
       ) as rows
    where row_number = 1
    

    On others (MySQL, SQLite), you'll need to write subqueries that will make you join the entire table with itself (example), so not recommended.

    Get WooCommerce product categories from WordPress

    Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:

    $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                echo  $sub_category->name ;
            }
    
        }
    

    with:

    $sub_cats = get_categories( $args2 );
                if($sub_cats) {
                    foreach($sub_cats as $sub_category) {
                        echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                    }
                }
    

    or if you also wish a counter for each subcategory, replace with this:

    $sub_cats = get_categories( $args2 );
                if($sub_cats) {
                    foreach($sub_cats as $sub_category) {
                        echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                        echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
                    }
                }
    

    Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

    You need to use a tool to view the HTTP headers sent with the file, something like LiveHTTPHeaders or HTTPFox are what I use. If the files are sent from the webserver without a MIME type, or with a default MIME type like text/plain, that might be what this error is about.

    How can I send emails through SSL SMTP with the .NET Framework?

    Try to check this free an open source alternative https://www.nuget.org/packages/AIM It is free to use and open source and uses the exact same way that System.Net.Mail is using To send email to implicit ssl ports you can use following code

    public static void SendMail()
    {    
        var mailMessage = new MimeMailMessage();
        mailMessage.Subject = "test mail";
        mailMessage.Body = "hi dude!";
        mailMessage.Sender = new MimeMailAddress("[email protected]", "your name");
        mailMessage.To.Add(new MimeMailAddress("[email protected]", "your friendd's name")); 
    // You can add CC and BCC list using the same way
        mailMessage.Attachments.Add(new MimeAttachment("your file address"));
    
    //Mail Sender (Smtp Client)
    
        var emailer = new SmtpSocketClient();
        emailer.Host = "your mail server address";
        emailer.Port = 465;
        emailer.SslType = SslMode.Ssl;
        emailer.User = "mail sever user name";
        emailer.Password = "mail sever password" ;
        emailer.AuthenticationMode = AuthenticationType.Base64;
        // The authentication types depends on your server, it can be plain, base 64 or none. 
    //if you do not need user name and password means you are using default credentials 
    // In this case, your authentication type is none            
        emailer.MailMessage = mailMessage;
        emailer.OnMailSent += new SendCompletedEventHandler(OnMailSent);
        emailer.SendMessageAsync();
    }
    
    // A simple call back function:
    private void OnMailSent(object sender, AsyncCompletedEventArgs asynccompletedeventargs)
    {
    if (e.UserState!=null)
        Console.Out.WriteLine(e.UserState.ToString());
    if (e.Error != null)
    {
        MessageBox.Show(e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    else if (!e.Cancelled)
    {
        MessageBox.Show("Send successfull!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    } 
    

    How to modify STYLE attribute of element with known ID using JQuery

    $("span").mouseover(function () {
    $(this).css({"background-color":"green","font-size":"20px","color":"red"});
    });
    
    <div>
    Sachin Tendulkar has been the most complete batsman of his time, the most prolific     runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting is based on the purest principles: perfect balance, economy of movement, precision in stroke-making.
    </div>
    

    Using Java 8 to convert a list of objects into a string obtained from the toString() method

    Also, you can do like this.

        List<String> list = Arrays.asList("One", "Two", "Three");
        String result = String.join(", ", list);
        System.out.println(result);
    

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

    Try these:

    1. Make sure that output path of project is correct (Project > Properties > Build > Output path)

    2. Go in menu to Build > Configuration Manager, and check if your main/entry project has checked Build. If not, check it.

    Where and why do I have to put the "template" and "typename" keywords?

    typedef typename Tail::inUnion<U> dummy;
    

    However, I'm not sure you're implementation of inUnion is correct. If I understand correctly, this class is not supposed to be instantiated, therefore the "fail" tab will never avtually fails. Maybe it would be better to indicates whether the type is in the union or not with a simple boolean value.

    template <typename T, typename TypeList> struct Contains;
    
    template <typename T, typename Head, typename Tail>
    struct Contains<T, UnionNode<Head, Tail> >
    {
        enum { result = Contains<T, Tail>::result };
    };
    
    template <typename T, typename Tail>
    struct Contains<T, UnionNode<T, Tail> >
    {
        enum { result = true };
    };
    
    template <typename T>
    struct Contains<T, void>
    {
        enum { result = false };
    };
    

    PS: Have a look at Boost::Variant

    PS2: Have a look at typelists, notably in Andrei Alexandrescu's book: Modern C++ Design

    Quickest way to convert a base 10 number to any base in .NET?

    If anyone is seeking a VB option, this was based on Pavel's answer:

    Public Shared Function ToBase(base10 As Long, Optional baseChars As String = "0123456789ABCDEFGHIJKLMNOPQRTSUVWXYZ") As String
    
        If baseChars.Length < 2 Then Throw New ArgumentException("baseChars must be at least 2 chars long")
    
        If base10 = 0 Then Return baseChars(0)
    
        Dim isNegative = base10 < 0
        Dim radix = baseChars.Length
        Dim index As Integer = 64 'because it's how long a string will be if the basechars are 2 long (binary)
        Dim chars(index) As Char '65 chars, 64 from above plus one for sign if it's negative
    
        base10 = Math.Abs(base10)
    
    
        While base10 > 0
            chars(index) = baseChars(base10 Mod radix)
            base10 \= radix
    
            index -= 1
        End While
    
        If isNegative Then
            chars(index) = "-"c
            index -= 1
        End If
    
        Return New String(chars, index + 1, UBound(chars) - index)
    
    End Function
    

    Commit only part of a file in Git

    With TortoiseGit:

    right click on the file and use Context Menu ? Restore after commit. This will create a copy of the file as it is. Then you can edit the file, e.g. in TortoiseGitMerge and undo all the changes you don't want to commit. After saving those changes you can commit the file.

    Vector of structs initialization

    You may also which to use aggregate initialization from a braced initialization list for situations like these.

    #include <vector>
    using namespace std;
    
    struct subject {
        string name;
        int    marks;
        int    credits;
    };
    
    int main() {
        vector<subject> sub {
          {"english", 10, 0},
          {"math"   , 20, 5}
        };
    }
    

    Sometimes however, the members of a struct may not be so simple, so you must give the compiler a hand in deducing its types.

    So extending on the above.

    #include <vector>
    using namespace std;
    
    struct assessment {
        int   points;
        int   total;
        float percentage;
    };
    
    struct subject {
        string name;
        int    marks;
        int    credits;
        vector<assessment> assessments;
    };
    
    int main() {
        vector<subject> sub {
          {"english", 10, 0, {
                                 assessment{1,3,0.33f},
                                 assessment{2,3,0.66f},
                                 assessment{3,3,1.00f}
                             }},
          {"math"   , 20, 5, {
                                 assessment{2,4,0.50f}
                             }}
        };
    }
    

    Without the assessment in the braced initializer the compiler will fail when attempting to deduce the type.

    The above has been compiled and tested with gcc in c++17. It should however work from c++11 and onward. In c++20 we may see the designator syntax, my hope is that it will allow for for the following

      {"english", 10, 0, .assessments{
                             {1,3,0.33f},
                             {2,3,0.66f},
                             {3,3,1.00f}
                         }},
    

    source: http://en.cppreference.com/w/cpp/language/aggregate_initialization

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

    I think it's a version problem, you just have to uninstall the old version of composer, then do a new installation of its new version.

     apt remove composer
    

    and follow the steps:

    1. download the composer from its official release site by making use of the following command.
     wget https://getcomposer.org/download/1.6.3/composer.phar
    
    1. Before you proceed with the installation, you should rename before you install and make it an executable file.
      mv composer.phar composer
    
      chmod +x composer
    
    1. Now install the package by making use the following command.
     ./composer
    
    1. The composer has been successfully installed now, make it access globally using the following command. for Ubuntu 16
     mv composer /usr/bin/
    

    for Ubuntu 18

     mv composer /usr/local/bin/
    

    Is try-catch like error handling possible in ASP Classic?

    For anytone who has worked in ASP as well as more modern languages, the question will provoke a chuckle. In my experience using a custom error handler (set up in IIS to handle the 500;100 errors) is the best option for ASP error handling. This article describes the approach and even gives you some sample code / database table definition.

    http://www.15seconds.com/issue/020821.htm

    Here is a link to Archive.org's version

    Make multiple-select to adjust its height to fit options without scroll bar

    Using the size attribute is the most practical solution, however there are quirks when it is applied to select elements with only two or three options.

    • Setting the size attribute value to "0" or "1" will mostly render a default select element (dropdown).
    • Setting the size attribute to a value greater than "1" will mostly render a selection list with a height capable of displaying at least four items. This also applies to lists with only two or three items, leading to unintended white-space.

    Simple JavaScript can be used to set the size attribute to the correct value automatically, e.g. see this fiddle.

    $(function() {
        $("#autoheight").attr("size", parseInt($("#autoheight option").length)); 
    });
    

    As mentioned above, this solution does not solve the issue when there are only two or three options.

    How do I view the SQL generated by the Entity Framework?

    Well, I am using Express profiler for that purpose at the moment, the drawback is that it only works for MS SQL Server. You can find this tool here: https://expressprofiler.codeplex.com/

    How to reset radiobuttons in jQuery so that none is checked

    In versions of jQuery before 1.6 use:

    $('input[name="correctAnswer"]').attr('checked', false);
    

    In versions of jQuery after 1.6 you should use:

    $('input[name="correctAnswer"]').prop('checked', false);
    

    but if you are using 1.6.1+ you can use the first form (see note 2 below).

    Note 1: it is important that the second argument be false and not "false" since "false" is not a falsy value. i.e.

    if ("false") {
        alert("Truthy value. You will see an alert");
    }
    

    Note 2: As of jQuery 1.6.0, there are now two similar methods, .attr and .prop that do two related but slightly different things. If in this particular case, the advice provide above works if you use 1.6.1+. The above will not work with 1.6.0, if you are using 1.6.0, you should upgrade. If you want the details, keep reading.

    Details: When working with straight HTML DOM elements, there are properties attached to the DOM element (checked, type, value, etc) which provide an interface to the running state of the HTML page. There is also the .getAttribute/.setAttribute interface which provides access to the HTML Attribute values as provided in the HTML. Before 1.6 jQuery blurred the distinction by providing one method, .attr, to access both types of values. jQuery 1.6+ provides two methods, .attr and .prop to get distinguish between these situations.

    .prop allows you to set a property on a DOM element, while .attr allows you to set an HTML attribute value. If you are working with plain DOM and set the checked property, elem.checked, to true or false you change the running value (what the user sees) and the value returned tracks the on page state. elem.getAttribute('checked') however only returns the initial state (and returns 'checked' or undefined depending on the initial state from the HTML). In 1.6.1+ using .attr('checked', false) does both elem.removeAttribute('checked') and elem.checked = false since the change caused a lot of backwards compatibility issues and it can't really tell if you wanted to set the HTML attribute or the DOM property. See more information in the documentation for .prop.

    What is the difference between vmalloc and kmalloc?

    Linux Kernel Development by Robert Love (Chapter 12, page 244 in 3rd edition) answers this very clearly.

    Yes, physically contiguous memory is not required in many of the cases. Main reason for kmalloc being used more than vmalloc in kernel is performance. The book explains, when big memory chunks are allocated using vmalloc, kernel has to map the physically non-contiguous chunks (pages) into a single contiguous virtual memory region. Since the memory is virtually contiguous and physically non-contiguous, several virtual-to-physical address mappings will have to be added to the page table. And in the worst case, there will be (size of buffer/page size) number of mappings added to the page table.

    This also adds pressure on TLB (the cache entries storing recent virtual to physical address mappings) when accessing this buffer. This can lead to thrashing.

    What's the difference between a POST and a PUT HTTP REQUEST?

    Both PUT and POST are Rest Methods .

    PUT - If we make the same request twice using PUT using same parameters both times, the second request will not have any effect. This is why PUT is generally used for the Update scenario,calling Update more than once with the same parameters doesn't do anything more than the initial call hence PUT is idempotent.

    POST is not idempotent , for instance Create will create two separate entries into the target hence it is not idempotent so CREATE is used widely in POST.

    Making the same call using POST with same parameters each time will cause two different things to happen, hence why POST is commonly used for the Create scenario

    CSS rotation cross browser with jquery.animate()

    Thanks yckart! Great contribution. I fleshed out your plugin a bit more. Added startAngle for full control and cross-browser css.

    $.fn.animateRotate = function(startAngle, endAngle, duration, easing, complete){
        return this.each(function(){
            var elem = $(this);
    
            $({deg: startAngle}).animate({deg: endAngle}, {
                duration: duration,
                easing: easing,
                step: function(now){
                    elem.css({
                      '-moz-transform':'rotate('+now+'deg)',
                      '-webkit-transform':'rotate('+now+'deg)',
                      '-o-transform':'rotate('+now+'deg)',
                      '-ms-transform':'rotate('+now+'deg)',
                      'transform':'rotate('+now+'deg)'
                    });
                },
                complete: complete || $.noop
            });
        });
    };
    

    Best way to restrict a text field to numbers only?

    I am using below in Angular to restrict character

    in HTML

    For Number Only

    <input
     type="text"
     id="score"
     (keypress) ="onInputChange($event,'[0-9]')"
     maxlength="3"
     class="form-control"> 
    

    for Alphabets Only

    <input
         type="text"
         id="state"
         (keypress) ="onInputChange($event,'[a-zA-Z]')"
         maxlength="3"
         class="form-control"> 
    

    In TypeScript

     onInputChange(event: any, inpPattern:string): void {   
            var input = event.key; 
            if(input.match(inpPattern)==null){
             event.preventDefault();
            }
          }
    

    How to run a maven created jar file using just the command line

    Use this command.

    mvn package
    

    to make the package jar file. Then, run this command.

    java -cp target/artifactId-version-SNAPSHOT.jar package.Java-Main-File-Name
    

    after mvn package command. Target folder with classes, test classes, jar file and other resources folder and files will be created.

    type your own artifactId, version and package and java main file.

    How do I download NLTK data?

    you should add python to your PATH during installation of python...after installation.. open cmd prompt type command-pip install nltk then go to IDLE and open a new file..save it as file.py..then open file.py type the following: import nltk

    nltk.download()
    

    Best place to insert the Google Analytics code

    Yes, it is recommended to put the GA code in the footer anyway, as the page shouldnt count as a page visit until its read all the markup.

    javascript createElement(), style problem

    yourElement.setAttribute("style", "background-color:red; font-size:2em;");
    

    Or you could write the element as pure HTML and use .innerHTML = [raw html code]... that's very ugly though.

    In answer to your first question, first you use var myElement = createElement(...);, then you do document.body.appendChild(myElement);.

    Tomcat request timeout

    You can set the default time out in the server.xml

    <Connector URIEncoding="UTF-8" 
        acceptCount="100" 
        connectionTimeout="20000" 
        disableUploadTimeout="true" 
        enableLookups="false" 
        maxHttpHeaderSize="8192" 
        maxSpareThreads="75" 
        maxThreads="150" 
        minSpareThreads="25" 
        port="7777" 
        redirectPort="8443"/>
    

    How to count the occurrence of certain item in an ndarray?

    You can use dictionary comprehension to create a neat one-liner. More about dictionary comprehension can be found here

    >>>counts = {int(value): list(y).count(value) for value in set(y)}
    >>>print(counts)
    {0: 8, 1: 4}
    

    This will create a dictionary with the values in your ndarray as keys, and the counts of the values as the values for the keys respectively.

    This will work whenever you want to count occurences of a value in arrays of this format.

    How to pass a textbox value from view to a controller in MVC 4?

    When you want to pass new information to your application, you need to use POST form. In Razor you can use the following

    View Code:

    @* By default BeginForm use FormMethod.Post *@
    @using(Html.BeginForm("Update")){
         @Html.Hidden("id", Model.Id)
         @Html.Hidden("productid", Model.ProductId)
         @Html.TextBox("qty", Model.Quantity)
         @Html.TextBox("unitrate", Model.UnitRate)
         <input type="submit" value="Update" />
    }
    

    Controller's actions

    [HttpGet]
    public ActionResult Update(){
         //[...] retrive your record object
         return View(objRecord);
    }
    
    [HttpPost]
    public ActionResult Update(string id, string productid, int qty, decimal unitrate)
    {
          if (ModelState.IsValid){
               int _records = UpdatePrice(id,productid,qty,unitrate);
               if (_records > 0){                    {
                  return RedirectToAction("Index1", "Shopping");
               }else{                   
                    ModelState.AddModelError("","Can Not Update");
               }
          }
          return View("Index1");
     }
    

    Note that alternatively, if you want to use @Html.TextBoxFor(model => model.Quantity) you can either have an input with the name (respectecting case) "Quantity" or you can change your POST Update() to receive an object parameter, that would be the same type as your strictly typed view. Here's an example:

    Model

    public class Record {
        public string Id { get; set; }
        public string ProductId { get; set; }
        public string Quantity { get; set; }
        public decimal UnitRate { get; set; }
    }
    

    View

    @using(Html.BeginForm("Update")){
         @Html.HiddenFor(model => model.Id)
         @Html.HiddenFor(model => model.ProductId)
         @Html.TextBoxFor(model=> model.Quantity)
         @Html.TextBoxFor(model => model.UnitRate)
         <input type="submit" value="Update" />
    }
    

    Post Action

    [HttpPost]
    public ActionResult Update(Record rec){ //Alternatively you can also use FormCollection object as well 
       if(TryValidateModel(rec)){
            //update code
       }
       return View("Index1");
    }
    

    File loading by getClass().getResource()

    The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):

    public static File getResourceAsFile(String resourcePath) {
        try {
            InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
            if (in == null) {
                return null;
            }
    
            File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
            tempFile.deleteOnExit();
    
            try (FileOutputStream out = new FileOutputStream(tempFile)) {
                //copy stream
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }
            return tempFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    

    Creating a select box with a search option

    This will work for most of us. The answer given by Hemanth Palle is the easiest way to do it, It worked for me and the JS code wasn't necessary. The only problem that I've found is that according to W3Schools, The datalist tag is not supported in Internet Explorer 9 and earlier versions, or in Safari.

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
    <input list="browsers">
    <datalist id="browsers">
      <option value="Internet Explorer">
      <option value="Firefox">
      <option value="Chrome">
      <option value="Opera">
      <option value="Safari">
    </datalist>  
    </body>
    </html>
    

    Java substring: 'string index out of range'

    I"m guessing i'm getting this error because the string is trying to substring a Null value. But wouldn't the ".length() > 0" part eliminate that issue?

    No, calling itemdescription.length() when itemdescription is null would not generate a StringIndexOutOfBoundsException, but rather a NullPointerException since you would essentially be trying to call a method on null.

    As others have indicated, StringIndexOutOfBoundsException indicates that itemdescription is not at least 38 characters long. You probably want to handle both conditions (I assuming you want to truncate):

    final String value;
    if (itemdescription == null || itemdescription.length() <= 0) {
        value = "_";
    } else if (itemdescription.length() <= 38) {
        value = itemdescription;
    } else { 
        value = itemdescription.substring(0, 38);
    }
    pstmt2.setString(3, value);
    

    Might be a good place for a utility function if you do that a lot...

    Using Rsync include and exclude options to include directory and file by pattern

    The problem is that --exclude="*" says to exclude (for example) the 1260000000/ directory, so rsync never examines the contents of that directory, so never notices that the directory contains files that would have been matched by your --include.

    I think the closest thing to what you want is this:

    rsync -nrv --include="*/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/
    

    (which will include all directories, and all files matching file_11*.jpg, but no other files), or maybe this:

    rsync -nrv --include="/[0-9][0-9][0-9]0000000/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/
    

    (same concept, but much pickier about the directories it will include).

    Is there an equivalent to background-size: cover and contain for image elements?

    I found a simple solution to emulate both cover and contain, which is pure CSS, and works for containers with dynamic dimensions, and also doesn't make any restriction on the image ratio.

    Note that if you don't need to support IE, or Edge before 16, then you better use object-fit.

    background-size: cover

    _x000D_
    _x000D_
    .img-container {_x000D_
      position: relative;_x000D_
      overflow: hidden;_x000D_
    }_x000D_
    _x000D_
    .background-image {_x000D_
      position: absolute;_x000D_
      min-width: 1000%;_x000D_
      min-height: 1000%;_x000D_
      left: 50%;_x000D_
      top: 50%;_x000D_
      transform: translateX(-50%) translateY(-50%) scale(0.1);_x000D_
      z-index: -1;_x000D_
    }
    _x000D_
    <div class="img-container">_x000D_
      <img class="background-image" src="https://picsum.photos/1024/768/?random">_x000D_
      <p style="padding: 20px; color: white; text-shadow: 0 0 10px black">_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
      </p>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    The 1000% is used here in case the image natural size is bigger than the size it is being displayed. For example, if the image is 500x500, but the container is only 200x200. With this solution, the image will be resized to 2000x2000 (due to min-width/min-height), then scaled down to 200x200 (due to transform: scale(0.1)).

    The x10 factor can be replaced by x100 or x1000, but it is usually not ideal to have a 2000x2000 image being rendered on a 20x20 div. :)

    background-size: contain

    Following the same principle, you can also use it to emulate background-size: contain:

    _x000D_
    _x000D_
    .img-container {_x000D_
      position: relative;_x000D_
      overflow: hidden;_x000D_
      z-index: 0;_x000D_
    }_x000D_
    _x000D_
    .background-image {_x000D_
      position: absolute;_x000D_
      max-width: 10%;_x000D_
      max-height: 10%;_x000D_
      left: 50%;_x000D_
      top: 50%;_x000D_
      transform: translateX(-50%) translateY(-50%) scale(10);_x000D_
      z-index: -1;_x000D_
    }
    _x000D_
    <div style="background-color: black">_x000D_
      <div class="img-container">_x000D_
        <img class="background-image" src="https://picsum.photos/1024/768/?random">_x000D_
        <p style="padding: 20px; color: white; text-shadow: 0 0 10px black">_x000D_
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
        </p>_x000D_
      </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Getting the last revision number in SVN?

    Someone else beat me to posting the answer about svnversion, which is definitely the best solution if you have a working copy (IIRC, it doesn't work with URLs). I'll add this: if you're on the server hosting SVN, the best way is to use the svnlook command. This is the command you use when writing a hook script to inspect the repository (and even the current transaction, in the case of pre-commit hooks). You can type svnlook help for details. You probably want to use the svnlook youngest command. Note that it requires direct access to the repo directory, so it must be used on the server.

    "Fatal error: Unable to find local grunt." when running "grunt" command

    This solved the issue for me. I mistakenly installed grunt using:

    sudo npm install -g grunt --save-dev
    

    and then ran the following command in the project folder:

    npm install
    

    This resulted in the error seen by the author of the question. I then uninstalled grunt using:

    sudo npm uninstall -g grunt
    

    Deleted the node_modules folder. And reinstalled grunt using:

    npm install grunt --save-dev
    

    and running the following in the project folder:

    npm install
    

    For some odd reason when you global install grunt using -g and then uninstall it, the node_modules folder holds on to something that prevents grunt from being installed locally to the project folder.

    Using C# to check if string contains a string in string array

    You can try this solution as well.

    string[] nonSupportedExt = { ".3gp", ".avi", ".opus", ".wma", ".wav", ".m4a", ".ac3", ".aac", ".aiff" };
            
    bool valid = Array.Exists(nonSupportedExt,E => E == ".Aac".ToLower());
    

    C# binary literals

    C# 7.0 supports binary literals (and optional digit separators via underscore characters).

    An example:

    int myValue = 0b0010_0110_0000_0011;
    

    You can also find more information on the Roslyn GitHub page.

    Get all validation errors from Angular 2 FormGroup

    Or you can just use this library to get all errors, even from deep and dynamic forms.

    npm i @naologic/forms
    

    If you want to use the static function on your own forms

    import {NaoFormStatic} from '@naologic/forms';
    ...
    const errorsFlat = NaoFormStatic.getAllErrorsFlat(fg); 
    console.log(errorsFlat);
    

    If you want to use NaoFromGroup you can import and use it

    import {NaoFormGroup, NaoFormControl, NaoValidators} from '@naologic/forms';
    ...
        this.naoFormGroup = new NaoFormGroup({
          firstName: new NaoFormControl('John'),
          lastName: new NaoFormControl('Doe'),
          ssn: new NaoFormControl('000 00 0000', NaoValidators.isSSN()),
        });
    
       const getFormErrors = this.naoFormGroup.getAllErrors();
       console.log(getFormErrors);
       // --> {first: {ok: false, isSSN: false, actualValue: "000 00 0000"}}
    

    Read the full documentation

    How can I search for a multiline pattern in a file?

    Why don't you go for awk:

    awk '/Start pattern/,/End pattern/' filename
    

    How to add option to select list in jQuery

    It looks like you want this pluging as it follows your existing code, maybe the plug in js file got left out somewhere.

    http://www.texotela.co.uk/code/jquery/select/

    var myOptions = {
    "Value 1" : "Text 1",
    "Value 2" : "Text 2",
    "Value 3" : "Text 3"
    } 
    $("#myselect2").addOption(myOptions, false); 
    // use true if you want to select the added options » Run
    

    Count distinct value pairs in multiple columns in SQL

    You can also do something like:

    SELECT COUNT(DISTINCT id + name + address) FROM mytable
    

    How do I add a library project to Android Studio?

    1. Press F4 to show Project Structure, click libraries or Global libraries, and click + to add the JAR file.
    2. Click Modules what you want add jar, select the Dependencies tab, click +, and add Library.

    MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

    That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.

    Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431

    update columns values with column of another table based on condition

    This will surely work:

    UPDATE table1
    SET table1.price=(SELECT table2.price
      FROM table2
      WHERE table2.id=table1.id AND table2.item=table1.item);
    

    How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

    You cannot do so - the browser will not allow this because of security concerns.

    When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.

    The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.

    And other

    You missed ); this at the end of the change event function.

    Also do not create function for change event instead just use it as below,

    <script type="text/javascript">
    
        $(function()
        {
            $('#fileUpload').on('change',function ()
            {
                var filePath = $(this).val();
                console.log(filePath);
            });
        });
    
    </script>
    

    How do I run Redis on Windows?

    Latest Redis x86 builds (32-bit) can be found here: http://bitsandpieces.it/redis-x86-32bit-builds-for-windows

    Says that he will maintain both 2.8.* and 3.0.* branches.

    Why is $$ returning the same id as the parent process?

    Try getppid() if you want your C program to print your shell's PID.

    Rails: select unique values from a column

    Model.select(:rating).distinct
    

    Does C have a string type?

    C does not support a first class string type.

    C++ has std::string

    Symfony - generate url with parameter in controller

    If you want absolute urls, you have the third parameter.

    $product_url = $this->generateUrl('product_detail', 
        array(
            'slug' => 'slug'
        ),
        UrlGeneratorInterface::ABSOLUTE_URL
    );
    

    Remember to include UrlGeneratorInterface.

    use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
    

    CSS Disabled scrolling

    I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype

    Change select box option background color

    Another option is to use Javascript:

    if (document.getElementById('selectID').value == '1') {
           document.getElementById('optionID').style.color = '#000';
    

    (Not as clean as the CSS attribute selector, but more powerful)

    Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

    Good to see someone's chimed in about Lucene - because I've no idea about that.

    Sphinx, on the other hand, I know quite well, so let's see if I can be of some help.

    • Result relevance ranking is the default. You can set up your own sorting should you wish, and give specific fields higher weightings.
    • Indexing speed is super-fast, because it talks directly to the database. Any slowness will come from complex SQL queries and un-indexed foreign keys and other such problems. I've never noticed any slowness in searching either.
    • I'm a Rails guy, so I've no idea how easy it is to implement with Django. There is a Python API that comes with the Sphinx source though.
    • The search service daemon (searchd) is pretty low on memory usage - and you can set limits on how much memory the indexer process uses too.
    • Scalability is where my knowledge is more sketchy - but it's easy enough to copy index files to multiple machines and run several searchd daemons. The general impression I get from others though is that it's pretty damn good under high load, so scaling it out across multiple machines isn't something that needs to be dealt with.
    • There's no support for 'did-you-mean', etc - although these can be done with other tools easily enough. Sphinx does stem words though using dictionaries, so 'driving' and 'drive' (for example) would be considered the same in searches.
    • Sphinx doesn't allow partial index updates for field data though. The common approach to this is to maintain a delta index with all the recent changes, and re-index this after every change (and those new results appear within a second or two). Because of the small amount of data, this can take a matter of seconds. You will still need to re-index the main dataset regularly though (although how regularly depends on the volatility of your data - every day? every hour?). The fast indexing speeds keep this all pretty painless though.

    I've no idea how applicable to your situation this is, but Evan Weaver compared a few of the common Rails search options (Sphinx, Ferret (a port of Lucene for Ruby) and Solr), running some benchmarks. Could be useful, I guess.

    I've not plumbed the depths of MySQL's full-text search, but I know it doesn't compete speed-wise nor feature-wise with Sphinx, Lucene or Solr.

    How to specify test directory for mocha?

    This doesn't seem to be any "easy" support for changing test directory.
    However, maybe you should take a look at this issue, relative to your question.

    How to make the first option of <select> selected with jQuery

    Use:

    $("#selectbox option:first").val()
    

    Please find the working simple in this JSFiddle.

    Cannot open include file 'afxres.h' in VC2010 Express

    You can also try replace afxres.h with WinResrc.h

    How to display HTML tags as plain text

    You can use htmlentities when echoing to the browser, this will show the tag rather than have html interpret it.

    See here http://uk3.php.net/manual/en/function.htmlentities.php

    Example:

     echo htmlentities("<strong>Look just like this line - so then know how to type it</strong>"); 
    

    Output:

    <strong>Look just like this line - so then know how to type it</strong>
    

    javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

    The algorithm you are using, "AES", is a shorthand for "AES/ECB/NoPadding". What this means is that you are using the AES algorithm with 128-bit key size and block size, with the ECB mode of operation and no padding.

    In other words: you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception.

    If you want to encrypt data in sizes that are not multiple of 16 bytes, you are either going to have to use some kind of padding, or a cipher-stream. For instance, you could use CBC mode (a mode of operation that effectively transforms a block cipher into a stream cipher) by specifying "AES/CBC/NoPadding" as the algorithm, or PKCS5 padding by specifying "AES/ECB/PKCS5", which will automatically add some bytes at the end of your data in a very specific format to make the size of the ciphertext multiple of 16 bytes, and in a way that the decryption algorithm will understand that it has to ignore some data.

    In any case, I strongly suggest that you stop right now what you are doing and go study some very introductory material on cryptography. For instance, check Crypto I on Coursera. You should understand very well the implications of choosing one mode or another, what are their strengths and, most importantly, their weaknesses. Without this knowledge, it is very easy to build systems which are very easy to break.


    Update: based on your comments on the question, don't ever encrypt passwords when storing them at a database!!!!! You should never, ever do this. You must HASH the passwords, properly salted, which is completely different from encrypting. Really, please, don't do what you are trying to do... By encrypting the passwords, they can be decrypted. What this means is that you, as the database manager and who knows the secret key, you will be able to read every password stored in your database. Either you knew this and are doing something very, very bad, or you didn't know this, and should get shocked and stop it.

    How do I inject a controller into another controller in AngularJS

    I'd suggest the question you should be asking is how to inject services into controllers. Fat services with skinny controllers is a good rule of thumb, aka just use controllers to glue your service/factory (with the business logic) into your views.

    Controllers get garbage collected on route changes, so for example, if you use controllers to hold business logic that renders a value, your going to lose state on two pages if the app user clicks the browser back button.

    var app = angular.module("testApp", ['']);
    
    app.factory('methodFactory', function () {
        return { myMethod: function () {
                console.log("methodFactory - myMethod");
        };
    };
    
    app.controller('TestCtrl1', ['$scope', 'methodFactory', function ($scope,methodFactory) {  //Comma was missing here.Now it is corrected.
        $scope.mymethod1 = methodFactory.myMethod();
    }]);
    
    app.controller('TestCtrl2', ['$scope', 'methodFactory', function ($scope, methodFactory) {
        $scope.mymethod2 = methodFactory.myMethod();
    }]);
    

    Here is a working demo of factory injected into two controllers

    Also, I'd suggest having a read of this tutorial on services/factories.

    How to check if the string is empty?

    Responding to @1290. Sorry, no way to format blocks in comments. The None value is not an empty string in Python, and neither is (spaces). The answer from Andrew Clark is the correct one: if not myString. The answer from @rouble is application-specific and does not answer the OP's question. You will get in trouble if you adopt a peculiar definition of what is a "blank" string. In particular, the standard behavior is that str(None) produces 'None', a non-blank string.

    However if you must treat None and (spaces) as "blank" strings, here is a better way:

    class weirdstr(str):
        def __new__(cls, content):
            return str.__new__(cls, content if content is not None else '')
        def __nonzero__(self):
            return bool(self.strip())
    

    Examples:

    >>> normal = weirdstr('word')
    >>> print normal, bool(normal)
    word True
    
    >>> spaces = weirdstr('   ')
    >>> print spaces, bool(spaces)
        False
    
    >>> blank = weirdstr('')
    >>> print blank, bool(blank)
     False
    
    >>> none = weirdstr(None)
    >>> print none, bool(none)
     False
    
    >>> if not spaces:
    ...     print 'This is a so-called blank string'
    ... 
    This is a so-called blank string
    

    Meets the @rouble requirements while not breaking the expected bool behavior of strings.

    PHP string "contains"

    PHP 8 or newer:

    Use the str_contains function.

    if (str_contains($str, "."))
    {
        echo 'Found it';
    }
    
    else
    {
        echo 'Not found.';
    }
    

    PHP 7 or older:

    if (strpos($str, '.') !== FALSE)
    {
        echo 'Found it';
    }
    
    else
    {
        echo 'Not found.';
    }
    

    Note that you need to use the !== operator. If you use != or <> and the '.' is found at position 0, the comparison will evaluate to true because 0 is loosely equal to false.

    "Android library projects cannot be launched"?

    In Eclipse Project -> Clean Modify project.properties like this :

    target=android-10
    android.library.reference.1=F:/svn/WiEngine_library
    

    Add shadow to custom shape on Android

    9 patch to the rescue, nice shadow could be achieved easily especially with this awesome tool -

    Android 9-patch shadow generator

    PS: if project won't be able to compile you will need to move black lines in android studio editor a little bit

    Conveniently map between enum and int / String

    http://www.javaspecialists.co.za/archive/Issue113.html

    The solution starts out similar to yours with an int value as part of the enum definition. He then goes on to create a generics-based lookup utility:

    public class ReverseEnumMap<V extends Enum<V> & EnumConverter> {
        private Map<Byte, V> map = new HashMap<Byte, V>();
        public ReverseEnumMap(Class<V> valueType) {
            for (V v : valueType.getEnumConstants()) {
                map.put(v.convert(), v);
            }
        }
    
        public V get(byte num) {
            return map.get(num);
        }
    }
    

    This solution is nice and doesn't require 'fiddling with reflection' because it's based on the fact that all enum types implicitly inherit the Enum interface.

    Catch browser's "zoom" event in JavaScript

    There is a nifty plugin built from yonran that can do the detection. Here is his previously answered question on StackOverflow. It works for most of the browsers. Application is as simple as this:

    window.onresize = function onresize() {
      var r = DetectZoom.ratios();
      zoomLevel.innerHTML =
        "Zoom level: " + r.zoom +
        (r.zoom !== r.devicePxPerCssPx
            ? "; device to CSS pixel ratio: " + r.devicePxPerCssPx
            : "");
    }
    

    Demo

    Filter items which array contains any of given values

    For those looking at this in 2020, you may notice that accepted answer is deprecated in 2020, but there is a similar approach available using terms_set and minimum_should_match_script combination.

    Please see the detailed answer here in the SO thread

    Break out of a While...Wend loop

    The best way is to use an And clause in your While statement

    Dim count as Integer
    count =0
    While True And count <= 10
        count=count+1
        Debug.Print(count)
    Wend
    

    Simple int to char[] conversion

    Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

    char c[2];
    int i=1;
    sprintf(c, "%d", i);
    

    PowerShell on Windows 7: Set-ExecutionPolicy for regular users

    If you (or a helpful admin) runs Set-ExecutionPolicy as administrator, the policy will be set for all users. (I would suggest "remoteSigned" rather than "unrestricted" as a safety measure.)

    NB.: On a 64-bit OS you need to run Set-ExecutionPolicy for 32-bit and 64-bit PowerShell separately.

    How to capitalize the first letter of word in a string using Java?

    I would like to add a NULL check and IndexOutOfBoundsException on the accepted answer.

    String output = input.substring(0, 1).toUpperCase() + input.substring(1);
    

    Java Code:

      class Main {
          public static void main(String[] args) {
            System.out.println("Capitalize first letter ");
            System.out.println("Normal  check #1      : ["+ captializeFirstLetter("one thousand only")+"]");
            System.out.println("Normal  check #2      : ["+ captializeFirstLetter("two hundred")+"]");
            System.out.println("Normal  check #3      : ["+ captializeFirstLetter("twenty")+"]");
            System.out.println("Normal  check #4      : ["+ captializeFirstLetter("seven")+"]");
    
            System.out.println("Single letter check   : ["+captializeFirstLetter("a")+"]");
            System.out.println("IndexOutOfBound check : ["+ captializeFirstLetter("")+"]");
            System.out.println("Null Check            : ["+ captializeFirstLetter(null)+"]");
          }
    
          static String captializeFirstLetter(String input){
                 if(input!=null && input.length() >0){
                    input = input.substring(0, 1).toUpperCase() + input.substring(1);
                }
                return input;
            }
        }
    

    Output:

    Normal  check #1      : [One thousand only]
    Normal  check #2      : [Two hundred]
    Normal  check #3      : [Twenty]
    Normal  check #4      : [Seven]
    Single letter check   : [A]
    IndexOutOfBound check : []
    Null Check            : [null]
    

    How do I get a UTC Timestamp in JavaScript?

    You generally don't need to do much of "Timezone manipulation" on the client side. As a rule I try to store and work with UTC dates, in the form of ticks or "number of milliseconds since midnight of January 1, 1970." This really simplifies storage, sorting, calculation of offsets, and most of all, rids you of the headache of the "Daylight Saving Time" adjustments. Here's a little JavaScript code that I use.

    To get the current UTC time:

    function getCurrentTimeUTC()
    {
        //RETURN:
        //      = number of milliseconds between current UTC time and midnight of January 1, 1970
        var tmLoc = new Date();
        //The offset is in minutes -- convert it to ms
        return tmLoc.getTime() + tmLoc.getTimezoneOffset() * 60000;
    }
    

    Then what you'd generally need is to format date/time for the end-user for their local timezone and format. The following takes care of all the complexities of date and time formats on the client computer:

    function formatDateTimeFromTicks(nTicks)
    {
        //'nTicks' = number of milliseconds since midnight of January 1, 1970
        //RETURN:
        //      = Formatted date/time
        return new Date(nTicks).toLocaleString();
    }
    
    function formatDateFromTicks(nTicks)
    {
        //'nTicks' = number of milliseconds since midnight of January 1, 1970
        //RETURN:
        //      = Formatted date
        return new Date(nTicks).toLocaleDateString();
    }
    
    function formatTimeFromTicks(nTicks)
    {
        //'nTicks' = number of milliseconds since midnight of January 1, 1970
        //RETURN:
        //      = Formatted time
        return new Date(nTicks).toLocaleTimeString();
    }
    

    So the following example:

    var ticks = getCurrentTimeUTC();  //Or get it from the server
    
    var __s = "ticks=" + ticks + 
        ", DateTime=" + formatDateTimeFromTicks(ticks) +
        ", Date=" + formatDateFromTicks(ticks) +
        ", Time=" + formatTimeFromTicks(ticks);
    
    document.write("<span>" + __s + "</span>");
    

    Returns the following (for my U.S. English locale):

    ticks=1409103400661, DateTime=8/26/2014 6:36:40 PM, Date=8/26/2014, Time=6:36:40 PM

    Check if instance is of a type

    Also, somewhat in the same vein

    Type.IsAssignableFrom(Type c)
    

    "True if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c."

    From here: http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx

    Error: could not find function ... in R

    If this occurs while you check your package (R CMD check), take a look at your NAMESPACE.

    You can solve this by adding the following statement to the NAMESPACE:

    exportPattern("^[^\\\\.]")
    

    This exports everything that doesn't start with a dot ("."). This allows you to have your hidden functions, starting with a dot:

    .myHiddenFunction <- function(x) cat("my hidden function")
    

    What is the difference between null and System.DBNull.Value?

    Well, null is not an instance of any type. Rather, it is an invalid reference.

    However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.

    *We would normally say null, but I don't want to confound the issue.

    So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).

    Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.

    Remove "Using default security password" on Spring Boot

    You only need to exclude UserDetailsServiceAutoConfiguration.

    spring:
      autoconfigure:
        exclude: org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration
    

    How to convert comma-delimited string to list in Python?

    You can use the str.split method.

    >>> my_string = 'A,B,C,D,E'
    >>> my_list = my_string.split(",")
    >>> print my_list
    ['A', 'B', 'C', 'D', 'E']
    

    If you want to convert it to a tuple, just

    >>> print tuple(my_list)
    ('A', 'B', 'C', 'D', 'E')
    

    If you are looking to append to a list, try this:

    >>> my_list.append('F')
    >>> print my_list
    ['A', 'B', 'C', 'D', 'E', 'F']
    

    Matplotlib scatterplot; colour as a function of a third variable

    In matplotlib grey colors can be given as a string of a numerical value between 0-1.
    For example c = '0.1'

    Then you can convert your third variable in a value inside this range and to use it to color your points.
    In the following example I used the y position of the point as the value that determines the color:

    from matplotlib import pyplot as plt
    
    x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    y = [125, 32, 54, 253, 67, 87, 233, 56, 67]
    
    color = [str(item/255.) for item in y]
    
    plt.scatter(x, y, s=500, c=color)
    
    plt.show()
    

    enter image description here

    Restore the mysql database from .frm files

    After much trial and error I was able to get this working based on user359187 answer and this blog post.

    To get my old .frm and .ibd transferred to a new MySQL database after copying the files over and assigning MySQL ownership, the key for me was to then log into MySQL and connect to the new database then let MySQL do the work by importing the tablespace.

    mysql> connect test;
    mysql> ALTER TABLE t1 IMPORT TABLESPACE;
    

    This will import the data using the copied .frm and .ibd files.

    I had to run the Alter command for each table separately but this worked and I was able to recover the tables and data.

    Passing functions with arguments to another function in Python?

    Here is a way to do it with a closure:

        def generate_add_mult_func(func):
            def function_generator(x):
                return reduce(func,range(1,x))
            return function_generator
    
        def add(x,y):
            return x+y
    
        def mult(x,y):
            return x*y
    
        adding=generate_add_mult_func(add)
        multiplying=generate_add_mult_func(mult)
    
        print adding(10)
        print multiplying(10)
    

    Python - Check If Word Is In A String

    Advanced way to check the exact word, that we need to find in a long string:

    import re
    text = "This text was of edited by Rock"
    #try this string also
    #text = "This text was officially edited by Rock" 
    for m in re.finditer(r"\bof\b", text):
        if m.group(0):
            print "Present"
        else:
            print "Absent"
    

    keyword not supported data source

    I was getting the same problem.
    but this code works good try it.

    <add name="MyCon" connectionString="Server=****;initial catalog=PortalDb;user id=**;password=**;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
    

    The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

    Adding the Tomcat server in the server runtime will do the job:

    Project properties ? Java Build Path ? Add Library ? Select "Server Runtime" from the list ? Next ? Select "Apache Tomcat" ? Finish.

    How to Rotate a UIImage 90 degrees?

    A thread safe rotation function is the following (it works much better):

    -(UIImage*)imageByRotatingImage:(UIImage*)initImage fromImageOrientation:(UIImageOrientation)orientation
    {
    CGImageRef imgRef = initImage.CGImage;
    
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient = orientation;
    switch(orient) {
    
        case UIImageOrientationUp: //EXIF = 1
            return initImage;
            break;
    
        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;
    
        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
    
        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;
    
        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
    
        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
    
        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
    
        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
    
        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
    
    }
    // Create the bitmap context
    CGContextRef    context = NULL;
    void *          bitmapData;
    int             bitmapByteCount;
    int             bitmapBytesPerRow;
    
    // Declare the number of bytes per row. Each pixel in the bitmap in this
    // example is represented by 4 bytes; 8 bits each of red, green, blue, and
    // alpha.
    bitmapBytesPerRow   = (bounds.size.width * 4);
    bitmapByteCount     = (bitmapBytesPerRow * bounds.size.height);
    bitmapData = malloc( bitmapByteCount );
    if (bitmapData == NULL)
    {
        return nil;
    }
    
    // Create the bitmap context. We want pre-multiplied ARGB, 8-bits
    // per component. Regardless of what the source image format is
    // (CMYK, Grayscale, and so on) it will be converted over to the format
    // specified here by CGBitmapContextCreate.
    CGColorSpaceRef colorspace = CGImageGetColorSpace(imgRef);
    context = CGBitmapContextCreate (bitmapData,bounds.size.width,bounds.size.height,8,bitmapBytesPerRow,
                                     colorspace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast);
    
    if (context == NULL)
        // error creating context
        return nil;
    
    CGContextScaleCTM(context, -1.0, -1.0);
    CGContextTranslateCTM(context, -bounds.size.width, -bounds.size.height);
    
    CGContextConcatCTM(context, transform);
    
    // Draw the image to the bitmap context. Once we draw, the memory
    // allocated for the context for rendering will then contain the
    // raw image data in the specified color space.
    CGContextDrawImage(context, CGRectMake(0,0,width, height), imgRef);
    
    CGImageRef imgRef2 = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    free(bitmapData);
    UIImage * image = [UIImage imageWithCGImage:imgRef2 scale:initImage.scale orientation:UIImageOrientationUp];
    CGImageRelease(imgRef2);
    return image;
    }
    

    Maven Java EE Configuration Marker with Java Server Faces 1.2

    This is an older thread,but I will post my answer for others. I have to recreate the project in a different workspace after the changes to make it work, as discussed in JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer