Programs & Examples On #Roaming profile

How to get keyboard input in pygame?

pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement:

while True:

    pressed_key= pygame.key.get_pressed()
    x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
    y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * speed

The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or movement:

while True:

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x -= speed
            if event.key == pygame.K_RIGHT:
                x += speed
            if event.key == pygame.K_UP:
                y -= speed
            if event.key == pygame.K_DOWN:
                y += speed

See also Key and Keyboard event


Minimal example of continuous movement: repl.it/@Rabbid76/PyGame-ContinuousMovement

import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

rect = pygame.Rect(0, 0, 20, 20)
rect.center = window.get_rect().center
vel = 5

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            print(pygame.key.name(event.key))

    keys = pygame.key.get_pressed()
    
    rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel
    rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel
        
    rect.centerx = rect.centerx % window.get_width()
    rect.centery = rect.centery % window.get_height()

    window.fill(0)
    pygame.draw.rect(window, (255, 0, 0), rect)
    pygame.display.flip()

pygame.quit()
exit()

Minimal example for a single action: repl.it/@Rabbid76/PyGame-ShootBullet

import pygame
pygame.init()

window = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()

tank_surf = pygame.Surface((60, 40), pygame.SRCALPHA)
pygame.draw.rect(tank_surf, (0, 96, 0), (0, 00, 50, 40))
pygame.draw.rect(tank_surf, (0, 128, 0), (10, 10, 30, 20))
pygame.draw.rect(tank_surf, (32, 32, 96), (20, 16, 40, 8))
tank_rect = tank_surf.get_rect(midleft = (20, window.get_height() // 2))

bullet_surf = pygame.Surface((10, 10), pygame.SRCALPHA)
pygame.draw.circle(bullet_surf, (64, 64, 62), bullet_surf.get_rect().center, bullet_surf.get_width() // 2)
bullet_list = []

run = True
while run:
    clock.tick(60)
    current_time = pygame.time.get_ticks()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:
            bullet_list.insert(0, tank_rect.midright)

    for i, bullet_pos in enumerate(bullet_list):
        bullet_list[i] = bullet_pos[0] + 5, bullet_pos[1]
        if bullet_surf.get_rect(center = bullet_pos).left > window.get_width():
            del bullet_list[i:]
            break

    window.fill((224, 192, 160))
    window.blit(tank_surf, tank_rect)
    for bullet_pos in bullet_list:
        window.blit(bullet_surf, bullet_surf.get_rect(center = bullet_pos))
    pygame.display.flip()

pygame.quit()
exit()

Using Mockito's generic "any()" method

You can use Mockito.isA() for that:

import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.verify;

verify(bar).doStuff(isA(Foo[].class));

http://site.mockito.org/mockito/docs/current/org/mockito/Matchers.html#isA(java.lang.Class)

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

Linq: GroupBy, Sum and Count

sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new Models.ResultLine
            {
                ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

How to use timer in C?

Yes, you need a loop. If you already have a main loop (most GUI event-driven stuff does) you can probably stick your timer into that. Use:

#include <time.h> 
time_t my_t, fire_t;

Then (for times over 1 second), initialize your timer by reading the current time:

my_t = time(NULL);

Add the number of seconds your timer should wait and store it in fire_t. A time_t is essentially a uint32_t, you may need to cast it.

Inside your loop do another

my_t = time(NULL);

if (my_t > fire_t) then consider the timer fired and do the stuff you want there. That will probably include resetting it by doing another fire_t = time(NULL) + seconds_to_wait for next time.

A time_t is a somewhat antiquated unix method of storing time as the number of seconds since midnight 1/1/1970 but it has many advantages. For times less than 1 second you need to use gettimeofday() (microseconds) or clock_gettime() (nanoseconds) and deal with a struct timeval or struct timespec which is a time_t and the microseconds or nanoseconds since that 1 second mark. Making a timer works the same way except when you add your time to wait you need to remember to manually do the carry (into the time_t) if the resulting microseconds or nanoseconds value goes over 1 second. Yes, it's messy. See man 2 time, man gettimeofday, man clock_gettime.

sleep(), usleep(), nanosleep() have a hidden benefit. You see it as pausing your program, but what they really do is release the CPU for that amount of time. Repeatedly polling by reading the time and comparing to the done time (are we there yet?) will burn a lot of CPU cycles which may slow down other programs running on the same machine (and use more electricity/battery). It's better to sleep() most of the time then start checking the time.

If you're trying to sleep and do work at the same time you need threads.

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

You are allowed to use IDs that start with a digit in your HTML5 documents:

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

But querySelector method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Use a value like b22 for the ID attribute and your code will work.

Since you want to select an element by ID you can also use .getElementById method:

document.getElementById('22')

MySQL Error: : 'Access denied for user 'root'@'localhost'

Okay, I know this is an old thread but if you reached this page via Google like I did and none of the above solutions worked, what turned out to be the error was 100% foolishness on my end. I didn't connect to the server. Once connected everything was smooth sailing.

In case it helps to know my setup, I'm using Sequel Pro and trying to connect to it with Node using the NPM package, mysql. I didn't think I needed to actually connect (other than run Sequel Pro) because I was doing that from my app already.

enter image description here

Read all files in a folder and apply a function to each data frame

Here is a tidyverse option that might not the most elegant, but offers some flexibility in terms of what is included in the summary:

library(tidyverse)
dir_path <- '~/path/to/data/directory/'
file_pattern <- 'Df\\.[0-9]\\.csv' # regex pattern to match the file name format

read_dir <- function(dir_path, file_name){
  read_csv(paste0(dir_path, file_name)) %>% 
    mutate(file_name = file_name) %>%                # add the file name as a column              
    gather(variable, value, A:B) %>%                 # convert the data from wide to long
    group_by(file_name, variable) %>% 
    summarize(sum = sum(value, na.rm = TRUE),
              min = min(value, na.rm = TRUE),
              mean = mean(value, na.rm = TRUE),
              median = median(value, na.rm = TRUE),
              max = max(value, na.rm = TRUE))
  }

df_summary <- 
  list.files(dir_path, pattern = file_pattern) %>% 
  map_df(~ read_dir(dir_path, .))

df_summary
# A tibble: 8 x 7
# Groups:   file_name [?]
  file_name variable   sum   min  mean median   max
  <chr>     <chr>    <int> <dbl> <dbl>  <dbl> <dbl>
1 Df.1.csv  A           34     4  5.67    5.5     8
2 Df.1.csv  B           22     1  3.67    3       9
3 Df.2.csv  A           21     1  3.5     3.5     6
4 Df.2.csv  B           16     1  2.67    2.5     5
5 Df.3.csv  A           30     0  5       5      11
6 Df.3.csv  B           43     1  7.17    6.5    15
7 Df.4.csv  A           21     0  3.5     3       8
8 Df.4.csv  B           42     1  7       6      16

Java - How to access an ArrayList of another class?

You can do this by providing in class numbers:

  • A method that returns the ArrayList object itself.
  • A method that returns a non-modifiable wrapper of the ArrayList. This prevents modification to the list without the knowledge of the class numbers.
  • Methods that provide the set of operations you want to support from class numbers. This allows class numbers to control the set of operations supported.

By the way, there is a strong convention that Java class names are uppercased.

Case 1 (simple getter):

public class Numbers {
      private List<Integer> list;
      public List<Integer> getList() { return list; }
      ...
}

Case 2 (non-modifiable wrapper):

public class Numbers {
      private List<Integer> list;
      public List<Integer> getList() { return Collections.unmodifiableList( list ); }
      ...
}

Case 3 (specific methods):

public class Numbers {
      private List<Integer> list;
      public void addToList( int i ) { list.add(i); }
      public int getValueAtIndex( int index ) { return list.get( index ); }
      ...
}

NSDictionary - Need to check whether dictionary contains key-value pair or not

With literal syntax you can check as follows

static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
  NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
 NSLog(@"Key pair do not exits for key: %@", kKeyToCheck); 

How can I add new keys to a dictionary?

Let's pretend you want to live in the immutable world and do NOT want to modify the original but want to create a new dict that is the result of adding a new key to the original.

In Python 3.5+ you can do:

params = {'a': 1, 'b': 2}
new_params = {**params, **{'c': 3}}

The Python 2 equivalent is:

params = {'a': 1, 'b': 2}
new_params = dict(params, **{'c': 3})

After either of these:

params is still equal to {'a': 1, 'b': 2}

and

new_params is equal to {'a': 1, 'b': 2, 'c': 3}

There will be times when you don't want to modify the original (you only want the result of adding to the original). I find this a refreshing alternative to the following:

params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params['c'] = 3

or

params = {'a': 1, 'b': 2}
new_params = params.copy()
new_params.update({'c': 3})

Reference: https://stackoverflow.com/a/2255892/514866

What does SQL clause "GROUP BY 1" mean?

SELECT account_id, open_emp_id
         ^^^^        ^^^^
          1           2

FROM account
GROUP BY 1;

In above query GROUP BY 1 refers to the first column in select statement which is account_id.

You also can specify in ORDER BY.

Note : The number in ORDER BY and GROUP BY always start with 1 not with 0.

How to get the last character of a string in a shell?

I know this is a very old thread, but no one mentioned which to me is the cleanest answer:

echo -n $str | tail -c 1

Note the -n is just so the echo doesn't include a newline at the end.

Expected response code 220 but got code "", with message "" in Laravel

I did as per sid saying my env after updating is

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<mygmailaddress>
MAIL_PASSWORD=<gmailpassword>
MAIL_ENCRYPTION=tls

this did work without 2 step verification. with 2 step verification enabled it did not work for me.

Check if a variable is null in plsql

Always remember to be careful with nulls in pl/sql conditional clauses as null is never greater, smaller, equal or unequal to anything. Best way to avoid them is to use nvl.

For example

declare
  i integer;
begin
  if i <> 1 then
    i:=1;
    foobar();
  end if;
end;
/

Never goes inside the if clause.

These would work.

if 1<>nvl(i,1) then
if i<> 1 or i is null then

Avoid line break between html elements

If you need this for several words or elements, but can't apply it to a whole TD or similar, the Span tag can be used.

<span style="white-space: nowrap">Text to break together</span>
    or 
<span class=nobr>Text to break together</span>

If you use the class version, remember to set up the CSS as detailed in the accepted answer.

Jquery click not working with ipad

I had a span that would create a popup. If I used "click touchstart" it would trigger parts of the popup during the touchend. I fixed this by making the span "click touchend".

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

If your mysql was previously working and has stopped suddenly just "reboot" the server.

Was facing this issue on my CentOS VPS.->

Was constantly getting

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'(2)

Tried all techniques, finally restarting the server fixed the issues ->

shutdown -r now

Hope this helps !!

Regex - Does not contain certain Characters

Here you go:

^[^<>]*$

This will test for string that has no < and no >

If you want to test for a string that may have < and >, but must also have something other you should use just

[^<>] (or ^.*[^<>].*$)

Where [<>] means any of < or > and [^<>] means any that is not of < or >.

And of course the mandatory link.

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

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

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

To quote from Microsoft:

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


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

What is the difference between varchar and nvarchar?

Is it possible to save HTML page as PDF using JavaScript or jquery?

This might be a late answer but this is the best around: https://github.com/eKoopmans/html2pdf

Pure javascript implementation. Allows you to specify just a single element by ID and convert it.

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Just an additional note - if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.

$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)

As Mike has noted below, HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

HTML Button : Navigate to Other Page - Different Approaches

I use method 3 because it's the most understandable for others (whenever you see an <a> tag, you know it's a link) and when you are part of a team, you have to make simple things ;).

And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.

How do I automatically play a Youtube video (IFrame API) muted?

Youtube don't provide muting through url parameter (see http://code.google.com/apis/youtube/player_parameters.html).

You have to use javascript for that. see http://code.google.com/apis/youtube/js_api_reference.html for details.

However, please note the warning on the page linked above: "The deprecation of the YouTube JavaScript Player API was announced on January 27, 2015. YouTube Flash embeds have also been deprecated. See the deprecation policy for more information. Please migrate your applications to the IFrame API, which can intelligently use whichever embedded player – HTML () or Flash () – the client supports."

Html

<iframe class="youtube-player" id="player" type="text/html" src="http://www.youtube.com/embed/JW5meKfy3fY?wmode=opaque&autohide=1&autoplay=1&enablejsapi=1" frameborder="0">&lt;br /&gt;</iframe>

please note enablejsapi=1 in the url.

Javascript

var player =  iframe.getElementById('player');
player.mute();

Update

Previous code had some issues and did not work with current API (playerVars syntax was wrong). Here is the updated code. You may need to tinker with the parameters you need.

_x000D_
_x000D_
         _x000D_
    <div id="player"></div>_x000D_
    <script>_x000D_
      // 1. This code loads the IFrame Player API code asynchronously._x000D_
      var tag = document.createElement('script');_x000D_
_x000D_
      tag.src = "https://www.youtube.com/iframe_api";_x000D_
      var firstScriptTag = document.getElementsByTagName('script')[0];_x000D_
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);_x000D_
_x000D_
      // 2. This function creates an <iframe> (and YouTube player)_x000D_
      //    after the API code downloads._x000D_
      var player;_x000D_
      function onYouTubeIframeAPIReady() {_x000D_
        player = new YT.Player('player', {_x000D_
          height: '100%',_x000D_
          width: '100%',_x000D_
          playerVars: {_x000D_
                    autoplay: 1,_x000D_
                    loop: 1,_x000D_
                    controls: 0,_x000D_
                    showinfo: 0,_x000D_
                    autohide: 1,_x000D_
                    modestbranding: 1,_x000D_
                    vq: 'hd1080'},_x000D_
          videoId: '1pzWROvY7gY',_x000D_
          events: {_x000D_
            'onReady': onPlayerReady,_x000D_
            'onStateChange': onPlayerStateChange_x000D_
          }_x000D_
        });_x000D_
      }_x000D_
