Programs & Examples On #Cdo

CDO is a free implementation of a Distributed Shared Model on top of the Eclipse Modeling Framework (EMF). With CDO, programmers can easily enhance existing EMF models in such a way that they can be stored and subsequently maintained in a central model repository.

CSS grid wrapping

I had a similar situation. On top of what you did, I wanted to center my columns in the container while not allowing empty columns to for them left or right:

.grid { 
    display: grid;
    grid-gap: 10px;
    justify-content: center;
    grid-template-columns: repeat(auto-fit, minmax(200px, auto));
}

Change the location of the ~ directory in a Windows install of Git Bash

1.Right click to Gitbash shortcut choose Properties
2.Choose "Shortcut" tab
3.Type your starting directory to "Start in" field
4.Remove "--cd-to-home" part from "Target" field

ffprobe or avprobe not found. Please install one

Compiling the last answers into one:

If you're on Windows, use chocolatey:

choco install ffmpeg

If you are on Mac, use Brew:

brew install ffmpeg

If you are on a Debian Linux distribution, use apt:

sudo apt-get install ffmpeg

And make sure Youtube-dl is updated:

youtube-dl -U

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

For my issue, I didn't want my images scaled to 100% when they weren't intended to be as large as the container.

For my xs container (<768px as .container), not having a fixed width drove the issue, so I put one back on to it (less the 15px col padding).

// Helps bootstrap 3.0 keep images constrained to container width when width isn't set a fixed value (below 768px), while avoiding all images at 100% width.
// NOTE: proper function relies on there being no inline styling on the element being given a defined width ( '.container'  )

function setWidth() {
    width_val = $( window ).width();
    if( width_val < 768 ) {
        $( '.container' ).width( width_val - 30 );
    } else {
        $( '.container' ).removeAttr( 'style' );
    }
}

setWidth();
$( window ).resize( setWidth );

What is the runtime performance cost of a Docker container?

Docker isn't virtualization, as such -- instead, it's an abstraction on top of the kernel's support for different process namespaces, device namespaces, etc.; one namespace isn't inherently more expensive or inefficient than another, so what actually makes Docker have a performance impact is a matter of what's actually in those namespaces.


Docker's choices in terms of how it configures namespaces for its containers have costs, but those costs are all directly associated with benefits -- you can give them up, but in doing so you also give up the associated benefit:

  • Layered filesystems are expensive -- exactly what the costs are vary with each one (and Docker supports multiple backends), and with your usage patterns (merging multiple large directories, or merging a very deep set of filesystems will be particularly expensive), but they're not free. On the other hand, a great deal of Docker's functionality -- being able to build guests off other guests in a copy-on-write manner, and getting the storage advantages implicit in same -- ride on paying this cost.
  • DNAT gets expensive at scale -- but gives you the benefit of being able to configure your guest's networking independently of your host's and have a convenient interface for forwarding only the ports you want between them. You can replace this with a bridge to a physical interface, but again, lose the benefit.
  • Being able to run each software stack with its dependencies installed in the most convenient manner -- independent of the host's distro, libc, and other library versions -- is a great benefit, but needing to load shared libraries more than once (when their versions differ) has the cost you'd expect.

And so forth. How much these costs actually impact you in your environment -- with your network access patterns, your memory constraints, etc -- is an item for which it's difficult to provide a generic answer.

A Generic error occurred in GDI+ in Bitmap.Save method

I use this solution

int G = 0;

private void toolStripMenuItem17_Click(object sender, EventArgs e)
{
  Directory.CreateDirectory("picture");// ??? ??????? ????? ???? ?? ???? ???? ????????
  G = G + 1;
  FormScreen();
  memoryImage1.Save("picture\\picture" + G.ToString() + ".jpg");
  pictureBox1.Image = Image.FromFile("picture\\picture" + G.ToString() + ".jpg");
}

How to send a simple email from a Windows batch file?

If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.

I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.

A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.

Strip off URL parameter with PHP

This is to complement Marc B's answer with an example, while it may look quite long, it's a safe way to remove a parameter. In this example we remove page_number

<?php
$x = 'http://url.com/search/?location=london&page_number=1';

$parsed = parse_url($x);
$query = $parsed['query'];

parse_str($query, $params);

unset($params['page_number']);
$string = http_build_query($params);
var_dump($string);

Make first letter of a string upper case (with maximum performance)

string s_Val = "test";
if (s_Val != "")
{
   s_Val  = char.ToUpper(s_Val[0]);
   if (s_Val.Length > 1)
   {
      s_Val += s_Val.Substring(1);
   }
 }

System not declared in scope?

Chances are that you've not included the header file that declares system().

In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include preprocessor directive. As the code does not #include the header file in which system() is declared, the compilation fails.

To fix this issue, find out which header file provides you with the declaration of system() and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>

Python base64 data decode

Well, I assume you are not on Interactive Mode and you used this code to decode your string:

import base64
your_string = 'Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YHcAAAAABDlgeCAAAAAEOWB5QAAAAAQ5YHpkNx8H9Dlge4REqBx0OWB8pEpZ10Q5YH3ES2lxFDlgfuRIuPbEOWB/9EA9SqQ5YIEUIFJtxDlggjAAAAAEOWCDVDDMm3Q5YIR0N5wOtDlghZQ4GkeEOWCGtDD0CbQ5YIfQAAAABDlgiOAAAAAEOWCKAAAAAAQ5YIsgAAAABDlob5AAAAAEOWhwsAAAAAQ5aHHQAAAABDlocvAAAAAEOWh0FBC+dQQ5aHU0NJ9WdDlodlQ9RK6kOWh3dEDRdFQ5aHiUQARjZDloebQ5xn3kOWh61C1TYMQ5aHvwAAAABDlofRAAAAAEOWh+MAAAAAQ5aH9QAAAABDnFl9AAAAAEOcWZAAAAAAQ5xZpAAAAABDnFm3AAAAAEOcWctDH72jQ5xZ3kNDentDnFnxQ0QCp0OcWgVDK52XQ5xaGEMDUuNDnFosAAAAAEOcWj8AAAAAQ5xaUwAAAABDnFpmAAAAAEOcWnkAAAAAQ5xajQAAAABDnFqgAAAAAEOcWrRBnlHwQ5xax0MvOY9DnFraQ6AiZkOcWu5DquEAQ5xbAUNtwQNDnFsVQqVdQEOcWygAAAAAQ5xbPAAAAABDnFtPAAAAAEOcW2IAAAAAQ6Cg+AAAAABDoKEMAAAAAEOgoSEAAAAAQ6ChNQAA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5Coc28REWQjAAAAABERZDKAAAAAERFkQgAAAAAREWRRgAAAABER8aUAAAAAERHxtQAAAAAREfHEwAAAABER8dTAAAAAERHx5JDh8FaREfH0UO9DJBER8gRQ9bfKERHyFBDzkoWREfIkEOuMHxER8jPAAAAAERHyQ4AAAAAREfJTgAAAABER8mNAAAAAERIbk4AAAAAREhujgAAAABESG7OAAAAAERIbw4AAAAAREhvTkMM9UlESG+NQ083Y0RIb81DOgL9REhwDUK2XghESHBNAAAAAERIcI0AAAAAREhwzQAAAABESHEMAAAAAERKh+IAAAAAREqIIwAAAABESohkAAAAAERKiKYAAAAAREqI50Lh96RESokoQ35MV0RKiWlDnMTYREqJqkNxeg9ESonrQr2M/kRKii0AAAAAREqKbgAAAABESoqvAAAAAERKivAAAAAAREvFtwAAAABES8X5AAAAAERLxjsAAAAAREvGfQAAAABES8a/QwTfiURLxwFDcL+ZREvHQ0OJfrJES8eFQ2HTSURLx8dDAQzpREvICQAAAABES8hLAAAAAERLyI0AAAAAREvIzwAAAABES8wpAAAAAERLzGsAAAAAREvMrQAAAABES8zvAAAAAERLzTFC78e2REvNc0NWbJ9ES821Q5QpeERLzfdDbnPBREvOOUJOhwhES857AAAAAERLzrwAAAAAREvO/gAAAABES89AAAAAAERMDGoAAAAAREwMrQAAAABETAzvAAAAAERMDTEAAAAAREwNc0MbaL1ETA21Q4XDPkRMDfdDlMa4REwOOkNYuqFETA58QoUC7kRMDr4AAAAAREwPAAAAAABETA9CAAAAAERMD4QAAAAARE+u2AAAAABET68dAAAAAERPr2EAAAAARE+vpgAAAABET6/qQyyLhURPsC9DWN/HRE+wc0NkY0tET7C4QxkM20RPsPwAAAAARE+xQQAAAABET7GFAAAAAERPscoAAAAARFAOCQAAAABEUA5OAAAAAERQDpMAAAAARFAO1wAAAABEUA8cQwDAqURQD2FDdvAjRFAPpkOL1RJEUA/qQ0OKJURQEC9CXTp0RFAQdAAAAABEUBC5AAAAAERQEP4AAAAARFARQgAAAABEVcuoAAAAAERVy/AAAAAARFXMOQAAAABEVcyCAAAAAERVzMpCzsoORFXNE0NaGXFEVc1bQ3R5C0RVzaRDKbY/RFXN7QAAAABEVc41AAAAAERVzn4AAAAARFXOxwAAAABEV5BlAAAAAERXkK4AAAAARFeQ+AAAAABEV5FCAAAAAERXkYxDKSu1RFeR1kNbVSFEV5IgQ1lH20RXkmlDOlYfRFeSs0M4QDVEV5L9Q0YP/0RXk0dDMzG5RFeTkQAAAABEV5PaAAAAAERXlCQAAAAARFeUbgAAAABEV6FpAAAAAERXobMAAAAARFeh/QAAAABEV6JHAAAAAERXopFDDVORRFei20NxGSNEV6MlQ22aoURXo25C9lnCRFejuAAAAABEV6QCAAAAAERXpEwAAAAARFeklgAAAABEV6W9AAAAAERXpgcAAAAARFemUQAAAABEV6abAAAAAERXpuVDLnHjRFenL0M9OBdEV6d5QxBdL0RXp8MAAAAARFeoDQAAAABEV6hWAAAAAERXqKAAAAAARF33JAAAAABEXfdzAAAAAERd98EAAAAARF34DwAAAABEXfheQy+tTURd+KxDS93XRF34+kM42jtEXflIQswuZkRd+ZcAAAAARF355QAAAABEXfozAAAAAERd+oEAAAAARF5M4QAAAABEXk0wAAAAAEReTX4AAAAARF5NzQAAAABEXk4bQrksMkReTmpDvnVcRF5OuEQoL11EXk8HREPcqkReT1VEI/uQRF5PpEPTigZEXk/zQ4LN9kReUEFDX7PhRF5QkAAAAABEXlDeAAAAAEReUS0AAAAARF5RewAAAABEXo0MAAAAAERejVsAAAAARF6NqQAAAABEXo34AAAAAERejkdDA7iRRF6OlUOCrD5EXo7kQ8vYCkRejzND56FuRF6PgUO0Y8BEXo/QQyOz3URekB8AAAAARF6QbgAAAABEXpC8AAAAAERekQsAAAAARF7MvgAAAABEXs0NAAAAAERezVwAAAAARF7NqgAAAABEXs35Q478yERezkhDw2IoRF7Ol0PtNthEXs7mQ+gZFERezzVDnL2ORF7PhAAAAABEXs/TAAAAAERe0CEAAAAARF7QcAAAAABEYs8hAAAAAERiz3MAAAAARGLPxQ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ERxU84AAAAARHUP2wAAAABEdRA6AAAAAER1EJkAAAAARHUQ+QAAAABEdRFYQoIpDER1EbhDbzAjRHUSF0OZA/BEdRJ2Q5gAnkR1EtZDj7qGRHUTNUN1fidEdROVQxFdtUR1E/QAAAAARHUUUwAAAABEdRSzAAAAAER1FRIAAAAARIFNGgAAAABEgU1PAAAAAESBTYQAAAAARIFNuQAAAABEgU3uQy178USBTiNDb4JRRIFOWEOhvR5EgU6NQ7dIFESBTsNDkg3MRIFO+ELaUAREgU8tAAAAAESBT2IAAAAARIFPlwAAAABEgU/MAAAAAESBpzIAAAAARIGnZwAAAABEgaecAAAAAESBp9IAAAAARIGoB0Jew0REgag9QzrtF0SBqHJDhC78RIGop0NtEDlEgajdQy4kQ0SBqRIAAAAARIGpSAAAAABEgal9AAAAAESBqbMAAAAARIHnXgAAAABEgeeUAAAAAESB58kAAAAARIHn/wAAAABEgeg1QwZ+g0SB6GpDhNUoRIHooEOId6xEgejWQvQoEkSB6QsAAAAARIHpQQAAAABEgel2AAAAAESB6awAAAAARIIHpwAAAABEggfdAAAAAESCCBMAAAAARIIISAAAAABEggh+Qv4nckSCCLRDWj6rRIII6kNbO+tEggkfQwvuw0SCCVUAAAAARIIJiwAAAABEggnBAAAAAESCCfYAAAAARIInlQAAAABEgifLAAAAAESCKAAAAAAARIIoNgAAAABEgihsQpgZsESCKKJDTqwDRIIo2ENlUilEgikOQwzsVUSCKUMAAAAARIIpeQAAAABEgimvAAAAAESCKeUAAAAARIJjZgAAAABEgmOcAAAAAESCY9IAAAAARIJkCAAAAABEgmQ+QxAFj0SCZHRDUubtRIJkq0NEJytEgmThQrRT7ESCZRcAAAAARIJlTQAAAABEgmWDAAAAAESCZbkAAAAARILgJgAAAABEguBcAAAAAESC4JMAAAAARILgyQAAAABEguEAQykld0SC4TZDdX0HRILhbENFmp9EguGjQb3PWESC4dkAAAAARILiEAAAAABEguJGAAAAAESC4n0AAAAARILldwAAAABEguWtAAAAAESC5eMAAAAARILmGgAAA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eqf3XQ0R360Sp/jNCwDr2RKn+jwAAAABEqf7rAAAAAESp/0YAAAAARKn/ogAAAABErEarAAAAAESsRwoAAAAARKxHaAAAAABErEfGAAAAAESsSCVCE4y4RKxIg0NICpdErEjhQ4IvIkSsSUBDKx7dRKxJngAAAABErEn8AAAAAESsSloAAAAARKxKuQAAAABEtQkRAAAAAES1CXkAAAAARLUJ4QAAAABEtQpKAAAAAES1CrJDJhD9RLULGkN2IZtEtQuCQ0j6M0S1C+pCqdwmRLUMUgAAAABEtQy6AAAAAES1DSMAAAAARLUNiwAAAABEt1aPAAAAAES3VvkAAAAARLdXZAAAAABEt1fPAAAAAES3WDpDesoPRLdYpUPA01ZEt1kPQ9YeGkS3WXpDvpdCRLdZ5UOX1rpEt1pQAAAAAES3WrsAAAAARLdbJgAAAABEt1uQAAAAAETFGvIAAAAARMUbbQAAAABExRvpAAAAAETFHGQAAAAARMUc30JvoHRExR1bQ31mOUTFHdZDt+aSRMUeUkPAB3pExR7NQ6mPcETFH0lDgLBwRMUfxEMHHK9ExSBAAAAAAETFILsAAAAARMUhNwAAAABExSGyAAAAAETHFHgAAAAARMcU9gAAAABExxV0AAAAAETHFfIAAAAARMcWcEM1n/lExxbuQ1u19UTHF2xDRxs7RMcX6kLjC6ZExxhoAAAAAETHGOYAAAAARMcZZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA'
base64.b64decode(your_string)

