Programs & Examples On #Beam

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

What ports does RabbitMQ use?

Port Access

Firewalls and other security tools may prevent RabbitMQ from binding to a port. When that happens, RabbitMQ will fail to start. Make sure the following ports can be opened:

4369: epmd, a peer discovery service used by RabbitMQ nodes and CLI tools

5672, 5671: used by AMQP 0-9-1 and 1.0 clients without and with TLS

25672: used by Erlang distribution for inter-node and CLI tools communication and is allocated from a dynamic range (limited to a single port by default, computed as AMQP port + 20000). See networking guide for details.

15672: HTTP API clients and rabbitmqadmin (only if the management plugin is enabled)

61613, 61614: STOMP clients without and with TLS (only if the STOMP plugin is enabled)

1883, 8883: (MQTT clients without and with TLS, if the MQTT plugin is enabled

15674: STOMP-over-WebSockets clients (only if the Web STOMP plugin is enabled)

15675: MQTT-over-WebSockets clients (only if the Web MQTT plugin is enabled)

Reference doc:

Set NA to 0 in R

A solution using mutate_all from dplyr in case you want to add that to your dplyr pipeline:

df %>%
  mutate_all(funs(ifelse(, 0, .)))


   A B C
1  0 0 0
2  1 0 0
3  2 0 2
4  3 0 5
5  0 0 2
6  0 0 1
7  1 0 1
8  2 0 5
9  3 0 2
10 0 0 4
11 0 0 3
12 1 0 5
13 2 0 5
14 3 0 0
15 0 0 1

If in any case you only want to replace the NA's in numeric columns, which I assume it might be the case in modeling, you can use mutate_if:

df %>%
  mutate_if(is.numeric, funs(ifelse(, 0, .)))

or in base R:

replace(, 0)


   A    B C
1  0    0 0
2  1 <NA> 0
3  2    0 2
4  3 <NA> 5
5  0    0 2
6  0 <NA> 1
7  1    0 1
8  2 <NA> 5
9  3    0 2
10 0 <NA> 4
11 0    0 3
12 1 <NA> 5
13 2    0 5
14 3 <NA> 0
15 0    0 1


with dplyr 1.0.0, across is introduced:

# Replace `NA` for all columns
df %>%
  mutate(across(everything(), ~ ifelse(, 0, .)))

# Replace `NA` for numeric columns
df %>%
  mutate(across(where(is.numeric), ~ ifelse(, 0, .)))


df <- data.frame(A=rep(c(0:3, NA), 3), 
                 B=rep(c("0", NA), length.out = 15), 
                 C=sample(c(0:5, NA), 15, replace = TRUE))

Beamer: How to show images as step-by-step images

I found a solution to my problem, by using the visble-command.


   \textbf{Some text}

LaTeX beamer: way to change the bullet indentation?

I use the package enumitem. You may then set such margins when you declare your lists (enumerate, description, itemize):

    \item Foo
    \item Bar

Naturally, the package provides lots of other nice customizations for lists (use 'label=' to change the bullet, use 'itemsep=' to change the spacing between items, etc...)

Get started with Latex on Linux

To get started with LaTeX on Linux, you're going to need to install a couple of packages:

  1. You're going to need a LaTeX distribution. This is the collection of programs that comprise the (La)TeX computer typesetting system. The standard LaTeX distribution on Unix systems used to be teTeX, but it has been superceded by TeX Live. Most Linux distributions have installation packages for TeX Live--see, for example, the package database entries for Ubuntu and Fedora.

  2. You will probably want to install a LaTeX editor. Standard Linux text editors will work fine; in particular, Emacs has a nice package of (La)TeX editing macros called AUCTeX. Specialized LaTeX editors also exist; of those, Kile (KDE Integrated LaTeX Environment) is particularly nice.

  3. You will probably want a LaTeX tutorial. The classic tutorial is "A (Not So) Short Introduction to LaTeX2e," but nowadays the LaTeX wikibook might be a better choice.

How to make System.out.println() shorter

Some interesting alternatives:


PrintStream p = System.out;


PrintWriter p = new PrintWriter(System.out, true);

Best way of invoking getter by reflection

The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.

Twitter Bootstrap tabs not working: when I click on them nothing happens

This solved it when none of the other examples did:

$('#myTab a').click(function (e) {

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

Check this key for 32 bits and 64 bits Windows machines.

 HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment

and this for Windows 64 bits with 32 Bits JRE.

 HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment

This will work for the oracle-sun JRE.

Can't execute jar- file: "no main manifest attribute"

I personally think all the answers here are mis-understanding the question. The answer to this lies in the difference of how spring-boot builds the .jar. Everyone knows that Spring Boot sets up a manifest like this, which varies from everyones asssumption that this is a standard .jar launch, which it may or may not be :

Start-Class: com.myco.eventlogging.MyService
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Spring-Boot-Version: 1.4.0.RELEASE
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_131
Main-Class: org.springframework.boot.loader.JarLauncher

Perhaps it needs to executed with org.springframework.boot.loader.JarLauncher on the classpath?

Is it possible to have multiple statements in a python lambda expression?

A Hacky way to combine multiple statements into a single statement in python is to use the "and" keyword as a short-circuit operator. Then you can use this single statement directly as part of the lambda expression.

This is similar to using "&&" as the short-circuit operator in shell languages such as bash.

Also note: You can always fix a function statement to return a true value by wrapping the function.


def p2(*args):
    return 1 # a true value

junky = lambda x, y: p2('hi') and p2('there') and p2(x) and p2(y)

junky("a", "b")

On second thought, its probably better to use 'or' instead of 'and' since many functions return '0' or None on success. Then you can get rid of the wrapper function in the above example:

junky = lambda x, y: print('hi') or print('there') or print(x) or print(y)

junky("a", "b")

'and' operate will evaluate the expressions until it gets to the first zero return value. after which it short-circuits. 1 and 1 and 0 and 1 evaluates: 1 and 1 and 0, and drops 1

'or' operate will evaluate the expressions until it gets to the first non-zero return value. after which it short-circuits.

0 or 0 or 1 or 0 evaluates 0 or 0 or 1, and drops 0

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).

In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

PowerShell To Set Folder Permissions

Another example using PowerShell for set permissions (File / Directory) :

Verify permissions

Get-Acl "C:\file.txt" | fl *

Apply full permissions for everyone

$acl = Get-Acl "C:\file.txt"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("everyone","FullControl","Allow")
$acl | Set-Acl "C:\file.txt"

Screenshots: enter image description here enter image description here

Hope this helps

How to destroy JWT Tokens on logout?

While other answers provide detailed solutions for various setups, this might help someone who is just looking for a general answer.

There are three general options, pick one or more:

  1. On the client side, delete the cookie from the browser using javascript.

  2. On the server side, set the cookie value to an empty string or something useless (for example "deleted"), and set the cookie expiration time to a time in the past.

  3. On the server side, update the refreshtoken stored in your database. Use this option to log out the user from all devices where they are logged in (their refreshtokens will become invalid and they have to log in again).

How to set breakpoints in inline Javascript in Google Chrome?

Refresh the page containing the script whilst the developer tools are open on the scripts tab. This will add a (program) entry in the file list which shows the html of the page including the script. From here you can add breakpoints.

Configuring IntelliJ IDEA for unit testing with JUnit

Press Ctrl+Shift+T in the code editor. It will show you popup with suggestion to create a test.

Mac OS: ? Cmd+Shift+T

Git status shows files as changed even though contents are the same

The only suspect entry in your config looks to me to be core.ignorecase. You could try unsetting that with:

  git config --unset core.ignorecase

... and see if the output from git status or git diff is different.

Some projects cannot be imported because they already exist in the workspace error in Eclipse

I have a slightly different situation whereby my eclipse stops responding and I have had to kill the session. After restarting Juno, then the particular project I was working on disappeared although .project file exists. Trying to import back into Eclipse would yield the same "Some projects cannot be imported .." or "A project with this name already exists" if trying to create a new project.

In the end, since I was using Working Sets, I managed to find this file .metadata.plugins\org.eclipse.ui.workbench\workingsets.xml. Manually added the missing entry and restarted eclipse and voila, it came back.

How to cherry-pick from a remote branch?

I solved this issue by going on the branch with the commit I want to cherry pick.

git checkout <branch With Commit To Cherry-Pick>

use log to find commit hash

git log

when you've found your hash cut and paste on note pad. if using command just scroll up to get the hash then checkout the branch you want to place the commit in.

git checkout < branch I Want To Place My Cherry-Picked-Hash In>

finally call cherry-pick from git (note) -x is to append your cherry-pick message to the original. "When recording the commit, append a line that says "(cherry picked from commit …?)" to the original commit message in order to indicate which commit this change was cherry-picked from. "

git cherry-pick -x <your hash commit to add to the current branch>

Text File Parsing in Java

While calling/invoking your programme you can use this command : java [-options] className [args...]
in place of [-options] provide more memory e.g -Xmx1024m or more. but this is just a workaround, u have to change ur parsing mechanism.

Cannot load properties file from resources directory

If it is simple application then getSystemResourceAsStream can also be used.

try (InputStream inputStream = ClassLoader.getSystemResourceAsStream(""))..

PHP: Calling another class' method


class ClassA
   private $name = 'John';

   function getName()
     return $this->name;

   include ("file1.php");

   class ClassB

     function __construct()

     function callA()
       $classA = new ClassA();
       $name = $classA->getName();
       echo $name;    //Prints John

   $classb = new ClassB();

Is it possible to style html5 audio tag?

Ken had it right as well.

a css tag:

audio {


will get you some results. seems it doesnt want the player any height above or below 25px but the width can be shortened or lengthened to an extent.

this was good enough for me; see this example (warning, audio plays automatically):

Multiple queries executed in java in single statement

You can use Batch update but queries must be action(i.e. insert,update and delete) queries

Statement s = c.createStatement();
String s1 = "update emp set name='abc' where salary=984";
String s2 = "insert into emp values ('Osama',1420)";  

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

Apache VirtualHost and localhost

You may want to use this:

<VirtualHost *:80>
    DocumentRoot "somepath\Apache2.2\htdocs"
    ServerName localhost
<VirtualHost *:80>

as your first virtual host (place it before another virtual hosts).

Can you put two conditions in an xslt test attribute?

It does have to be wrapped in an <xsl:choose> since it's a when. And lowercase the "and".

   <xsl:when test="4 &lt; 5 and 1 &lt; 2" >
   <!-- do something -->
   <!-- do something else -->

Understanding Apache's access log

I also don't under stand what the "-" means after the 200 140 section of the log

That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)

JavaScript variable assignments from tuples

As an update to The Minister's answer, you can now do this with es2015:

function Tuple(...args) {
  args.forEach((val, idx) => 
    Object.defineProperty(this, "item"+idx, { get: () => val })

var t = new Tuple("a", 123)
console.log(t.item0) // "a"
t.item0 = "b"
console.log(t.item0) // "a",console

how to call javascript function in html.actionlink in mvc?

<a onclick="MyFunc()">blabla..</a>

There is nothing more in @Html.ActionLink that you could utilize in this case. And razor is evel by itself, drop it from where you can.

C# function to return array

Two changes are needed:

  1. Change the return type of the method from Array[] to ArtWorkData[]
  2. Change Labels[] in the return statement to Labels

How is CountDownLatch used in Java Multithreading?

As mentioned in JavaDoc (, CountDownLatch is a synchronization aid, introduced in Java 5. Here the synchronization does not mean restricting access to a critical section. But rather sequencing actions of different threads. The type of synchronization achieved through CountDownLatch is similar to that of Join. Assume that there is a thread "M" which needs to wait for other worker threads "T1", "T2", "T3" to complete its tasks Prior to Java 1.5, the way this can be done is, M running the following code


The above code makes sure that thread M resumes its work after T1, T2, T3 completes its work. T1, T2, T3 can complete their work in any order. The same can be achieved through CountDownLatch, where T1,T2, T3 and thread M share same CountDownLatch object.
"M" requests : countDownLatch.await();
where as "T1","T2","T3" does countDownLatch.countdown();

One disadvantage with the join method is that M has to know about T1, T2, T3. If there is a new worker thread T4 added later, then M has to be aware of it too. This can be avoided with CountDownLatch. After implementation the sequence of action would be [T1,T2,T3](the order of T1,T2,T3 could be anyway) -> [M]

Disable copy constructor

Make SymbolIndexer( const SymbolIndexer& ) private. If you're assigning to a reference, you're not copying.

How do I convert an enum to a list in C#?

Here for usefulness... some code for getting the values into a list, which converts the enum into readable form for the text

public class KeyValuePair
    public string Key { get; set; }

    public string Name { get; set; }

    public int Value { get; set; }

    public static List<KeyValuePair> ListFrom<T>()
      var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>());
      return array
        .Select(a => new KeyValuePair
            Key = a.ToString(),
            Name = a.ToString().SplitCapitalizedWords(),
            Value = Convert.ToInt32(a)
          .OrderBy(kvp => kvp.Name)

.. and the supporting System.String extension method:

/// <summary>
/// Split a string on each occurrence of a capital (assumed to be a word)
/// e.g. MyBigToe returns "My Big Toe"
/// </summary>
public static string SplitCapitalizedWords(this string source)
  if (String.IsNullOrEmpty(source)) return String.Empty;
  var newText = new StringBuilder(source.Length * 2);
  for (int i = 1; i < source.Length; i++)
    if (char.IsUpper(source[i]))
      newText.Append(' ');
  return newText.ToString();

Binding ConverterParameter

There is also an alternative way to use MarkupExtension in order to use Binding for a ConverterParameter. With this solution you can still use the default IValueConverter instead of the IMultiValueConverter because the ConverterParameter is passed into the IValueConverter just like you expected in your first sample.

Here is my reusable MarkupExtension:

/// <summary>
///     <example>
///         <TextBox>
///             <TextBox.Text>
///                 <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
///                     Converter="{StaticResource TestValueConverter}"
///                     ConverterParameterBinding="{Binding ConcatSign}" />
///             </TextBox.Text>
///         </TextBox>
///     </example>
/// </summary>
public class ConverterBindableParameter : MarkupExtension
    #region Public Properties

    public Binding Binding { get; set; }
    public BindingMode Mode { get; set; }
    public IValueConverter Converter { get; set; }
    public Binding ConverterParameter { get; set; }


    public ConverterBindableParameter()
    { }

    public ConverterBindableParameter(string path)
        Binding = new Binding(path);

    public ConverterBindableParameter(Binding binding)
        Binding = binding;

    #region Overridden Methods

    public override object ProvideValue(IServiceProvider serviceProvider)
        var multiBinding = new MultiBinding();
        Binding.Mode = Mode;
        if (ConverterParameter != null)
            ConverterParameter.Mode = BindingMode.OneWay;
        var adapter = new MultiValueConverterAdapter
            Converter = Converter
        multiBinding.Converter = adapter;
        return multiBinding.ProvideValue(serviceProvider);


    private class MultiValueConverterAdapter : IMultiValueConverter
        public IValueConverter Converter { get; set; }

        private object lastParameter;

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
            if (Converter == null) return values[0]; // Required for VS design-time
            if (values.Length > 1) lastParameter = values[1];
            return Converter.Convert(values[0], targetType, lastParameter, culture);

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
            if (Converter == null) return new object[] { value }; // Required for VS design-time

            return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };

With this MarkupExtension in your code base you can simply bind the ConverterParameter the following way:

<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
     <wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
                 Converter="{StaticResource AccessLevelToVisibilityConverter}"
                 ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />          

Which looks almost like your initial proposal.

Add a new item to recyclerview programmatically?

simply add to your data structure ( mItems ) , and then notify your adapter about dataset change

private void addItem(String item) {

addItem("New Item");

throwing exceptions out of a destructor

Throwing out of a destructor can result in a crash, because this destructor might be called as part of "Stack unwinding". Stack unwinding is a procedure which takes place when an exception is thrown. In this procedure, all the objects that were pushed into the stack since the "try" and until the exception was thrown, will be terminated -> their destructors will be called. And during this procedure, another exception throw is not allowed, because it's not possible to handle two exceptions at a time, thus, this will provoke a call to abort(), the program will crash and the control will return to the OS.

Placeholder in UITextView

I've written a cleaner implementation after trying some of the proposed approaches and posted it to Github. Pull requests and issues are welcome.

Some key improvements that versus other approaches presented here:

  • Doesn't allocate a UILabel inside drawRect:. (Please don't ever do that.)
  • Doesn't compare the text view's current text to a desired placeholder to swap colors.
  • Hides the placeholder while dictation is active (like UITextField).

How to remove an element slowly with jQuery?

You mean like



sql like operator to get the numbers only

With SQL 2012 and later, you could use TRY_CAST/TRY_CONVERT to try converting to a numeric type, e.g. TRY_CAST(answer AS float) IS NOT NULL -- note though that this will match scientific notation too (1+E34). (If you use decimal, then scientific notation won't match)

Open Bootstrap Modal from code-behind

By default Bootstrap javascript files are included just before the closing body tag

        <script src="vendors/jquery-1.9.1.min.js"></script>
        <script src="bootstrap/js/bootstrap.min.js"></script>
        <script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
        <script src="assets/scripts.js"></script>

I took these javascript files into the head section right before the body tag and I wrote a small function to call the modal popup:

    <script src="vendors/jquery-1.9.1.min.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
    <script src="assets/scripts.js"></script>

 <script type="text/javascript">
    function openModal() {

then I could call the modal popup from code-behind with the following:

protected void lbEdit_Click(object sender, EventArgs e) {   
      ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);

How to include a sub-view in Blade templates?

You can use the blade template engine:


'' would live in your main views folder:

// for laravel 4.X

// for laravel 5.X

Another example


would display the following view

// for laravel 4.X

// for laravel 5.X

Another example


would display the following view

// for Laravel 4.X

// for Laravel 5.X

So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views folder for laravel 4.x or your resources/views folder in laravel 5.x


If you want to pass parameters: @include('', array('paramName' => 'value'))

You can then use the value in your views like so <p>{{$paramName}}</p>

How do I find the authoritative name-server for a domain name?

You could find out the nameservers for a domain with the "host" command:

[davidp@supernova:~]$ host -t ns name server name server

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

document.getElementById('something') can be 'undefined'. Usually (thought not always) it's sufficient to do tests like if (document.getElementById('something')).

How to add two strings as if they were numbers?

@cr05s19xx suggested on a duplicate question:

JavaScript is a bit funny when it comes to numbers and addition.

Giving the following

'20' - '30' = 10; // returns 10 as a number '20' + '30' = '2030'; // Returns them as a string The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:

function myFunction() {
  var per = parseInt(document.getElementById('input1').value);
  var num = parseInt(document.getElementById('input2').value);
  var sum = (num / 100) * per;
  var output = num - sum;


  document.getElementById('demo').innerHTML = output;

function myFunction2() {
  var per = parseInt(document.getElementById('input3').value);
  var num = parseInt(document.getElementById('input4').value);
  var sum = (num / 100) * per;
  var output = sum + num;


  document.getElementById('demo1').innerHTML = output;

Checking the equality of two slices

You should use reflect.DeepEqual()

DeepEqual is a recursive relaxation of Go's == operator.

DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.

Array values are deeply equal when their corresponding elements are deeply equal.

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

Func values are deeply equal if both are nil; otherwise they are not deeply equal.

Interface values are deeply equal if they hold deeply equal concrete values.

Map values are deeply equal if they are the same map object or if they have the same length and their corresponding keys (matched using Go equality) map to deeply equal values.

Pointer values are deeply equal if they are equal using Go's == operator or if they point to deeply equal values.

Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.

Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

Bootstrap 3 - 100% height of custom div inside column

You need to set the height of every parent element of the one you want the height defined.

<html style="height: 100%;">
  <body style="height: 100%;">
    <div style="height: 100%;">
        Make this division 100% height.


JsFiddle example

Creating a data frame from two vectors using cbind

Vectors and matrices can only be of a single type and cbind and rbind on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.

(Note that in your rbind example, the promotion happens within the c call:

> c(10, "[]", "[[1,2]]")
[1] "10"      "[]"      "[[1,2]]"

If you want a rectangular structure where the columns can be different types, you want a data.frame. Any of the following should get you what you want:

> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
  v1 v2      v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ v1: num  10 20
 $ v2: Factor w/ 1 level "[]": 1 1
 $ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using specifically the data.frame version of cbind)

> x =, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c(10, 20)              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using cbind, but making the first a data.frame so that it combines as data.frames do):

> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c.10..20.              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

Add new row to dataframe, at specific row-index, not appended?

You should try dplyr package

a <- data.frame(A = c(1, 2, 3, 4),
               B = c(11, 12, 13, 14))

for (i in 50:1000) {
    b <- data.frame(A = i, B = i * i)
    a <- bind_rows(a, b)



   user  system elapsed 
   0.25    0.00    0.25

In contrast with using rbind function

a <- data.frame(A = c(1, 2, 3, 4),
                B = c(11, 12, 13, 14))

    for (i in 50:1000) {
        b <- data.frame(A = i, B = i * i)
        a <- rbind(a, b)



   user  system elapsed 
   0.49    0.00    0.49 

There is some performance gain.

Css transition from display none to display block, navigation with subnav

As you know the display property cannot be animated BUT just by having it in your CSS it overrides the visibility and opacity transitions.

The solution...just removed the display properties.

nav.main ul ul {_x000D_
  position: absolute;_x000D_
  list-style: none;_x000D_
  opacity: 0;_x000D_
  visibility: hidden;_x000D_
  padding: 10px;_x000D_
  background-color: rgba(92, 91, 87, 0.9);_x000D_
  -webkit-transition: opacity 600ms, visibility 600ms;_x000D_
  transition: opacity 600ms, visibility 600ms;_x000D_
nav.main ul li:hover ul {_x000D_
  visibility: visible;_x000D_
  opacity: 1;_x000D_
<nav class="main">_x000D_
      <a href="">Lorem</a>_x000D_
        <li><a href="">Ipsum</a>_x000D_
        <li><a href="">Dolor</a>_x000D_
        <li><a href="">Sit</a>_x000D_
        <li><a href="">Amet</a>_x000D_

MySql export schema without data

You can use the -d option with mysqldump command

mysqldump -u root -p -d databasename > database.sql

Why doesn't Console.Writeline, Console.Write work in Visual Studio Express?

I run into a similar problem while running a Unit Test. Console.WriteLine() did not write anything into the VS Output Window.

Using System.Diagnostics.Debug.WriteLine() solved the problem. is deprecated, what should I use instead?

The usage of org.apache.commons.httpclient.URI is not strictly an issue; what is an issue is that you target the wrong constructor, which is depreciated.

Using just

new URI( [string] );

Will indeed flag it as depreciated. What is needed is to provide at minimum one additional argument (the first, below), and ideally two:

  1. escaped: true if URI character sequence is in escaped form. false otherwise.
  2. charset: the charset string to do escape encoding, if required

This will target a non-depreciated constructor within that class. So an ideal usage would be as such:

new URI( [string], true, StandardCharsets.UTF_8.toString() );

A bit crazy-late in the game (a hair over 11 years later - egad!), but I hope this helps someone else, especially if the method at the far end is still expecting a URI, such as org.apache.commons.httpclient.setURI().

iPhone/iPad browser simulator?

I use mobile-browser-emulator chrome plug-in which is has iphone device types. It actually uses user-agent and size of device on which based responsive pages are rendered

How do I resolve `The following packages have unmet dependencies`

I just solved this issue. The problem was in version conflict. Nodejs 10 installed with npm. So before installing nodejs - remove old npm. Or remove new node -> remove npm -> install node again.

This is the only way which helped me.

How can I use Bash syntax in Makefile targets?

You can call bash directly within your Makefile instead of using the default shell:

bash -c "ls -al"

instead of:

ls -al

Why are only a few video games written in Java?

Minor points first:

  • any productivity boost from Java is hypothetical. The syntax is almost identical to C++ so you're really just banking on savings from memory management and standard libraries. The libraries have little to offer games developers and memory management is a contentious issue due to garbage collection.

  • cross-platform "for free" is not as good as you think because few developers want to use OpenGL and several key platforms probably lack a good Java implementation or wrappers for their native libraries, whether for graphics, audio, networking, etc.

But mainly, the issue is backwards compatibility. Games developers moved to C++ from C and to C from assembly purely because the migration route was smooth. Each interoperates closely with the previous, and all their previous code was usable in the new language, often via a single compiler. Therefore migration was as slow or as fast as you liked. For example, some of our old headers in use today still have #ifdef WATCOMC in, and I don't think anybody has used the Watcom compiler here in a decade or more. There is a massive investment in old code and each bit is only replaced as needed. That process of replacing and upgrading bits and pieces from one game to the next is nowhere near as practical if you changed to a language that doesn't natively interoperate with your existing code. Yes, C++/Java interoperability is possible, but very impractical by comparison to simply writing "C with a bit of C++" or embedding asm blocks in C.

To properly supercede C++ as the game developers' language of choice, it must do one of two things:

  1. Be easily interoperable with existing legacy code, thus preserving investment and maintaining access to existing libraries and tools, OR
  2. Demonstrably show up-front enough of a productivity boost that the cost of rewriting all your own code (or reworking the interfaces into reusable components that can be used from that language) is more than covered.

Subjectively, I don't think Java meets either of those. A higher-level language might meet the 2nd, if someone is brave enough to be the pioneer. (EVE Online is probably the best example we have of Python being usable, but which uses a fork of the main Python language, many C++ components for performance, and even that is for a fairly undemanding game in modern terms.)

How do I concatenate strings and variables in PowerShell?

While expression:

"string1" + "string2" + "string3"

will concatenate the string, you need to put a $ in front of the parenthesis to make it evaluate as a single argument when passed to a PowerShell command. Example:

Write-Host $( "string1" + "string2" + "string3" )

As a bonus, if you want it to span multiple lines, then you need to use the awkward backtick syntax at the end of the line (without any spaces or characters to the right of the backtick).


Write-Host $(`
    "The rain in "        +`
    "Spain falls mainly " +`
    "in the plains"       )`
    -ForegroundColor Yellow

(Actually, I think PowerShell is currently implemented a little bit wrong by requiring unnecessary backticks between parentheses. If Microsoft would just follow Python or Tcl parenthesis rules of allowing you to put as many newlines as you want between the starting and ending parenthesis then they would solve most of the problems that people don't like about PowerShell related to line continuation, and concatenation of strings.

I've found that you can leave the backticks off sometimes on line continuations between parenthesis, but it's really flaky and unpredictable if it will work... It's better to just add the backticks.)

How to validate a date?

This is ES6 (with let declaration).

function checkExistingDate(year, month, day){ // year, month and day should be numbers
     // months are intended from 1 to 12
    let months31 = [1,3,5,7,8,10,12]; // months with 31 days
    let months30 = [4,6,9,11]; // months with 30 days
    let months28 = [2]; // the only month with 28 days (29 if year isLeap)

    let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);

    let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);

    return valid; // it returns true or false

In this case I've intended months from 1 to 12. If you prefer or use the 0-11 based model, you can just change the arrays with:

let months31 = [0,2,4,6,7,9,11];
let months30 = [3,5,8,10];
let months28 = [1];

If your date is in form dd/mm/yyyy than you can take off day, month and year function parameters, and do this to retrieve them:

let arrayWithDayMonthYear = myDateInString.split('/');
let year = parseInt(arrayWithDayMonthYear[2]);
let month  = parseInt(arrayWithDayMonthYear[1]);
let day = parseInt(arrayWithDayMonthYear[0]);

How to Delete node_modules - Deep Nested Folder in Windows

You can use Git Bash to remove the folder:

example: c:\users\stu\projects\mynodeproject

rm /c/users/stu/projects/mynodeproject -rfd

Compiling with g++ using multiple cores

You can do this with make - with gnu make it is the -j flag (this will also help on a uniprocessor machine).

For example if you want 4 parallel jobs from make:

make -j 4

You can also run gcc in a pipe with

gcc -pipe

This will pipeline the compile stages, which will also help keep the cores busy.

If you have additional machines available too, you might check out distcc, which will farm compiles out to those as well.

Fixed GridView Header with horizontal and vertical scrolling in

I was looking for a solution for this for a long time and found most of the answers are not working or not suitable for my situation i also find most of the java script code for that they worked but only with the vertical scroll not with the horizontal scroll and also combination of header and rows doesn't match.

Finally i have found a solution with javascript here is the link bellow :-

scrollable horizontal and vertical grid view with fixed headers

Easiest way to convert month name to month number in JS ? (Jan = 01)

Here is a simple one liner function

function GetMonth(anyDate) { 
   return 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')[anyDate.getMonth()];
// ECMA6
var GetMonth = (anyDate) => 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')[anyDate.getMonth()];

Directory-tree listing in Python

Here is a one line Pythonic version:

import os
dir = 'given_directory_name'
filenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]

This code lists the full path of all files and directories in the given directory name.

ArrayList filter

Iterate through the list and check if contains your string "How" and if it does then remove. You can use following code:

// need to construct a new ArrayList otherwise remove operation will not be supported
List<String> list = new ArrayList<String>(Arrays.asList(new String[] 
                                  {"How are you?", "How you doing?","Joe", "Mike"}));
System.out.println("List Before: " + list);
for (Iterator<String> it=list.iterator(); it.hasNext();) {
    if (!"How"))
        it.remove(); // NOTE: Iterator's remove method, not ArrayList's, is used.
System.out.println("List After: " + list);


List Before: [How are you?, How you doing?, Joe, Mike]
List After: [How are you?, How you doing?]

How to align LinearLayout at the center of its parent?

Try <TableRow android:gravity="center_horizontal"> This will center the inner LinearLayout within the tablerow.

Moving from one activity to another Activity in Android

When you have to go from one page to another page in android changes made in 2 files

Intent intentSignUP = new Intent(this,SignUpActivity.class);

add activity in androidManifest file also like

 <activity android:name=".SignUpActivity"></activity>

Pytorch tensor to numpy array

There are 4 dimensions of the tensor you want to convert.

[:, ::-1, :, :] 

: means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.

::-1 means that for the second axes it reverses the the axes

How do I remove/delete a virtualenv?

Use rmvirtualenv

Remove an environment, in the $WORKON_HOME.


rmvirtualenv ENVNAME

You must use deactivate before removing the current environment.

$ rmvirtualenv my_env


How do I split a string by a multi-character delimiter in C#?

...In short:

string[] arr = "This is a sentence".Split(new string[] { "is" }, StringSplitOptions.None);

How do I find the parent directory in C#?

You can use System.IO.Directory.GetParent() to retrieve the parent directory of a given directory.

Display XML content in HTML page

Simple solution is to embed inside of a <textarea> element, which will preserve both the formatting and the angle brackets. I have also removed the border with style="border:none;" which makes the textarea invisible.

Here is a sample:

How to fix git error: RPC failed; curl 56 GnuTLS

Simply executing command

git init

before cloning resolved it for me.

How to configure nginx to enable kinda 'file browser' mode?

You should try HttpAutoindexModule.

Set autoindex option to on. It is off by default.

Your example configuration should be ok

location /{ 
   root /home/yozloy/html/; 
   index index.html; 
   autoindex on;

Without autoindex option you should be getting Error 403 for requests that end with / on directories that do not have an index.html file. With this option you should be getting a simple listing:

<head><title>Index of /</title></head>
<body bgcolor="white">
<h1>Index of /test/</h1><hr><pre><a href="../">../</a>
<a href="test.txt">test.txt</a>                 19-May-2012 10:43            0

Edit: Updated the listing to delete any references to test

Extension methods must be defined in a non-generic static class

Change it to

public static class LinqHelper

Split and join C# string

You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.

string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');

if (lnSpace > -1)
    string lcFirst = lcStart.Substring(0, lnSpace);
    string lcRest = lcStart.Substring(lnSpace + 1);

Why can't Python import Image from PIL?

For me, I had typed image with a lower case "i" instead of Image. So I did:

from PIL import Image NOT from PIL import image

Recommended Fonts for Programming?

I never found a reason to stray from Courier New. I don't think I'd have a problem with any font so long as it's sans-serif. Mono-spaced fonts are nice for coding, too.

Courier New has serifs.

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

You can try "SelectedIndexChanged", it will trigger the event even if the same item is selected.

How do I add PHP code/file to HTML(.html) files?

MODERN REVISION: you also now need to fix it by changing the little known ''security.limit_extensions' in php-fpm doing this. You will probably already know the well documented mechanism of changing apache to AddHandler/AddType I will not go into that here.

  1. YOU MUST find out where php-fpm/conf is in your set up. I did it by doing this

    # grep -rnw '/etc/' -e 'security.limit_extensions'

  2. I got this back

    '/etc/php-fpm.d/www.conf:387:;security.limit_extensions = .php .php3 .php4 .php5 .php7'

  3. go to this file, edit it and MAKE SURE YOU REALISE IT IS COMMENTED OUT EG: change it from ';security.limit_extensions = .php .php3 .php4 .php5 .php7' <- NB: note the ";" - this line is actually DISABLED by default - and you do not need all the nonsense extensions, in fact they are probably dangerous.. change it to 'security.limit_extensions = .php .htm' <- note the semi colon is now removed. then restart apache/(or nginx) and restart php-fpm # service php-fpm restart # service httpd restart

Radio buttons not checked in jQuery

This works too. It seems shortest working notation: !$('#selector:checked')

Can you break from a Groovy "each" closure?

Replace each loop with any closure.

def list = [1, 2, 3, 4, 5]
list.any { element ->
    if (element == 2)
        return // continue

    println element

    if (element == 3)
        return true // break



How can I specify the required Node.js version in package.json?

There's another, simpler way to do this:

  1. npm install Node@8 (saves Node 8 as dependency in package.json)
  2. Your app will run using Node 8 for anyone - even Yarn users!

This works because node is just a package that ships node as its package binary. It just includes as node_module/.bin which means it only makes node available to package scripts. Not main shell.

See discussion on Twitter here:

How to import local packages without gopath

There's no such thing as "local package". The organization of packages on a disk is orthogonal to any parent/child relations of packages. The only real hierarchy formed by packages is the dependency tree, which in the general case does not reflect the directory tree.

Just use

import "myproject/packageN"

and don't fight the build system for no good reason. Saving a dozen of characters per import in any non trivial program is not a good reason, because, for example, projects with relative import paths are not go-gettable.

The concept of import paths have some important properties:

  • Import paths can be be globally unique.
  • In conjunction with GOPATH, import path can be translated unambiguously to a directory path.
  • Any directory path under GOPATH can be unambiguously translated to an import path.

All of the above is ruined by using relative import paths. Do not do it.

PS: There are few places in the legacy code in Go compiler tests which use relative imports. ATM, this is the only reason why relative imports are supported at all.

How to check if a value exists in an array in Ruby

Use Enumerable#include:

a = %w/Cat Dog Bird/

a.include? 'Dog'

Or, if a number of tests are done,1 you can get rid of the loop (that even include? has) and go from O(n) to O(1) with:

h = Hash[[a, a].transpose]

1. I hope this is obvious but to head off objections: yes, for just a few lookups, the Hash[] and transpose ops dominate the profile and are each O(n) themselves.

Calculating distance between two points (Latitude, Longitude)

Since you're using SQL Server 2008, you have the geography data type available, which is designed for exactly this kind of data:

DECLARE @source geography = 'POINT(0 51.5)'
DECLARE @target geography = 'POINT(-3 56)'

SELECT @source.STDistance(@target)



(1 row(s) affected)

Telling us it is about 538 km from (near) London to (near) Edinburgh.

Naturally there will be an amount of learning to do first, but once you know it it's far far easier than implementing your own Haversine calculation; plus you get a LOT of functionality.

If you want to retain your existing data structure, you can still use STDistance, by constructing suitable geography instances using the Point method:

DECLARE @orig_lat DECIMAL(12, 9)
DECLARE @orig_lng DECIMAL(12, 9)
SET @orig_lat=53.381538 set @orig_lng=-1.463526

DECLARE @orig geography = geography::Point(@orig_lat, @orig_lng, 4326);

    @orig.STDistance(geography::Point(dest.Latitude, dest.Longitude, 4326)) 
       AS distance
--INTO #includeDistances
FROM #orig dest

Scikit-learn train_test_split with indices

If you are using pandas you can access the index by calling .index of whatever array you wish to mimic. The train_test_split carries over the pandas indices to the new dataframes.

In your code you simply use x1.index and the returned array is the indexes relating to the original positions in x.

Rotate axis text in python matplotlib

import pylab as pl
pl.xticks(rotation = 90)


You cannot include non-aggregated columns in your result set which are not grouped. If a train has only one destination, then just add the destination column to your group by clause, otherwise you need to rethink your query.


SELECT t.Train, t.Dest, r.MaxTime
      SELECT Train, MAX(Time) as MaxTime
      FROM TrainTable
      GROUP BY Train
) r
INNER JOIN TrainTable t
ON t.Train = r.Train AND t.Time = r.MaxTime

Comparing two integer arrays in Java

Arrays.equals(ary1,ary2); // returns boolean value

you can use Arrays.deepEquals(ary1,ary2) to compare 2D arrays as well

also check this link for comparision comparision between Arrays.equls(ar1,ar2) and Arrays.deepEquals(ar1,ar2)

Java Arrays.equals() returns false for two dimensional arrays

if you dont want to use these library methods then you can easily implement your method like this:

public static boolean ArrayCompare(int[] a, int[] a2) {
    if (a==a2)   // checks for same array reference
        return true;
    if (a==null || a2==null)  // checks for null arrays
        return false;

    int length = a.length;
    if (a2.length != length)  // arrays should be of equal length
        return false;

    for (int i=0; i<length; i++)  // compare array values
        if (a[i] != a2[i])
            return false;

    return true;

PostgreSQL IF statement

      DELETE FROM orders;
      INSERT INTO orders VALUES (1,2,3);
   END IF;

There are no procedural elements in standard SQL. The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command.

You need a semicolon (;) at the end of each statement in plpgsql (except for the final END).

You need END IF; at the end of the IF statement.

A sub-select must be surrounded by parentheses:

    IF (SELECT count(*) FROM orders) > 0 ...


    IF (SELECT count(*) > 0 FROM orders) ...

This is equivalent and much faster, though:

    IF EXISTS (SELECT FROM orders) ...


The additional SELECT is not needed. This does the same, faster:

   DELETE FROM orders;
      INSERT INTO orders VALUES (1,2,3);
   END IF;

Though unlikely, concurrent transactions writing to the same table may interfere. To be absolutely sure, write-lock the table in the same transaction before proceeding as demonstrated.

How to check if a table exists in a given schema

For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), (""). Ignores schema2 in ("",schema2).
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;

Is it possible to have different Git configuration for different projects?

The .git/config file in a particular clone of a repository is local to that clone. Any settings placed there will only affect actions for that particular project.

(By default, git config modifies .git/config, not ~/.gitconfig - only with --global does it modify the latter.)

Does Java have a complete enum for HTTP response codes?

If you are using Netty, you can use:

Import Error: No module named numpy

pip3 may not refer to the python3 you use. run python3 -m pip install numpy instead.

Bootstrap 3 Navbar Collapse

The nabvar will collapse on small devices. The point of collapsing is defined by @grid-float-breakpoint in variables. By default this will by before 768px. For screens below the 768 pixels screen width, the navbar will look like:

enter image description here

It's possible to change the @grid-float-breakpoint in variables.less and recompile Bootstrap. When doing this you also will have to change @screen-xs-max in navbar.less. You will have to set this value to your new @grid-float-breakpoint -1. See also: This is needed to change navbar forms and dropdowns at the @grid-float-breakpoint to their mobile version too.

How to install a specific version of package using Composer?

I tried to require a development branch from a different repository and not the latest version and I had the same issue and non of the above worked for me :(

after a while I saw in the documentation that in cases of dev branch you need to require with a 'dev-' prefix to the version and the following worked perfectly.

composer require [vendorName]/[packageName]:dev-[gitBranchName]

serialize/deserialize java 8 java.time with Jackson JSON mapper


add these dependencies and enable these modules. that should help

    private static final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();

Public class is inaccessible due to its protection level

Also if you want to do something like ClassB.Run("thing");, make sure the Method Run(); is static or you could call it like this: thing.Run("thing");.

How can I enable cURL for an installed Ubuntu LAMP stack?

Try this:

sudo apt-get install -y curl

Change the size of a JTextField inside a JBorderLayout

Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:

JPanel displayPanel = new JPanel(new GridLayout(4, 2)); 
JTextField titleText = new JTextField("title"); 
JPanel wrapper = new JPanel( new FlowLayout(0, 0, FlowLayout.LEADING) );
wrapper.add( titleText );

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

Some code examples for simple GET request. Maybe this helps understanding the difference. Using then:

$http.get('/someURL').then(function(response) {
    var data =,
        status = response.status,
        header = response.header,
        config = response.config;
    // success handler
}, function(response) {
    var data =,
        status = response.status,
        header = response.header,
        config = response.config;
    // error handler

Using success/error:

$http.get('/someURL').success(function(data, status, header, config) {
    // success handler
}).error(function(data, status, header, config) {
    // error handler

Change div height on button click

Do this:

function changeHeight() {
document.getElementById('chartdiv').style.height = "200px"
<button type="button" onClick="changeHeight();"> Click Me!</button>

Android - Set text to TextView

Maybe you have assigned the text in onResume() function

Custom height Bootstrap's navbar

You need also to set .min-height: 0px; please see bellow:

.navbar-inner {
    min-height: 0px;

.navbar-nav li a {
    line-height: 150px;
    height: 150px;
    padding-top: 0;

If you set .min-height: 0px; then you can choose any height you want!

Good Luck!

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

evict non ISO-8859-1 characters, will be replace by '?' (before send to a ISO-8859-1 DB by example):

utf8String = new String ( utf8String.getBytes(), "ISO-8859-1" );

Why does Firebug say toFixed() is not a function?

You need convert to number type:


Pass arguments into C program from command line

You could use getopt.

 #include <ctype.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>

 main (int argc, char **argv)
   int bflag = 0;
   int sflag = 0;
   int index;
   int c;

   opterr = 0;

   while ((c = getopt (argc, argv, "bs")) != -1)
     switch (c)
       case 'b':
         bflag = 1;
       case 's':
         sflag = 1;
       case '?':
         if (isprint (optopt))
           fprintf (stderr, "Unknown option `-%c'.\n", optopt);
           fprintf (stderr,
                    "Unknown option character `\\x%x'.\n",
         return 1;
         abort ();

   printf ("bflag = %d, sflag = %d\n", bflag, sflag);

   for (index = optind; index < argc; index++)
     printf ("Non-option argument %s\n", argv[index]);
   return 0;

How do I send a JSON string in a POST request in Go

If you already have a struct.

import (

// .....

type Student struct {
    Name    string `json:"name"`
    Address string `json:"address"`

// .....

body := &Student{
    Name:    "abc",
    Address: "xyz",

payloadBuf := new(bytes.Buffer)
req, _ := http.NewRequest("POST", url, payloadBuf)

client := &http.Client{}
res, e := client.Do(req)
if e != nil {
    return e

defer res.Body.Close()

fmt.Println("response Status:", res.Status)
// Print the body to the stdout
io.Copy(os.Stdout, res.Body)

Full gist.

How do you compare two version Strings in Java?

public int compare(String v1, String v2) {
        v1 = v1.replaceAll("\\s", "");
        v2 = v2.replaceAll("\\s", "");
        String[] a1 = v1.split("\\.");
        String[] a2 = v2.split("\\.");
        List<String> l1 = Arrays.asList(a1);
        List<String> l2 = Arrays.asList(a2);

        int i=0;
            Double d1 = null;
            Double d2 = null;

                d1 = Double.parseDouble(l1.get(i));
            }catch(IndexOutOfBoundsException e){

                d2 = Double.parseDouble(l2.get(i));
            }catch(IndexOutOfBoundsException e){

            if (d1 != null && d2 != null) {
                if (d1.doubleValue() > d2.doubleValue()) {
                    return 1;
                } else if (d1.doubleValue() < d2.doubleValue()) {
                    return -1;
            } else if (d2 == null && d1 != null) {
                if (d1.doubleValue() > 0) {
                    return 1;
            } else if (d1 == null && d2 != null) {
                if (d2.doubleValue() > 0) {
                    return -1;
            } else {
        return 0;

type checking in javascript

Try this code:

 alert(typeof(1) == "number");

How to change button text in Swift Xcode 6?

You can do:

button.setTitle("my text here", forState: .normal)

Swift 3 and 4:

button.setTitle("my text here", for: .normal)

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

$this->db->count_all_results is part of an Active Record query (preparing the query, to only return the number, not the actual results).

$query->num_rows() is performed on a resultset object (after returning results from the DB).

Automatically get loop index in foreach loop in Perl

It can be done with a while loop (foreach doesn't support this):

my @arr = (1111, 2222, 3333);

while (my ($index, $element) = each(@arr))
   # You may need to "use feature 'say';"
   say "Index: $index, Element: $element";


Index: 0, Element: 1111
Index: 1, Element: 2222
Index: 2, Element: 3333

Perl version: 5.14.4

Java: Multiple class declarations in one file

1.Is there a tidy name for this technique (analogous to inner, nested, anonymous)?

Multi-class single-file demo.

2.The JLS says the system may enforce the restriction that these secondary classes can't be referred to by code in other compilation units of the package, e.g., they can't be treated as package-private. Is that really something that changes between Java implementations?

I'm not aware of any which don't have that restriction - all the file based compilers won't allow you to refer to source code classes in files which are not named the same as the class name. ( if you compile a multi-class file, and put the classes on the class path, then any compiler will find them )

Server Error in '/' Application. ASP.NET

I got the same problem and my solution was to remove webconfig file from the directory.. then it works..

Using local makefile for CLion instead of CMake

Newest version has better support literally for any generated Makefiles, through the compiledb

Three steps:

  1. install compiledb

    pip install compiledb
  2. run a dry make

    compiledb -n make 

    (do the autogen, configure if needed)

  3. there will be a compile_commands.json file generated open the project and you will see CLion will load info from the json file. If you your CLion still try to find CMakeLists.txt and cannot read compile_commands.json, try to remove the entire folder, re-download the source files, and redo step 1,2,3

Orignal post: Working with Makefiles in CLion using Compilation DB

Cannot install node modules that require compilation on Windows 7 x64/VS2012

I had also a lot of problem to compile nodejs zmq.

For the problem with with vcbuild.exe, just add it to the PATH

For other problems I could compile just using Windows 7.1 SDK Command Prompt

(Menu Programs -> Microsoft Windows SDK v7.1 -> Windows 7.1 SDK Command Prompt)

And from the prompt:

npm install zmq

That's works :)

Ineligible Devices section appeared in Xcode 6.x.x

I can confirm that the answer it to upgrade Xcode to 6.1. If you are using Xcode 6.0.x you will not be able to select a device running 8.1. Your deployment targets and OS version should have nothing to do with this.

If your OS version is greater than 10.9.4 I would recommend this. First, un-attaching all devices. Download Xcode 6.1. After opening the new version of Xcode attach your device. You should be good to go.

Another good thing would be to look at the release notes. It's and easy read and gives you a general idea of what still needs to be fixed.

How can I add a Google search box to my website?

Sorry for replying on an older question, but I would like to clarify the last question.

You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:[value from input-field]

But when you search with google, you notice the following URL:

Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.

Regular expression - starting and ending with a character string

^wp.*\.php$ Should do the trick.

The .* means "any character, repeated 0 or more times". The next . is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.

Reading numbers from a text file into an array in C

There are two problems in your code:

  • the return value of scanf must be checked
  • the %d conversion does not take overflows into account (blindly applying *10 + newdigit for each consecutive numeric character)

The first value you got (-104204697) is equals to 5623125698541159 modulo 2^32; it is thus the result of an overflow (if int where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.

The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf, the number of items successfully matched):

#include <stdio.h>

int main(int argc, char *argv[]) {
    int i, j;
    short unsigned digitArray[16];
    i = 0;
    while (
        i != sizeof(digitArray) / sizeof(digitArray[0])
     && 1 == scanf("%1hu", digitArray + i)
    ) {
    for (j = 0; j != i; j++) {
        printf("%hu\n", digitArray[j]);
    return 0;

window.close() doesn't work - Scripts may close only the windows that were opened by it

The below code worked for me :)'your current page URL', '_self', '');

Apply pandas function to column to create multiple new columns?

Just use result_type="expand"

df = pd.DataFrame(np.random.randint(0,10,(10,2)), columns=["random", "a"])
df[["sq_a","cube_a"]] = df.apply(lambda x: [x.a**2, x.a**3], axis=1, result_type="expand")

Design Patterns web based applications

In the beaten-up MVC pattern, the Servlet is "C" - controller.

Its main job is to do initial request evaluation and then dispatch the processing based on the initial evaluation to the specific worker. One of the worker's responsibilities may be to setup some presentation layer beans and forward the request to the JSP page to render HTML. So, for this reason alone, you need to pass the request object to the service layer.

I would not, though, start writing raw Servlet classes. The work they do is very predictable and boilerplate, something that framework does very well. Fortunately, there are many available, time-tested candidates ( in the alphabetical order ): Apache Wicket, Java Server Faces, Spring to name a few.

Start/Stop and Restart Jenkins service on Windows

       jenkins.exe stop
       jenkins.exe start
       jenkins.exe restart

These commands will work from cmd only if you run CMD with admin permissions

How do I split a string with multiple separators in JavaScript?

Hi for example if you have split and replace in String 07:05:45PM

var hour = time.replace("PM", "").split(":");


[ '07', '05', '45' ]

XAMPP - Apache could not start - Attempting to start Apache service


Check to see if the port 80 is in use first as this can be an issue. You can do this by typing "netstat -an" into cmd. The look for under Local Address, if you find this is in use then follow the solution from @Karthik. However, I had a similar issue but my port 80 was not in use. My XAMPP had wrong paths locations, steps to fix this:

1.Find out the Apache version you are using, you can find this by looking in Services (Control panel, Admin Tools, Services) and finding Apache in my case it was listed as Apache2.4

2.Close XAMPP.

3.Run cmd as admin.

4.execute 'sc delete "Apache2.4"' (put your version in place of mine and without the surrounding ' ', but with the " " around Apache).

5.execute 'sc delete "mySQL"', again remove the '' when you type it.

6.reopen XAMPP and try starting Apache

If you are having trouble with FileZill, Mercury, or Tomcat you could try it here too, but I have not tested that myself.

Hope this helps!

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

You shouldn't use LIs in email. They are unpredictable across email clients. Instead you have to code each bullet point like this:

<table width="100%" cellspacing="0" border="0" cellpadding="0">
        <td align="left" valign="top" width="10" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">&bull;</td>
        <td align="left" valign="top" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">This is the first bullet point</td>
        <td align="left" valign="top" width="10" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">&bull;</td>
        <td align="left" valign="top" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">This is the second bullet point</td>

This will ensure that your bullets work in every email client.

Make a td fixed size (width,height) while rest of td's can expand

This will take care of the empty td:

<td style="min-width: 20px;"></td>

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

In my case it was libjpeg. All I had to do was run brew reinstall libjpeg and everything just worked!

Java Enum return Int

If you need to get the int value, just have a getter for the value in your ENUM:

private enum DownloadType {
    private final int value;

    private DownloadType(int value) {
        this.value = value;

    public int getValue() {
        return value;

public static void main(String[] args) {
    System.out.println(DownloadType.AUDIO.getValue());           //returns 1
    System.out.println(DownloadType.VIDEO.getValue());           //returns 2
    System.out.println(DownloadType.AUDIO_AND_VIDEO.getValue()); //returns 3

Or you could simple use the ordinal() method, which would return the position of the enum constant in the enum.

private enum DownloadType {
    //rest of the code

System.out.println(DownloadType.AUDIO.ordinal());            //returns 0
System.out.println(DownloadType.VIDEO.ordinal());            //returns 1
System.out.println(DownloadType.AUDIO_AND_VIDEO.ordinal()); //returns 2

How to convert ActiveRecord results into an array of hashes

For current ActiveRecord (4.2.4+) there is a method to_hash on the Result object that returns an array of hashes. You can then map over it and convert to symbolized hashes:

# Get an array of hashes representing the result (column => value):
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
# => [{:id => 1, :title => "title_1", :body => "body_1"},
      {:id => 2, :title => "title_2", :body => "body_2"},

See the ActiveRecord::Result docs for more info.

Update statement using with clause

The WITH syntax appears to be valid in an inline view, e.g.

UPDATE (WITH comp AS ...
        SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
   SET SomeColumn=ComputedValue;

But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.

You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:

MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON ( =

But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING clause arbitrarily complex, incorporating multiple WITH clauses.

Replace duplicate spaces with a single space in T-SQL

Just Adding Another Method-

Replacing Multiple Spaces with Single Space WITHOUT Using REPLACE in SQL Server-


('HAPPY         NEWYEAR     2020'),
('WELCOME       ALL     !');

    CAST('<r><![CDATA[' + input + ']]></r>' AS XML).value('(/r/text())[1] cast as xs:token?','VARCHAR(MAX)')
    AS Expected_Result
FROM @TestTable;


Static class initializer in PHP

If you don't like public static initializer, reflection can be a workaround.


class LanguageUtility
    public static function initializeClass($class)
            // Get a static method named 'initialize'. If not found,
            // ReflectionMethod() will throw a ReflectionException.
            $ref = new \ReflectionMethod($class, 'initialize');

            // The 'initialize' method is probably 'private'.
            // Make it accessible before calling 'invoke'.
            // Note that 'setAccessible' is not available
            // before PHP version 5.3.2.

            // Execute the 'initialize' method.
        catch (Exception $e)

class MyClass
    private static function initialize()




create database if not exists `test`;

USE `test`;


/*Table structure for table `test` */

  `id` int(11) NOT NULL auto_increment,   
  `recid` int(11) NOT NULL default '0',       
  `cvfilename` varchar(250)  NOT NULL default '',     
  `cvpagenumber`  int(11) NULL,     
  `cilineno` int(11)  NULL,    
  `batchname`  varchar(100) NOT NULL default '',
  `type` varchar(20) NOT NULL default '',    
  `data` varchar(100) NOT NULL default '',
   PRIMARY KEY  (`id`)

Mongoose (mongodb) batch insert?

Sharing working and relevant code from our project:

//documentsArray is the list of sampleCollection objects
    .then((res) => {
        console.log("insert sampleCollection result ", res);
    .catch(err => {
        console.log("bulk insert sampleCollection error ", err);

Compress images on client side before uploading

If you are looking for a library to carry out client-side image compression, you can check this out:compress.js. This will basically help you compress multiple images purely with JavaScript and convert them to base64 string. You can optionally set the maximum size in MB and also the preferred image quality.

How to develop Android app completely using python?

There are two primary contenders for python apps on Android


This integrates with the Android build system, it provides a Python API for all android features. To quote the site "The complete Android API and user interface toolkit are directly at your disposal."

Beeware (Toga widget toolkit)

This provides a multi target transpiler, supports many targets such as Android and iOS. It uses a generic widget toolkit (toga) that maps to the host interface calls.

Which One?

Both are active projects and their github accounts shows a fair amount of recent activity.

Beeware Toga like all widget libraries is good for getting the basics out to multiple platforms. If you have basic designs, and a desire to expand to other platforms this should work out well for you.

On the other hand, Chaquopy is a much more precise in its mapping of the python API to Android. It also allows you to mix in Java, useful if you want to use existing code from other resources. If you have strict design targets, and predominantly want to target Android this is a much better resource.

word-wrap break-word does not work in this example

Work-Break has nothing to do with inline-block.

Make sure you specify width and notice if there are any overriding attributes in parent nodes. Make sure there is not white-space: nowrap.

see this codepen



  <style scoped>
    .parent {
      width: 100vw;

    p {
      border: 1px dashed black;
      padding: 1em;
      font-size: calc(0.6vw + 0.6em);
      direction: ltr;
      width: 30vw;
      word-break: break-word;
      white-space: pre-line;
      overflow-wrap: break-word;
      -ms-word-break: break-word;
      word-break: break-word;
      -ms-hyphens: auto;
      -moz-hyphens: auto;
      -webkit-hyphens: auto;
      hyphens: auto;

  <div class="parent">

      Note: Mind that, as for now, break-word is not part of the standard specification for webkit; therefore, you might be interested in employing the break-all instead. This alternative value provides a undoubtedly drastic solution; however, it conforms to
      the standard.





How to get video duration, dimension and size in PHP?

getID3 supports video formats. See:

Edit: So, in code format, that'd be like:

$getID3 = new getID3;
$file = $getID3->analyze($filename);
echo("Duration: ".$file['playtime_string'].
" / Dimensions: ".$file['video']['resolution_x']." wide by ".$file['video']['resolution_y']." tall".
" / Filesize: ".$file['filesize']." bytes<br />");

Note: You must include the getID3 classes before this will work! See the above link.

Edit: If you have the ability to modify the PHP installation on your server, a PHP extension for this purpose is ffmpeg-php. See:

Visual Studio Code open tab in new window

With Visual Studio 1.43 (Q1 2020), the Ctrl+K then O keyboard shortcut will work for a file.

See issue 89989:

It should be possible to e.g. invoke the "Open Active File in New Window" command and open that file into an empty workspace in the web.

new windows --

How to convert a DataFrame back to normal RDD in pyspark?

@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.

Try this:

rdd =


rdd =

estimating of testing effort as a percentage of development time

Testing time is probably more closely correlated to feature scope than development time. I'd also argue (perhaps controversially) that testing time is correlated to the skill of your development team.

For a 6-to-9 month development effort, I demand a absolute minimum of 2 weeks testing time, performed by actual testers (not the development team) who are well-versed in the software they will be testing (i.e., 2 weeks does not include ramp-up time). This is for a project that has ~5 developers.

Map a 2D array onto a 1D array

The typical formula for recalculation of 2D array indices into 1D array index is

index = indexX * arrayWidth + indexY;

Alternatively you can use

index = indexY * arrayHeight + indexX;

(assuming that arrayWidth is measured along X axis, and arrayHeight along Y axis)

Of course, one can come up with many different formulae that provide alternative unique mappings, but normally there's no need to.

In C/C++ languages built-in multidimensional arrays are stored in memory so that the last index changes the fastest, meaning that for an array declared as

int xy[10][10];

element xy[5][3] is immediately followed by xy[5][4] in memory. You might want to follow that convention as well, choosing one of the above two formulae depending on which index (X or Y) you consider to be the "last" of the two.

Flutter: how to make a TextField with HintText but no Underline?

Here is a supplemental answer that shows some fuller code:

enter image description here

    decoration: BoxDecoration(
      color: Colors.tealAccent,
      borderRadius:  BorderRadius.circular(32),
    child: TextField(
      decoration: InputDecoration(
        hintStyle: TextStyle(fontSize: 17),
        hintText: 'Search your trips',
        suffixIcon: Icon(,
        border: InputBorder.none,
        contentPadding: EdgeInsets.all(20),


  • The dark background (code not shown) is Colors.teal.
  • InputDecoration also has a filled and fillColor property, but I couldn't get them to have a corner radius, so I used a container instead.

How to add (vertical) divider to a horizontal LinearLayout?

I just ran into the same problem today. As the previous answers indicate, the problem stems from the use of a color in the divider tag, rather than a drawable. However, instead of writing my own drawable xml, I prefer to use themed attributes as much as possible. You can use the android:attr/dividerHorizontal and android:attr/dividerVertical to get a predefined drawable instead:

    <!-- other views -->

The attributes are available in API 11 and above.

Also, as mentioned by bocekm in his answer, the dividerPadding property does NOT add extra padding on either side of a vertical divider, as one might assume. Instead it defines top and bottom padding and thus may truncate the divider if it's too large.

Chrome desktop notification example

I made this simple Notification wrapper. It works on Chrome, Safari and Firefox.

Probably on Opera, IE and Edge as well but I haven't tested it yet.

Just get the notify.js file from here and put it into your page.

Get it on Bower

$ bower install js-notify

This is how it works:

notify('title', {
    body: 'Notification Text',
    icon: 'path/to/image.png',
    onclick: function(e) {}, // e -> Notification object
    onclose: function(e) {},
    ondenied: function(e) {}

You have to set the title but the json object as the second argument is optional.

Get random integer in range (x, y]?

How about:

Random generator = new Random();
int i = 10 - generator.nextInt(10);

Intersect Two Lists in C#

You need to first transform data1, in your case by calling ToString() on each element.

Use this if you want to return strings.

List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};

var newData = data1.Select(i => i.ToString()).Intersect(data2);

Use this if you want to return integers.

List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};

var newData = data1.Intersect(data2.Select(s => int.Parse(s));

Note that this will throw an exception if not all strings are numbers. So you could do the following first to check:

int temp;
if(data2.All(s => int.TryParse(s, out temp)))
    // All data2 strings are int's

What is the fastest way to send 100,000 HTTP requests in Python?

Twistedless solution:

from urlparse import urlparse
from threading import Thread
import httplib, sys
from Queue import Queue

concurrent = 200

def doWork():
    while True:
        url = q.get()
        status, url = getStatus(url)
        doSomethingWithResult(status, url)

def getStatus(ourl):
        url = urlparse(ourl)
        conn = httplib.HTTPConnection(url.netloc)   
        conn.request("HEAD", url.path)
        res = conn.getresponse()
        return res.status, ourl
        return "error", ourl

def doSomethingWithResult(status, url):
    print status, url

q = Queue(concurrent * 2)
for i in range(concurrent):
    t = Thread(target=doWork)
    t.daemon = True
    for url in open('urllist.txt'):
except KeyboardInterrupt:

This one is slighty faster than the twisted solution and uses less CPU.

Convert array into csv

Well maybe a little late after 4 years haha... but I was looking for solution to do OBJECT to CSV, however most solutions here is actually for ARRAY to CSV...

After some tinkering, here is my solution to convert object into CSV, I think is pretty neat. Hope this would help someone else.

$resp = array();
foreach ($entries as $entry) {
    $row = array();
    foreach ($entry as $key => $value) {
        array_push($row, $value);
    array_push($resp, implode(',', $row));
echo implode(PHP_EOL, $resp);

Note that for the $key => $value to work, your object's attributes must be public, the private ones will not get fetched.

The end result is that you get something like this:


jQuery .val change doesn't change input value

<script src="//"></script>
function changes() {
$('#link').val('new value');
<button onclick="changes()">a</button>
<input type='text' value='' id='link'>

how to get 2 digits after decimal point in tsql?

So, something like

SELECT @i / 3

I would however recomend that this be done in the UI/Report layer, as this will cuase loss of precision.

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

How to bind RadioButtons to an enum?

This work for Checkbox too.

public class EnumToBoolConverter:IValueConverter
    private int val;
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        int intParam = (int)parameter;
        val = (int)value;

        return ((intParam & val) != 0);

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        val ^= (int)parameter;
        return Enum.Parse(targetType, val.ToString());

Binding a single enum to multiple checkboxes.

Binding value to style

  • In your app.component.html use:

  • In app.ts declare variable of string type backcolor:string.

  • Set the variable this.backcolor="red".

jQuery AJAX single file upload

A. Grab file data from the file field

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
  files =;

This saves the file data to a file variable for later use.

B. Handle the file upload on submit

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening


// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
    data.append(key, value);

    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
        if(typeof data.error === 'undefined')
            // Success so call function to process the form
            submitForm(event, data);
            // Handle errors here
            console.log('ERRORS: ' + data.error);
    error: function(jqXHR, textStatus, errorThrown)
        // Handle errors here
        console.log('ERRORS: ' + textStatus);

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.

C. Upload the files

Quick and dirty php script to upload the files and pass back some info:

<?php // You need to add server side validation and better error handling here

$data = array();

$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
        $files[] = $uploaddir .$file['name'];
        $error = true;
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);

echo json_encode($data);


IMP: Don't use this, write your own.

D. Handle the form submit

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

function submitForm(event, data)
  // Create a jQuery object from the form
$form = $(;

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
    formData = formData + '&filenames[]=' + value;

    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
        if(typeof data.error === 'undefined')
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
            // Handle errors here
            console.log('ERRORS: ' + data.error);
    error: function(jqXHR, textStatus, errorThrown)
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    complete: function()

Final note

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.

Referenced From

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

You can replace IList<DzieckoAndOpiekun> resultV with var resultV.

MongoDB query multiple collections at once

As mentioned before in MongoDB you can't JOIN between collections.

For your example a solution could be:

var myCursor = db.users.find({admin:1});
var user_id = myCursor.hasNext() ? : null;
db.posts.find({owner_id : user_id._id});

See the reference manual - cursors section:

Other solution would be to embed users in posts collection, but I think for most web applications users collection need to be independent for security reasons. Users collection might have Roles, permissons, etc.

 "content":"Some content",
 "user":{"_id":"12345", "admin":1},
 "content":"Some other content",
 "user":{"_id":"123456789", "admin":0},

and then:

db.posts.find({user.admin: 1 });

How can I insert into a BLOB column from an insert statement in sqldeveloper?

  1. insert into mytable(id, myblob) values (1,EMPTY_BLOB);
  2. SELECT * FROM mytable mt where for update
  3. Click on the Lock icon to unlock for editing
  4. Click on the ... next to the BLOB to edit
  5. Select the appropriate tab and click open on the top left.
  6. Click OK and commit the changes.

Google maps API V3 - multiple markers on exact same spot

Offsetting the markers isn't a real solution if they're located in the same building. What you might want to do is modify the markerclusterer.js like so:

  1. Add a prototype click method in the MarkerClusterer class, like so - we will override this later in the map initialize() function:

    MarkerClusterer.prototype.onClick = function() { 
        return true; 
  2. In the ClusterIcon class, add the following code AFTER the clusterclick trigger:

    // Trigger the clusterclick event.
    google.maps.event.trigger(markerClusterer, 'clusterclick', this.cluster_);
    var zoom = this.map_.getZoom();
    var maxZoom = markerClusterer.getMaxZoom();
    // if we have reached the maxZoom and there is more than 1 marker in this cluster
    // use our onClick method to popup a list of options
    if (zoom >= maxZoom && this.cluster_.markers_.length > 1) {
       return markerClusterer.onClickZoom(this);
  3. Then, in your initialize() function where you initialize the map and declare your MarkerClusterer object:

    markerCluster = new MarkerClusterer(map, markers);
    // onClickZoom OVERRIDE
    markerCluster.onClickZoom = function() { return multiChoice(markerCluster); }

    Where multiChoice() is YOUR (yet to be written) function to popup an InfoWindow with a list of options to select from. Note that the markerClusterer object is passed to your function, because you will need this to determine how many markers there are in that cluster. For example:

    function multiChoice(mc) {
         var cluster = mc.clusters_;
         // if more than 1 point shares the same lat/long
         // the size of the cluster array will be 1 AND
         // the number of markers in the cluster will be > 1
         // REMEMBER: maxZoom was already reached and we can't zoom in anymore
         if (cluster.length == 1 && cluster[0].markers_.length > 1)
              var markers = cluster[0].markers_;
              for (var i=0; i < markers.length; i++)
                  // you'll probably want to generate your list of options here...
              return false;
         return true;

Char to int conversion in C

Yes, this is a safe conversion. C requires it to work. This guarantee is in section 5.2.1 paragraph 2 of the latest ISO C standard, a recent draft of which is N1570:

Both the basic source and basic execution character sets shall have the following members:
the 10 decimal digits
0 1 2 3 4 5 6 7 8 9
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

Both ASCII and EBCDIC, and character sets derived from them, satisfy this requirement, which is why the C standard was able to impose it. Note that letters are not contiguous iN EBCDIC, and C doesn't require them to be.

There is no library function to do it for a single char, you would need to build a string first:

int digit_to_int(char d)
 char str[2];

 str[0] = d;
 str[1] = '\0';
 return (int) strtol(str, NULL, 10);

You could also use the atoi() function to do the conversion, once you have a string, but strtol() is better and safer.

As commenters have pointed out though, it is extreme overkill to call a function to do this conversion; your initial approach to subtract '0' is the proper way of doing this. I just wanted to show how the recommended standard approach of converting a number as a string to a "true" number would be used, here.

MySQL SELECT AS combine two columns into one

In case of NULL columns it is better to use IF clause like this which combine the two functions of : CONCAT and COALESCE and uses special chars between the columns in result like space or '_'

SELECT FirstName , LastName , 
IF(FirstName IS NULL AND LastName IS NULL, NULL,' _ ',CONCAT(COALESCE(FirstName ,''), COALESCE(LastName ,''))) 
AS Contact_Phone FROM   TABLE1

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

Set EditText cursor color

The only valid answer should be to change the theme of the activity: <item name="colorAccent">#000000</item> You should not use the android:textCursorDrawable to @null because this only concerns the cursor itself but not the pin below the cursor if you want to drag that cursor. The theming solution is the most serious one.

How to print like printf in Python3?

In Python2, print was a keyword which introduced a statement:

print "Hi"

In Python3, print is a function which may be invoked:

print ("Hi")

In both versions, % is an operator which requires a string on the left-hand side and a value or a tuple of values or a mapping object (like dict) on the right-hand side.

So, your line ought to look like this:

print("a=%d,b=%d" % (f(x,n),g(x,n)))

Also, the recommendation for Python3 and newer is to use {}-style formatting instead of %-style formatting:

print('a={:d}, b={:d}'.format(f(x,n),g(x,n)))

Python 3.6 introduces yet another string-formatting paradigm: f-strings.

print(f'a={f(x,n):d}, b={g(x,n):d}')

Java, Calculate the number of days between two dates

Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.

I would recommend that you use Joda Time, which is a much better API than Date/Calendar. It sounds like you should use the LocalDate type in this case. You can then use:

int days = Days.daysBetween(date1, date2).getDays();

ImportError: DLL load failed: The specified module could not be found

Quick note: Check if you have other Python versions, if you have removed them, make sure you did that right. If you have Miniconda on your system then Python will not be removed easily.

What worked for me: removed other Python versions and the Miniconda, reinstalled Python and the matplotlib library and everything worked great.

RESTful call in Java

You can check out the CXF. You can visit the JAX-RS Article here

Calling is as simple as this (quote):

BookStore store = JAXRSClientFactory.create("", BookStore.class);
// (1) remote GET call to
Books books = store.getAllBooks();
// (2) no remote call
BookResource subresource = store.getBookSubresource(1);
// {3} remote GET call to
Book b = subresource.getDescription();

Getting new Twitter API consumer and secret keys

step 1.Go to

step 2.Create app(fill up the form)

step 3.Change permissions if necessary(depending if you want to just read,write or execute)

step 4.Go To API keys section and click generate ACCESS TOKEN.

5 years late to answer :)

Now you have these tokens which is all you need.

'oauth_access_token' => Access token
'oauth_access_token_secret' => Access token secret
'consumer_key' => API key
'consumer_secret' => API secret

How to use environment variables in docker compose

env SOME_VAR="I am some var" OTHER_VAR="I am other var" docker stack deploy -c docker-compose.yml

Use the version 3.6 :

version: "3.6"
    image: "nginx:alpine"
      foo: "bar"
      baz: "${OTHER_VAR}"
      some-label: "$SOME_VAR"
    image: "nginx:alpine"
      hello: "world"
      world: "${SOME_VAR}"
      some-label: "$OTHER_VAR"

I got it form this link

Microsoft Excel mangles Diacritics in .csv files?

Excel 2007 properly reads UTF-8 with BOM (EF BB BF) encoded csv.

Excel 2003 (and maybe earlier) reads UTF-16LE with BOM (FF FE), but with TABs instead of commas or semicolons.

How can I run an external command asynchronously from Python?

I've had good success with the asyncproc module, which deals nicely with the output from the processes. For example:

import os
from asynproc import Process
myProc = Process("")

while True:
    # check to see if process has ended
    poll = myProc.wait(os.WNOHANG)
    if poll is not None:
    # print any new output
    out =
    if out != "":
        print out

File Upload using AngularJS


<input type="file" id="file" name='file' onchange="angular.element(this).scope().profileimage(this)" />

add 'profileimage()' method to your controller

    $scope.profileimage = function(selectimage) {
 var selectfile=selectimage.files[0];
        r = new FileReader();
        r.onloadend = function (e) {
            var data =;


ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

trim left characters in sql server?

To remove the left-most word, you'll need to use either RIGHT or SUBSTRING. Assuming you know how many characters are involved, that would look either of the following:

SELECT RIGHT('Hello World', 5)
SELECT SUBSTRING('Hello World', 6, 100)

If you don't know how many characters that first word has, you'll need to find out using CHARINDEX, then substitute that value back into SUBSTRING:

SELECT SUBSTRING('Hello World', CHARINDEX(' ', 'Hello World') + 1, 100)

This finds the position of the first space, then takes the remaining characters to the right.

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in


Then you might need to add another index (this time index.jsp) to


Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

I had the similar issue. I change the ssh keys and restarted and tried all other 'n' solutions. But the actual issue for me was our gitlab default protocol changed from ssh to https.

check the remote url with

git remote -v

change the remote url

git remote set-url origin https://URL

Pass C# ASP.NET array to Javascript array

Here is another alternative solution. You can use ClientScriptManager Page.ClientScript.RegisterArrayDeclaration. Here is an example for chart data.

var page = HttpContext.Current.CurrentHandler as Page;

_data = "[Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
         ,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
         ,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
         ,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]";
page.ClientScript.RegisterArrayDeclaration("chartdata0", _data);

This code creates an array on the client side

var chartdata0 = new Array([Date.UTC(2018, 9, 29, 0, 3), parseFloat(21.84)]
             ,[Date.UTC(2018, 9, 29, 0, 13), parseFloat(21.84)]
             ,[Date.UTC(2018, 9, 29, 0, 23), parseFloat(21.83)]
             ,[Date.UTC(2018, 9, 29, 0, 33), parseFloat(21.83)]);

See the following article

This solution has an issue with bigger arrays on chrome 64 browser including "Version 78.0.3904.70 (Official Build) (64-bit)". You may get "Uncaught RangeError: Maximum call stack size exceeded". However it is working with IE11, Microsoft Edge, and FireFox.

Ignore duplicates when producing map using streams

As said in JavaDocs:

If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys may have duplicates, use toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction) instead.

So you should use toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction) instead. Just provide a merge function, that will determine which one of duplicates is put in the map.

For example, if you don't care which one, just call

Map<String, String> phoneBook =
                                        (a1, a2) -> a1));

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Serialize Property as Xml Attribute in Element

You will need wrapper classes:

public class SomeIntInfo
    public int Value { get; set; }

public class SomeStringInfo
    public string Value { get; set; }

public class SomeModel
    public SomeStringInfo SomeString { get; set; }

    public SomeIntInfo SomeInfo { get; set; }

or a more generic approach if you prefer:

public class SomeInfo<T>
    public T Value { get; set; }

public class SomeModel
    public SomeInfo<string> SomeString { get; set; }

    public SomeInfo<int> SomeInfo { get; set; }

And then:

class Program
    static void Main()
        var model = new SomeModel
            SomeString = new SomeInfo<string> { Value = "testData" },
            SomeInfo = new SomeInfo<int> { Value = 5 }
        var serializer = new XmlSerializer(model.GetType());
        serializer.Serialize(Console.Out, model);

will produce:

<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="" xmlns:xsd="">
  <SomeStringElementName Value="testData" />
  <SomeInfoElementName Value="5" />

Ubuntu: OpenJDK 8 - Unable to locate package

I'm getting OpenJDK 8 from the official Debian repositories, rather than some random PPA or non-free Oracle binary. Here's how I did it:

sudo apt-get install debian-keyring debian-archive-keyring

Make /etc/apt/sources.list.d/debian-jessie-backports.list:

deb jessie-backports main

Make /etc/apt/preferences.d/debian-jessie-backports:

Package: *
Pin: release o=Debian,a=jessie-backports
Pin-Priority: -200

Then finally do the install:

sudo apt-get update
sudo apt-get -t jessie-backports install openjdk-8-jdk

Convert NSDate to String in iOS Swift

you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here for e.g , do like

let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let myString = formatter.string(from: Date()) // string purpose I add here 
// convert your string to date
let yourDate = myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringafd = formatter.string(from: yourDate!)


you get the output as

enter image description here

How to use private Github repo as npm dependency

With git there is a https format

This format accepts User + password

https://bot-user:[email protected]/equivalent/we_demand_serverless_ruby.git

So what you can do is create a new user that will be used just as a bot, add only enough permissions that he can just read the repository you want to load in NPM modules and just have that directly in your packages.json

 Github > Click on Profile > Settings > Developer settings > Personal access tokens > Generate new token

In Select Scopes part, check the on repo: Full control of private repositories

This is so that token can access private repos that user can see

Now create new group in your organization, add this user to the group and add only repositories that you expect to be pulled this way (READ ONLY permission !)

You need to be sure to push this config only to private repo

Then you can add this to your / packages.json (bot-user is name of user, xxxxxxxxx is the generated personal token)

// packages.json

  // ....
    "name_of_my_lib": "https://bot-user:[email protected]/ghuser/name_of_my_lib.git"
  // ...

Why doesn't Java support unsigned ints?

I've heard stories that they were to be included close to the orignal Java release. Oak was the precursor to Java, and in some spec documents there was mention of usigned values. Unfortunately these never made it into the Java language. As far as anyone has been able to figure out they just didn't get implemented, likely due to a time constraint.

Angular, Http GET with parameter?

An easy and usable way to solve this problem

getGetSuppor(filter): Observale<any[]> {
   return this.https.get<any[]>('/api/callCenter/getSupport' + '?' + this.toQueryString(filter));

private toQueryString(query): string {
   var parts = [];
   for (var property in query) {
     var value = query[propery];
     if (value != null && value != undefined)
        parts.push(encodeURIComponent(propery) + '=' + encodeURIComponent(value))
   return parts.join('&');

Pandas split column of lists into multiple columns

Here's another solution using df.transform and df.set_index:

>>> (df['teams']
       .transform([lambda x:x[0], lambda x:x[1]])

  team1 team2
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG

A valid provisioning profile for this executable was not found... (again)

In my case it was just after a new Program Licence Agreement was released so we had to accept them and it was fine.

mysql after insert trigger which updates another table's column

With your requirements you don't need BEGIN END and IF with unnecessary SELECT in your trigger. So you can simplify it to this

CREATE TRIGGER occupy_trig AFTER INSERT ON occupiedroom 
  UPDATE BookingRequest
     SET status = 1
   WHERE idRequest = NEW.idRequest;

Chrome violation : [Violation] Handler took 83ms of runtime

It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

Java int to String - Integer.toString(i) vs new Integer(i).toString()

I also highly recommend using

int integer = 42;
String string = integer + "";

Simple and effective.

Shell script to check if file exists

The following script will help u to go to a process if that script exist in a specified variable,

cat > waitfor.csh


    while !( -e $1 )

    sleep 10m



here -e is for working with files,

$1 is a shell variable,

sleep for 10 minutes

u can execute the script by ./waitfor.csh ./temp ; echo "the file exits"

Failed to resolve:

Need to Update

Android SDK : SDK Tools -> Support Repository -> Google Repository

After updating the Android SDK need to sync gradle build in Android studio.

jQuery: Uncheck other checkbox on one checked

you could use class for all your checkboxes, and do:

$(".check_class").click(function() {
  $(".check_class").attr("checked", false); //uncheck all checkboxes
  $(this).attr("checked", true);  //check the clicked one

Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

Regarding number of days in month just use static switch command and check if (year % 4 == 0) in which case February will have 29 days.

Minute, hour, day etc:

var someMillisecondValue = 511111222127;
var date = new Date(someMillisecondValue);
var minute = date.getMinutes();
var hour = date.getHours();
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
alert([minute, hour, day, month, year].join("\n"));

How to retry image pull in a kubernetes Pods?

$ kubectl replace --force -f <resource-file>

if all goes well, you should see something like:

<resource-type> <resource-name> deleted
<resource-type> <resource-name> replaced

details of this can be found in the Kubernetes documentation, "manage-deployment" and kubectl-cheatsheet pages at the time of writing.


if it is standalone program, download mysql connector jar and add it to your classpath.

if it is a maven project, add below dependency and run your program.