_x000D_
      // 3. The API will call this function when the video player is ready._x000D_
      function onPlayerReady(event) {_x000D_
        event.target.playVideo();_x000D_
        player.mute();_x000D_
      }_x000D_
_x000D_
      var done = false;_x000D_
      function onPlayerStateChange(event) {_x000D_
        _x000D_
      }_x000D_
      function stopVideo() {_x000D_
        player.stopVideo();_x000D_
      }_x000D_
    </script>
_x000D_
_x000D_
_x000D_

How to express a One-To-Many relationship in Django

In Django, a one-to-many relationship is called ForeignKey. It only works in one direction, however, so rather than having a number attribute of class Dude you will need

class Dude(models.Model):
    ...

class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)

Many models can have a ForeignKey to one other model, so it would be valid to have a second attribute of PhoneNumber such that

class Business(models.Model):
    ...
class Dude(models.Model):
    ...
class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)
    business = models.ForeignKey(Business)

You can access the PhoneNumbers for a Dude object d with d.phonenumber_set.objects.all(), and then do similarly for a Business object.

Fade Effect on Link Hover?

You can do this with JQueryUI:

$('a').mouseenter(function(){
  $(this).animate({
    color: '#ff0000'
  }, 1000);
}).mouseout(function(){
  $(this).animate({
    color: '#000000'
  }, 1000);
});

http://jsfiddle.net/dWCbk/

Best way to implement keyboard shortcuts in a Windows Forms application?

If you have a menu then changing ShortcutKeys property of the ToolStripMenuItem should do the trick.

If not, you could create one and set its visible property to false.

How to parse float with two decimal places in javascript?

ceil from lodash is probably the best

_.ceil("315.9250488",2) 
_.ceil(315.9250488,2) 
_.ceil(undefined,2)
_.ceil(null,2)
_.ceil("",2)

will work also with a number and it's safe

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

Empty refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty then it would return true.

IsEmpty refers to no value being initialized.

In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty. If you want to see if something is currently in its default value then use Empty.

MySql server startup error 'The server quit without updating PID file '

Somehow I screwed up my permissions on El Capitan and decided to reinstall MySQL from scratch.

I use brew on el capitan, and decided to reinstall:

brew uninstall mysql
sudo rm -rf /usr/local/var/mysql
brew install mysql
mysql.server start # ... SUCCESS

The file permissions on fresh install changed from _mysql to include my username

› ls -alh /usr/local/var/mysql
drwxr-xr-x   22 lfender  admin   748B Mar 22 09:58 .
# ... etc

Show and hide a View with a slide up/down animation

You can used the simple three lines of code to show the animation...

//getting the hiding view by animation

 mbinding.butn.setOnClickListener {

                val SlideOutLeft = AnimationUtils.loadAnimation(this, R.anim.slide_out_left)
                simplelayout.visibility = View.INVISIBLE
                simplelayout.startAnimation(SlideOutLeft)


                val SlideInRight = AnimationUtils.loadAnimation(applicationContext, R.anim.slide_in_right)
                animation1.visibility = View.VISIBLE
                animation1.startAnimation(SlideInRight)

            }
            //again unhide the view animation
            mbinding.buttn.setOnClickListener {


               val SlideInLeft=AnimationUtils.loadAnimation(this,R.anim.slide_in_left)
                //set the layout
               simplelayout.visibility=View.VISIBLE
               simplelayout.startAnimation(SlideInLeft)

               val SlideOutRight=AnimationUtils.loadAnimation(this,R.anim.slide_out_right)
               animation1.visibility=View.INVISIBLE
               animation1.startAnimation(SlideOutRight)

            }

How may I align text to the left and text to the right in the same line?

If you don't want to use floating elements and want to make sure that both blocks do not overlap, try:

<p style="text-align: left; width:49%; display: inline-block;">LEFT</p>
<p style="text-align: right; width:50%;  display: inline-block;">RIGHT</p>

How to update value of a key in dictionary in c#?

Try this simple function to add an dictionary item if it does not exist or update when it exists:

    public void AddOrUpdateDictionaryEntry(string key, int value)
    {
        if (dict.ContainsKey(key))
        {
            dict[key] = value;
        }
        else
        {
            dict.Add(key, value);
        }
    }

This is the same as dict[key] = value.

Java converting Image to BufferedImage

If you use Kotlin, you can add an extension method to Image in the same manner Sri Harsha Chilakapati suggests.

fun Image.toBufferedImage(): BufferedImage {
    if (this is BufferedImage) {
        return this
    }
    val bufferedImage = BufferedImage(this.getWidth(null), this.getHeight(null), BufferedImage.TYPE_INT_ARGB)

    val graphics2D = bufferedImage.createGraphics()
    graphics2D.drawImage(this, 0, 0, null)
    graphics2D.dispose()

    return bufferedImage
}

And use it like this:

myImage.toBufferedImage()

Command-line Git on Windows

As @birryree said, add msysgit's binary to your PATH, or use Git Bash (installed with msysgit as far as I remember) which is better than Windows' console and similar to the Unix one.

Sockets - How to find out what port and address I'm assigned

The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.

How to store(bitmap image) and retrieve image from sqlite database in android?

If you are working with Android's MediaStore database, here is how to store an image and then display it after it is saved.

on button click write this

 Intent in = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            in.putExtra("crop", "true");
            in.putExtra("outputX", 100);
            in.putExtra("outputY", 100);
            in.putExtra("scale", true);
            in.putExtra("return-data", true);

            startActivityForResult(in, 1);

then do this in your activity

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {

            Bitmap bmp = (Bitmap) data.getExtras().get("data");

            img.setImageBitmap(bmp);
            btnadd.requestFocus();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] b = baos.toByteArray();
            String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);

            byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
            Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
                    bytarray.length);

        }

    }

WebDriver: check if an element exists?

you can do an assertion.

see the example

driver.asserts().assertElementFound("Page was not loaded",
By.xpath("//div[@id='actionsContainer']"),Constants.LOOKUP_TIMEOUT);

you can use this this is native :

public static void waitForElementToAppear(Driver driver, By selector, long timeOutInSeconds, String timeOutMessage) {
    try {
      WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
      wait.until(ExpectedConditions.visibilityOfElementLocated(selector));
    } catch (TimeoutException e) {
      throw new IllegalStateException(timeOutMessage);
    }
  }

Remove decimal values using SQL query

Here column name must be decimal.

select CAST(columnname AS decimal(38,0)) from table

Python coding standards/best practices

I follow it extremely rigorously. The only god before PEP-8 is existing code bases.

src absolute path problem

You should be referencing it as localhost. Like this:

<img src="http:\\localhost\site\img\mypicture.jpg"/>

how to overlap two div in css?

add to second div bottomDiv

and add this to css.

 .bottomDiv{
       position:relative;
       bottom:150px;
       left:150px;
    }

http://jsfiddle.net/aw8RD/1/

Map enum in JPA with fixed values?

My own solution to solve this kind of Enum JPA mapping is the following.

Step 1 - Write the following interface that we will use for all enums that we want to map to a db column:

public interface IDbValue<T extends java.io.Serializable> {

    T getDbVal();

}

Step 2 - Implement a custom generic JPA converter as follows:

import javax.persistence.AttributeConverter;

public abstract class EnumDbValueConverter<T extends java.io.Serializable, E extends Enum<E> & IDbValue<T>>
        implements AttributeConverter<E, T> {

    private final Class<E> clazz;

    public EnumDbValueConverter(Class<E> clazz){
        this.clazz = clazz;
    }

    @Override
    public T convertToDatabaseColumn(E attribute) {
        if (attribute == null) {
            return null;
        }
        return attribute.getDbVal();
    }

    @Override
    public E convertToEntityAttribute(T dbData) {
        if (dbData == null) {
            return null;
        }
        for (E e : clazz.getEnumConstants()) {
            if (dbData.equals(e.getDbVal())) {
                return e;
            }
        }
        // handle error as you prefer, for example, using slf4j:
        // log.error("Unable to convert {} to enum {}.", dbData, clazz.getCanonicalName());
        return null;
    }

}

This class will convert the enum value E to a database field of type T (e.g. String) by using the getDbVal() on enum E, and vice versa.

Step 3 - Let the original enum implement the interface we defined in step 1:

public enum Right implements IDbValue<Integer> {
    READ(100), WRITE(200), EDITOR (300);

    private final Integer dbVal;

    private Right(Integer dbVal) {
        this.dbVal = dbVal;
    }

    @Override
    public Integer getDbVal() {
        return dbVal;
    }
}

Step 4 - Extend the converter of step 2 for the Right enum of step 3:

public class RightConverter extends EnumDbValueConverter<Integer, Right> {
    public RightConverter() {
        super(Right.class);
    }
}

Step 5 - The final step is to annotate the field in the entity as follows:

@Column(name = "RIGHT")
@Convert(converter = RightConverter.class)
private Right right;

Conclusion

IMHO this is the cleanest and most elegant solution if you have many enums to map and you want to use a particular field of the enum itself as mapping value.

For all others enums in your project that need similar mapping logic, you only have to repeat steps 3 to 5, that is:

  • implement the interface IDbValue on your enum;
  • extend the EnumDbValueConverter with only 3 lines of code (you may also do this within your entity to avoid creating a separated class);
  • annotate the enum attribute with @Convert from javax.persistence package.

Hope this helps.

WorksheetFunction.CountA - not working post upgrade to Office 2010

This code works for me:

Sub test()
    Dim myRange As Range
    Dim NumRows As Integer

    Set myRange = Range("A:A")
    NumRows = Application.WorksheetFunction.CountA(myRange)

    MsgBox NumRows
End Sub

python, sort descending dataframe with pandas

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

I don't think you should ever provide the False value in square brackets (ever), also the column values when they are more than one, then only they are provided as a list! Not like ['one'].

test = df.sort_values(by='one', ascending = False)

Convert month int to month name

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);

See Here for more details.

Or

DateTime dt = DateTime.Now;
Console.WriteLine( dt.ToString( "MMMM" ) );

Or if you want to get the culture-specific abbreviated name.

GetAbbreviatedMonthName(1);

Reference

How to configure static content cache per folder and extension in IIS7?

You can do it on a per file basis. Use the path attribute to include the filename

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <location path="YourFileNameHere.xml">
        <system.webServer>
            <staticContent>
                <clientCache cacheControlMode="DisableCache" />
            </staticContent>
        </system.webServer>
    </location>
</configuration>

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

Adding n seconds to 1970-01-01 will give you a UTC date because n, the Unix timestamp, is the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970.