Well first of all you need to assign the finished product to a variable to be able to be printed out:

code_string = base64.b64decode(your_string)

Then like any beginner programmer would know, you would print the results out: Python 2.7x:

print code_string

Python 3.x:

print(code_string)

After the successful decoding, you will get a string about the size of the not yet decoded string. I hope this helps you!

Left align block of equations

Try to use the fleqn document class option.

\documentclass[fleqn]{article}

(See also http://en.wikibooks.org/wiki/LaTeX/Basics for a list of other options.)

Producer/Consumer threads using a Queue

OK, as others note, the best thing to do is to use java.util.concurrent package. I highly recommend "Java Concurrency in Practice". It's a great book that covers almost everything you need to know.

As for your particular implementation, as I noted in the comments, don't start Threads from Constructors -- it can be unsafe.

Leaving that aside, the second implementation seem better. You don't want to put queues in static fields. You are probably just loosing flexibility for nothing.

If you want to go ahead with your own implementation (for learning purpose I guess?), supply a start() method at least. You should construct the object (you can instantiate the Thread object), and then call start() to start the thread.

Edit: ExecutorService have their own queue so this can be confusing.. Here's something to get you started.

public class Main {
    public static void main(String[] args) {
        //The numbers are just silly tune parameters. Refer to the API.
        //The important thing is, we are passing a bounded queue.
        ExecutorService consumer = new ThreadPoolExecutor(1,4,30,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(100));

        //No need to bound the queue for this executor.
        //Use utility method instead of the complicated Constructor.
        ExecutorService producer = Executors.newSingleThreadExecutor();

        Runnable produce = new Produce(consumer);
        producer.submit(produce);   
    }
}

class Produce implements Runnable {
    private final ExecutorService consumer;

    public Produce(ExecutorService consumer) {
        this.consumer = consumer;
    }

    @Override
    public void run() {
        Pancake cake = Pan.cook();
        Runnable consume = new Consume(cake);
        consumer.submit(consume);
    }
}

class Consume implements Runnable {
    private final Pancake cake;

    public Consume(Pancake cake){
        this.cake = cake;
    }

    @Override
    public void run() {
        cake.eat();
    }
}

Further EDIT: For producer, instead of while(true), you can do something like:

@Override
public void run(){
    while(!Thread.currentThread().isInterrupted()){
        //do stuff
    }
}

This way you can shutdown the executor by calling .shutdownNow(). If you'd use while(true), it won't shutdown.

Also note that the Producer is still vulnerable to RuntimeExceptions (i.e. one RuntimeException will halt the processing)

Search an array for matching attribute

Must be too late now, but the right version would be:

for(var i = 0; i < restaurants.restaurant.length; i++)
{
  if(restaurants.restaurant[i].food == 'chicken')
  {
    return restaurants.restaurant[i].name;
  }
}

Floating point inaccuracy examples

Here is my simple understanding.

Problem: The value 0.45 cannot be accurately be represented by a float and is rounded up to 0.450000018. Why is that?

Answer: An int value of 45 is represented by the binary value 101101. In order to make the value 0.45 it would be accurate if it you could take 45 x 10^-2 (= 45 / 10^2.) But that’s impossible because you must use the base 2 instead of 10.

So the closest to 10^2 = 100 would be 128 = 2^7. The total number of bits you need is 9 : 6 for the value 45 (101101) + 3 bits for the value 7 (111). Then the value 45 x 2^-7 = 0.3515625. Now you have a serious inaccuracy problem. 0.3515625 is not nearly close to 0.45.

How do we improve this inaccuracy? Well we could change the value 45 and 7 to something else.

How about 460 x 2^-10 = 0.44921875. You are now using 9 bits for 460 and 4 bits for 10. Then it’s a bit closer but still not that close. However if your initial desired value was 0.44921875 then you would get an exact match with no approximation.

So the formula for your value would be X = A x 2^B. Where A and B are integer values positive or negative. Obviously the higher the numbers can be the higher would your accuracy become however as you know the number of bits to represent the values A and B are limited. For float you have a total number of 32. Double has 64 and Decimal has 128.

How to capitalize the first character of each word in a string

    s.toLowerCase().trim();
    result += Character.toUpperCase(s.charAt(0));
    result += s.substring(1, s.indexOf(" ") + 1);
    s = s.substring(s.indexOf(" ") + 1);

    do {
        if (s.contains(" ")) {
            result += " ";
            result += Character.toUpperCase(s.charAt(0));
            result += s.substring(1, s.indexOf(" "));
            s = s.substring(s.indexOf(" ") + 1);
        } else {
            result += " ";
            result += Character.toUpperCase(s.charAt(0));
            result += s.substring(1);
            break;
        }
    } while (true);
    System.out.println(result);

What is the difference between range and xrange functions in Python 2.X?

range(x,y) returns a list of each number in between x and y if you use a for loop, then range is slower. In fact, range has a bigger Index range. range(x.y) will print out a list of all the numbers in between x and y

xrange(x,y) returns xrange(x,y) but if you used a for loop, then xrange is faster. xrange has a smaller Index range. xrange will not only print out xrange(x,y) but it will still keep all the numbers that are in it.

[In] range(1,10)
[Out] [1, 2, 3, 4, 5, 6, 7, 8, 9]
[In] xrange(1,10)
[Out] xrange(1,10)

If you use a for loop, then it would work

[In] for i in range(1,10):
        print i
[Out] 1
      2
      3
      4
      5
      6
      7
      8
      9
[In] for i in xrange(1,10):
         print i
[Out] 1
      2
      3
      4
      5
      6
      7
      8
      9

There isn't much difference when using loops, though there is a difference when just printing it!

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.

How to write a basic swap function in Java

Here is one trick:

public static int getItself(int itself, int dummy)
{
    return itself;
}

public static void main(String[] args)
{
    int a = 10;
    int b = 20;

    a = getItself(b, b = a);
}

Reload a DIV without reloading the whole page

Your code works, but the fadeIn doesn't, because it's already visible. I think the effect you want to achieve is: fadeOutloadfadeIn:

var auto_refresh = setInterval(function () {
    $('.View').fadeOut('slow', function() {
        $(this).load('/echo/json/', function() {
            $(this).fadeIn('slow');
        });
    });
}, 15000); // refresh every 15000 milliseconds

Try it here: http://jsfiddle.net/kelunik/3qfNn/1/

Additional notice: As Khanh TO mentioned, you may need to get rid of the browser's internal cache. You can do so using $.ajax and $.ajaxSetup ({ cache: false }); or the random-hack, he mentioned.

Use of exit() function

on unix like operating systems exit belongs to group of system calls. system calls are special calls which enable user code (your code) to call kernel code. so exit call makes some OS specific clean-up actions before returning control to OS, it terminates the program.

#include <stdlib.h>

// example 1
int main(int argc, char *argv){
  exit(EXIT_SUCCESS);
}

// example 2
int main(int argc, char *argv){
  return 0;
}

Some compilers will give you the same opcode from both of these examples but some won't. For example opcode from first function will not include any kind of stack positioning opcode which will be included in the second example like for any other function. You could compile both examples and disassemble them and you will see the difference.

You can use exit from any part of your code and be sure that process terminates. Don't forget to include integer parameter.

Failed to resolve: com.android.support:appcompat-v7:28.0

my problem was just network connection. using VPN solved the issue.

Unknown SSL protocol error in connection

I was able to solve it by running

git config --list --show-origin

and then seeing that I had a line:

file:c:/Users/user/.gitconfig http.sslversion=sslv3

I edited the file, c:/Users/user/.gitconfig, and deleted the line [http] and the line sslversion=sslv3 and that fixed it for me.

List of enum values in java

It is possible but you should use EnumSet instead

enum MyEnum {
    ONE, TWO;
    public static final EnumSet<MyEnum> all = EnumSet.of(ONE, TWO);
}

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

Resolve issue Immediate, It's related to internal security

We, SnippetBucket.com working for enterprise linux RedHat, found httpd server don't allow proxy to run, neither localhost or 127.0.0.1, nor any other external domain.

As investigate in server log found

[error] (13)Permission denied: proxy: AJP: attempt to connect to
   10.x.x.x:8069 (virtualhost.virtualdomain.com) failed

Audit log found similar port issue

type=AVC msg=audit(1265039669.305:14): avc:  denied  { name_connect } for  pid=4343 comm="httpd" dest=8069 
scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:port_t:s0 tclass=tcp_socket

Due to internal default security of linux, this cause, now to fix (temporary)

 /usr/sbin/setsebool httpd_can_network_connect 1

Resolve Permanent Issue

/usr/sbin/setsebool -P httpd_can_network_connect 1

How to find substring inside a string (or how to grep a variable)?

Well, what about something like this:

PS3="Select database or <Q> to quit: "
select DB in db1 db2 db3; do
   [ "${REPLY^*}" = 'Q' ] && break
   echo "Should backup $DB..."
done

Escape invalid XML characters in C#

string XMLWriteStringWithoutIllegalCharacters(string UnfilteredString)
{
    if (UnfilteredString == null)
        return string.Empty;

    return XmlConvert.EncodeName(UnfilteredString);
}

string XMLReadStringWithoutIllegalCharacters(string FilteredString)
{
    if (UnfilteredString == null)
        return string.Empty;

    return XmlConvert.DecodeName(UnfilteredString);
}

This simple method replace the invalid characters with the same value but accepted in the XML context.


To write string use XMLWriteStringWithoutIllegalCharacters(string UnfilteredString).
To read string use XMLReadStringWithoutIllegalCharacters(string FilteredString).

Stopping a CSS3 Animation on last frame

You're looking for:

animation-fill-mode: forwards;

More info on MDN and browser support list on canIuse.

How to merge two files line by line in Bash

Try following.

pr -tmJ a.txt b.txt > c.txt

How to call javascript function on page load in asp.net

Calling JavaScript function on code behind i.e. On Page_Load

ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

If you have UpdatePanel there then try like this

ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

View Blog Article : How to Call javascript function from code behind in asp.net c#

Combination of async function + await + setTimeout

This is a quicker fix in one-liner.

Hope this will help.

// WAIT FOR 200 MILISECONDS TO GET DATA //
await setTimeout(()=>{}, 200);

How to use JavaScript to change the form action

function chgAction( action_name )
{
    if( action_name=="aaa" ) {
        document.search-theme-form.action = "/AAA";
    }
    else if( action_name=="bbb" ) {
        document.search-theme-form.action = "/BBB";
    }
    else if( action_name=="ccc" ) {
        document.search-theme-form.action = "/CCC";
    }
}

And your form needs to have name in this case:

<form action="/"  accept-charset="UTF-8" method="post" name="search-theme-form" id="search-theme-form">

How to explain callbacks in plain english? How are they different from calling one function from another function?

There's two points to explain, one is how a callback works (passing around a function that can be called without any knowledge of its context), the other what it's used for (handling events asynchronously).

The analogy of waiting for a parcel to arrive that has been used by other answers is a good one to explain both. In a computer program, you would tell the computer to expect a parcel. Ordinarily, it would now sit there and wait (and do nothing else) until the parcel arrives, possibly indefinitely if it never arrives. To humans, this sounds silly, but without further measures, this is totally natural to a computer.

Now the callback would be the bell at your front door. You provide the parcel service with a way to notify you of the parcel's arrival without them having to know where (even if) you are in the house, or how the bell works. (For instance, some "bells" actually dispatch a phone call.) Because you provided a "callback function" that can be "called" at any time, out of context, you can now stop sitting at the front porch and "handle the event" (of parcel arrival) whenever it's time.

Auto line-wrapping in SVG text

This functionality can also be added using JavaScript. Carto.net has an example:

http://old.carto.net/papers/svg/textFlow/

Something else that also might be useful to are you are editable text areas:

http://old.carto.net/papers/svg/gui/textbox/

Restrict varchar() column to specific values?

Have you already looked at adding a check constraint on that column which would restrict values? Something like:

CREATE TABLE SomeTable
(
   Id int NOT NULL,
   Frequency varchar(200),
   CONSTRAINT chk_Frequency CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
)

CSS: How to align vertically a "label" and "input" inside a "div"?

_x000D_
_x000D_
div {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
    height: 50px;_x000D_
    border: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
    <label for='name'>Name:</label>_x000D_
    <input type='text' id='name' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

The advantages of this method is that you can change the height of the div, change the height of the text field and change the font size and everything will always stay in the middle.

http://jsfiddle.net/53ALd/6/

height style property doesn't work in div elements

You cannot set height and width for elements with display:inline;. Use display:inline-block; instead.

From the CSS2 spec:

10.6.1 Inline, non-replaced elements

The height property does not apply. The height of the content area should be based on the font, but this specification does not specify how. A UA may, e.g., use the em-box or the maximum ascender and descender of the font. (The latter would ensure that glyphs with parts above or below the em-box still fall within the content area, but leads to differently sized boxes for different fonts; the former would ensure authors can control background styling relative to the 'line-height', but leads to glyphs painting outside their content area.)

EDIT — You're also missing a ; terminator for the height property:

<div style="display:inline; height:20px width: 70px">My Text Here</div>
<!--                                  ^^ here                       -->

Working example: http://jsfiddle.net/FpqtJ/

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

  1. Cancel all async operation in componentWillUnmount
  2. Check component is already unmounted when async call setState,
    since isMounted flag is deprecated

int to string in MySQL

You can do this:

select t2.*
from t1
join t2 on t2.url = 'site.com/path/' + CAST(t1.id AS VARCHAR(10)) + '/more' 
where t1.id > 9000

Pay attention to CAST(t1.id AS VARCHAR(10)).

Run an Ansible task only when the variable contains a specific string

I used

failed_when: not(promtool_version.stdout.find('1.5.2') != -1)

means - failed only when the previously registered variable "promtool_version" doesn't contains string '1.5.2'.

How to make a hyperlink in telegram without using bots?

On Telegram Desktop for macOS, the shortcuts differ. You can right-click a highlighted text, then hover over Transformations to see the available options:

macOS Telegram Desktop Formatting Shortcuts

Create a hexadecimal colour based on a string with JavaScript

All you really need is a good hash function. On node, I just use

const crypto = require('crypto');
function strToColor(str) {
    return '#' + crypto.createHash('md5').update(str).digest('hex').substr(0, 6);
}

SQL Server date format yyyymmdd

SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM table; //converts any date format to YYYY-MM-DD

Add image in pdf using jspdf

Though I'm not sure, the image might not be added because you create the output before you add it. Try:

function convert(){
    var doc = new jsPDF();
    var imgData = 'data:image/jpeg;base64,'+ Base64.encode('Koala.jpeg');
    console.log(imgData);
    doc.setFontSize(40);
    doc.text(30, 20, 'Hello world!');
    doc.addImage(imgData, 'JPEG', 15, 40, 180, 160);
    doc.output('datauri');
}

Rounding float in Ruby

def rounding(float,precision)
    return ((float * 10**precision).round.to_f) / (10**precision)
end

Setting the correct encoding when piping stdout in Python

I had a similar issue last week. It was easy to fix in my IDE (PyCharm).

Here was my fix:

Starting from PyCharm menu bar: File -> Settings... -> Editor -> File Encodings, then set: "IDE Encoding", "Project Encoding" and "Default encoding for properties files" ALL to UTF-8 and she now works like a charm.

Hope this helps!

Set Text property of asp:label in Javascript PROPER way

Use the following code

<span id="sptext" runat="server"></span>

Java Script

document.getElementById('<%=sptext'%>).innerHTML='change text';

C#

sptext.innerHTML

“tag already exists in the remote" error after recreating the git tag

The reason you are getting rejected is that your tag lost sync with the remote version. This is the same behaviour with branches.

sync with the tag from the remote via git pull --rebase <repo_url> +refs/tags/<TAG> and after you sync, you need to manage conflicts. If you have a diftool installed (ex. meld) git mergetool meld use it to sync remote and keep your changes.

The reason you're pulling with --rebase flag is that you want to put your work on top of the remote one so you could avoid other conflicts.

Also, what I don't understand is why would you delete the dev tag and re-create it??? Tags are used for specifying software versions or milestones. Example of git tags v0.1dev, v0.0.1alpha, v2.3-cr(cr - candidate release) and so on..


Another way you can solve this is issue a git reflog and go to the moment you pushed the dev tag on remote. Copy the commit id and git reset --mixed <commmit_id_from_reflog> this way you know your tag was in sync with the remote at the moment you pushed it and no conflicts will arise.

Intellij idea subversion checkout error: `Cannot run program "svn"`

Fix of this problem is add SVN directory(C:\Program Files\TortoiseSVN\bin) to Path system property

Converting array to list in Java

In Java 8, you can use streams:

int[] spam = new int[] { 1, 2, 3 };
Arrays.stream(spam)
      .boxed()
      .collect(Collectors.toList());

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"

Checking if type == list in python

Your issue is that you have re-defined list as a variable previously in your code. This means that when you do type(tmpDict[key])==list if will return False because they aren't equal.

That being said, you should instead use isinstance(tmpDict[key], list) when testing the type of something, this won't avoid the problem of overwriting list but is a more Pythonic way of checking the type.

Why don't self-closing script elements work?

In case anyone's curious, the ultimate reason is that HTML was originally a dialect of SGML, which is XML's weird older brother. In SGML-land, elements can be specified in the DTD as either self-closing (e.g. BR, HR, INPUT), implicitly closeable (e.g. P, LI, TD), or explicitly closeable (e.g. TABLE, DIV, SCRIPT). XML, of course, has no concept of this.

The tag-soup parsers used by modern browsers evolved out of this legacy, although their parsing model isn't pure SGML anymore. And of course, your carefully-crafted XHTML is being treated as badly-written SGML-inspired tag-soup unless you send it with an XML mime type. This is also why...

<p><div>hello</div></p>

...gets interpreted by the browser as:

<p></p><div>hello</div><p></p>

...which is the recipe for a lovely obscure bug that can throw you into fits as you try to code against the DOM.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

public String TAG() {
    return this.getClass().getSimpleName();
}

private AtomicInteger lastFldId = null;

public int generateViewId(){

    if(lastFldId == null) {
        int maxFld = 0;
        String fldName = "";
        Field[] flds = R.id.class.getDeclaredFields();
        R.id inst = new R.id();

        for (int i = 0; i < flds.length; i++) {
            Field fld = flds[i];

            try {
                int value = fld.getInt(inst);

                if (value > maxFld) {
                    maxFld = value;
                    fldName = fld.getName();
                }
            } catch (IllegalAccessException e) {
                Log.e(TAG(), "error getting value for \'"+ fld.getName() + "\' " + e.toString());
            }
        }
        Log.d(TAG(), "maxId="+maxFld +"  name="+fldName);
        lastFldId = new AtomicInteger(maxFld);
    }

    return lastFldId.addAndGet(1);
}

Submit HTML form on self page

You can do it using the same page on the action attribute: action='<yourpage>'

Get scroll position using jquery

Older IE and Firefox browsers attach the scrollbar to the documentElement, or what would be the <html> tag in HTML.

All other browsers attach the scrollbar to document.body, or what would be the <body> tag in HTML.

The correct solution would be to check which one to use, depending on browser

var doc = document.documentElement.clientHeight ? document.documentElement : document.body;
var s   = $(doc).scrollTop();

jQuery does make this a little easier, when passing in either window or document jQuery's scrollTop does a similar check and figures it out, so either of these should work cross-browser

var s = $(document).scrollTop();

or

var s = $(window).scrollTop();

jQuery scrollTop() docs

Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.


...nothing that works for my div, just the full page

If it's for a DIV, you'd have to target the element that has the scrollbar attached, to get the scrolled amount

$('div').scrollTop();

If you need to get the elements distance from the top of the document, you can also do

$('div').offset().top

Calling a method inside another method in same class

Recursion is a method that call itself. In this case it is a recursion. However it will be overloading until you put a restriction inside the method to stop the loop (if-condition).

ArrayAdapter in android to create simple listview

public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)

I am also new to Android , so i might be wrong. But as per my understanding while using this for listview creation 2nd argument is the layout of list items. A layout consists of many views (image view,text view etc). With 3rd argument you are specifying in which view or textview you want the text to be displayed.

Oracle: how to INSERT if a row doesn't exist

I found the examples a bit tricky to follow for the situation where you want to ensure a row exists in the destination table (especially when you have two columns as the primary key), but the primary key might not exist there at all so there's nothing to select.

This is what worked for me:

MERGE INTO table1 D
    USING (
        -- These are the row(s) you want to insert.
        SELECT 
        'val1' AS FIELD_A,
        'val2' AS FIELD_B
        FROM DUAL

    ) S ON (
        -- This is the criteria to find the above row(s) in the
        -- destination table.  S refers to the rows in the SELECT
        -- statement above, D refers to the destination table.
        D.FIELD_A = S.FIELD_A
        AND D.FIELD_B = S.FIELD_B
    )

    -- This is the INSERT statement to run for each row that
    -- doesn't exist in the destination table.
    WHEN NOT MATCHED THEN INSERT (
        FIELD_A,
        FIELD_B,
        FIELD_C
    ) VALUES (
        S.FIELD_A,
        S.FIELD_B,
        'val3'
    )

The key points are:

  • The SELECT statement inside the USING block must always return rows. If there are no rows returned from this query, no rows will be inserted or updated. Here I select from DUAL so there will always be exactly one row.
  • The ON condition is what sets the criteria for matching rows. If ON does not have a match then the INSERT statement is run.
  • You can also add a WHEN MATCHED THEN UPDATE clause if you want more control over the updates too.

git push to specific branch

The answers in question you linked-to are all about configuring git so that you can enter very short git push commands and have them do whatever you want. Which is great, if you know what you want and how to spell that in Git-Ese, but you're new to git! :-)

In your case, Petr Mensik's answer is the (well, "a") right one. Here's why:

The command git push remote roots around in your .git/config file to find the named "remote" (e.g., origin). The config file lists:

  • where (URL-wise) that remote "lives" (e.g., ssh://hostname/path)
  • where pushes go, if different
  • what gets pushed, if you didn't say what branch(es) to push
  • what gets fetched when you run git fetch remote

When you first cloned the repo—whenever that was—git set up default values for some of these. The URL is whatever you cloned from and the rest, if set or unset, are all "reasonable" defaults ... or, hmm, are they?

The issue with these is that people have changed their minds, over time, as to what is "reasonable". So now (depending on your version of git and whether you've configured things in detail), git may print a lot of warnings about defaults changing in the future. Adding the name of the "branch to push"—amd_qlp_tester—(1) shuts it up, and (2) pushes just that one branch.

If you want to push more conveniently, you could do that with:

git push origin

or even:

git push

but whether that does what you want, depends on whether you agree with "early git authors" that the original defaults are reasonable, or "later git authors" that the original defaults aren't reasonable. So, when you want to do all the configuration stuff (eventually), see the question (and answers) you linked-to.

As for the name origin/amd_qlp_tester in the first place: that's actually a local entity (a name kept inside your repo), even though it's called a "remote branch". It's git's best guess at "where amd_qlp_tester is over there". Git updates it when it can.

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

Add the annotation @Repository to the implementation of UserDaoImpl

@Repository
public class UserDaoImpl implements UserDao {
    private static Log log = LogFactory.getLog(UserDaoImpl.class);

    @Autowired
    @Qualifier("sessionFactory")
    private LocalSessionFactoryBean sessionFactory;

    //...

}

async for loop in node.js

I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.

var results = [];
var config = JSON.parse(queries);
for (var key in config) {
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
    });
}
res.writeHead( ... );
res.end(results);

The problem with the previous code is that the search function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results is empty.

To fix the problem, you have to put the code after the loop in the callback function.

    search(query, function(result) {
        results.push(result);
        // Put res.writeHead( ... ) and res.end(results) here
    });

However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.

To get a list of all keys, use Object.keys. Then, to iterate through this list, I use .forEach (you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }, but that could give problems, see JavaScript closure inside loops – simple practical example).