In SQL Server 2016, you can convert one time zone to another using AT TIME ZONE. You just need to know the name of the time zone in Windows standard format:

SELECT *
FROM (VALUES (1514808000), (1527854400)) AS Tests(UnixTimestamp)
CROSS APPLY (SELECT DATEADD(SECOND, UnixTimestamp, '1970-01-01') AT TIME ZONE 'UTC') AS CA1(UTCDate)
CROSS APPLY (SELECT UTCDate AT TIME ZONE 'Pacific Standard Time') AS CA2(LocalDate)
| UnixTimestamp | UTCDate                    | LocalDate                  |
|---------------|----------------------------|----------------------------|
| 1514808000    | 2018-01-01 12:00:00 +00:00 | 2018-01-01 04:00:00 -08:00 |
| 1527854400    | 2018-06-01 12:00:00 +00:00 | 2018-06-01 05:00:00 -07:00 |

Or simply:

SELECT *, DATEADD(SECOND, UnixTimestamp, '1970-01-01') AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time'
FROM (VALUES (1514808000), (1527854400)) AS Tests(UnixTimestamp)
| UnixTimestamp | LocalDate                  |
|---------------|----------------------------|
| 1514808000    | 2018-01-01 04:00:00 -08:00 |
| 1527854400    | 2018-06-01 05:00:00 -07:00 |

Notes:

  • You can chop off the timezone information by casting DATETIMEOFFSET to DATETIME.
  • The conversion takes daylight savings time into account. Pacific time was UTC-08:00 on January 2018 and UTC-07:00 on Jun 2018.

Failed to execute 'atob' on 'Window'

you don't need to pass the entire encoded string to atob method, you need to split the encoded string and pass the required string to atob method

_x000D_
_x000D_
const token= "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJob3NzYW0iLCJUb2tlblR5cGUiOiJCZWFyZXIiLCJyb2xlIjoiQURNSU4iLCJpc0FkbWluIjp0cnVlLCJFbXBsb3llZUlkIjoxLCJleHAiOjE2MTI5NDA2NTksImlhdCI6MTYxMjkzNzA1OX0.8f0EeYbGyxt9hjggYW1vR5hMHFVXL4ZvjTA6XgCCAUnvacx_Dhbu1OGh8v5fCsCxXQnJ8iAIZDIgOAIeE55LUw"
console.log(atob(token.split(".")[1]));
_x000D_
_x000D_
_x000D_

default select option as blank

<select required>
  <option value="" disabled selected>None</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You can avoid custom validation in this case.

How do I return multiple values from a function?

I vote for the dictionary.

I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.

Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have to search through the code to find out what it is)

If your concerned about type look up, use descriptive dictionary keys, for example, 'x-values list'.

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

Get the time difference between two datetimes

The following approach is valid for all cases (difference between dates less than 24 hours and difference greater than 24 hours):

// Defining start and end variables
let start = moment('04/09/2013 15:00:00', 'DD/MM/YYYY hh:mm:ss');
let end   = moment('04/09/2013 14:20:30', 'DD/MM/YYYY hh:mm:ss');

// Getting the difference: hours (h), minutes (m) and seconds (s)
let h  = end.diff(start, 'hours');
let m  = end.diff(start, 'minutes') - (60 * h);
let s  = end.diff(start, 'seconds') - (60 * 60 * h) - (60 * m);

// Formating in hh:mm:ss (appends a left zero when num < 10)
let hh = ('0' + h).slice(-2);
let mm = ('0' + m).slice(-2);
let ss = ('0' + s).slice(-2);

console.log(`${hh}:${mm}:${ss}`); // 00:39:30

How to change 1 char in the string?

I made a Method to do this

    string test = "Paul";
    test = ReplaceAtIndex(0, 'M', test);

    (...)

    static string ReplaceAtIndex(int i, char value, string word)
    {
        char[] letters = word.ToCharArray();
        letters[i] = value;
        return string.Join("", letters);
    }

Pip Install not installing into correct directory?

1 - Something that might work

The pip executable is actually a Python script.

By default it contains (on Linux):

#!/usr/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==1.5.6','console_scripts','pip'
__requires__ = 'pip==1.5.6'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('pip==1.5.6', 'console_scripts', 'pip')()
    )

So if you got the same in MacOS, pip would always use /usr/bin/python.

But this is a default. You can still provide the version of python you want either by editing the file or by using python explicitly.

If which python returns /usr/bin/python then something went wrong when you installed your own version. If it is /Library/Frameworks/Python.framework/Versions/2.7/bin/python, you can directly call:

sudo python `which pip` install scikit-learn --upgrade

However, chances are high that it won't work. The reason is that sudo is resetting all your environment variables. To make it work, the easiest would be to use:

sudo -E pip install scikit-learn --upgrade

or

sudo -E python `which pip` install scikit-learn --upgrade

depending on your setup.

2 - What you should do

pip was not thought of as something that root should execute. The actual best way to use it is to install a local, non-root, python version. You just have to make sure that you use it by default by setting up the correct environment variables (such as PATH on Linux) and then install pip without sudo using that python version.

An even better way would be to setup virtualenvs from your root install.

This way, you can install/update whatever you want without root privileges and never bother again about why sudo pip is not working. You would also avoid to provide root privileges to whatever is on Pypi and that would warrant that you don't mix system libs with your own.

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

You should replace the old OpenSSL binary file by the new one via a symlink:

sudo ln -sf /usr/local/ssl/bin/openssl `which openssl`

Remember that after this procedure you should reboot the server or restart all the services related to OpenSSL.

Adding HTML entities using CSS content

You have to use the escaped unicode :

Like

.breadcrumbs a:before {
    content: '\0000a0';
}

More info on : http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/

Pandas left outer join multiple dataframes on multiple columns

Merge them in two steps, df1 and df2 first, and then the result of that to df3.

In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])

I dropped year from df3 since you don't need it for the last join.

In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
                       how='left', on=['Week', 'Colour'])

In [40]: df
Out[40]: 
   Year Week Colour  Val1  Val2 Val3
0  2014    A    Red    50   NaN  NaN
1  2014    B    Red    60   NaN   60
2  2014    B  Black    70   100   10
3  2014    C    Red    10    20  NaN
4  2014    D  Green    20   NaN   20

[5 rows x 6 columns]

SQL Case Expression Syntax?

Sybase has the same case syntax as SQL Server:

Description

Supports conditional SQL expressions; can be used anywhere a value expression can be used.

Syntax

case 
     when search_condition then expression 
    [when search_condition then expression]...
    [else expression]
end

Case and values syntax

case expression
     when expression then expression 
    [when expression then expression]...
    [else expression]
end

Parameters

case

begins the case expression.

when

precedes the search condition or the expression to be compared.

search_condition

is used to set conditions for the results that are selected. Search conditions for case expressions are similar to the search conditions in a where clause. Search conditions are detailed in the Transact-SQL User’s Guide.

then

precedes the expression that specifies a result value of case.

expression

is a column name, a constant, a function, a subquery, or any combination of column names, constants, and functions connected by arithmetic or bitwise operators. For more information about expressions, see “Expressions” in.

Example

select disaster, 
       case
            when disaster = "earthquake" 
                then "stand in doorway"
            when disaster = "nuclear apocalypse" 
                then "hide in basement"
            when monster = "zombie apocalypse" 
                then "hide with Chuck Norris"
            else
                then "ask mom"
       end 
  from endoftheworld

replacing NA's with 0's in R dataframe

dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5);
data <- as.data.frame(dataset)
[,1] [,2] [,3] [,4] [,5] 
[1,]    2    3    5    5    4
[2,]    2    4    3    2    4
[3,]    2   NA   NA   NA    2
[4,]    2    3   NA    5    5
[5,]    2    3    2    2    3
data[is.na(data)] <- 0

Eclipse IDE for Java - Full Dark Theme

Update August 2016:

Tejas Padliya adds in the comments:

Dark theme works well with Eclipse 4.5 onward with Windows 10.
No more black text on black background


Update June 2014:

As mentioned din "Dark Theme, Top Eclipse Luna Feature #5", Eclipse 4.4 (Luna) has a dark theme included in it (see informatik01's comment):

http://eclipsesource.com/blogs/wp-content/uploads/2014/06/darklinux.png

When Eclipse 3.0 shipped in 2004 it brought a new look to the workbench. Now, 10 years later, an entirely new Dark Theme is launching.

The theme extends to more than just the Widgets. Syntax highlighting has also been improved to take advantage of the new look.

The What's new page mentions:

A new dark window theme has been introduced. This popular community theme demonstrates the power of the underlying Eclipse 4 styling engine.
You can enable it from the General > Appearance preference page.
Plug-ins can contribute extensions to this theme to style their own specific views and editors to match the window theme.


Update April 2013:

It seems the solution below don't work well with Eclipse Juno 4.2 and Windows 8, according to Lennart in the comments.

One solution which (mostly) work is the Eclipse Chrome Theme (compatible Juno 4.2 and even Kepler 4.3), from the GitHub project eclipse-themes, by Jeeeyul Lee.

This post mentions:

The first is to change the appearance of what is inside the editor windows.
That can be done with the Eclipse Colour Theme plugin (http://eclipsecolorthemes.org/). My favourite editor theme is Vibrant Ink with the Monaco font. They explain how to install their themes very well (http://eclipsecolorthemes.org/?view=how-to-use), although you get a fine set of dark themes with the default plugin install and may not need to come back to their website for any more. Get the plugin here.

The second stage is darkening the chrome of the UI, which is all the widgets and menus and everything outside of the child window canvases.
This plugin gives you a GUI editor for the chrome colour scheme: https://github.com/jeeeyul/eclipse-themes/.
If you want a dark one, go ahead and click away until eclipse is dark.

Once you are done, some GUI surface area will show through the system theme as mentioned at the top of this post.
Rather than using that editor, you could install the pre-baked Dark Juno theme instead.
The install is manual.
Start by downloading it from here: https://github.com/eclipse-color-theme/eclipse-ui-themes.
It has to be copied into your eclipse dropins folder. This lives next to the eclipse executable, not in your workspace or someplace like that. In my case the command to do the copy was:

cp ./plugins/com.github.eclipsecolortheme.themes_1.0.0.201207121019.jar /usr/lib/eclipse/dropins/

You could be running eclipse from any directory though, so which eclipse will tell you where it should go.
Restart eclipse and you should find a Dark Juno option under Preferences::General::Appearance. It is a nice neutral grey with some gradients and is a very good option.

~~~~~~~~~~~~~~

Update December 2012 (20 months later):

The blog post "Jin Mingjian: Eclipse Darker Theme" mentions this GitHub repo "eclipse themes - darker":

enter image description here

The big fun is that, the codes are minimized by using Eclipse4 platform technologies like dependency injection.
It proves that again, the concise codes and advanced features could be achieved by contributing or extending with the external form(like library, framework).
New language is not necessary just for this kind of purpose.


Update July 2012 (15 months later):

I have seen one! (Ie, a fully dark theme for Eclipse), as reported by Lars Vogel in "Eclipse 4 is beautiful – Create your own Eclipse 4 theme":

Eclipse fully dark theme

If you want to play with it, you only need to write a plug-in, create a CSS file and use the org.eclipse.e4.ui.css.swt.theme extension point to point to your file.
If you export your plug-in, place it in the “dropins” folder of your Eclipse installation and your styling is available.

pixeldude mentions in the comments having publish "Dark Juno" on GitHub!

Komododave mentions that you don't always need a plugin: see "Ubuntu + Eclipse 4.2 - Dark theme - How to darken sidebar backgrounds?" for an example, based on gtkrc resource.


Original answer: March 2011

Note that a full dark theme will be possible with e4.
(see dynamic css with e4 or A week at e4 – Themeing in e4):

dark theme extension

full dark theme

In the meantime, only for editors though (which isn't what you want but still merit to be mentioned):

www.eclipsecolorthemes.org:

"Fresh up your Eclipse with super-awesome color themes!"

themes for editors

Clicking URLs opens default browser

in some cases you might need an override of onLoadResource if you get a redirect which doesn't trigger the url loading method. in this case i tried the following:

@Override
public void onLoadResource(WebView view, String url)
{
    if (url.equals("http://redirectexample.com"))
    {
        //do your own thing here
    }
    else
    {
        super.onLoadResource(view, url);
    }           
}

How to draw checkbox or tick mark in GitHub Markdown table?

Edit the document or wiki page, and use the - [ ] and - [x] syntax to update your task list. Furthermore you can refer to this link.

What is the difference between JDK and JRE?

suppose, if you are a developer then your role is to develop program as well as to execute the program. so you must have environment for developing and executing, which is provided by JDK.

suppose, if you are a client then you don't have to worry about developing.Just you need is, an environment to run program and get result only, which is provided by JRE.

JRE executes the application but JVM reads the instructions line by line so it's interpreter.

JDK=JRE+Development Tools

JRE=JVM+Library Classes

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Building on Joan-Diego Rodriguez's routine with Jordi's approach and some of Jacek Kotowski's code - This function converts any table name for the active workbook into a usable address for SQL queries.

Note to MikeL: Addition of "[#All]" includes headings avoiding problems you reported.

Function getAddress(byVal sTableName as String) as String 

    With Range(sTableName & "[#All]")
        getAddress= "[" & .Parent.Name & "$" & .Address(False, False) & "]"
    End With

End Function

How to fix height of TR?

Setting the td height to less than the natural height of its content

Since table cells want to be at least big enough to encase their content, if the content has no apparent height, the cells can be arbitrarily resized.

By resizing the cells, we can control the row height.

One way to do this, is to set the content with an absolute position within the relative cell, and set the height of the cell, and the left and top of the content.

_x000D_
_x000D_
table {_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #999;_x000D_
}_x000D_
.set-height td {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  height: 3em;_x000D_
}_x000D_
.set-height p {_x000D_
  position: absolute;_x000D_
  margin: 0;_x000D_
  top: 0;_x000D_
}_x000D_
/* table layout fixed */_x000D_
.layout-fixed {_x000D_
  table-layout: fixed;_x000D_
}_x000D_
/* td width */_x000D_
.td-width td:first-child {_x000D_
  width: 33%;_x000D_
}
_x000D_
<table><tbody>_x000D_
  <tr class="set-height">_x000D_
    <td><p>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.</p></td>_x000D_
    <td>Foo</td></tr><tr><td>Bar</td><td>Baz</td></tr><tr><td>Qux</td>_x000D_
    <td>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.</td>_x000D_
  </tr>_x000D_
</tbody></table>_x000D_
<h3>With <code>table-layout: fixed</code> applied:</h3>_x000D_
<table class="layout-fixed"><tbody>_x000D_
  <tr class="set-height">_x000D_
    <td><p>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.</p></td>_x000D_
    <td>Foo</td></tr><tr><td>Bar</td><td>Baz</td></tr><tr><td>Qux</td>_x000D_
    <td>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.</td>_x000D_
  </tr>_x000D_
</tbody></table>_x000D_
<h3>With <code>&lt;td&gt; width</code> applied:</h3>_x000D_
<table class="td-width"><tbody>_x000D_
  <tr class="set-height">_x000D_
    <td><p>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.</p></td>_x000D_
    <td>Foo</td></tr><tr><td>Bar</td><td>Baz</td></tr><tr><td>Qux</td>_x000D_
    <td>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.</td>_x000D_
  </tr>_x000D_
</tbody></table>
_x000D_
_x000D_
_x000D_

The table-layout property

The second table in the snippet above has table-layout: fixed applied, which causes cells to be given equal width, regardless of their content, within the parent.

According to caniuse.com, there are no significant compatibility issues regarding the use of table-layout as of Sept 12, 2019.

Or simply apply width to specific cells as in the third table.

These methods allow the cell containing the effectively sizeless content created by applying position: absolute to be given some arbitrary girth.

Much more simply...

I really should have thought of this from the start; we can manipulate block level table cell content in all the usual ways, and without completely destroying the content's natural size with position: absolute, we can leave the table to figure out what the width should be.

_x000D_
_x000D_
table {_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #999;_x000D_
}_x000D_
table p {_x000D_
  margin: 0;_x000D_
}_x000D_
.cap-height p {_x000D_
  max-height: 3em;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<table><tbody>_x000D_
  <tr class="cap-height">_x000D_
    <td><p>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.</p></td>_x000D_
    <td>Foo</td>_x000D_
  </tr>_x000D_
  <tr class="cap-height">_x000D_
    <td><p>Bar</p></td>_x000D_
    <td>Baz</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>Qux</td>_x000D_
    <td><p>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.</p></td>_x000D_
  </tr>_x000D_
</tbody></table>
_x000D_
_x000D_
_x000D_

What happens if you mount to a non-empty mount point with fuse?

force it with -l

    sudo umount -l ${HOME}/mount_dir

Change table header color using bootstrap

Here is another way to separate your table header and table body:

thead th {
    background-color: #006DCC;
    color: white;
}

tbody td {
    background-color: #EEEEEE;
}

Have a look at this example for separation of head and body of table. JsFiddleLink

How to tell PowerShell to wait for each command to end before starting the next?

Normally, for internal commands PowerShell does wait before starting the next command. One exception to this rule is external Windows subsystem based EXE. The first trick is to pipeline to Out-Null like so:

Notepad.exe | Out-Null

PowerShell will wait until the Notepad.exe process has been exited before continuing. That is nifty but kind of subtle to pick up from reading the code. You can also use Start-Process with the -Wait parameter:

Start-Process <path to exe> -NoNewWindow -Wait

If you are using the PowerShell Community Extensions version it is:

$proc = Start-Process <path to exe> -NoNewWindow -PassThru
$proc.WaitForExit()

Another option in PowerShell 2.0 is to use a background job:

$job = Start-Job { invoke command here }
Wait-Job $job
Receive-Job $job

What is the command to exit a Console application in C#?

You can use Environment.Exit(0); and Application.Exit

Environment.Exit(0) is cleaner.

'AND' vs '&&' as operator

If you use AND and OR, you'll eventually get tripped up by something like this:

$this_one = true;
$that = false;

$truthiness = $this_one and $that;

Want to guess what $truthiness equals?

If you said false... bzzzt, sorry, wrong!

$truthiness above has the value true. Why? = has a higher precedence than and. The addition of parentheses to show the implicit order makes this clearer:

($truthiness = $this_one) and $that

If you used && instead of and in the first code example, it would work as expected and be false.

As discussed in the comments below, this also works to get the correct value, as parentheses have higher precedence than =:

$truthiness = ($this_one and $that)

Is optimisation level -O3 dangerous in g++?

Recently I experienced a problem using optimization with g++. The problem was related to a PCI card, where the registers (for command and data) were repreented by a memory address. My driver mapped the physical address to a pointer within the application and gave it to the called process, which worked with it like this:

unsigned int * pciMemory;
askDriverForMapping( & pciMemory );
...
pciMemory[ 0 ] = someCommandIdx;
pciMemory[ 0 ] = someCommandLength;
for ( int i = 0; i < sizeof( someCommand ); i++ )
    pciMemory[ 0 ] = someCommand[ i ];

The card didn't act as expected. When I saw the assembly I understood that the compiler only wrote someCommand[ the last ] into pciMemory, omitting all preceding writes.

In conclusion: be accurate and attentive with optimization.

How to write PNG image to string with the PIL?

You can use the BytesIO class to get a wrapper around strings that behaves like a file. The BytesIO object provides the same interface as a file, but saves the contents just in memory:

import io

with io.BytesIO() as output:
    image.save(output, format="GIF")
    contents = output.getvalue()

You have to explicitly specify the output format with the format parameter, otherwise PIL will raise an error when trying to automatically detect it.

If you loaded the image from a file it has a format parameter that contains the original file format, so in this case you can use format=image.format.

In old Python 2 versions before introduction of the io module you would have used the StringIO module instead.

Install sbt on ubuntu

It seems like you installed a zip version of sbt, which is fine. But I suggest you install the native debian package if you are on Ubuntu. That is how I managed to install it on my Ubuntu 12.04. Check it out here: http://www.scala-sbt.org/release/docs/Installing-sbt-on-Linux.html Or simply directly download it from here.

Is there a way to view past mysql queries with phpmyadmin?

You just need to click on console at the bottom of the screen in phpMyAdmin and you will get the Executed history:

enter image description here

What is the main difference between PATCH and PUT request?

PUT and PATCH methods are similar in nature, but there is a key difference.

PUT - in PUT request, the enclosed entity would be considered as the modified version of a resource which residing on server and it would be replaced by this modified entity.

PATCH - in PATCH request, enclosed entity contains the set of instructions that how the entity which residing on server, would be modified to produce a newer version.

How to pass event as argument to an inline event handler in JavaScript?

to pass the event object:

<p id="p" onclick="doSomething(event)">

to get the clicked child element (should be used with event parameter:

function doSomething(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    console.log(target);
}

to pass the element itself (DOMElement):

<p id="p" onclick="doThing(this)">

see live example on jsFiddle.

You can specify the name of the event as above, but alternatively your handler can access the event parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.

jQuery, get html of a whole element

You can clone it to get the entire contents, like this:

var html = $("<div />").append($("#div1").clone()).html();

Or make it a plugin, most tend to call this "outerHTML", like this:

jQuery.fn.outerHTML = function() {
  return jQuery('<div />').append(this.eq(0).clone()).html();
};

Then you can just call:

var html = $("#div1").outerHTML();

How to go up a level in the src path of a URL in HTML?

Use .. to indicate the parent directory:

background-image: url('../images/bg.png');

How do I see which checkbox is checked?

Try this

index.html

<form action="form.php" method="post">
    Do you like stackoverflow?
    <input type="checkbox" name="like" value="Yes" />  
    <input type="submit" name="formSubmit" value="Submit" /> 
</form>

form.php

<html>
<head>
</head>
<body>

<?php
    if(isset($_POST['like']))
    {
        echo "<h1>You like Stackoverflow.<h1>";
    }
    else
    {
        echo "<h1>You don't like Stackoverflow.</h1>";
    }   
?>

</body>
</html>

Or this

<?php
    if(isset($_POST['like'])) && 
    $_POST['like'] == 'Yes') 
    {
        echo "You like Stackoverflow.";
    }
    else
    {
        echo "You don't like Stackoverflow.";
    }   
?>

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

How to manually include external aar package using new Gradle Android Build System

I've just succeeded!

  1. Copy the mylib-0.1.aar file into the libs/ folder

  2. Add these lines to the bottom of build.gradle (should be app, not project):

    repositories {
       flatDir {
           dirs 'libs'
       }
    }
    dependencies {
        compile 'com.example.lib:mylib:0.1@aar'
    }
    
  3. So far so good. Here comes the most important point:

Gradle needs to access the network for dependencies unless offline mode is enabled.

Make sure that you have enabled Offline work via the checkbox in Project Structures/Gradle

-- OR --

Configure the proxy settings in order to access the network.

To configure the proxy settings you have to modify the project's gradle.properties file, configuring http and https separately as below:

systemProp.http.proxyHost=proxy.example.com
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=user
systemProp.http.proxyPassword=pass
systemProp.http.nonProxyHosts=localhost
systemProp.http.auth.ntlm.domain=example <for NT auth>

systemProp.https.proxyHost=proxy.example.com
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=user
systemProp.https.proxyPassword=pass
systemProp.https.nonProxyHosts=localhost
systemProp.https.auth.ntlm.domain=example <for NT auth>

Hope this works.

How to find the largest file in a directory and its subdirectories?

ls -alR|awk '{ if ($5 > max) {max=$5;ff=$9}} END {print max "\t" ff;}'

Adding asterisk to required fields in Bootstrap 3

This CSS worked for me:

.form-group.required.control-label:before{
   color: red;
   content: "*";
   position: absolute;
   margin-left: -10px;
}

and this HTML:

<div class="form-group required control-label">
  <label for="emailField">Email</label>
  <input type="email" class="form-control" id="emailField" placeholder="Type Your Email Address Here" />
</div>

How do I turn off autocommit for a MySQL client?

For auto commit off then use the below command for sure. Set below in my.cnf file:

    [mysqld]
    autocommit=0

How to find the size of integer array

If array is static allocated:

size_t size = sizeof(arr) / sizeof(int);

if array is dynamic allocated(heap):

int *arr = malloc(sizeof(int) * size);

where variable size is a dimension of the arr.

Correlation heatmap

If your data is in a Pandas DataFrame, you can use Seaborn's heatmap function to create your desired plot.

import seaborn as sns

Var_Corr = df.corr()
# plot the heatmap and annotation on it
sns.heatmap(Var_Corr, xticklabels=Var_Corr.columns, yticklabels=Var_Corr.columns, annot=True)

Correlation plot

From the question, it looks like the data is in a NumPy array. If that array has the name numpy_data, before you can use the step above, you would want to put it into a Pandas DataFrame using the following:

import pandas as pd
df = pd.DataFrame(numpy_data)

Does C# have a String Tokenizer like Java's?

The split method of a string is what you need. In fact the tokenizer class in Java is deprecated in favor of Java's string split method.

What is the right way to POST multipart/form-data using curl?

The following syntax fixes it for you:

curl -v -F key1=value1 -F upload=@localfilename URL

How do I set browser width and height in Selenium WebDriver?

For me, the only thing that worked in Java 7 on OS X 10.9 was this:

// driver = new RemoteWebDriver(new URL(grid), capability);
driver.manage().window().setPosition(new Point(0,0));
driver.manage().window().setSize(new Dimension(1024,768));

Where 1024 is the width, and 768 is the height.

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

I'd recommend reading that PEP the error gives you. The problem is that your code is trying to use the ASCII encoding, but the pound symbol is not an ASCII character. Try using UTF-8 encoding. You can start by putting # -*- coding: utf-8 -*- at the top of your .py file. To get more advanced, you can also define encodings on a string by string basis in your code. However, if you are trying to put the pound sign literal in to your code, you'll need an encoding that supports it for the entire file.

Access denied for root user in MySQL command-line

I had the same issue, and it turned out to be that MariaDB was set to allow only root to log in locally via the unix_socket plug-in, so clearing that setting allowed successfully logging in with the user specified on the command line, provided a correct password is entered, of course. See this answer on Ask Ubuntu

Viewing localhost website from mobile device

Use Conveyor by Keyoti (extensión de Visual Studio). Extension visual studio

Is there a library function for Root mean square error (RMSE) in python?

from sklearn import metrics
import bumpy as np
print(no.sqrt(metrics.mean_squared_error(actual,predicted)))

How to select a CRAN mirror in R

You could also disable all graphical menus by running this or placing it in your Rprofile

options(menu.graphics = FALSE)

Twitter bootstrap 3 two columns full height

Modern and very simple solution:

HTML:

<div class="container">
  <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-9"></div>
  </div>
</div>

CSS:

.row{
    display: flex;
}

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

What is the "right" JSON date format?

The following code has worked for me. This code will print date in DD-MM-YYYY format.

DateValue=DateValue.substring(6,8)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(0,4);

else, you can also use:

DateValue=DateValue.substring(0,4)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(6,8);

Initializing default values in a struct

Yes. bar.a and bar.b are set to true, but bar.c is undefined. However, certain compilers will set it to false.

See a live example here: struct demo

According to C++ standard Section 8.5.12:

if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value

For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.

If you don't really want undefined bar.c to start with, you should also initialize it like you did for bar.a and bar.b.

Placing a textview on top of imageview in android

Try this:

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rel_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
    android:id="@+id/ImageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src=//source of image />

<TextView
    android:id="@+id/ImageViewText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@id/ImageView"
    android:layout_alignTop="@id/ImageView"
    android:layout_alignRight="@id/ImageView"
    android:layout_alignBottom="@id/ImageView"
    android:text=//u r text here
    android:gravity="center"
    />

Hope this could help you.

Delete all duplicate rows Excel vba

The duplicate values in any column can be deleted with a simple for loop.

Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub

Docker compose, running containers in net:host

Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.

Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none

version: '3.7'
services:
  app:
    image: ramansharma/einwohnertomcat:v0.0.1
    deploy:
      replicas: 1
      ports:
       - '8080:8080'
    volumes:
     - type: bind
       source: /proc
       target: /hostfs/proc
       read_only: true
     - type: bind
       source: /sys/fs/cgroup
       target: /hostfs/sys/fs/cgroup
       read_only: true
     - type: bind
       source: /
       target: /hostfs
       read_only: true
    networks:
     hostnet: {}
    networks:
     - einwohner_net
     - elk_elk_net
networks:
 einwohner_net:
 elk_elk_net:
   external: true
 hostnet:
   external: true
   name: host

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

How to split a dataframe string column into two columns?

Surprised I haven't seen this one yet. If you only need two splits, I highly recommend. . .

Series.str.partition

partition performs one split on the separator, and is generally quite performant.

df['row'].str.partition(' ')[[0, 2]]

       0                   2
0  00000       UNITED STATES
1  01000             ALABAMA
2  01001  Autauga County, AL
3  01003  Baldwin County, AL
4  01005  Barbour County, AL

If you need to rename the rows,

df['row'].str.partition(' ')[[0, 2]].rename({0: 'fips', 2: 'row'}, axis=1)

    fips                 row
0  00000       UNITED STATES
1  01000             ALABAMA
2  01001  Autauga County, AL
3  01003  Baldwin County, AL
4  01005  Barbour County, AL

If you need to join this back to the original, use join or concat:

df.join(df['row'].str.partition(' ')[[0, 2]])

pd.concat([df, df['row'].str.partition(' ')[[0, 2]]], axis=1)

                        row      0                   2
0       00000 UNITED STATES  00000       UNITED STATES
1             01000 ALABAMA  01000             ALABAMA
2  01001 Autauga County, AL  01001  Autauga County, AL
3  01003 Baldwin County, AL  01003  Baldwin County, AL
4  01005 Barbour County, AL  01005  Barbour County, AL

Twitter Bootstrap 3, vertically center content

Option 1 is to use display:table-cell. You need to unfloat the Bootstrap col-* using float:none..

.center {
    display:table-cell;
    vertical-align:middle;
    float:none;
}

http://bootply.com/94394


Option 2 is display:flex to vertical align the row with flexbox:

.row.center {
   display: flex;
   align-items: center;
}

http://www.bootply.com/7rAuLpMCwr


Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456

PHP post_max_size overrides upload_max_filesize

Your server configuration settings allows users to upload files upto 16MB (because you have set upload_max_filesize = 16Mb) but the post_max_size accepts post data upto 8MB only. This is why it throws an error.

Quoted from the official PHP site:

  1. To upload large files, post_max_size value must be larger than upload_max_filesize.

  2. memory_limit should be larger than post_max_size

You should always set your post_max_size value greater than the upload_max_filesize value.

failed to push some refs to [email protected]

I had similar issue where local build was working fine however when I push my branch onto heroku it would fail to build. Issue was that I had some devDependencies in my package.json which were not installed during npm install which was causing my build to fail.

If you need access to packages declared under devDependencies in a different buildpack or at runtime, then you can set NPM_CONFIG_PRODUCTION=false or YARN_PRODUCTION=false to skip the pruning step.

Also you can move you devDependencies into dependencies...

Rethrowing exceptions in Java without losing the stack trace

I was just having a similar situation in which my code potentially throws a number of different exceptions that I just wanted to rethrow. The solution described above was not working for me, because Eclipse told me that throw e; leads to an unhandeled exception, so I just did this:

try
{
...
} catch (NoSuchMethodException | SecurityException | IllegalAccessException e) {                    
    throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage() + "\n" + e.getStackTrace().toString());
}

Worked for me....:)

How to reference image resources in XAML?

If you've got an image in the Icons folder of your project and its build action is "Resource", you can refer to it like this:

<Image Source="/Icons/play_small.png" />

That's the simplest way to do it. This is the only way I could figure doing it purely from the resource standpoint and no project files:

var resourceManager = new ResourceManager(typeof (Resources));
var bitmap = resourceManager.GetObject("Search") as System.Drawing.Bitmap;

var memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Position = 0;

var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();

this.image1.Source = bitmapImage;

Using Chrome's Element Inspector in Print Preview Mode?

Note: This answer covers several versions of Chrome, scroll to see v52, v48, v46, v43 and v42 each with their updated changes.

Chrome v52+:

  • Open the Developer Tools (Windows: F12 or Ctrl+Shift+I, Mac: Cmd+Opt+I)
  • Click the Customize and control DevTools hamburger menu button and choose More tools > Rendering settings (or Rendering in newer versions).
  • Check the Emulate print media checkbox at the Rendering tab and select the Print media type.

Chrome v52+

Chrome v48+ (Thanks Alex for noticing):

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (CTRLSHIFTM).
  • Make sure the console is shown by clicking Show console in menu at (1) (ESC key toggles the console if Developer Toolbar has focus).
  • Check Emulate print media at the rendering tab which can be opened by selecting Rendering in menu at (2).

Chrome v48+

Chrome v46+:

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (1).
  • Make sure the console is shown by clicking the menu button (2) > Show console (3) or pressing the ESC key to toggle the console (only works when Developer Toolbar has the focus).
  • Open the Emulation (4) > Media (5) tabs, check CSS media and select print (3).

Chrome v46+ support

Chrome v43+:

  • The drawer icon at step 2 has changed.

Emulate print media query on Chrome v43

Chrome v42:

  • Open the Developer Tools (CTRLSHIFTI or F12)
  • Click the Toggle device mode button in the left top corner (1).
  • Make sure the drawer is shown by clicking the Show drawer button (2) or pressing the ESC key to toggle the drawer.
  • Under Emulation > Media check CSS media and select print (3).

Emulate print media query on Chrome v42

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

Don't quote the column filename

mysql> INSERT INTO risks (status, subject, reference_id, location, category, team,    technology, owner, manager, assessment, notes,filename) 
VALUES ('san', 'ss', 1, 1, 1, 1, 2, 1, 1, 'sment', 'notes','santu');

How to Compare a long value is equal to Long value

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if(a == b.longValue())
    {
        System.out.println("Equals");
    }else{
        System.out.println("not equals");
    }
  }

or:

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if(a == b)
    {
        System.out.println("Equals");
    }else{
        System.out.println("not equals");
    }
  }