Here's a complete example:

var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
    res.writeHead( ... );
    res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
   onComplete();
} else {
    // There is at least one element, so the callback will be called.
    keys.forEach(function(key) {
        var query = config[key].query;
        search(query, function(result) {
            results.push(result);
            if (--tasksToGo === 0) {
                // No tasks left, good to go
                onComplete();
            }
        });
    });
}

Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:

var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
    if (index === keys.length) { // No items left
        res.writeHead( ... );
        res.end(results);
        return;
    }
    var key = keys[index];
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
        next(index + 1);
    });
})(0);

What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.

Toggle show/hide on click with jQuery

You can use .toggle() function instead of .click()....

Using getopts to process long and short command line options

An improved solution:

# translate long options to short
# Note: This enable long options but disable "--?*" in $OPTARG, or disable long options after  "--" in option fields.
for ((i=1;$#;i++)) ; do
    case "$1" in
        --)
            # [ ${args[$((i-1))]} == ... ] || EndOpt=1 ;;& # DIRTY: we still can handle some execptions...
            EndOpt=1 ;;&
        --version) ((EndOpt)) && args[$i]="$1"  || args[$i]="-V";;
        # default case : short option use the first char of the long option:
        --?*) ((EndOpt)) && args[$i]="$1"  || args[$i]="-${1:2:1}";;
        # pass through anything else:
        *) args[$i]="$1" ;;
    esac
    shift
done
# reset the translated args
set -- "${args[@]}"

function usage {
echo "Usage: $0 [options] files" >&2
    exit $1
}

# now we can process with getopt
while getopts ":hvVc:" opt; do
    case $opt in
        h)  usage ;;
        v)  VERBOSE=true ;;
        V)  echo $Version ; exit ;;
        c)  source $OPTARG ;;
        \?) echo "unrecognized option: -$opt" ; usage -1 ;;
        :)
        echo "option -$OPTARG requires an argument"
        usage -1
        ;;
    esac
done

shift $((OPTIND-1))
[[ "$1" == "--" ]] && shift

Virtual network interface in Mac OS X

Take a look at this tutorial, it's for FreeBSD but also applies to OS X. http://people.freebsd.org/~arved/vlan/vlan_en.html

Uses of Action delegate in C#

Well one thing you could do is if you have a switch:

switch(SomeEnum)
{
  case SomeEnum.One:
      DoThings(someUser);
      break;
  case SomeEnum.Two:
      DoSomethingElse(someUser);
      break;
}

And with the might power of actions you can turn that switch into a dictionary:

Dictionary<SomeEnum, Action<User>> methodList = 
    new Dictionary<SomeEnum, Action<User>>()

methodList.Add(SomeEnum.One, DoSomething);
methodList.Add(SomeEnum.Two, DoSomethingElse); 

...

methodList[SomeEnum](someUser);

Or you could take this farther:

SomeOtherMethod(Action<User> someMethodToUse, User someUser)
{
    someMethodToUse(someUser);
}  

....

var neededMethod = methodList[SomeEnum];
SomeOtherMethod(neededMethod, someUser);

Just a couple of examples. Of course the more obvious use would be Linq extension methods.

Search text in stored procedure in SQL Server

It might help you!

SELECT DISTINCT 
      A.NAME AS OBJECT_NAME,
      A.TYPE_DESC
      FROM SYS.SQL_MODULES M 
      INNER JOIN SYS.OBJECTS A ON M.OBJECT_ID = A.OBJECT_ID
      WHERE M.DEFINITION LIKE '%['+@SEARCH_TEXT+']%'
      ORDER BY TYPE_DESC

Convert Dictionary to JSON in Swift

You are making a wrong assumption. Just because the debugger/Playground shows your dictionary in square brackets (which is how Cocoa displays dictionaries) that does not mean that is the way the JSON output is formatted.

Here is example code that will convert a dictionary of strings to JSON:

Swift 3 version:

import Foundation

let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
    withJSONObject: dictionary,
    options: []) {
    let theJSONText = String(data: theJSONData,
                               encoding: .ascii)
    print("JSON string = \(theJSONText!)")
}

To display the above in "pretty printed" format you'd change the options line to:

    options: [.prettyPrinted]

Or in Swift 2 syntax:

import Foundation
 
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
let theJSONData = NSJSONSerialization.dataWithJSONObject(
  dictionary ,
  options: NSJSONWritingOptions(0),
  error: nil)
let theJSONText = NSString(data: theJSONData!,
  encoding: NSASCIIStringEncoding)
println("JSON string = \(theJSONText!)")

The output of that is

"JSON string = {"anotherKey":"anotherValue","aKey":"aValue"}"

Or in pretty format:

{
  "anotherKey" : "anotherValue",
  "aKey" : "aValue"
}

The dictionary is enclosed in curly braces in the JSON output, just as you'd expect.

EDIT:

In Swift 3/4 syntax, the code above looks like this:

  let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
    if let theJSONData = try?  JSONSerialization.data(
      withJSONObject: dictionary,
      options: .prettyPrinted
      ),
      let theJSONText = String(data: theJSONData,
                               encoding: String.Encoding.ascii) {
          print("JSON string = \n\(theJSONText)")
    }
  }

How to get length of a list of lists in python

The method len() returns the number of elements in the list.

 list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
    print "First list length : ", len(list1)
    print "Second list length : ", len(list2)

When we run above program, it produces the following result -

First list length : 3 Second list length : 2

Step-by-step debugging with IPython

the right, easy, cool, exact answer for the question is to use %run macro with -d flag.

In [4]: run -d myscript.py
NOTE: Enter 'c' at the ipdb>  prompt to continue execution.        
> /cygdrive/c/Users/mycodefolder/myscript.py(4)<module>()
      2                                                            
      3                        
----> 4 a=1                                            
      5 b=2

What are the First and Second Level caches in (N)Hibernate?

First Level Cache

Session object holds the first level cache data. It is enabled by default. The first level cache data will not be available to entire application. An application can use many session object.

Second Level Cache

SessionFactory object holds the second level cache data. The data stored in the second level cache will be available to entire application. But we need to enable it explicitly.

Git Push ERROR: Repository not found

Just use the SSH remote url instead of the HTTPS

Reverse colormap in matplotlib

There is no built-in way (yet) of reversing arbitrary colormaps, but one simple solution is to actually not modify the colorbar but to create an inverting Normalize object:

from matplotlib.colors import Normalize

class InvertedNormalize(Normalize):
    def __call__(self, *args, **kwargs):
        return 1 - super(InvertedNormalize, self).__call__(*args, **kwargs)

You can then use this with plot_surface and other Matplotlib plotting functions by doing e.g.

inverted_norm = InvertedNormalize(vmin=10, vmax=100)
ax.plot_surface(..., cmap=<your colormap>, norm=inverted_norm)

This will work with any Matplotlib colormap.

Jetty: HTTP ERROR: 503/ Service Unavailable

I had the same problem. I solved it by removing the line break from the xml file. I did

<operationBindings>
    <OperationBinding>
        <operationType>update</operationType>
        <operationId>makePdf</operationId>
        <serverObject>
            <className>com.myclass</className>
            <lookupStyle>new</lookupStyle>
        </serverObject>
        <serverMethod>makePdf</serverMethod>
    </OperationBinding>
</operationBindings>

instead of ...

<serverObject>
            <className>com.myclass
</className>
            <lookupStyle>new</lookupStyle>
</serverObject>

Setting the character encoding in form submit for Internet Explorer

With decent browsers:

<form accept-charset="ISO-8859-1" .... >

With IE (any):

document.charset = 'ISO-8859-1'; // do this before submitting your non-utf8 <form>!

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

  • Context Menu key (one one with the menu on it, next to the right Windows key)
  • Then choose "Resolve" from the menu. That can be done by pressing "s".

How do I check for null values in JavaScript?

just replace the == with === in all places.

== is a loose or abstract equality comparison

=== is a strict equality comparison

See the MDN article on Equality comparisons and sameness for more detail.

How to set proper codeigniter base url?

Well that's very interesting, Here is quick and working code:

index.php

/**
 * Define APP_URL Dynamically
 * Write this at the bottom of index.php
 *
 * Automatic base url
 */