Array initializing in Scala

scala> val arr = Array("Hello","World")
arr: Array[java.lang.String] = Array(Hello, World)

Impersonate tag in Web.Config

The identity section goes under the system.web section, not under authentication:

<system.web>
  <authentication mode="Windows"/>
  <identity impersonate="true" userName="foo" password="bar"/>
</system.web>

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

If you don't wish to use interop, you may want to try out OfficeWriter. Depending on how much processing you really need to do on the file, it might be overkill though. You can request a free trial. There's a fully documented api available at the documentation site.

DISCLAIMER: I'm one of the engineers who built the latest version.

Clearing an input text field in Angular2

1. First Method

you have to assign null or empty string here

this.searchValue = null;
//or
this.searchValue = ' ';

Working Plunker

because no event is being fired from angular change detection. so you have to assign some value either null or string with space

2. Second Method

  • use of [(ngModel)] it should work with ngModel.

why ?

because as you did binding with value attribute which is only property binding not event binding. so angular doesn't run change detection because no event relevant to Angular is fired. If you bind to an event then Angular runs change detection and the binding works and value should be changes.

see working example of same with ngModel

Working Example with ngModel

Convert SVG image to PNG with PHP

You can use Raphaël—JavaScript Library and achieve it easily. It will work in IE also.

What jar should I include to use javax.persistence package in a hibernate based application?

If you are developing an OSGi system I would recommend you to download the "bundlefied" version from Springsource Enterprise Bundle Repository.

Otherwise its ok to use a regular jar-file containing the javax.persistence package

How to print all key and values from HashMap in Android?

It's because your TextView recieve new text on every iteration and previuos value thrown away. Concatenate strings by StringBuilder and set TextView value after loop. Also you can use this type of loop:

for (Map.Entry<String, String> e : map.entrySet()) {
    //to get key
    e.getKey();
    //and to get value
    e.getValue();
}

how to toggle (hide/show) a table onClick of <a> tag in java script

inside your function toggleTable when you do this line