define('APP_URL', ($_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . "://{$_SERVER['SERVER_NAME']}".str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME'])); 

config.php

/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
|   http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = APP_URL;

CodeIgniter ROCKS!!! :)

How to convert "0" and "1" to false and true

In a single line of code:

bool bVal = Convert.ToBoolean(Convert.ToInt16(returnValue))

How to declare a variable in a PostgreSQL query

Using a Temp Table outside of pl/PgSQL

Outside of using pl/pgsql or other pl/* language as suggested, this is the only other possibility I could think of.

begin;
select 5::int as var into temp table myvar;
select *
  from somewhere s, myvar v
 where s.something = v.var;
commit;

Add Whatsapp function to website, like sms, tel

Here is the solution to your problem! You just need to use this format:

<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>

In the place of "urlencodedtext" you need to keep the content in Url-encode format.

UPDATE-- Use this from now(Nov-2018)

<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>

Use: https://wa.me/15551234567

Don't use: https://wa.me/+001-(555)1234567

To create your own link with a pre-filled message that will automatically appear in the text field of a chat, use https://wa.me/whatsappphonenumber/?text=urlencodedtext where whatsappphonenumber is a full phone number in international format and URL-encodedtext is the URL-encoded pre-filled message.

Example:https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale

To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext

Example:https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing

After clicking on the link, you will be shown a list of contacts you can send your message to.

For more information, see https://www.whatsapp.com/faq/en/general/26000030

Convert an integer to a byte array

I agree with Brainstorm's approach: assuming that you're passing a machine-friendly binary representation, use the encoding/binary library. The OP suggests that binary.Write() might have some overhead. Looking at the source for the implementation of Write(), I see that it does some runtime decisions for maximum flexibility.

func Write(w io.Writer, order ByteOrder, data interface{}) error {
    // Fast path for basic types.
    var b [8]byte
    var bs []byte
    switch v := data.(type) {
    case *int8:
        bs = b[:1]
        b[0] = byte(*v)
    case int8:
        bs = b[:1]
        b[0] = byte(v)
    case *uint8:
        bs = b[:1]
        b[0] = *v
    ...

Right? Write() takes in a very generic data third argument, and that's imposing some overhead as the Go runtime then is forced into encoding type information. Since Write() is doing some runtime decisions here that you simply don't need in your situation, maybe you can just directly call the encoding functions and see if it performs better.

Something like this:

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    bs := make([]byte, 4)
    binary.LittleEndian.PutUint32(bs, 31415926)
    fmt.Println(bs)
}

Let us know how this performs.

Otherwise, if you're just trying to get an ASCII representation of the integer, you can get the string representation (probably with strconv.Itoa) and cast that string to the []byte type.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    bs := []byte(strconv.Itoa(31415926))
    fmt.Println(bs)
}

how to align img inside the div to the right?

You can give the surrounding div a

text-align: right

this will leave white space to the left of the image. (= the image will occupy the whole line).

If you want content to be shown to the left hand side of the image, use

float: right

on the image. However, the surrounding div will then need overflow: auto to stretch to the needed height.

Python concatenate text files

An alternative to @inspectorG4dget answer (best answer to date 29-03-2016). I tested with 3 files of 436MB.

@inspectorG4dget solution: 162 seconds

The following solution : 125 seconds

from subprocess import Popen
filenames = ['file1.txt', 'file2.txt', 'file3.txt']
fbatch = open('batch.bat','w')
str ="type "
for f in filenames:
    str+= f + " "
fbatch.write(str + " > file4results.txt")
fbatch.close()
p = Popen("batch.bat", cwd=r"Drive:\Path\to\folder")
stdout, stderr = p.communicate()

The idea is to create a batch file and execute it, taking advantage of "old good technology". Its semi-python but works faster. Works for windows.

How do you change the formatting options in Visual Studio Code?

If we are talking Visual Studio Code nowadays you set a default formatter in your settings.json:

  // Defines a default formatter which takes precedence over all other formatter settings. 
  // Must be the identifier of an extension contributing a formatter.
  "editor.defaultFormatter": null,

Point to the identifier of any installed extension, i.e.

"editor.defaultFormatter": "esbenp.prettier-vscode"

You can also do so format-specific:

"[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[sass]": {
    "editor.defaultFormatter": "michelemelluso.code-beautifier"
},

Also see here.


You could also assign other keys for different formatters in your keyboard shortcuts (keybindings.json). By default, it reads:

{
  "key": "shift+alt+f",
  "command": "editor.action.formatDocument",
  "when": "editorHasDocumentFormattingProvider && editorHasDocumentFormattingProvider && editorTextFocus && !editorReadonly"
}

Lastly, if you decide to use the Prettier plugin and prettier.rc, and you want for example different indentation for html, scss, json...

{
    "semi": true,
    "singleQuote": false,
    "trailingComma": "none",
    "useTabs": false,

    "overrides": [
        {
            "files": "*.component.html",
            "options": {
                "parser": "angular",
                "tabWidth": 4
            }
        },
        {
            "files": "*.scss",
            "options": {
                "parser": "scss",
                "tabWidth": 2
            }
        },
        {
            "files": ["*.json", ".prettierrc"],
            "options": {
                "parser": "json",
                "tabWidth": 4
            }
        }
    ]
}

What does if __name__ == "__main__": do?

If this .py file are imported by other .py files, the code under "the if statement" will not be executed.

If this .py are run by python this_py.py under shell, or double clicked in Windows. the code under "the if statement" will be executed.

It is usually written for testing.

jquery mobile background image

Try this. This should work:

<div data-role="page" id="page" style="background-image: url('#URL'); background-attachment: fixed; background-repeat: no-repeat; background-size: 100% 100%;"
    data-theme="a">

Pass parameters in setInterval function

You need to create an anonymous function so the actual function isn't executed right away.

setInterval( function() { funca(10,3); }, 500 );

update query with join on two tables

Using table aliases in the join condition:

update addresses a
set cid = b.id 
from customers b 
where a.id = b.id

How to store Node.js deployment settings/configuration files?

Just do a simple settings.js with exports:

exports.my_password = 'value'

Then, in your script, do a require:

var settings = require('./settings.js');

All your settings now will be availabe via settings variable:

settings.my_password // 'value'

Which exception should I raise on bad/illegal argument combinations in Python?

Agree with Markus' suggestion to roll your own exception, but the text of the exception should clarify that the problem is in the argument list, not the individual argument values. I'd propose:

class BadCallError(ValueError):
    pass

Used when keyword arguments are missing that were required for the specific call, or argument values are individually valid but inconsistent with each other. ValueError would still be right when a specific argument is right type but out of range.

Shouldn't this be a standard exception in Python?

In general, I'd like Python style to be a bit sharper in distinguishing bad inputs to a function (caller's fault) from bad results within the function (my fault). So there might also be a BadArgumentError to distinguish value errors in arguments from value errors in locals.

How to use MD5 in javascript to transmit a password

if you're using php jquery, this might help:

   $.ajax({
        url:'phpmd5file.php',
        data:{'mypassword',mypassword},
        dataType:"json",
        method:"POST",
        success:function(mymd5password){
            alert(mymd5password);
        }
    });

on your phpmd5.php file:

echo json_encode($_POST["mypassword"]);

no jsplugins needed. just use ajax and let php md5() do the job.

"Cannot allocate an object of abstract type" error

You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

Adding <validation validateIntegratedModeConfiguration="false"/> addresses the symptom, but is not appropriate for all circumstances. Having ran around this issue a few times, I hope to help others not only overcome the problem but understand it. (Which becomes more and more important as IIS 6 fades into myth and rumor.)

Background:

This issue and the confusion surrounding it started with the introduction of ASP.NET 2.0 and IIS 7. IIS 6 had and continues to have only one pipeline mode, and it is equivalent to what IIS 7+ calls "Classic" mode. The second, newer, and recommended pipeline mode for all applications running on IIS 7+ is called "Integrated" mode.

So, what's the difference? The key difference is how ASP.NET interacts with IIS.

  • Classic mode is limited to an ASP.NET pipeline that cannot interact with the IIS pipeline. Essentially a request comes in and if IIS 6/Classic has been told, through server configuration, that ASP.NET can handle it then IIS hands off the request to ASP.NET and moves on. The significance of this can be gleaned from an example. If I were to authorize access to static image files, I would not be able to do it with an ASP.NET module because the IIS 6 pipeline will handle those requests itself and ASP.NET will never see those requests because they were never handed off.* On the other hand, authorizing which users can access a .ASPX page such as a request for Foo.aspx is trivial even in IIS 6/Classic because IIS always hands those requests off to the ASP.NET pipeline. In Classic mode ASP.NET does not know what it hasn't been told and there is a lot that IIS 6/Classic may not be telling it.

  • Integrated mode is recommended because ASP.NET handlers and modules can interact directly with the IIS pipeline. No longer does the IIS pipeline simply hand off the request to the ASP.NET pipeline, now it allows ASP.NET code to hook directly into the IIS pipeline and all the requests that hit it. This means that an ASP.NET module can not only observe requests to static image files, but can intercept those requests and take action by denying access, logging the request, etc.

Overcoming the error:

  1. If you are running an older application that was originally built for IIS 6, perhaps you moved it to a new server, there may be absolutely nothing wrong with running the application pool of that application in Classic mode. Go ahead you don't have to feel bad.
  2. Then again maybe you are giving your application a face-lift or it was chugging along just fine until you installed a 3rd party library via NuGet, manually, or by some other means. In that case it is entirely possible httpHandlers or httpModules have been added to system.web. The outcome is the error that you are seeing because validateIntegratedModeConfiguration defaults true. Now you have two choices:

    1. Remove the httpHandlers and httpModules elements from system.web. There are a couple possible outcomes from this:
      • Everything works fine, a common outcome;
      • Your application continues to complain, there may be a web.config in a parent folder you are inheriting from, consider cleaning up that web.config too;
      • You grow tired of removing the httpHandlers and httpModules that NuGet packages keep adding to system.web, hey do what you need to.
  3. If those options do not work or are more trouble than it is worth then I'm not going to tell you that you can't set validateIntegratedModeConfiguration to false, but at least you know what you're doing and why it matters.

Good reads:

*Of course there are ways to get all kind of strange things into the ASP.NET pipeline from IIS 6/Classic via incantations like wildcard mappings, if you like that sort of thing.

AddRange to a Collection

Remember that each Add will check the capacity of the collection and resize it whenever necessary (slower). With AddRange, the collection will be set the capacity and then added the items (faster). This extension method will be extremely slow, but will work.

Algorithm to randomly generate an aesthetically-pleasing color palette

An answer that shouldn't be overlooked, because it's simple and presents advantages, is sampling of real life photos and paintings. sample as many random pixels as you want random colors on thumbnails of modern art pics, cezanne, van gogh, monnet, photos... the advantage is that you can get colors by theme and that they are organic colors. just put 20 - 30 pics in a folder and random sample a random pic every time.

Conversion to HSV values is a widespread code algorithm for psychologically based palette. hsv is easier to randomize.

How do I convert strings between uppercase and lowercase in Java?

There are methods in the String class; toUppercase() and toLowerCase().

i.e.

String input = "Cricket!";
String upper = input.toUpperCase(); //stores "CRICKET!"
String lower = input.toLowerCase(); //stores "cricket!" 

This will clarify your doubt

Laravel 5 route not defined, while it is?

Please note that the command

php artisan route:list

Or to get more filter down list

php artisan route:list | grep your_route|your_controller

the forth column tells you the names of routes that are registered (usually generated by Route::resource)

Moving up one directory in Python

Obviously that os.chdir('..') is the right answer here. But just FYI, if in the future you come across situation when you have to extensively manipulate directories and paths, here is a great package (Unipath) which lets you treat them as Python objects: https://pypi.python.org/pypi/Unipath

so that you could do something like this:

>>> from unipath import Path
>>> p = Path("/usr/lib/python2.5/gopherlib.py")
>>> p.parent
Path("/usr/lib/python2.5")
>>> p.name
Path("gopherlib.py")
>>> p.ext
'.py'

Session variables not working php

I had the same issue for a while and had a very hard time figuring it out. My problem was that I had the site working for a while with the sessions working right, and then all of the sudden everything broke.

Apparently, your session_save_path(), for me it was /var/lib/php5/, needs to have correct permissions (the user running php, eg www-data needs write access to the directory). I accidentally changed it, breaking sessions completely.

Run sudo chmod -R 700 /var/lib/php5/ and then sudo chown -R www-data /var/lib/php5/ so that the php user has access to the folder.

.gitignore all the .DS_Store files in every folder and subfolder

You can also add the --cached flag to auco's answer to maintain local .DS_store files, as Edward Newell mentioned in his original answer. The modified command looks like this: find . -name .DS_Store -print0 | xargs -0 git rm --cached --ignore-unmatch ..cheers and thanks!

Fastest way to find second (third...) highest/lowest value in vector or column

I wrapped Rob's answer up into a slightly more general function, which can be used to find the 2nd, 3rd, 4th (etc.) max:

maxN <- function(x, N=2){
  len <- length(x)
  if(N>len){
    warning('N greater than length(x).  Setting N=length(x)')
    N <- length(x)
  }
  sort(x,partial=len-N+1)[len-N+1]
}

maxN(1:10)

How to connect to a remote Windows machine to execute commands using python?

For connection

c=wmi.WMI('machine name',user='username',password='password')

#this connects to remote system. c is wmi object

for commands

process_id, return_value = c.Win32_Process.Create(CommandLine="cmd.exe /c  <your command>")

#this will execute commands

SHA1 vs md5 vs SHA256: which to use for a PHP login?

MD5 is bad because of collision problems - two different passwords possibly generating the same md-5.

Sha-1 would be plenty secure for this. The reason you store the salted sha-1 version of the password is so that you the swerver do not keep the user's apassword on file, that they may be using with other people's servers. Otherwise, what difference does it make?

If the hacker steals your entire unencrypted database some how, the only thing a hashed salted password does is prevent him from impersonating the user for future signons - the hacker already has the data.

What good does it do the attacker to have the hashed value, if what your user inputs is a plain password?

And even if the hacker with future technology could generate a million sha-1 keys a second for a brute force attack, would your server handle a million logons a second for the hacker to test his keys? That's if you are letting the hacker try to logon with the salted sha-1 instead of a password like a normal logon.

The best bet is to limit bad logon attempts to some reasonable number - 25 for example, and then time the user out for a minute or two. And if the cumulative bady logon attempts hits 250 within 24 hours, shut the account access down and email the owner.

How do I get unique elements in this array?

Have you looked at this page?

http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct

That might save you some time?

eg db.addresses.distinct("zip-code");

Difference between private, public, and protected inheritance

1) Public Inheritance:

a. Private members of Base class are not accessible in Derived class.

b. Protected members of Base class remain protected in Derived class.

c. Public members of Base class remain public in Derived class.

So, other classes can use public members of Base class through Derived class object.

2) Protected Inheritance:

a. Private members of Base class are not accessible in Derived class.

b. Protected members of Base class remain protected in Derived class.

c. Public members of Base class too become protected members of Derived class.

So, other classes can't use public members of Base class through Derived class object; but they are available to subclass of Derived.

3) Private Inheritance:

a. Private members of Base class are not accessible in Derived class.

b. Protected & public members of Base class become private members of Derived class.

So, no members of Base class can be accessed by other classes through Derived class object as they are private in Derived class. So, even subclass of Derived class can't access them.

How do I draw a circle in iOS Swift?

A much easier and resource friendly approach would be.

import UIKit

@IBDesignable
class CircleDrawView: UIView {

    @IBInspectable var borderColor: UIColor = UIColor.red;

    @IBInspectable var borderSize: CGFloat = 4

    override func draw(_ rect: CGRect)
    {
        layer.borderColor = borderColor.cgColor
        layer.borderWidth = borderSize
        layer.cornerRadius = self.frame.height/2
    }

}

With Border Color and Border Size and the default Background property you can define the appearance of the circle.

enter image description here

Please note, to draw a circle the view's height and width have to be equal in size.

The code is working for Swift >= 4 and Xcode >= 9.

The name 'controlname' does not exist in the current context

I fixed this in my project by backing up the current files (so I still had my code), deleting the current aspx (and child pages), making a new one, and copying the contents of the backup files into the new files.

How to get the position of a character in Python?

What happens when the string contains a duplicate character? from my experience with index() I saw that for duplicate you get back the same index.

For example:

s = 'abccde'
for c in s:
    print('%s, %d' % (c, s.index(c)))

would return:

a, 0
b, 1
c, 2
c, 2
d, 4

In that case you can do something like that:

for i, character in enumerate(my_string):
   # i is the position of the character in the string

In Laravel, the best way to pass different types of flash messages in the session

You can pass different type of message using with

return redirect()->back()->with('error', 'Your current account is inactive ')->with('error2','please check'); 

To show message

@if(session('error'))
<div class="alert alert-danger" role="alert">
   <p> {{session('error')}} </p>
   <p> {{session('error2')}}</p>
</div>

@endif

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

I am using Visual Studio 2013 & SQL Server 2014. I got the below error Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0 not found by visual studio. I have tried all the things like installing

  • ENU\x64\SharedManagementObjects.msi for X64 OS or

  • ENU\x86\SharedManagementObjects.msi for X86 OS

  • ENU\x64\SQLSysClrTypes.msi

  • Reinstalling Sql Server 2014

What actually solved my problem is to repair the visual studio 2013(or any other version you are using) now the problem is removed . What i think it is problem of Visual Studio not Sql Server as i was able to access and use the Sql Server tool.

Changing specific text's color using NSMutableAttributedString in Swift

Based on the answers before I created a string extension

extension String {

func highlightWordsIn(highlightedWords: String, attributes: [[NSAttributedStringKey: Any]]) -> NSMutableAttributedString {
     let range = (self as NSString).range(of: highlightedWords)
     let result = NSMutableAttributedString(string: self)

     for attribute in attributes {
         result.addAttributes(attribute, range: range)
     }

     return result
    }
}

You can pass the attributes for the text to the method

Call like this

  let attributes = [[NSAttributedStringKey.foregroundColor:UIColor.red], [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17)]]
  myLabel.attributedText = "This is a text".highlightWordsIn(highlightedWords: "is a text", attributes: attributes)

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

Check service dependencies if they are disabled.

Set those dependencies to Automatic, Start them and it should work.

CakePHP 3.0 installation: intl extension missing from system

MAKE this

In XAMPP, intl extension is included but you have to uncomment extension=php_intl.dll in php.ini and restart the server through the XAMPP Control Panel. In WAMP, the intl extension is “activated” by default but not working. To make it work you have to go to php folder (by default) C:\wamp\bin\php\php{version}, copy all the files that looks like icu*.dll and paste them into the apache bin directory C:\wamp\bin\apache\apache{version}\bin. Then restart all services and it should be OK.

if you use XAMPP do this 1. turn off XAMPP 2. Modifed the php.ini is located in c/:xampp/php/php.ini 3. intl extension is included but you have to uncomment extension=php_intl.dll in php.ini and restart the server through the XAMPP Control Panel.

Understanding string reversal via slicing

I think the following makes a bit more sense for print strings in reverse, but maybe that's just me:

for char in reversed( myString ):  
  print( char, end = "" )

Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

I just had this same problem because I had used improper syntax in my config file. I meant to add:

maxmemory-policy allkeys-lru

to my config file, but instead only added:

allkeys-lru

which evidently prevented Redis from parsing the config file, which in turn prevented me from connecting through the cli. Fixing this syntax allowed me to connect to Redis.

Create a table without a header in Markdown

@thamme-gowda's solution works for images too!

| | |:----------------------------------------------------------------------------:| | ![](https://gravatar.com/avatar/4cc702785290b4934c531c56f6061e5e "Tonejito") |

You can check this out on a gist I made for that. Here is a render of the table hack on GitHub and GitLab:

How much memory can a 32 bit process access on a 64 bit operating system?

A 32-bit process is still limited to the same constraints in a 64-bit OS. The issue is that memory pointers are only 32-bits wide, so the program can't assign/resolve any memory address larger than 32 bits.

How to call a PHP function on the click of a button

You can simply do this. In php, you can determine button click by use of

if(isset($_Post['button_tag_name']){
echo "Button Clicked";
}

Therefore you should modify you code as follows:


<?php

if(isset($_Post['select']){
 echo "select button clicked and select method should be executed";
}
if(isset($_Post['insert']){
 echo "insert button clicked and insert method should be executed";
}
           
        ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <body>
        <form action="functioncalling.php">
            <input type="text" name="txt" />
            <input type="submit" name="insert" value="insert" onclick="insert()" />
            <input type="submit" name="select" value="select" onclick="select()" />
        </form>

<script>
//This will be processed on the client side
function insert(){
  window.alert("You click insert button");
}

function select(){
  window.alert("You click insert button");
}
</script>
</body>
</html>


        

Convert Bitmap to File

Converting Bitmap to File needs to be done in background (NOT IN THE MAIN THREAD) it hangs the UI specially if the bitmap was large

File file;

public class fileFromBitmap extends AsyncTask<Void, Integer, String> {

    Context context;
    Bitmap bitmap;
    String path_external = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg";

    public fileFromBitmap(Bitmap bitmap, Context context) {
        this.bitmap = bitmap;
        this.context= context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // before executing doInBackground
        // update your UI
        // exp; make progressbar visible
    }

    @Override
    protected String doInBackground(Void... params) {

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
        try {
            FileOutputStream fo = new FileOutputStream(file);
            fo.write(bytes.toByteArray());
            fo.flush();
            fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        // back to main thread after finishing doInBackground
        // update your UI or take action after
        // exp; make progressbar gone

         sendFile(file);

    }
}

Calling it

new fileFromBitmap(my_bitmap, getApplicationContext()).execute();

you MUST use the file in onPostExecute .

To change directory of file to be stored in cache replace line :

 file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");

with :

file  = new File(context.getCacheDir(), "temporary_file.jpg");

Read an Excel file directly from a R script

An Excel file can be read directly into R as follows:

my_data <- read.table(file = "xxxxxx.xls", sep = "\t", header=TRUE)

Reading xls and xlxs files using readxl package

library("readxl")
my_data <- read_excel("xxxxx.xls")
my_data <- read_excel("xxxxx.xlsx")

YAML Multi-Line Arrays

If what you are needing is an array of arrays, you can do this way:

key:
  - [ 'value11', 'value12', 'value13' ]
  - [ 'value21', 'value22', 'value23' ]

How can I detect when an Android application is running in the emulator?

you can check the IMEI #, http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29

if i recall on the emulator this return 0. however, there's no documentation i can find that guarantees that. although the emulator might not always return 0, it seems pretty safe that a registered phone would not return 0. what would happen on a non-phone android device, or one without a SIM card installed or one that isn't currently registered on the network?

seems like that'd be a bad idea, to depend on that.

it also means you'd need to ask for permission to read the phone state, which is bad if you don't already require it for something else.

if not that, then there's always flipping some bit somewhere before you finally generate your signed app.

How can I execute PHP code from the command line?

If you're going to do PHP in the command line, I recommend you install phpsh, a decent PHP shell. It's a lot more fun.

Anyway, the php command offers two switches to execute code from the command line:

-r <code>        Run PHP <code> without using script tags <?..?>
-R <code>        Run PHP <code> for every input line

You can use php's -r switch as such:

php -r 'echo function_exists("foo") ? "yes" : "no";'

The above PHP command above should output no and returns 0 as you can see:

>>> php -r 'echo function_exists("foo") ? "yes" : "no";'
no
>>> echo $? # print the return value of the previous command
0

Another funny switch is php -a:

-a               Run as interactive shell

It's sort of lame compared to phpsh, but if you don't want to install the awesome interactive shell for PHP made by Facebook to get tab completion, history, and so on, then use -a as such:

>>> php -a
Interactive shell

php > echo function_exists("foo") ? "yes" : "no";
no
php >

If it doesn't work on your box like on my boxes (tested on Ubuntu and Arch Linux), then probably your PHP setup is fuzzy or broken. If you run this command:

php -i | grep 'API'

You should see:

Server API => Command Line Interface

If you don't, this means that maybe another command will provides the CLI SAPI. Try php-cli; maybe it's a package or a command available in your OS.

If you do see that your php command uses the CLI (command-line interface) SAPI (Server API), then run php -h | grep code to find out which crazy switch - as this hasn't changed for year- allows to run code in your version/setup.

Another couple of examples, just to make sure it works on my boxes:

>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";'
no
>>> php -r 'echo function_exists("print_r") ? "yes" : "no";'
yes

Also, note that it is possible that an extension is loaded in the CLI and not in the CGI or Apache SAPI. It is likely that several PHP SAPIs use different php.ini files, e.g., /etc/php/cli/php.ini vs. /etc/php/cgi/php.ini vs. /etc/php/apache/php.ini on a Gentoo Linux box. Find out which ini file is used with php -i | grep ini.

Comparing the contents of two files in Sublime Text

View - Layout and View - Groups will do in latest Sublime 3

eg:

Shift+Alt+2 --> creates 2 columns

Ctrl+2 --> move selected file to column 2

This is for side by side comparison. For actual diff, there is the diff function other already mentioned. Unfortunately, I can't find a way to make columns scroll at the same time, which would be a nice feature.

If else embedding inside html

I recommend the following syntax for readability.

<? if ($condition): ?>
  <p>Content</p>
<? elseif ($other_condition): ?>
  <p>Other Content</p>
<? else: ?>
  <p>Default Content</p>
<? endif; ?>

Note, omitting php on the open tags does require that short_open_tags is enabled in your configuration, which is the default. The relevant curly-brace-free conditional syntax is always enabled and can be used regardless of this directive.

What is the difference between IEnumerator and IEnumerable?

An IEnumerator is a thing that can enumerate: it has the Current property and the MoveNext and Reset methods (which in .NET code you probably won't call explicitly, though you could).

An IEnumerable is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator.

Which do you use? The only reason to use IEnumerator is if you have something that has a nonstandard way of enumerating (that is, of returning its various elements one-by-one), and you need to define how that works. You'd create a new class implementing IEnumerator. But you'd still need to return that IEnumerator in an IEnumerable class.

For a look at what an enumerator (implementing IEnumerator<T>) looks like, see any Enumerator<T> class, such as the ones contained in List<T>, Queue<T>, or Stack<T>. For a look at a class implementing IEnumerable, see any standard collection class.

PostgreSQL Error: Relation already exists

There should be no single quotes here 'A'. Single quotes are for string literals: 'some value'.
Either use double quotes to preserve the upper case spelling of "A":

CREATE TABLE "A" ...

Or don't use quotes at all:

CREATE TABLE A ...

which is identical to

CREATE TABLE a ...

because all unquoted identifiers are folded to lower case automatically in PostgreSQL.


You could avoid problems with the index name completely by using simpler syntax:

CREATE TABLE csd_relationship (
    csd_relationship_id serial PRIMARY KEY,
    type_id integer NOT NULL,
    object_id integer NOT NULL
);

Does the same as your original query, only it avoids naming conflicts automatically. It picks the next free identifier automatically. More about the serial type in the manual.

json_decode() expects parameter 1 to be string, array given

Ok I was running into the same issue. What I failed to notice is that I was using json_decode() instead of using json_encode() so for those who are going to come here please make sure you are using the right function, which is json_encode()

Note: Depends on what you are working on but make sure you are using the right function.

Find if value in column A contains value from column B?

You can try this. :) simple solution!

=IF(ISNUMBER(MATCH(I1,E:E,0)),"TRUE","")

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

enter image description hereI had the same problem and it was really annoying each time with the terminal. I run the command to the terminal and it was fixed

For those try to remove nvm from brew

it may not be enough to just brew uninstall nvm

if you see npm prefix is still /usr/local, run this command

sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}

How to set response header in JAX-RS so that user sees download popup for Excel?

I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.

package local.test.servlet;

import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;

@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        try {

            URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
            //   /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
            System.out.println(templateFileUrl.getPath());
            String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
            String outputFileDir = "MasatoExcelHorizontalOutput";

            ReportProcessor reportProcessor = new ReportProcessor();
            ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);

            ReportSheet outputSheet = new ReportSheet("MySheet");
            outputBook.addReportSheet(outputSheet);

            reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
            System.out.println("wtf???");
            reportProcessor.process(outputBook);


            System.out.println("done!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }

    } //end doGet()

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}//end class



class OutputStreamExporter extends ReportBookExporter {

    private HttpServletResponse response;

    public OutputStreamExporter(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public String getExtention() {
        return null;
    }

    @Override
    public String getFormatType() {
        return ExcelExporter.FORMAT_TYPE;
    }

    @Override
    public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {

        System.out.println(book.getFirstVisibleTab());
        System.out.println(book.getSheetName(0));

        //TODO write to stream
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
            book.write(response.getOutputStream());
            response.getOutputStream().close();
            System.out.println("booya!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}//end class

Using ALTER to drop a column if it exists in MySQL

You can use this script, use your column, schema and table name

 IF EXISTS (SELECT *
                         FROM INFORMATION_SCHEMA.COLUMNS
                         WHERE TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName' 
                                             AND TABLE_SCHEMA = SchemaName)
    BEGIN
       ALTER TABLE TableName DROP COLUMN ColumnName;
    END;

OWIN Security - How to Implement OAuth2 Refresh Tokens

I don't think that you should be using an array to maintain tokens. Neither you need a guid as a token.

You can easily use context.SerializeTicket().

See my below code.

public class RefreshTokenProvider : IAuthenticationTokenProvider
{
    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        Create(context);
    }

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        Receive(context);
    }

    public void Create(AuthenticationTokenCreateContext context)
    {
        object inputs;
        context.OwinContext.Environment.TryGetValue("Microsoft.Owin.Form#collection", out inputs);

        var grantType = ((FormCollection)inputs)?.GetValues("grant_type");

        var grant = grantType.FirstOrDefault();

        if (grant == null || grant.Equals("refresh_token")) return;

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);

        context.SetToken(context.SerializeTicket());
    }

    public void Receive(AuthenticationTokenReceiveContext context)
    {
        context.DeserializeTicket(context.Token);

        if (context.Ticket == null)
        {
            context.Response.StatusCode = 400;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "invalid token";
            return;
        }

        if (context.Ticket.Properties.ExpiresUtc <= DateTime.UtcNow)
        {
            context.Response.StatusCode = 401;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "unauthorized";
            return;
        }

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);
        context.SetTicket(context.Ticket);
    }
}

Add a new item to a dictionary in Python

It can be as simple as:

default_data['item3'] = 3

As Chris' answer says, you can use update to add more than one item. An example:

default_data.update({'item4': 4, 'item5': 5})

Please see the documentation about dictionaries as data structures and dictionaries as built-in types.

How can I execute a python script from an html button?

I've done exactly this on Windows. I have a local .html page that I use as a "dashboard" for all my current work. In addition to the usual links, I've been able to add clickable links that open MS-Word documents, Excel spreadsheets, open my IDE, ssh to servers, etc. It is a little involved but here's how I did it ...

First, update the Windows registry. Your browser handles usual protocols like http, https, ftp. You can define your own protocol and a handler to be invoked when a link of that protocol-type is clicked. Here's the config (run with regedit)

[HKEY_CLASSES_ROOT\mydb]
@="URL:MyDB Document"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\mydb\shell]
@="open"

[HKEY_CLASSES_ROOT\mydb\shell\open]

[HKEY_CLASSES_ROOT\mydb\shell\open\command]
@="wscript C:\_opt\Dashboard\Dashboard.vbs \"%1\""

With this, when I have a link like <a href="mydb:open:ProjectX.docx">ProjectX</a>, clicking it will invoke C:\_opt\Dashboard\Dashboard.vbs passing it the command line parameter open:ProjectX.docx. My VBS code looks at this parameter and does the necessary thing (in this case, because it ends in .docx, it invokes MS-Word with ProjectX.docx as the parameter to it.

Now, I've written my handler in VBS only because it is very old code (like 15+ years). I haven't tried it, but you might be able to write a Python handler, Dashboard.py, instead. I'll leave it up to you to write your own handler. For your scripts, your link could be href="mydb:runpy:whatever.py" (the runpy: prefix tells your handle to run with Python).

Beautiful way to remove GET-variables with PHP?

just use echo'd javascript to rid the URL of any variables with a self-submitting, blank form:

    <?
    if (isset($_GET['your_var'])){
    //blah blah blah code
    echo "<script type='text/javascript'>unsetter();</script>"; 
    ?> 

Then make this javascript function:

    function unsetter() {
    $('<form id = "unset" name = "unset" METHOD="GET"><input type="submit"></form>').appendTo('body');
    $( "#unset" ).submit();
    }

How to make a back-to-top button using CSS and HTML only?

To add to the existing answers, you can avoid affecting the URL by overriding the link with JavaScript. This will still take you to the top of the page without JavaScript, but will append # to the URL.

<a href="#" onclick="document.body.scrollTop=0;document.documentElement.scrollTop=0;event.preventDefault()">Back to top</a>

Strings in C, how to get subString

I think it's easy way... but I don't know how I can pass the result variable directly then I create a local char array as temp and return it.

char* substr(char *buff, uint8_t start,uint8_t len, char* substr)
{
    strncpy(substr, buff+start, len);
    substr[len] = 0;
    return substr;
}

Create multiple threads and wait all of them to complete

In .NET 4.0, you can use the Task Parallel Library.

In earlier versions, you can create a list of Thread objects in a loop, calling Start on each one, and then make another loop and call Join on each one.

'Operation is not valid due to the current state of the object' error during postback

If your stack trace looks like following then you are sending a huge load of json objects to server

Operation is not valid due to the current state of the object. 
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
    at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
    at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
    at Failing.Page_Load(Object sender, EventArgs e) 
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
    at System.Web.UI.Control.OnLoad(EventArgs e)
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something

<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>

For more details, please read this Microsoft kb article

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

You can do the following to install java 8 on your machine. First get the link of tar that you want to install. You can do this by:

  1. go to java downloads page and find the appropriate download.
  2. Accept the license agreement and download it.
  3. In the download page in your browser right click and copy link address.

Then in your terminal:

$ cd /tmp
$ wget http://download.oracle.com/otn-pub/java/jdk/8u74-b02/jdk-8u74-linux-x64.tar.gz\?AuthParam\=1458001079_a6c78c74b34d63befd53037da604746c
$ tar xzf jdk-8u74-linux-x64.tar.gz?AuthParam=1458001079_a6c78c74b34d63befd53037da604746c
$ sudo mv jdk1.8.0_74 /opt
$ cd /opt/jdk1.8.0_74/
$ sudo update-alternatives --install /usr/bin/java java /opt/jdk1.8.0_91/bin/java 2
$ sudo update-alternatives --config java // select version
$ sudo update-alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_91/bin/jar 2
$ sudo update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_91/bin/javac 2
$ sudo update-alternatives --set jar /opt/jdk1.8.0_91/bin/jar
$ sudo update-alternatives --set javac /opt/jdk1.8.0_74/bin/javac
$ java -version // you should have the updated java

How to set the font style to bold, italic and underlined in an Android TextView?

Without quotes works for me:

<item name="android:textStyle">bold|italic</item>

Write HTML to string

The most straight forward way is to use an XmlWriter object. This can be used to produce valid HTML and will take care of all of the nasty escape sequences for you.

How to create a Custom Dialog box in android?

Full Screen Custom Alert Dialog Class in Kotlin

  1. Create XML file, same as you would an activity

  2. Create AlertDialog custom class

    class Your_Class(context:Context) : AlertDialog(context){
    
     init {
      requestWindowFeature(Window.FEATURE_NO_TITLE)
      setCancelable(false)
     }
    
     override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.your_Layout)
      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)
    
      //continue custom code here
      //call dismiss() to close
     }
    }
    
  3. Call the dialog within the activity

    val dialog = Your_Class(this)
    //can set some dialog options here
    dialog.show()
    

Note**: If you do not want your dialog to be full screen, delete the following lines

      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)

Then edit the layout_width & layout_height of your top layout within your XML file to be either wrap_content or a fixed DP value.

I generally do not recommend using fixed DP as you would likely want your app to be adaptable to multiple screen sizes, however if you keep your size values small enough you should be fine

To show only file name without the entire directory path

(cd dir && ls)

will only output filenames in dir. Use ls -1 if you want one per line.

(Changed ; to && as per Sactiw's comment).

How to use conditional breakpoint in Eclipse?

From Eclipsepedia on how to set a conditional breakpoint:

First, set a breakpoint at a given location. Then, use the context menu on the breakpoint in the left editor margin or in the Breakpoints view in the Debug perspective, and select the breakpoint’s properties. In the dialog box, check Enable Condition, and enter an arbitrary Java condition, such as list.size()==0. Now, each time the breakpoint is reached, the expression is evaluated in the context of the breakpoint execution, and the breakpoint is either ignored or honored, depending on the outcome of the expression.

Conditions can also be expressed in terms of other breakpoint attributes, such as hit count.

Program does not contain a static 'Main' method suitable for an entry point

Project Properties \ Output file -> Select Class Library :)

Pass value to iframe from a window

Depends on your specific situation, but if the iframe can be deployed after the rest of the page's loading, you can simply use a query string, a la:

<iframe src="some_page.html?somedata=5&more=bacon"></iframe>

And then somewhere in some_page.html:

<script>
var params = location.href.split('?')[1].split('&');
data = {};
for (x in params)
 {
data[params[x].split('=')[0]] = params[x].split('=')[1];
 }
</script>

Why am I getting a " Traceback (most recent call last):" error?

I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:

TypeError: 'int' object is not callable

My code for Python 3 is as follows:

# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error

raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: {M_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: {F_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: {G_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: {inches_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    # Printing error in the line below
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

I hope this helps.

no module named urllib.parse (How should I install it?)

python3 supports urllib.parse and python2 supports urlparse

If you want both compatible then the following code can help.

import sys

if ((3, 0) <= sys.version_info <= (3, 9)):
    from urllib.parse import urlparse
elif ((2, 0) <= sys.version_info <= (2, 9)):
    from urlparse import urlparse

Update: Change if condition to support higher versions if (3, 0) <= sys.version_info:.

Get most recent row for given ID

SELECT *
FROM   tbl
WHERE  id = 1
ORDER  BY signin DESC
LIMIT  1;

The obvious index would be on (id), or a multicolumn index on (id, signin DESC).

Conveniently for the case, MySQL sorts NULL values last in descending order. That's what you typically want if there can be NULL values: the row with the latest not-null signin.

To get NULL values first:

ORDER BY signin IS NOT NULL, signin DESC

You may want to append more expressions to ORDER BY to get a deterministic pick from (potentially) multiple rows with NULL.
The same applies without NULL if signin is not defined UNIQUE.

Related:

The SQL standard does not explicitly define a default sort order for NULL values. The behavior varies quite a bit across different RDBMS. See:

But there are the NULLS FIRST / NULLS LAST clauses defined in the SQL standard and supported by most major RDBMS, but not by MySQL. See:

Python non-greedy regexes

>>> x = "a (b) c (d) e"
>>> re.search(r"\(.*\)", x).group()
'(b) c (d)'
>>> re.search(r"\(.*?\)", x).group()
'(b)'

According to the docs:

The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behavior isn’t desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.

Sort array of objects by object fields

$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

usort($array, build_sorter('key_b'));

Android Service Stops When App Is Closed

This may help you. I may be mistaken but it seems to me that this is related with returning START_STICKY in your onStartCommand() method. You can avoid the service from being called again by returning START_NOT_STICKY instead.

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

Reason:

Your second URL is considered an absolute path, The Combine method will only return the last path if the last path is an absolute path.

Solution: Just remove the starting slash / of your second Path (/SecondPath to SecondPath). Then it works as you excepted.

How do I concatenate two text files in PowerShell?

I think the "powershell way" could be :

set-content destination.log -value (get-content c:\FileToAppend_*.log )

What is the effect of extern "C" in C++?

Just wanted to add a bit of info, since I haven't seen it posted yet.

You'll very often see code in C headers like so:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

What this accomplishes is that it allows you to use that C header file with your C++ code, because the macro "__cplusplus" will be defined. But you can also still use it with your legacy C code, where the macro is NOT defined, so it won't see the uniquely C++ construct.

Although, I have also seen C++ code such as:

extern "C" {
#include "legacy_C_header.h"
}

which I imagine accomplishes much the same thing.

Not sure which way is better, but I have seen both.

How to add text at the end of each line in Vim?

Following Macro can also be used to accomplish your task.

qqA,^[0jq4@q

How to call a C# function from JavaScript?

.CS File    
    namespace Csharp
    {
      public void CsharpFunction()
      {
        //Code;
      }
    }

    JS code:
    function JSFunction() {
            <%#ProjectName.Csharp.CsharpFunction()%> ;
    }

Note :in JS Function when call your CS page function.... first name of project then name of name space of CS page then function name

PostgreSQL, checking date relative to "today"

select * from mytable where mydate > now() - interval '1 year';

If you only care about the date and not the time, substitute current_date for now()

Registry Key '...' has value '1.7', but '1.6' is required. Java 1.7 is Installed and the Registry is Pointing to it

Just had the similar error when installing java 8 (jdk & jre) on a system already running Java 7.

Error: Registry key 'Software\JavaSoft\Java Runtime

Environment'\CurrentVersion' has value '1.8', but '1.7' is required.

Error: could not find java.dll Error: Could not find Java SE Runtime Environment.

My environment was set up correctly (Path & java_home correctly defined), but the problem arises from the way pre-8 Java installers worked, which is that they used to copy the three executables (java.exe, javaw.exe & javaws.exe) to the Windows system directory. These remain unless overwritten by a new pre-8 installation.

However the Java 8 installer instead creates symbolic links in a new directory, C:\ProgramData\Oracle\Java\javapath, pointing to the actual JRE 8 location.

This means that you'll actually run the old 7 exes but use the new 8 DLLs.

So, the solution is simply to delete the 3 Java exes, as above, from the windows system directory.

If you are running 32-bit Java on a 64-bit Windows, the exes would be in Windows\SysWOW64, otherwise in Windows\System32.

Iterating each character in a string using Python

Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.

i = 0
while i < len(str):
    print str[i]
    i += 1

But then again, why do that when strings are inherently iterable?

for i in str:
    print i

How can I get a list of all values in select box?

As per the DOM structure you can use below code:

var x = document.getElementById('mySelect');
     var txt = "";
     var val = "";
     for (var i = 0; i < x.length; i++) {
         txt +=x[i].text + ",";
         val +=x[i].value + ",";
      }

What is the difference between tree depth and height?

I wanted to make this post because I'm an undergrad CS student and more and more we use OpenDSA and other open source textbooks. It seems like from the top rated answer that the way height and depth is being taught has changed from one generation to the next, and I'm posting this so everyone is aware that this discrepancy now exists and hopefully won't cause bugs in any programs! Thanks.

From the OpenDSA Data Structures & Algos book:

If n1, n2,...,nk is a sequence of nodes in the tree such that ni is the parent of ni+1 for 1<=i<k, then this sequence is called a path from n1 to nk. The length of the path is k-1. If there is a path from node R to node M, then R is an ancestor of M, and M is a descendant of R. Thus, all nodes in the tree are descendants of the root of the tree, while the root is the ancestor of all nodes. The depth of a node M in the tree is the length of the path from the root of the tree to M. The height of a tree is one more than the depth of the deepest node in the tree. All nodes of depth d are at level d in the tree. The root is the only node at level 0, and its depth is 0.

Figure 7.2.1

Figure 7.2.1: A binary tree. Node A is the root. Nodes B and C are A's children. Nodes B and D together form a subtree. Node B has two children: Its left child is the empty tree and its right child is D. Nodes A, C, and E are ancestors of G. Nodes D, E, and F make up level 2 of the tree; node A is at level 0. The edges from A to C to E to G form a path of length 3. Nodes D, G, H, and I are leaves. Nodes A, B, C, E, and F are internal nodes. The depth of I is 3. The height of this tree is 4.

Adding files to java classpath at runtime

The way I have done this is by using my own class loader

URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
DynamicURLClassLoader dynalLoader = new DynamicURLClassLoader(urlClassLoader);

And create the following class:

public class DynamicURLClassLoader extends URLClassLoader {

    public DynamicURLClassLoader(URLClassLoader classLoader) {
        super(classLoader.getURLs());
    }

    @Override
    public void addURL(URL url) {
        super.addURL(url);
    }
}

Works without any reflection

Paused in debugger in chrome?

Really silly issue that I ran into that led me here with the debugger; command.: "debugger;" has a watch set on it.

It caused a page that just said debugger; to appear between every page load.

The way to disable it is to just right-click said Watch and click "Delete watch expression".

multiple axis in matplotlib with different scales

Since Steve Tjoa's answer always pops up first and mostly lonely when I search for multiple y-axes at Google, I decided to add a slightly modified version of his answer. This is the approach from this matplotlib example.

Reasons:

  • His modules sometimes fail for me in unknown circumstances and cryptic intern errors.
  • I don't like to load exotic modules I don't know (mpl_toolkits.axisartist, mpl_toolkits.axes_grid1).
  • The code below contains more explicit commands of problems people often stumble over (like single legend for multiple axes, using viridis, ...) rather than implicit behavior.

Plot

import matplotlib.pyplot as plt 

# Create figure and subplot manually
# fig = plt.figure()
# host = fig.add_subplot(111)

# More versatile wrapper
fig, host = plt.subplots(figsize=(8,5)) # (width, height) in inches
# (see https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html)
    
par1 = host.twinx()
par2 = host.twinx()
    
host.set_xlim(0, 2)
host.set_ylim(0, 2)
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)
    
host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")

color1 = plt.cm.viridis(0)
color2 = plt.cm.viridis(0.5)
color3 = plt.cm.viridis(.9)

p1, = host.plot([0, 1, 2], [0, 1, 2],    color=color1, label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2],    color=color2, label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], color=color3, label="Velocity")

lns = [p1, p2, p3]
host.legend(handles=lns, loc='best')

# right, left, top, bottom
par2.spines['right'].set_position(('outward', 60))

# no x-ticks                 
par2.xaxis.set_ticks([])

# Sometimes handy, same for xaxis
#par2.yaxis.set_ticks_position('right')

# Move "Velocity"-axis to the left
# par2.spines['left'].set_position(('outward', 60))
# par2.spines['left'].set_visible(True)
# par2.yaxis.set_label_position('left')
# par2.yaxis.set_ticks_position('left')

host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
par2.yaxis.label.set_color(p3.get_color())

# Adjust spacings w.r.t. figsize
fig.tight_layout()
# Alternatively: bbox_inches='tight' within the plt.savefig function 
#                (overwrites figsize)

# Best for professional typesetting, e.g. LaTeX
plt.savefig("pyplot_multiple_y-axis.pdf")
# For raster graphics use the dpi argument. E.g. '[...].png", dpi=200)'

Playing mp3 song on python

At this point, why not mentioning python-audio-tools:

It's the best solution I found.

(I needed to install libasound2-dev, on Raspbian)

Code excerpt loosely based on:
https://github.com/tuffy/python-audio-tools/blob/master/trackplay

#!/usr/bin/python

import os
import re
import audiotools.player


START = 0
INDEX = 0

PATH = '/path/to/your/mp3/folder'

class TracklistPlayer:
    def __init__(self,
                 tr_list,
                 audio_output=audiotools.player.open_output('ALSA'),  
                 replay_gain=audiotools.player.RG_NO_REPLAYGAIN,
                 skip=False):

        if skip:
            return

        self.track_index = INDEX + START - 1
        if self.track_index < -1:
            print('--> [track index was negative]')
            self.track_index = self.track_index + len(tr_list)

        self.track_list = tr_list

        self.player = audiotools.player.Player(
                audio_output,
                replay_gain,
                self.play_track)

        self.play_track(True, False)

    def play_track(self, forward=True, not_1st_track=True):
        try:
            if forward:
                self.track_index += 1
            else:
                self.track_index -= 1

            current_track = self.track_list[self.track_index]
            audio_file = audiotools.open(current_track)
            self.player.open(audio_file)
            self.player.play()

            print('--> index:   ' + str(self.track_index))
            print('--> PLAYING: ' + audio_file.filename)

            if not_1st_track:
                pass  # here I needed to do something :)

            if forward:
                pass  # ... and also here

        except IndexError:
            print('\n--> playing finished\n')

    def toggle_play_pause(self):
        self.player.toggle_play_pause()

    def stop(self):
        self.player.stop()

    def close(self):
        self.player.stop()
        self.player.close()


def natural_key(el):
    """See http://www.codinghorror.com/blog/archives/001018.html"""
    return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', el)]


def natural_cmp(a, b):
    return cmp(natural_key(a), natural_key(b))


if __name__ == "__main__":

    print('--> path:    ' + PATH)

    # remove hidden files (i.e. ".thumb")
    raw_list = filter(lambda element: not element.startswith('.'), os.listdir(PATH))

    # mp3 and wav files only list
    file_list = filter(lambda element: element.endswith('.mp3') | element.endswith('.wav'), raw_list)

    # natural order sorting
    file_list.sort(key=natural_key, reverse=False)

    track_list = []
    for f in file_list:
        track_list.append(os.path.join(PATH, f))


    TracklistPlayer(track_list)

Align two inline-blocks left and right on same line

For both elements use

display: inline-block;

the for the 'nav' element use

float: right;

Converting integer to digit list

you can use:

First convert the value in a string to iterate it, Them each value can be convert to a Integer value = 12345

l = [ int(item) for item in str(value) ]

How to convert Map keys to array?

OK, let's go a bit more comprehensive and start with what's Map for those who don't know this feature in JavaScript... MDN says:

The Map object holds key-value pairs and remembers the original insertion order of the keys.
Any value (both objects and primitive values) may be used as either a key or a value.

As you mentioned, you can easily create an instance of Map using new keyword... In your case:

let myMap = new Map().set('a', 1).set('b', 2);

So let's see...

The way you mentioned is an OK way to do it, but yes, there are more concise ways to do that...

Map has many methods which you can use, like set() which you already used to assign the key values...

One of them is keys() which returns all the keys...

In your case, it will return:

MapIterator {"a", "b"}

and you easily convert them to an Array using ES6 ways, like spread operator...

const b = [...myMap.keys()];

Listing all extras of an Intent

Here's what I used to get information on an undocumented (3rd-party) intent:

Bundle bundle = intent.getExtras();
if (bundle != null) {
    for (String key : bundle.keySet()) {
        Log.e(TAG, key + " : " + (bundle.get(key) != null ? bundle.get(key) : "NULL"));
    }
}

Make sure to check if bundle is null before the loop.

presentViewController and displaying navigation bar

I use this code. It's working fine in iOS 8.

MyProfileEditViewController *myprofileEdit=[self.storyboard instantiateViewControllerWithIdentifier:@"myprofileeditSid"];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:myprofileEdit];
[self presentViewController:navigationController animated:YES completion:^{}];

How to have css3 animation to loop forever

Whilst Elad's solution will work, you can also do it inline:

   -moz-animation: fadeinphoto 7s 20s infinite;
-webkit-animation: fadeinphoto 7s 20s infinite;
     -o-animation: fadeinphoto 7s 20s infinite;
        animation: fadeinphoto 7s 20s infinite;

How do operator.itemgetter() and sort() work?

#sorting first by age then profession,you can change it in function "fun".
a = []

def fun(v):
    return (v[1],v[2])

# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul",  8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])

a.sort(key=fun)


print a

How to Replace dot (.) in a string in Java

You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.

str=xpath.replaceAll("\\.", "/*/");          //replaces a literal . with /*/

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

How can I close a browser window without receiving the "Do you want to close this window" prompt?

In the body tag:

<body onload="window.open('', '_self', '');">

To close the window:

<a href="javascript:window.close();">

Tested on Safari 4.0.5, FF for Mac 3.6, IE 8.0, and FF for Windows 3.5

How to submit a form using Enter key in react.js?

Use keydown event to do it:

   input: HTMLDivElement | null = null;

   onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
      // 'keypress' event misbehaves on mobile so we track 'Enter' key via 'keydown' event
      if (event.key === 'Enter') {
        event.preventDefault();
        event.stopPropagation();
        this.onSubmit();
      }
    }

    onSubmit = (): void => {
      if (input.textContent) {
         this.props.onSubmit(input.textContent);
         input.focus();
         input.textContent = '';
      }
    }

    render() {
      return (
         <form className="commentForm">
           <input
             className="comment-input"
             aria-multiline="true"
             role="textbox"
             contentEditable={true}
             onKeyDown={this.onKeyDown}
             ref={node => this.input = node} 
           />
           <button type="button" className="btn btn-success" onClick={this.onSubmit}>Comment</button>
         </form>
      );
    }