document.getElementById("loginLink").onclick = toggleTable(....

you are actually calling the function again. so toggleTable gets called again, and again and again, you're falling in an infinite recursive call.

make it simple.

function toggleTable()
{
     var elem=document.getElementById("loginTable");
     var hide = elem.style.display =="none";
     if (hide) {
         elem.style.display="table";
    } 
    else {
       elem.style.display="none";
    }
}

see this fiddle

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

Visual Studio loading symbols

Unchecking "Enable JavaScript debugging for ASP.NET (Chrome and IE)" in Tools->Options->Debugging->General resolved my case with unavailability to launch VS2017 debugger with pre-set breakpoints.

How to get Bitmap from an Uri?

you can do this structure:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                    Uri selectedImage = imageReturnedIntent.getData();
                    Bundle extras = imageReturnedIntent.getExtras();
                    bitmap = extras.getParcelable("data");
            }
            break;
   }

by this you can easily convert a uri to bitmap. hope help u.

Changing Tint / Background color of UITabBar

for me its very simple to change the color of Tabbar like :-

[self.TabBarController.tabBar setTintColor:[UIColor colorWithRed:0.1294 green:0.5686 blue:0.8353 alpha:1.0]];


[self.TabBarController.tabBar setTintColor:[UIColor "YOUR COLOR"];

Try this!!!

React PropTypes : Allow different types of PropTypes for one prop

import React from 'react';              <--as normal
import PropTypes from 'prop-types';     <--add this as a second line

    App.propTypes = {
        monkey: PropTypes.string,           <--omit "React."
        cat: PropTypes.number.isRequired    <--omit "React."
    };

    Wrong:  React.PropTypes.string
    Right:  PropTypes.string

How to round up integer division and have int result in Java?

To round up an integer division you can use

import static java.lang.Math.abs;

public static long roundUp(long num, long divisor) {
    int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
    return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}

or if both numbers are positive

public static long roundUp(long num, long divisor) {
    return (num + divisor - 1) / divisor;
}

How to set 777 permission on a particular folder?

Easiest way to set permissions to 777 is to connect to Your server through FTP Application like FileZilla, right click on folder, module_installation, and click Change Permissions - then write 777 or check all permissions.

Making text bold using attributed string in swift

If you're working with localised strings, you might not be able to rely on the bold string always being at the end of the sentence. If this is the case then the following works well:

e.g. Query "blah" does not match any items

/* Create the search query part of the text, e.g. "blah". 
   The variable 'text' is just the value entered by  the user. */
let searchQuery = "\"\(text)\""

/* Put the search text into the message */
let message = "Query \(searchQuery). does not match any items"

/* Find the position of the search string. Cast to NSString as we want
   range to be of type NSRange, not Swift's Range<Index> */
let range = (message as NSString).rangeOfString(searchQuery)

/* Make the text at the given range bold. Rather than hard-coding a text size,
   Use the text size configured in Interface Builder. */
let attributedString = NSMutableAttributedString(string: message)
attributedString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(label.font.pointSize), range: range)

/* Put the text in a label */
label.attributedText = attributedString

How to get second-highest salary employees in a table

The simple way is to use OFFSET. Not only second, any position we can query using offset.

SELECT SALARY,NAME FROM EMPLOYEE ORDER BY SALARY DESC LIMIT 1 OFFSET 1 --Second largest

SELECT SALARY,NAME FROM EMPLOYEE ORDER BY SALARY DESC LIMIT 1 OFFSET 9 --For 10th largest

Hide keyboard in react-native

How about placing a touchable component around/beside the TextInput?

var INPUTREF = 'MyTextInput';

class TestKb extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <View style={{ flex: 1, flexDirection: 'column', backgroundColor: 'blue' }}>
                <View>
                    <TextInput ref={'MyTextInput'}
                        style={{
                            height: 40,
                            borderWidth: 1,
                            backgroundColor: 'grey'
                        }} ></TextInput>
                </View>
                <TouchableWithoutFeedback onPress={() => this.refs[INPUTREF].blur()}>
                    <View 
                        style={{ 
                            flex: 1, 
                            flexDirection: 'column', 
                            backgroundColor: 'green' 
                        }} 
                    />
                </TouchableWithoutFeedback>
            </View>
        )
    }
}

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

use this syntax: alter table table_name modify column col_name varchar (10000);

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

I am not sure I understand what you want, but based on what I understood

the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"

you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)

p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")

worked for me, see the picture

enter image description here

I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code

Iterate a list with indexes in Python

If you have multiple lists, you can do this combining enumerate and zip:

list1 = [1, 2, 3, 4, 5]
list2 = [10, 20, 30, 40, 50]
list3 = [100, 200, 300, 400, 500]
for i, (l1, l2, l3) in enumerate(zip(list1, list2, list3)):
    print(i, l1, l2, l3)
Output:
0 1 10 100
1 2 20 200
2 3 30 300
3 4 40 400
4 5 50 500

Note that parenthesis is required after i. Otherwise you get the error: ValueError: need more than 2 values to unpack

How to assign a select result to a variable?

I just had the same problem and...

declare @userId uniqueidentifier
set @userId = (select top 1 UserId from aspnet_Users)

or even shorter:

declare @userId uniqueidentifier
SELECT TOP 1 @userId = UserId FROM aspnet_Users

UIButton title text color

swift 5 version:

By using default inbuilt color:

  1. button.setTitleColor(UIColor.green, for: .normal)

OR

You can use your custom color by using RGB method:

  1. button.setTitleColor(UIColor(displayP3Red: 0.0/255.0, green: 180.0/255.0, blue: 2.0/255.0, alpha: 1.0), for: .normal)

php refresh current page?

Another elegant one is

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;

allowing only alphabets in text box using java script

just use onkeypress event like below:

<input type="text" name="onlyalphabet" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">

Using jQuery to compare two arrays of Javascript objects

I don't think there's a good "jQuery " way to do this, but if you need efficiency, map one of the arrays by a certain key (one of the unique object fields), and then do comparison by looping through the other array and comparing against the map, or associative array, you just built.

If efficiency is not an issue, just compare every object in A to every object in B. As long as |A| and |B| are small, you should be okay.

PySpark: multiple conditions in when clause

You get SyntaxError error exception because Python has no && operator. It has and and & where the latter one is the correct choice to create boolean expressions on Column (| for a logical disjunction and ~ for logical negation).

Condition you created is also invalid because it doesn't consider operator precedence. & in Python has a higher precedence than == so expression has to be parenthesized.

(col("Age") == "") & (col("Survived") == "0")
## Column<b'((Age = ) AND (Survived = 0))'>

On a side note when function is equivalent to case expression not WHEN clause. Still the same rules apply. Conjunction:

df.where((col("foo") > 0) & (col("bar") < 0))

Disjunction:

df.where((col("foo") > 0) | (col("bar") < 0))

You can of course define conditions separately to avoid brackets:

cond1 = col("Age") == "" 
cond2 = col("Survived") == "0"

cond1 & cond2

Postgresql query between date ranges

From PostreSQL 9.2 Range Types are supported. So you can write this like:

SELECT user_id
FROM user_logs
WHERE '[2014-02-01, 2014-03-01]'::daterange @> login_date

this should be more efficient than the string comparison

Is it possible to send a variable number of arguments to a JavaScript function?

For those who were redirected here from Passing variable number of arguments from one function to another (which should not be marked as a duplicate of this question):

If you're trying to pass a variable number of arguments from one function to another, since JavaScript 1.8.5 you can simply call apply() on the second function and pass in the arguments parameter:

var caller = function()
{
    callee.apply( null, arguments );
}

var callee = function()
{
    alert( arguments.length );
}

caller( "Hello", "World!", 88 ); // Shows "3".

Note: The first argument is the this parameter to use. Passing null will call the function from the global context, i.e. as a global function instead of the method of some object.

According to this document, the ECMAScript 5 specification redefined the apply() method to take any "generic array-like object", instead of strictly an Array. Thus, you can directly pass the arguments list into the second function.

Tested in Chrome 28.0, Safari 6.0.5, and IE 10. Try it out with this JSFiddle.

How can I change the app display name build with Flutter?

The way of changing the name for iOS and Android is clearly mentioned in the documentation as follows:

But, the case of iOS after you change the Display Name from Xcode, you are not able to run the application in the Flutter way, like flutter run.

Because the Flutter run expects the app name as Runner. Even if you change the name in Xcode, it doesn't work.

So, I fixed this as follows:

Move to the location on your Flutter project, ios/Runner.xcodeproj/project.pbxproj, and find and replace all instances of your new name with Runner.

Then everything should work in the flutter run way.

But don't forget to change the name display name on your next release time. Otherwise, the App Store rejects your name.

RecyclerView: Inconsistency detected. Invalid item position

this problem may happen when you try clearing your list, if you are going to clear your data list especially when you are using pull to refresh try to use a boolean flag, initialize it as false and inside OnRefresh method make it true, clear your dataList if flag is true just before adding the new data to it and after that make it false.

your code might be like this

 private boolean pullToRefreshFlag = false ;
 private ArrayList<your object> dataList ;
 private Adapter adapter ;

 public class myClass extend Fragment implements SwipeRefreshLayout.OnRefreshListener{

 private void requestUpdateList() {

     if (pullToRefresh) {
        dataList.clear
        pullToRefreshFlag = false;
     }

     dataList.addAll(your data);
     adapter.notifyDataSetChanged;


 @Override
 OnRefresh() {
 PullToRefreshFlag = true
 reqUpdateList() ; 
 }

}

How can I get onclick event on webview in android?

Thats because its tied to the web view not the button. I had the same problem after implementing. The button had no affect but the page in the web view did.

How do I write a Python dictionary to a csv file?

Your code was very close to working.

Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.

Here's some code that writes each key/value pair on a separate row:

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

If instead you want all the keys on one row and all the values on the next, that is also easy:

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr) so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f).

How can I start and check my MySQL log?

Its given on OFFICIAL MYSQL website.

SET GLOBAL general_log = 'ON';

You can also use custom path:

[mysqld]
# Set Slow Query Log
long_query_time = 1
slow_query_log = 1
slow_query_log_file = "C:/slowquery.log"

#Set General Log
log = "C:/genquery.log"

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

I made some modification to @jvd10's solution. The '!important' seems too strong that the container doesn't adapt well when TOC sidebar is displayed. I removed it and added 'min-width' to limit the minimal width.

Here is my .juyputer/custom/custom.css:

/* Make the notebook cells take almost all available width and limit minimal width to 1110px */
.container {
    width: 99%;
    min-width: 1110px;
}   

/* Prevent the edit cell highlight box from getting clipped;
 * important so that it also works when cell is in edit mode*/
div.cell.selected {
    border-left-width: 1px;
}

Run Excel Macro from Outside Excel Using VBScript From Command Line

I tried the above methods but I got the "macro cannot be found" error. This is final code that worked!

Option Explicit

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True

  ' Import Add-Ins
xlApp.Workbooks.Open "C:\<pathOfXlaFile>\MyMacro.xla"
xlApp.AddIns("MyMacro").Installed = True

'
Open Excel workbook
Set xlBook = xlApp.Workbooks.Open("<pathOfXlsFile>\MyExcel.xls", 0, True)

' Run Macro
xlApp.Run "Sheet1.MyMacro"

xlBook.Close
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Quit

In my case, MyMacro happens to be under Sheet1, thus Sheet1.MyMacro.

how to view the contents of a .pem certificate

Use the -printcert command like this:

keytool -printcert -file certificate.pem

Case insensitive comparison NSString

An alternative if you want more control than just case insensitivity is:

[someString compare:otherString options:NSCaseInsensitiveSearch];

Numeric search and diacritical insensitivity are two handy options.

Disable beep of Linux Bash on Windows 10

In addition to what jgr208 said, you may have a ~/.profile file already and ~/.bash_profile may not be present, as was the case with me.

In this case, add setterm -blength 0 to the .profile.

If you create a .bash_profile, your .profile will be ignored and anything Windows wrote there will not work.

Replace text inside td using jQuery having td containing other elements

A bit late to the party, but JQuery change inner text but preserve html has at least one approach not mentioned here:

var $td = $("#demoTable td");
$td.html($td.html().replace('Tap on APN and Enter', 'new text'));

Without fixing the text, you could use (snother)[https://stackoverflow.com/a/37828788/1587329]:

var $a = $('#demoTable td');
var inner = '';
$a.children.html().each(function() {
    inner = inner + this.outerHTML;
});
$a.html('New text' + inner);

How do I change Android Studio editor's background color?

How do I change Android Studio editor's background color?

Changing Editor's Background

Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there

IDE will display a dialog like this, Press 'No'

Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?

Changing IDE's Theme

Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there

Press OK. Android Studio will ask you to restart the IDE.

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

Shell calls to reverse (as mentioned above) are very good to debug these problems, but there are two critical conditions:

  • you must supply arguments that matches whatever arguments the view needs,
  • these arguments must match regexp patterns.

Yes, it's logical. Yes, it's also confusing because reverse will only throw the exception and won't give you any further hints.

An example of URL pattern:

url(r'^cookies/(?P<hostname>[^/]+)/(?P<url_id>\d+)/$', 'register_site.views.show_cookies', name='show_cookies'),

And then what happens in shell:

>>> from register_site.views import show_cookies
>>> reverse(show_cookies)
NoReverseMatch: Reverse for 'register_site.views.show_cookies' with arguments '()' and keyword arguments '{}' not found.

It doesn't work because I supplied no arguments.

>>> reverse('show_cookies', kwargs={'url_id':123,'hostname': 'aaa'})
'/cookies/aaa/123'

Now it worked, but...

>>> reverse('show_cookies', kwargs={'url_id':'x','hostname': 'www.dupa.com'})
NoReverseMatch: Reverse for 'show_cookies' with arguments '()' and keyword arguments '{'url_id': 'x', 'hostname': 'www.dupa.com'}' not found.

Now it didn't work because url_id didn't match the regexp (expected numeric, supplied string).

You can use reverse with both positional arguments and keyword arguments. The syntax is:

reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None)

As it comes to the url template tag, there's funny thing about it. Django documentation gives example of using quoted view name:

{% url 'news.views.year_archive' yearvar %}

So I used it in a similar way in my HTML template:

{% url 'show_cookies' hostname=u.hostname url_id=u.pk %}

But this didn't work for me. But the exception message gave me a hint of what could be wrong - note the double single quotes around view name:

Reverse for ''show_cookies'' with arguments...

It started to work when I removed the quotes:

{% url show_cookies hostname=u.hostname url_id=u.pk %}

And this is confusing.

What is better, adjacency lists or adjacency matrices for graph problems in C++?

Lets assume we have a graph which has n number of nodes and m number of edges,

Example graph
enter image description here

Adjacency Matrix: We are creating a matrix that has n number of rows and columns so in memory it will take space that is proportional to n2. Checking if two nodes named as u and v has an edge between them will take T(1) time. For example checking for (1, 2) is an edge will look like as follows in the code:

if(matrix[1][2] == 1)

If you want to identify all edges, you have to iterate over matrix at this will require two nested loops and it will take T(n2). (You may just use the upper triangular part of the matrix to determine all edges but it will be again T(n2))

Adjacency List: We are creating a list that each node also points to another list. Your list will have n elements and each element will point to a list that has number of items that is equal to number of neighbors of this node (look image for better visualization). So it will take space in memory that is proportional to n+m. Checking if (u, v) is an edge will take O(deg(u)) time in which deg(u) equals number of neighbors of u. Because at most, you have to iterate over the list that is pointed by the u. Identifying all edges will take T(n+m).

Adjacency list of example graph

enter image description here
You should make your choice according to your needs. Because of my reputation I couldn't put image of matrix, sorry for that

Add list to set?

Here is how I usually do it:

def add_list_to_set(my_list, my_set):
    [my_set.add(each) for each in my_list]
return my_set

How to count string occurrence in string?

The parameters: ustring: the superset string countChar: the substring

A function to count substring occurrence in JavaScript:

_x000D_
_x000D_
function subStringCount(ustring, countChar){
  var correspCount = 0;
  var corresp = false;
  var amount = 0;
  var prevChar = null;
  
 for(var i=0; i!=ustring.length; i++){

     if(ustring.charAt(i) == countChar.charAt(0) && corresp == false){
       corresp = true;
       correspCount += 1;
       if(correspCount == countChar.length){
         amount+=1;
         corresp = false;
         correspCount = 0;
       }
       prevChar = 1;
     }
     else if(ustring.charAt(i) == countChar.charAt(prevChar) && corresp == true){
       correspCount += 1;
       if(correspCount == countChar.length){
         amount+=1;
         corresp = false;
         correspCount = 0;
         prevChar = null;
       }else{
         prevChar += 1 ;
       }
     }else{
       corresp = false;
       correspCount = 0;
     }
 } 
 return amount;
}

console.log(subStringCount('Hello World, Hello World', 'll'));
_x000D_
_x000D_
_x000D_

Exception.Message vs Exception.ToString()

Well, I'd say it depends what you want to see in the logs, doesn't it? If you're happy with what ex.Message provides, use that. Otherwise, use ex.toString() or even log the stack trace.

What's the best way to get the current URL in Spring MVC?

You can also add a UriComponentsBuilder to the method signature of your controller method. Spring will inject an instance of the builder created from the current request.

@GetMapping
public ResponseEntity<MyResponse> doSomething(UriComponentsBuilder uriComponentsBuilder) {
    URI someNewUriBasedOnCurrentRequest = uriComponentsBuilder
            .replacePath(null)
            .replaceQuery(null)
            .pathSegment("some", "new", "path")
            .build().toUri();
  //...
}

Using the builder you can directly start creating URIs based on the current request e.g. modify path segments.

See also UriComponentsBuilderMethodArgumentResolver

getResourceAsStream() is always returning null

I don't know if this applies to JAX-WS, but for JAX-RS I was able to access a file by injecting a ServletContext and then calling getResourceAsStream() on it:

@Context ServletContext servletContext;
...
InputStream is = servletContext.getResourceAsStream("/WEB-INF/test_model.js");

Note that, at least in GlassFish 3.1, the path had to be absolute, i.e., start with slash. More here: How do I use a properties file with jax-rs?

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

I've learned that error messages like this are usually right. When it couldn't POSSIBLY (in your mind) be what the error being reported says, you go hunting for a problem in another area...only to find out hours later that the original error message was indeed right.

Since you're using Eclipse, I think Thilo has it right The most likely reason you are getting this message is because one of your projects is compiling 1.6 classes. It doesn't matter if you only have a 1.5 JRE on the system, because Eclipse has its own compiler (not javac), and only needs a 1.5 JRE to compile 1.6 classes. It may be weird, and a setting needs to be unchecked to allow this, but I just managed to do it.

For the project in question, check the Project Properties (usually Alt+Enter), Java Compiler section. Here's an image of a project configured to compile 1.6, but with only a 1.5 JRE.

enter image description here

How to use regex in String.contains() method in Java

public static void main(String[] args) {
    String test = "something hear - to - find some to or tows";
    System.out.println("1.result: " + contains("- to -( \\w+) som", test, null));
    System.out.println("2.result: " + contains("- to -( \\w+) som", test, 5));
}
static boolean contains(String pattern, String text, Integer fromIndex){
    if(fromIndex != null && fromIndex < text.length())
        return Pattern.compile(pattern).matcher(text).find();

    return Pattern.compile(pattern).matcher(text).find();
}

1.result: true

2.result: true

How to change the map center in Leaflet.js

You can also use:

map.setView(new L.LatLng(40.737, -73.923), 8);

It just depends on what behavior you want. map.panTo() will pan to the location with zoom/pan animation, while map.setView() immediately set the new view to the desired location/zoom level.

How can I clear event subscriptions in C#?

The best practice to clear all subscribers is to set the someEvent to null by adding another public method if you want to expose this functionality to outside. This has no unseen consequences. The precondition is to remember to declare SomeEvent with the keyword 'event'.

Please see the book - C# 4.0 in the nutshell, page 125.

Some one here proposed to use Delegate.RemoveAll method. If you use it, the sample code could follow the below form. But it is really stupid. Why not just SomeEvent=null inside the ClearSubscribers() function?

public void ClearSubscribers ()
{
   SomeEvent = (EventHandler) Delegate.RemoveAll(SomeEvent, SomeEvent);
   // Then you will find SomeEvent is set to null.
}

How to get Node.JS Express to listen only on localhost?

You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.

Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:

var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);

app.get('/', function(req, res) {
    res.send("Hello World!");
});

server.listen(3000, 'localhost');
server.on('listening', function() {
    console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});

This works just fine in nodejs v0.6+ and Express v3.0+.

What is the default Jenkins password?

I don't believe that the Jenkins user that is installed via apt has a password. If it does, I have never seen documentation. Based on the commands you entered, I am guessing you are using a Debian distro?

Is there any particular reason you must use the jenkins user to do the install instead of the user which was set up when you created your instance?

Pass array to where in Codeigniter Active Record

Use where_in()

$ids = array('20', '15', '22', '46', '86');
$this->db->where_in('id', $ids );

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

From an answer of @NimChimpsky in similar question:

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

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

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

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

Binding value to input in Angular JS

{{widget.title}} Try this it will work

How can I make a thumbnail <img> show a full size image when clicked?

<img src='thumb.gif' onclick='this.src="full_size.gif"' />

Of course you can change the onclick event to load the image wherever you want.

How can I pass a file argument to my bash script using a Terminal command in Linux?

Assuming you do as David Zaslavsky suggests, so that the first argument simply is the program to run (no option-parsing required), you're dealing with the question of how to pass arguments 2 and on to your external program. Here's a convenient way:

#!/bin/bash
ext_program="$1"
shift
"$ext_program" "$@"