Is there any way to prevent input type="number" getting negative values?

Here's an angular 2 solution:

create a class OnlyNumber

import {Directive, ElementRef, HostListener} from '@angular/core';

@Directive({
  selector: '[OnlyNumber]'
})
export class OnlyNumber {

  // Allow decimal numbers. The \. is only allowed once to occur
  private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);

  // Allow key codes for special events. Reflect :
  // Backspace, tab, end, home
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];

  constructor(private el: ElementRef) {
  }

  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }

    // Do not use event.keycode this is deprecated.
    // See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
    let current: string = this.el.nativeElement.value;
    // We need this because the current value on the DOM element
    // is not yet updated with the value from this event
    let next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

add OnlyNumber to declarations in app.module.ts and use like it like this anywhere in your app

<input OnlyNumber="true">

Is there a W3C valid way to disable autocomplete in a HTML form?

HTML 4: No

HTML 5: Yes

The autocomplete attribute is an enumerated attribute. The attribute has two states. The on keyword maps to the on state, and the off keyword maps to the off state. The attribute may also be omitted. The missing value default is the on state. The off state indicates that by default, form controls in the form will have their autofill field name set to off; the on state indicates that by default, form controls in the form will have their autofill field name set to "on".

Reference: W3

Convert float to string with precision & number of decimal digits specified?

Here I am providing a negative example where your want to avoid when converting floating number to strings.

float num=99.463;
float tmp1=round(num*1000);
float tmp2=tmp1/1000;
cout << tmp1 << " " << tmp2 << " " << to_string(tmp2) << endl;

You get

99463 99.463 99.462997

Note: the num variable can be any value close to 99.463, you will get the same print out. The point is to avoid the convenient c++11 "to_string" function. It took me a while to get out this trap. The best way is the stringstream and sprintf methods (C language). C++11 or newer should provided a second parameter as the number of digits after the floating point to show. Right now the default is 6. I am positing this so that others won't wast time on this subject.

I wrote my first version, please let me know if you find any bug that needs to be fixed. You can control the exact behavior with the iomanipulator. My function is for showing the number of digits after the decimal point.

string ftos(float f, int nd) {
   ostringstream ostr;
   int tens = stoi("1" + string(nd, '0'));
   ostr << round(f*tens)/tens;
   return ostr.str();
}

Getting the number of filled cells in a column (VBA)

You can also use

Cells.CurrentRegion

to give you a range representing the bounds of your data on the current active sheet

Msdn says on the topic

Returns a Range object that represents the current region. The current region is a range bounded by any combination of blank rows and blank columns. Read-only.

Then you can determine the column count via

Cells.CurrentRegion.Columns.Count

and the row count via

Cells.CurrentRegion.Rows.Count

Default passwords of Oracle 11g?

Login into the machine as oracle login user id( where oracle is installed)..

  1. Add ORACLE_HOME = <Oracle installation Directory> in Environment variable

  2. Open a command prompt

  3. Change the directory to %ORACLE_HOME%\bin

  4. type the command sqlplus /nolog

  5. SQL> connect /as sysdba

  6. SQL> alter user SYS identified by "newpassword";