The shift will remove the first argument, renaming the rest ($2 becomes $1, and so on).$@` refers to the arguments, as an array of words (it must be quoted!).

If you must have your --file syntax (for example, if there's a default program to run, so the user doesn't necessarily have to supply one), just replace ext_program="$1" with whatever parsing of $1 you need to do, perhaps using getopt or getopts.

If you want to roll your own, for just the one specific case, you could do something like this:

if [ "$#" -gt 0 -a "${1:0:6}" == "--file" ]; then
    ext_program="${1:7}"
else
    ext_program="default program"
fi

Reverse ip, find domain names on ip address

You can use nslookup on the IP. Reverse DNS is defined with the .in-addr.arpa domain.

Example:

nslookup somedomain.com

yields 123.21.2.3, and then you do:

nslookup 123.21.2.3

this will ask 3.2.21.123.in-addr.arpa and yield the domain name (if there is one defined for reverse DNS).

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

And the simplest solution - check if your slash is back...

I spent about an hour trying to figure out what's wrong with SERVER/INSTANCENAME when everything is configured correctly, named pipes, user access rights... and suddenly it struck me, it's not a slash, it's a backslash (\).

The horror, the shame...

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

There are two steps to fix this.

First edit phpMyAdmin/libraries/DatabaseInterface.class.php

Change:

    if (PMA_MYSQL_INT_VERSION >  50503) {
        $default_charset = 'utf8mb4';
        $default_collation = 'utf8mb4_general_ci';
    } else {
        $default_charset = 'utf8';
        $default_collation = 'utf8_general_ci';
    }

To:

    //if (PMA_MYSQL_INT_VERSION >  50503) {
    //    $default_charset = 'utf8mb4';
    //    $default_collation = 'utf8mb4_general_ci';
    //} else {
        $default_charset = 'utf8';
        $default_collation = 'utf8_general_ci';
    //}

Then delete this cookie from your browser "pma_collation_connection".
Or delete all Cookies.

Then restart your phpMyAdmin.

(It would be nice if phpMyAdmin allowed you to set the charset and collation per server in the config.inc.php)

How to deserialize xml to object

Your classes should look like this

[XmlRoot("StepList")]
public class StepList
{
    [XmlElement("Step")]
    public List<Step> Steps { get; set; }
}

public class Step
{
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("Desc")]
    public string Desc { get; set; }
}

Here is my testcode.

string testData = @"<StepList>
                        <Step>
                            <Name>Name1</Name>
                            <Desc>Desc1</Desc>
                        </Step>
                        <Step>
                            <Name>Name2</Name>
                            <Desc>Desc2</Desc>
                        </Step>
                    </StepList>";

XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
    StepList result = (StepList) serializer.Deserialize(reader);
}

If you want to read a text file you should load the file into a FileStream and deserialize this.

using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open)) 
{
    StepList result = (StepList) serializer.Deserialize(fileStream);
}

How to remove leading and trailing spaces from a string

String.Trim

Removes all leading and trailing white-space characters from the current String object.

Usage:

txt = txt.Trim();

If this isn't working then it highly likely that the "spaces" aren't spaces but some other non printing or white space character, possibly tabs. In this case you need to use the String.Trim method which takes an array of characters:

  char[] charsToTrim = { ' ', '\t' };
  string result = txt.Trim(charsToTrim);

Source

You can add to this list as and when you come across more space like characters that are in your input data. Storing this list of characters in your database or configuration file would also mean that you don't have to rebuild your application each time you come across a new character to check for.

NOTE

As of .NET 4 .Trim() removes any character that Char.IsWhiteSpace returns true for so it should work for most cases you come across. Given this, it's probably not a good idea to replace this call with the one that takes a list of characters you have to maintain.

It would be better to call the default .Trim() and then call the method with your list of characters.

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

You are having issue with newly MySQL version that came with "caching_sha2_password" plugin, follow the below command to get it resolved.

DROP USER 'your_user_name'@'%';
CREATE USER 'your_user_name'@'%' IDENTIFIED WITH mysql_native_password BY 'your_user_password';
GRANT ALL PRIVILEGES ON your_db_name.* TO 'your_user_name'@'%' identified by 'your_user_password';

Or you can just use the below command to keep your privileges as it is:

ALTER USER your_user_name IDENTIFIED WITH mysql_native_password;

Java IOException "Too many open files"

Recently, I had a program batch processing files, I have certainly closed each file in the loop, but the error still there.

And later, I resolved this problem by garbage collect eagerly every hundreds of files:

int index;
while () {
    try {
        // do with outputStream...
    } finally {
        out.close();
    }
    if (index++ % 100 = 0)
        System.gc();
}

Sending data from HTML form to a Python script in Flask

You need a Flask view that will receive POST data and an HTML form that will send it.

from flask import request

@app.route('/addRegion', methods=['POST'])
def addRegion():
    ...
    return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
    Project file path: <input type="text" name="projectFilePath"><br>
    <input type="submit" value="Submit">
</form>

Server certificate verification failed: issuer is not trusted

can you try to run svn checkout once manually to your URL https://yoururl/trunk C:\ant-1.8.1\Test_Checkout using command line and accept certificate.

Or as @AndrewSpear says below

Rather than checking out manually run svn list https://your.repository.url from Terminal (Mac) / Command Line (Win) to get the option to accept the certificate permanently

svn will ask you for confirmation. accept it permanently.

After that this should work for subsequent requests from ant script.

Correctly determine if date string is a valid date in that format

Determine if any string is a date

function checkIsAValidDate($myDateString){
    return (bool)strtotime($myDateString);
}

How to loop in excel without VBA or macros?

I was just searching for something similar:

I want to sum every odd row column.

SUMIF has TWO possible ranges, the range to sum from, and a range to consider criteria in.

SUMIF(B1:B1000,1,A1:A1000)

This function will consider if a cell in the B range is "=1", it will sum the corresponding A cell only if it is.

To get "=1" to return in the B range I put this in B:

=MOD(ROWNUM(B1),2)

Then auto fill down to get the modulus to fill, you could put and calculatable criteria here to get the SUMIF or SUMIFS conditions you need to loop through each cell.

Easier than ARRAY stuff and hides the back-end of loops!

Homebrew install specific version of formula?

Homebrew changed recently. Things that used to work do not work anymore. The easiest way I found to work (January 2021), was to:

  • Find the .rb file for my software (first go to Formulas, find the one I need and then click "History"; for CMake, this is at https://github.com/Homebrew/homebrew-core/commits/master/Formula/cmake.rb)
    • Pick the desired version among the revisions, e.g. 3.18.4, click three dots in the top right corner of the .rb file diff (...) and then click Raw. Copy the URL.
  • Unlink the old version brew unlink cmake
  • Installing directly from the git URL does not work anymore (brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/2bf16397f163187ae5ac8be41ca7af25b5b2e2cc/Formula/cmake.rb will fail)
    • Instead, download it and install from a local file curl -O https://raw.githubusercontent.com/Homebrew/homebrew-core/2bf16397f163187ae5ac8be41ca7af25b5b2e2cc/Formula/cmake.rb && brew install ./cmake.rb

Voila! You can delete the downloaded .rb file now.

Text size and different android screen sizes

Sometimes, it's better to have only three options

 style="@android:style/TextAppearance.Small"

Use small and large to differentiate from normal screen size.

<TextView
            android:id="@+id/TextViewTopBarTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@android:style/TextAppearance.Small"/>

For normal, you don't have to specify anything.

<TextView
            android:id="@+id/TextViewTopBarTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

Using this, you can avoid testing and specifying dimensions for different screen sizes.

How to increase the timeout period of web service in asp.net?

1 - You can set a timeout in your application :

var client = new YourServiceReference.YourServiceClass();
client.Timeout = 60; // or -1 for infinite

It is in milliseconds.

2 - Also you can increase timeout value in httpruntime tag in web/app.config :

<configuration>
     <system.web>
          <httpRuntime executionTimeout="<<**seconds**>>" />
          ...
     </system.web>
</configuration>

For ASP.NET applications, the Timeout property value should always be less than the executionTimeout attribute of the httpRuntime element in Machine.config. The default value of executionTimeout is 90 seconds. This property determines the time ASP.NET continues to process the request before it returns a timed out error. The value of executionTimeout should be the proxy Timeout, plus processing time for the page, plus buffer time for queues. -- Source

Stopping Excel Macro executution when pressing Esc won't work

Use CRTL+BREAK to suspend execution at any point. You will be put into break mode and can press F5 to continue the execution or F8 to execute the code step-by-step in the visual debugger.

Of course this only works when there is no message box open, so if your VBA code constantly opens message boxes for some reason it will become a little tricky to press the keys at the right moment.

You can even edit most of the code while it is running.

Use Debug.Print to print out messages to the Immediate Window in the VBA editor, that's way more convenient than MsgBox.

Use breakpoints or the Stop keyword to automatically halt execution in interesting areas.

You can use Debug.Assert to halt execution conditionally.

Update Git submodule to latest commit on origin

It seems like two different scenarios are being mixed together in this discussion:

Scenario 1

Using my parent repository's pointers to submodules, I want to check out the commit in each submodule that the parent repository is pointing to, possibly after first iterating through all submodules and updating/pulling these from remote.

This is, as pointed out, done with

git submodule foreach git pull origin BRANCH
git submodule update

Scenario 2, which I think is what OP is aiming at

New stuff has happened in one or more submodules, and I want to 1) pull these changes and 2) update the parent repository to point to the HEAD (latest) commit of this/these submodules.

This would be done by

git submodule foreach git pull origin BRANCH
git add module_1_name
git add module_2_name
......
git add module_n_name
git push origin BRANCH

Not very practical, since you would have to hardcode n paths to all n submodules in e.g. a script to update the parent repository's commit pointers.

It would be cool to have an automated iteration through each submodule, updating the parent repository pointer (using git add) to point to the head of the submodule(s).

For this, I made this small Bash script:

git-update-submodules.sh

#!/bin/bash

APP_PATH=$1
shift

if [ -z $APP_PATH ]; then
  echo "Missing 1st argument: should be path to folder of a git repo";
  exit 1;
fi

BRANCH=$1
shift

if [ -z $BRANCH ]; then
  echo "Missing 2nd argument (branch name)";
  exit 1;
fi

echo "Working in: $APP_PATH"
cd $APP_PATH

git checkout $BRANCH && git pull --ff origin $BRANCH

git submodule sync
git submodule init
git submodule update
git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"

for i in $(git submodule foreach --quiet 'echo $path')
do
  echo "Adding $i to root repo"
  git add "$i"
done

git commit -m "Updated $BRANCH branch of deployment repo to point to latest head of submodules"
git push origin $BRANCH

To run it, execute

git-update-submodules.sh /path/to/base/repo BRANCH_NAME

Elaboration

First of all, I assume that the branch with name $BRANCH (second argument) exists in all repositories. Feel free to make this even more complex.

The first couple of sections is some checking that the arguments are there. Then I pull the parent repository's latest stuff (I prefer to use --ff (fast-forwarding) whenever I'm just doing pulls. I have rebase off, BTW).

git checkout $BRANCH && git pull --ff origin $BRANCH

Then some submodule initializing, might be necessary, if new submodules have been added or are not initialized yet:

git submodule sync
git submodule init
git submodule update

Then I update/pull all submodules:

git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"

Notice a few things: First of all, I'm chaining some Git commands using && - meaning previous command must execute without error.

After a possible successful pull (if new stuff was found on the remote), I do a push to ensure that a possible merge-commit is not left behind on the client. Again, it only happens if a pull actually brought in new stuff.

Finally, the final || true is ensuring that script continues on errors. To make this work, everything in the iteration must be wrapped in the double-quotes and the Git commands are wrapped in parentheses (operator precedence).

My favourite part:

for i in $(git submodule foreach --quiet 'echo $path')
do
  echo "Adding $i to root repo"
  git add "$i"
done

Iterate all submodules - with --quiet, which removes the 'Entering MODULE_PATH' output. Using 'echo $path' (must be in single-quotes), the path to the submodule gets written to output.

This list of relative submodule paths is captured in an array ($(...)) - finally iterate this and do git add $i to update the parent repository.

Finally, a commit with some message explaining that the parent repository was updated. This commit will be ignored by default, if nothing was done. Push this to origin, and you're done.

I have a script running this in a Jenkins job that chains to a scheduled automated deployment afterwards, and it works like a charm.

I hope this will be of help to someone.

Find the number of columns in a table

It's working (mysql) :

SELECT TABLE_NAME , count(COLUMN_NAME)
FROM information_schema.columns
GROUP BY TABLE_NAME 

What is the difference between class and instance methods?

Also remember, the same idea applies to variables. You will come across terms like static, member, instance, class and so on when talking about variables the same as you would for methods/functions.

It seems the common term in the Obj-C community is ivar for instance variable, but I am not an Obj-C guy, yet.

Can a JSON value contain a multiline string

Not pretty good solution, but you can try the hjson tool. It allows you to write text multi-lined in editor and then converts it to the proper valid JSON format.

Note: it adds '\n' characters for the new lines, but you can simply delete them in any text editor with the "Replace all.." function.

Bootstrap 3 navbar active li not changing background-color

You need to add CSS to .active instead of .active a.

Fiddle: http://jsfiddle.net/T5X6h/2/

Something like this:

.navbar-default .navbar-nav > .active{
    color: #000;
    background: #d65c14;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
    color: #000;
    background: #d65c14;
}

How to loop through an array containing objects and access their properties

Looping through an array of objects is a pretty fundamental functionality. This is what works for me.

_x000D_
_x000D_
var person = [];_x000D_
person[0] = {_x000D_
  firstName: "John",_x000D_
  lastName: "Doe",_x000D_
  age: 60_x000D_
};_x000D_
_x000D_
var i, item;_x000D_
_x000D_
for (i = 0; i < person.length; i++) {_x000D_
  for (item in person[i]) {_x000D_
    document.write(item + ": " + person[i][item] + "<br>");_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Find a private field with Reflection?

Yes, however you will need to set your Binding flags to search for private fields (if your looking for the member outside of the class instance).

The binding flag you will need is: System.Reflection.BindingFlags.NonPublic

Why can't I have "public static const string S = "stuff"; in my Class?

A const member is considered static by the compiler, as well as implying constant value semantics, which means references to the constant might be compiled into the using code as the value of the constant member, instead of a reference to the member.

In other words, a const member containing the value 10, might get compiled into code that uses it as the number 10, instead of a reference to the const member.

This is different from a static readonly field, which will always be compiled as a reference to the field.

Note, this is pre-JIT. When the JIT'ter comes into play, it might compile both these into the target code as values.

Python pandas: fill a dataframe row by row

This is a simpler version

import pandas as pd
df = pd.DataFrame(columns=('col1', 'col2', 'col3'))
for i in range(5):
   df.loc[i] = ['<some value for first>','<some value for second>','<some value for third>']`

How to revert the last migration?

If you are facing trouble while reverting back the migration, and somehow have messed it, you can perform fake migrations.

./manage.py migrate <name> --ignore-ghost-migrations --merge --fake

For django version < 1.7 this will create entry in south_migrationhistory table, you need to delete that entry.

Now you'll be able to revert back the migration easily.

PS: I was stuck for a lot of time and performing fake migration and then reverting back helped me out.