One more check, while oracle installation and database confiuration assistant setup, if you configure any database then you might have given password and checked the same password for all other accounts.. If so, then you try with the password which you have given in your database configuration assistant setup.

Hope this will work for you..

How to Inspect Element using Safari Browser

in menu bar click on Edit->preference->advance at bottom click the check box true that is for Show develop menu in menu bar now a develop menu is display at menu bar where you can see all develop option and inspect.

Asp.net - Add blank item at top of dropdownlist

You could also have a union of the blank select with the select that has content:

select '' value, '' name
union
select value, name from mytable

$http get parameters does not work

From $http.get docs, the second parameter is a configuration object:

get(url, [config]);

Shortcut method to perform GET request.

You may change your code to:

$http.get('accept.php', {
    params: {
        source: link, 
        category_id: category
    }
});

Or:

$http({
    url: 'accept.php', 
    method: 'GET',
    params: { 
        source: link, 
        category_id: category
    }
});

As a side note, since Angular 1.6: .success should not be used anymore, use .then instead:

$http.get('/url', config).then(successCallback, errorCallback);

How to retrieve images from MySQL database and display in an html tag

add $row = mysql_fetch_object($result); after your mysql_query();

your html <img src="<?php echo $row->dvdimage; ?>" width="175" height="200" />

Comparing floating point number to zero

You can use std::nextafter with a fixed factor of the epsilon of a value like the following:

bool isNearlyEqual(double a, double b)
{
  int factor = /* a fixed factor of epsilon */;

  double min_a = a - (a - std::nextafter(a, std::numeric_limits<double>::lowest())) * factor;
  double max_a = a + (std::nextafter(a, std::numeric_limits<double>::max()) - a) * factor;

  return min_a <= b && max_a >= b;
}

How do I pass environment variables to Docker containers?

You can pass environment variables to your containers with the -e flag.

An example from a startup script:

sudo docker run -d -t -i -e REDIS_NAMESPACE='staging' \ 
-e POSTGRES_ENV_POSTGRES_PASSWORD='foo' \
-e POSTGRES_ENV_POSTGRES_USER='bar' \
-e POSTGRES_ENV_DB_NAME='mysite_staging' \
-e POSTGRES_PORT_5432_TCP_ADDR='docker-db-1.hidden.us-east-1.rds.amazonaws.com' \
-e SITE_URL='staging.mysite.com' \
-p 80:80 \
--link redis:redis \  
--name container_name dockerhub_id/image_name

Or, if you don't want to have the value on the command-line where it will be displayed by ps, etc., -e can pull in the value from the current environment if you just give it without the =:

sudo PASSWORD='foo' docker run  [...] -e PASSWORD [...]

If you have many environment variables and especially if they're meant to be secret, you can use an env-file:

$ docker run --env-file ./env.list ubuntu bash

The --env-file flag takes a filename as an argument and expects each line to be in the VAR=VAL format, mimicking the argument passed to --env. Comment lines need only be prefixed with #

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

Remove all classes that begin with a certain string

I also use hyphen'-' and digits for class name. So my version include '\d-'

$('#a')[0].className = $('#a')[0].className.replace(/\bbg.\d-*?\b/g, '');

Android Completely transparent Status Bar?

You Can Use Below Code To Make Status Bar Transparent. See Images With red highlight which helps you to identify use of Below code

1]

Kotlin code snippet for your android app

Step:1 Write down code in On create Method

if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
    setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true)
}
if (Build.VERSION.SDK_INT >= 19) {
    window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
if (Build.VERSION.SDK_INT >= 21) {
    setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false)
    window.statusBarColor = Color.TRANSPARENT
}

Step2: You Need SetWindowFlag method which describe in Below code.

private fun setWindowFlag(bits: Int, on: Boolean) {
    val win = window
    val winParams = win.attributes
    if (on) {
        winParams.flags = winParams.flags or bits
    } else {
        winParams.flags = winParams.flags and bits.inv()
    }
    win.attributes = winParams
}

Java code snippet for your android app:

Step1: Main Activity Code

if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
    setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
}
if (Build.VERSION.SDK_INT >= 19) {
    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}

if (Build.VERSION.SDK_INT >= 21) {
    setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
    getWindow().setStatusBarColor(Color.TRANSPARENT);
}

Step2: SetWindowFlag Method

public static void setWindowFlag(Activity activity, final int bits, boolean on) {
    Window win = activity.getWindow();
    WindowManager.LayoutParams winParams = win.getAttributes();
    if (on) {
        winParams.flags |= bits;
    } else {
        winParams.flags &= ~bits;
    }
    win.setAttributes(winParams);
}

How to do error logging in CodeIgniter (PHP)

More oin regards to question part 4 How do you e-mail that error to an email address? The error_log function has email destination too. http://php.net/manual/en/function.error-log.php

Agha, here I found an example that shows a usage. Send errors message via email using error_log()

error_log($this->_errorMsg, 1, ADMIN_MAIL, "Content-Type: text/html; charset=utf8\r\nFrom: ".MAIL_ERR_FROM."\r\nTo: ".ADMIN_MAIL);

Getting value of HTML text input

Yes, you can use jQuery to make this done, the idea is

Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.

<form name="input" action="handle_email.php" method="post">
  <input type="hidden" name="email" id="email" />
  <input type="submit" value="Submit" />
</form> 

<script>
   $("form").submit(function() {
     var emailFromOtherTextBox = $("#email_textbox").val();
     $("#email").val(emailFromOtherTextBox ); 
     return true;
  });
</script>

also see http://api.jquery.com/submit/

How can I check if a string is a number?

Regex.IsMatch(stringToBeChecked, @"^\d+$")

Regex.IsMatch("141241", @"^\d+$")  // True

Regex.IsMatch("232a23", @"^\d+$")  // False

Regex.IsMatch("12412a", @"^\d+$")  // False

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):

import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"

evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)

in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.

HTML Input="file" Accept Attribute File Type (CSV)

Dom this attribute is very old and not accepted in modern browsers as far as I know, But here is an alternative to it, Try this

<script type="text/javascript" language="javascript">
function checkfile(sender) {
    var validExts = new Array(".xlsx", ".xls", ".csv");
    var fileExt = sender.value;
    fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
    if (validExts.indexOf(fileExt) < 0) {
      alert("Invalid file selected, valid files are of " +
               validExts.toString() + " types.");
      return false;
    }
    else return true;
}
</script>

<input type="file" id="file" onchange="checkfile(this);" />

I guess it'll help you of course you can change this script according to your needs.

Difference between res.send and res.json in Express.js

res.json forces the argument to JSON. res.send will take an non-json object or non-json array and send another type. For example:

This will return a JSON number.

res.json(100)

This will return a status code and issue a warning to use sendStatus.

res.send(100)

If your argument is not a JSON object or array (null,undefined,boolean,string), and you want to ensure it is sent as JSON, use res.json.

The system cannot find the file specified. in Visual Studio

I resolved this issue after deleting folder where I was trying to add the file in Visual Studio. Deleted folder from window explorer also. After doing all this, successfully able to add folder and file.

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Suppose a 9800GT GPU:

  • it has 14 multiprocessors (SM)
  • each SM has 8 thread-processors (AKA stream-processors, SP or cores)
  • allows up to 512 threads per block
  • warpsize is 32 (which means each of the 14x8=112 thread-processors can schedule up to 32 threads)

https://www.tutorialspoint.com/cuda/cuda_threads.htm

A block cannot have more active threads than 512 therefore __syncthreads can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:

func1();
__syncthreads();
func2();
__syncthreads();

then the kernel must run twice and the order of execution will be:

  1. func1 is executed for the first 512 threads
  2. func2 is executed for the first 512 threads
  3. func1 is executed for the remaining threads
  4. func2 is executed for the remaining threads

Note:

The main point is __syncthreads is a block-wide operation and it does not synchronize all threads.


I'm not sure about the exact number of threads that __syncthreads can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.

Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads.

I would greatly appreciate if someone test this again for a more accurate piece of information.

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

I'm not sure how efficient this is but you can use range() to slice in both axis

 x=np.arange(16).reshape((4,4))
 x[range(1,3), :][:,range(1,3)] 

Java error - "invalid method declaration; return type required"

You forgot to declare double as a return type

public double diameter()
{
    double d = radius * 2;
    return d;
}

How can I escape a single quote?

Probably the easiest way:

<input type='text' id='abc' value="hel'lo">

Relationship between hashCode and equals method in Java

The problem you will have is with collections where unicity of elements is calculated according to both .equals() and .hashCode(), for instance keys in a HashMap.

As its name implies, it relies on hash tables, and hash buckets are a function of the object's .hashCode().

If you have two objects which are .equals(), but have different hash codes, you lose!

The part of the contract here which is important is: objects which are .equals() MUST have the same .hashCode().

This is all documented in the javadoc for Object. And Joshua Bloch says you must do it in Effective Java. Enough said.

Apache Spark: map vs mapPartitions?

Imp. TIP :

Whenever you have heavyweight initialization that should be done once for many RDD elements rather than once per RDD element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), use mapPartitions() instead of map(). mapPartitions() provides for the initialization to be done once per worker task/thread/partition instead of once per RDD data element for example : see below.

val newRd = myRdd.mapPartitions(partition => {
  val connection = new DbConnection /*creates a db connection per partition*/

  val newPartition = partition.map(record => {
    readMatchingFromDB(record, connection)
  }).toList // consumes the iterator, thus calls readMatchingFromDB 

  connection.close() // close dbconnection here
  newPartition.iterator // create a new iterator
})

Q2. does flatMap behave like map or like mapPartitions?

Yes. please see example 2 of flatmap.. its self explanatory.

Q1. What's the difference between an RDD's map and mapPartitions

map works the function being utilized at a per element level while mapPartitions exercises the function at the partition level.

Example Scenario : if we have 100K elements in a particular RDD partition then we will fire off the function being used by the mapping transformation 100K times when we use map.

Conversely, if we use mapPartitions then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.

There will be performance gain since map works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions).

map

Applies a transformation function on each item of the RDD and returns the result as a new RDD.

Listing Variants

def map[U: ClassTag](f: T => U): RDD[U]

Example :

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
 val b = a.map(_.length)
 val c = a.zip(b)
 c.collect
 res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8)) 

mapPartitions

This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.

preservesPartitioning indicates whether the input function preserves the partitioner, which should be false unless this is a pair RDD and the input function doesn't modify the keys.

Listing Variants

def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]

Example 1

val a = sc.parallelize(1 to 9, 3)
 def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
   var res = List[(T, T)]()
   var pre = iter.next
   while (iter.hasNext)
   {
     val cur = iter.next;
     res .::= (pre, cur)
     pre = cur;
   }
   res.iterator
 }
 a.mapPartitions(myfunc).collect
 res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8)) 

Example 2

val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
 def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
   var res = List[Int]()
   while (iter.hasNext) {
     val cur = iter.next;
     res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
   }
   res.iterator
 }
 x.mapPartitions(myfunc).collect
 // some of the number are not outputted at all. This is because the random number generated for it is zero.
 res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10) 

The above program can also be written using flatMap as follows.

Example 2 using flatmap

val x  = sc.parallelize(1 to 10, 3)
 x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect

 res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10) 

Conclusion :

mapPartitions transformation is faster than map since it calls your function once/partition, not once/element..

Further reading : foreach Vs foreachPartitions When to use What?

How to Bulk Insert from XLSX file extension?

It can be done using SQL Server Import and Export Wizard. But if you're familiar with SSIS and don't want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.

How to read a line from a text file in c/c++?

im not really that good at C , but i believe this code should get you complete single line till the end...

 #include<stdio.h>

 int main()   
{      
  char line[1024];    
  FILE *f=fopen("filename.txt","r");    
  fscanf(*f,"%[^\n]",line);    
  printf("%s",line);    
 }    

Regular expression for validating names and surnames?

You could use the following regex code to validate 2 names separeted by a space with the following regex code:

^[A-Za-zÀ-ú]+ [A-Za-zÀ-ú]+$

or just use:

[[:lower:]] = [a-zà-ú]

[[:upper:]] =[A-ZÀ-Ú]

[[:alpha:]] = [A-Za-zÀ-ú]

[[:alnum:]] = [A-Za-zÀ-ú0-9]

How can I style an Android Switch?

You can customize material styles by setting different color properties. For example custom application theme

<style name="CustomAppTheme" parent="Theme.AppCompat">
    <item name="android:textColorPrimaryDisableOnly">#00838f</item>
    <item name="colorAccent">#e91e63</item>
</style>

Custom switch theme

<style name="MySwitch" parent="@style/Widget.AppCompat.CompoundButton.Switch">
    <item name="android:textColorPrimaryDisableOnly">#b71c1c</item>
    <item name="android:colorControlActivated">#1b5e20</item>
    <item name="android:colorForeground">#f57f17</item>
    <item name="android:textAppearance">@style/TextAppearance.AppCompat</item>
</style>

You can customize switch track and switch thumb like below image by defining xml drawables. For more information http://www.zoftino.com/android-switch-button-and-custom-switch-examples

custom switch track and thumb

How to handle a single quote in Oracle SQL

Use two single-quotes

SQL> SELECT 'D''COSTA' name FROM DUAL;

NAME
-------
D'COSTA

Alternatively, use the new (10g+) quoting method:

SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;

NAME
-------
D'COSTA

How do I find out my root MySQL password?

sudo mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YOUR_PASSWORD_HERE';
FLUSH PRIVILEGES;

mysql -u root -p # and it works

VB.net Need Text Box to Only Accept Numbers

This may be too late, but for other new blood on VB out there, here's something simple.

First, in any case, unless your application would require, blocking user's key entry is somehow not a good thing to do, users may misinterpret the action as problem on the hardware keyboard and at the same time may not see where their keypreesed entry error came from.

Here's a simple one, let user's freely type their entry then trap the error later:

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim theNumber As Integer
        Dim theEntry As String = Trim(TextBox1.Text)

        'This check if entry can be converted to
        'numeric value from 0-10, if cannot return a negative value.
        Try
            theNumber = Convert.ToInt32(theEntry)
            If theNumber < 0 Or theNumber > 10 Then theNumber = -1
        Catch ex As Exception
            theNumber = -1
        End Try

        'Trap for the valid and invalid numeric number
        If theNumber < 0 Or theNumber > 10 Then
            MsgBox("Invalid Entry, allows (0-10) only.")
            'entry was invalid return cursor to entry box.
            TextBox1.Focus()
        Else
            'Entry accepted:
            ' Continue process your thing here...

        End If
    End Sub

Select all 'tr' except the first one

I'm surprised nobody mentioned the use of sibling combinators, which are supported by IE7 and later:

tr + tr /* CSS2, adjacent sibling */
tr ~ tr /* CSS3, general sibling */

They both function in exactly the same way (in the context of HTML tables anyway) as:

tr:not(:first-child)