Programs & Examples On #Tarfile

either a tar archive file or a Python module used to handle tar archive files

How to create full compressed tar file using Python?

In this tar.gz file compress in open view directory In solve use os.path.basename(file_directory)

with tarfile.open("save.tar.gz","w:gz"):
      for file in ["a.txt","b.log","c.png"]:
           tar.add(os.path.basename(file))

its use in tar.gz file compress in directory

prevent iphone default keyboard when focusing an <input>

You can add a callback function to your DatePicker to tell it to blur the input field before showing the DatePicker.

$('.selector').datepicker({
   beforeShow: function(){$('input').blur();}
});

Note: The iOS keyboard will appear for a fraction of a second and then hide.

Array of PHP Objects

Another intuitive solution could be:

class Post
{
    public $title;
    public $date;
}

$posts = array();

$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';

$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';

foreach ($posts as $post) {
  echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}

How to get std::vector pointer to the raw data?

something.data() will return a pointer to the data space of the vector.

Document Root PHP

Just / refers to the root of your website from the public html folder. DOCUMENT_ROOT refers to the local path to the folder on the server that contains your website.

For example, I have EasyPHP setup on a machine...

$_SERVER["DOCUMENT_ROOT"] gives me file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www but any file I link to with just / will be relative to my www folder.

If you want to give the absolute path to a file on your server (from the server's root) you can use DOCUMENT_ROOT. if you want to give the absolute path to a file from your website's root, use just /.

jQuery: Get selected element tag name

jQuery 1.6+

jQuery('selector').prop("tagName").toLowerCase()

Older versions

jQuery('selector').attr("tagName").toLowerCase()

toLowerCase() is not mandatory.

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

Viewing full version tree in git

You can try the following:

gitk --all

You can tell gitk what to display using anything that git rev-list understands, so if you just want a few branches, you can do:

gitk master origin/master origin/experiment

... or more exotic things like:

gitk --simplify-by-decoration --all

Most efficient way to see if an ArrayList contains an object in Java

If you need to search many time in the same list, it may pay off to build an index.

Iterate once through, and build a HashMap with the equals value you are looking for as the key and the appropriate node as the value. If you need all instead of anyone of a given equals value, then let the map have a value type of list and build the whole list in the initial iteration.

Please note that you should measure before doing this as the overhead of building the index may overshadow just traversing until the expected node is found.

Display two fields side by side in a Bootstrap Form

How about using an input group to style it on the same line?

Here's the final HTML to use:

<div class="input-group">
    <input type="text" class="form-control" placeholder="Start"/>
    <span class="input-group-addon">-</span>
    <input type="text" class="form-control" placeholder="End"/>
</div>

Which will look like this:

screenshot

Here's a Stack Snippet Demo:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
    <input type="text" class="form-control" placeholder="Start"/>_x000D_
    <span class="input-group-addon">-</span>_x000D_
    <input type="text" class="form-control" placeholder="End"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I'll leave it as an exercise to the reader to translate it into an asp:textbox element

Check if a JavaScript string is a URL

2020 Update. To expand on both excellent answerd from @iamnewton and @Fernando Chavez Herrera I've started to see @ being used in the path of URLs.

So the updated regex is:

RegExp('(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+@]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$', 'i');

If you want to allow it in the query string and hash, use:

RegExp('(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+@]*)*(\\?[;&a-z\\d%_.~+=-@]*)?(\\#[-a-z\\d_@]*)?$', 'i');

That being said, I'm not sure if there's a whitepaper rule disallowing @ in the query string or hash.

equivalent of rm and mv in windows .cmd

If you want to see a more detailed discussion of differences for the commands, see the Details about Differences section, below.

From the LeMoDa.net website1 (archived), specifically the Windows and Unix command line equivalents page (archived), I found the following2. There's a better/more complete table in the next edit.

Windows command     Unix command
rmdir               rmdir
rmdir /s            rm -r
move                mv

I'm interested to hear from @Dave and @javadba to hear how equivalent the commands are - how the "behavior and capabilities" compare, whether quite similar or "woefully NOT equivalent".

All I found out was that when I used it to try and recursively remove a directory and its constituent files and subdirectories, e.g.

(Windows cmd)>rmdir /s C:\my\dirwithsubdirs\

gave me a standard Windows-knows-better-than-you-do-are-you-sure message and prompt

dirwithsubdirs, Are you sure (Y/N)?

and that when I typed Y, the result was that my top directory and its constituent files and subdirectories went away.


Edit

I'm looking back at this after finding this answer. I retried each of the commands, and I'd change the table a little bit.

Windows command     Unix command
rmdir               rmdir
rmdir /s /q         rm -r
rmdir /s /q         rm -rf
rmdir /s            rm -ri
move                mv
del <file>          rm <file>

If you want the equivalent for

rm -rf

you can use

rmdir /s /q

or, as the author of the answer I sourced described,

But there is another "old school" way to do it that was used back in the day when commands did not have options to suppress confirmation messages. Simply ECHO the needed response and pipe the value into the command.

echo y | rmdir /s


Details about Differences

I tested each of the commands using Windows CMD and Cygwin (with its bash).

Before each test, I made the following setup.

Windows CMD

>mkdir this_directory
>echo some text stuff > this_directory/some.txt
>mkdir this_empty_directory

Cygwin bash

$ mkdir this_directory
$ echo "some text stuff" > this_directory/some.txt
$ mkdir this_empty_directory

That resulted in the following file structure for both.

base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

Here are the results. Note that I'll not mark each as CMD or bash; the CMD will have a > in front, and the bash will have a $ in front.

RMDIR

>rmdir this_directory
The directory is not empty.

>tree /a /f .
Folder PATH listing for volume Windows
Volume serial number is ¦¦¦¦¦¦¦¦ ¦¦¦¦:¦¦¦¦
base
+---this_directory
|       some.txt
|
\---this_empty_directory

> rmdir this_empty_directory

>tree /a /f .
base
\---this_directory
        some.txt
$ rmdir this_directory
rmdir: failed to remove 'this_directory': Directory not empty

$ tree --charset=ascii
base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

2 directories, 1 file

$ rmdir this_empty_directory

$ tree --charset=ascii
base
`-- this_directory
    `-- some.txt

RMDIR /S /Q and RM -R ; RM -RF

>rmdir /s /q this_directory

>tree /a /f
base
\---this_empty_directory

>rmdir /s /q this_empty_directory

>tree /a /f
base
No subfolders exist
$ rm -r this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -r this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files
$ rm -rf this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -rf this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files

RMDIR /S AND RM -RI Here, we have a bit of a difference, but they're pretty close.

>rmdir /s this_directory
this_directory, Are you sure (Y/N)? y

>tree /a /f
base
\---this_empty_directory

>rmdir /s this_empty_directory
this_empty_directory, Are you sure (Y/N)? y

>tree /a /f
base
No subfolders exist
$ rm -ri this_directory
rm: descend into directory 'this_directory'? y
rm: remove regular file 'this_directory/some.txt'? y
rm: remove directory 'this_directory'? y

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -ri this_empty_directory
rm: remove directory 'this_empty_directory'? y

$ tree --charset=ascii
base
0 directories, 0 files

I'M HOPING TO GET A MORE THOROUGH MOVE AND MV TEST


Notes

  1. I know almost nothing about the LeMoDa website, other than the fact that the info is

Copyright © Ben Bullock 2009-2018. All rights reserved.

(archived copyright notice)

and that there seem to be a bunch of useful programming tips along with some humour (yes, the British spelling) and information on how to fix Japanese toilets. I also found some stuff talking about the "Ibaraki Report", but I don't know if that is the website.

I think I shall go there more often; it's quite useful. Props to Ben Bullock, whose email is on his page. If he wants me to remove this info, I will.

I will include the disclaimer (archived) from the site:

Disclaimer Please read the following disclaimer before using any of the computer program code on this site.

There Is No Warranty For The Program, To The Extent Permitted By Applicable Law. Except When Otherwise Stated In Writing The Copyright Holders And/Or Other Parties Provide The Program “As Is” Without Warranty Of Any Kind, Either Expressed Or Implied, Including, But Not Limited To, The Implied Warranties Of Merchantability And Fitness For A Particular Purpose. The Entire Risk As To The Quality And Performance Of The Program Is With You. Should The Program Prove Defective, You Assume The Cost Of All Necessary Servicing, Repair Or Correction.

In No Event Unless Required By Applicable Law Or Agreed To In Writing Will Any Copyright Holder, Or Any Other Party Who Modifies And/Or Conveys The Program As Permitted Above, Be Liable To You For Damages, Including Any General, Special, Incidental Or Consequential Damages Arising Out Of The Use Or Inability To Use The Program (Including But Not Limited To Loss Of Data Or Data Being Rendered Inaccurate Or Losses Sustained By You Or Third Parties Or A Failure Of The Program To Operate With Any Other Programs), Even If Such Holder Or Other Party Has Been Advised Of The Possibility Of Such Damages.


  1. Actually, I found the information with a Google search for "cmd equivalent of rm"

https://www.google.com/search?q=cmd+equivalent+of+rm

The information I'm sharing came up first.

Pip install Matplotlib error with virtualenv

Another option is to install anaconda, which comes with packages such as: Matplotlib, numpy and pandas.

https://anaconda.org

Eclipse : Maven search dependencies doesn't work

The maven add dependency is actually from the maven indexes. If the indexes is up to date, the result should be from there.

If you go to the maven repository, then select global repository, you should see a central ... tab, and select that, there should be a list of folders, and you should be able to see all the indexes from there. If not, then it means you didn't get the full index, then you can right click that and enable full index.

Another thing I annoyed me most is even I did everything, it still not showing anything when I type "spring". This is actually where I did wrong. If you just type some additional text "springframework", BOOM, the result is there.

WPF C# button style

Here's my attempt. Looks more similar to the OP's sample and provides settable properties for icon (FrameworkElement), title (string) and subtitle (string). The output looks like this:

enter image description here

Here's XAML:

<Button x:Class="Controls.FancyButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Controls"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" Width="300" Height="80"
          BorderBrush="{x:Null}" BorderThickness="0">
  <Button.Effect>
    <DropShadowEffect BlurRadius="12" Color="Gray" Direction="270" Opacity=".8" ShadowDepth="3" />
  </Button.Effect>

  <Button.Template>
    <ControlTemplate TargetType="Button">
      <Grid Width="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualWidth}"
        Height="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualHeight}">

        <Border x:Name="MainBorder" CornerRadius="3" Grid.ColumnSpan="2" Margin="0,0,4,4" BorderBrush="Black" BorderThickness="1">
          <Border.Background>
            <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
              <GradientStop Color="#FF5E5E5E" Offset="0" />
              <GradientStop Color="#FF040404" Offset="1" />
            </LinearGradientBrush>
          </Border.Background>

          <Grid >
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="1.2*"/>
              <ColumnDefinition Width="3*"/>
            </Grid.ColumnDefinitions>

            <Border CornerRadius="2" Margin="0" BorderBrush="LightGray" BorderThickness="0,1,0,0" Grid.ColumnSpan="2" Grid.RowSpan="2" />

            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="0" HorizontalAlignment="Right" Stroke="#0C0C0C" Grid.RowSpan="2" />
            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="1" HorizontalAlignment="Left" Grid.RowSpan="2">
              <Line.Stroke>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                  <GradientStop Color="#4D4D4D" Offset="0" />
                  <GradientStop Color="#2C2C2C" Offset="1" />
                </LinearGradientBrush>
              </Line.Stroke>
            </Line>

            <ContentControl HorizontalAlignment="Center" VerticalAlignment="Center" Grid.RowSpan="2">
              <ContentControl.Content>
                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Image">
                  <Binding.FallbackValue>
                    <Path Data="M0,0 L30,15 L0,30Z">
                      <Path.Effect>
                        <DropShadowEffect Direction="50" ShadowDepth="2" />
                      </Path.Effect>
                      <Path.Fill>
                        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
                          <GradientStop Color="#4B86B2" Offset="0" />
                          <GradientStop Color="#477FA8" Offset="1" />
                        </LinearGradientBrush>
                      </Path.Fill>
                    </Path>
                  </Binding.FallbackValue>
                </Binding>
              </ContentControl.Content>
            </ContentControl>


            <Grid Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center">
              <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
              </Grid.RowDefinitions>

              <TextBlock x:Name="Title" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title, FallbackValue='Watch Now'}" Grid.Column="1" VerticalAlignment="Bottom" FontFamily="Calibri" FontWeight="Bold" FontSize="28" Foreground="White" Margin="20,0,0,0" />
              <TextBlock x:Name="SubTitle" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SubTitle, FallbackValue='Duration: 50 min'}" Grid.Column="1" Grid.Row="1" VerticalAlignment="top" FontFamily="Calibri" FontSize="14" Foreground="White" Margin="20,0,0,0" />
            </Grid>
          </Grid>
        </Border>
      </Grid>

      <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
          <Setter TargetName="Title" Property="TextDecorations" Value="Underline" />
          <Setter TargetName="SubTitle" Property="TextDecorations" Value="Underline" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
          <Setter TargetName="MainBorder" Property="Background">
            <Setter.Value>
              <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                <GradientStop Color="#FF5E5E5E" Offset="0" />
                <GradientStop Color="#FFA4A4A4" Offset="1" />
              </LinearGradientBrush>
            </Setter.Value>
          </Setter>
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
  </Button.Template>
</Button>

Here's the code-behind:

using System.Windows;
using System.Windows.Controls;

namespace Controls
{
  public partial class FancyButton : Button
  {
    public FancyButton()
    {
      InitializeComponent();
    }

    public string Title
    {
      get { return (string)GetValue(TitleProperty); }
      set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register("Title", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("Title", FrameworkPropertyMetadataOptions.AffectsRender));

    public string SubTitle
    {
      get { return (string)GetValue(SubTitleProperty); }
      set { SetValue(SubTitleProperty, value); }
    }

    public static readonly DependencyProperty SubTitleProperty =
        DependencyProperty.Register("SubTitle", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("SubTitle", FrameworkPropertyMetadataOptions.AffectsRender));

    public FrameworkElement Image
    {
      get { return (FrameworkElement)GetValue(ImageProperty); }
      set { SetValue(ImageProperty, value); }
    }

    public static readonly DependencyProperty ImageProperty =
        DependencyProperty.Register("Image", typeof(FrameworkElement), typeof(FancyButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
  }
}

Here is how to use it:

<controls:FancyButton Grid.Row="1" HorizontalAlignment="Right" Margin="3" Title="Watch Now" SubTitle="Duration: 50 min">
  <controls:FancyButton.Image>
    <Path Data="M0,0 L30,15 L0,30Z">
      <Path.Effect>
        <DropShadowEffect Direction="50" ShadowDepth="2" />
      </Path.Effect>
      <Path.Fill>
        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
          <GradientStop Color="#4B86B2" Offset="0" />
          <GradientStop Color="#477FA8" Offset="1" />
        </LinearGradientBrush>
      </Path.Fill>
    </Path>
  </controls:FancyButton.Image>
</controls:FancyButton>

Global Variable from a different file Python

Importing file2 in file1.py makes the global (i.e., module level) names bound in file2 available to following code in file1 -- the only such name is SomeClass. It does not do the reverse: names defined in file1 are not made available to code in file2 when file1 imports file2. This would be the case even if you imported the right way (import file2, as @nate correctly recommends) rather than in the horrible, horrible way you're doing it (if everybody under the Sun forgot the very existence of the construct from ... import *, life would be so much better for everybody).

Apparently you want to make global names defined in file1 available to code in file2 and vice versa. This is known as a "cyclical dependency" and is a terrible idea (in Python, or anywhere else for that matter).

So, rather than showing you the incredibly fragile, often unmaintainable hacks to achieve (some semblance of) a cyclical dependency in Python, I'd much rather discuss the many excellent way in which you can avoid such terrible structure.

For example, you could put global names that need to be available to both modules in a third module (e.g. file3.py, to continue your naming streak;-) and import that third module into each of the other two (import file3 in both file1 and file2, and then use file3.foo etc, that is, qualified names, for the purpose of accessing or setting those global names from either or both of the other modules, not barenames).

Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly why you think you need a cyclical dependency (just one easy prediction: no matter what makes you think you need a cyclical dependency, you're wrong;-).

Option to ignore case with .contains method?

If you are looking for contains & not equals then i would propose below solution. Only drawback is if your searchItem in below solution is "DE" then also it would match

    List<String> list = new ArrayList<>();
    public static final String[] LIST_OF_ELEMENTS = { "ABC", "DEF","GHI" };
    String searchItem= "def";

     if(String.join(",", LIST_OF_ELEMENTS).contains(searchItem.toUpperCase())) {
            System.out.println("found element");
            break;
    }

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

What is the parameter "next" used for in Express?

Before understanding next, you need to have a little idea of Request-Response cycle in node though not much in detail. It starts with you making an HTTP request for a particular resource and it ends when you send a response back to the user i.e. when you encounter something like res.send(‘Hello World’);

let’s have a look at a very simple example.

app.get('/hello', function (req, res, next) {
  res.send('USER')
})

Here we do not need next(), because resp.send will end the cycle and hand over the control back to the route middleware.

Now let’s take a look at another example.

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

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

Here we have 2 middleware functions for the same path. But you always gonna get the response from the first one. Because that is mounted first in the middleware stack and res.send will end the cycle.

But what if we always do not want the “Hello World !!!!” response back. For some conditions we may want the "Hello Planet !!!!" response. Let’s modify the above code and see what happens.

app.get('/hello', function (req, res, next) {
  if(some condition){
    next();
    return;
  }
  res.send("Hello World !!!!");  
});

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

What’s the next doing here. And yes you might have gusses. It’s gonna skip the first middleware function if the condition is true and invoke the next middleware function and you will have the "Hello Planet !!!!" response.

So, next pass the control to the next function in the middleware stack.

What if the first middleware function does not send back any response but do execute a piece of logic and then you get the response back from second middleware function.

Something like below:-

app.get('/hello', function (req, res, next) {
  // Your piece of logic
  next();
});

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

In this case you need both the middleware functions to be invoked. So, the only way you reach the second middleware function is by calling next();

What if you do not make a call to next. Do not expect the second middleware function to get invoked automatically. After invoking the first function your request will be left hanging. The second function will never get invoked and you will not get back the response.

How can I use modulo operator (%) in JavaScript?

That would be the modulo operator, which produces the remainder of the division of two numbers.

What are the benefits of learning Vim?

I use VIM pretty much exclusively now.

I used to use Vim for editing and VS Editor for debugging. This probably seems a bit crazy, but I found the Vi paradigm (macros, home key based editing etc) such a boost to my productivity, that editing in VS was paintful.

Thanks to Viemu, I don't even have to do the switching any more. It is not the perfect solution yet (code completion is sometimes not as elegant as in native vim and the macro recording isn't perfect), but it is much better than switching back and forth constantly.

The learning curve for Vim is probably exaggerated. I think once you get into it, it is pretty intuitive.

Binary search (bisection) in Python

This code works with integer lists in a recursive way. Looks for the simplest case scenario, which is: list length less than 2. It means the answer is already there and a test is performed to check for the correct answer. If not, a middle value is set and tested to be the correct, if not bisection is performed by calling again the function, but setting middle value as the upper or lower limit, by shifting it to the left or right

def binary_search(intList, intValue, lowValue, highValue):
    if(highValue - lowValue) < 2:
        return intList[lowValue] == intValue or intList[highValue] == intValue
    middleValue = lowValue + ((highValue - lowValue)/2)
    if intList[middleValue] == intValue:
        return True
    if intList[middleValue] > intValue:
        return binary_search(intList, intValue, lowValue, middleValue - 1)
   return binary_search(intList, intValue, middleValue + 1, highValue)

Changing the space between each item in Bootstrap navbar

You can change this in your CSS with the property padding:

.navbar-nav > li{
  padding-left:30px;
  padding-right:30px;
}

Also you can set margin

.navbar-nav > li{
  margin-left:30px;
  margin-right:30px;
}

Newline in JLabel

JLabel is actually capable of displaying some rudimentary HTML, which is why it is not responding to your use of the newline character (unlike, say, System.out).

If you put in the corresponding HTML and used <BR>, you would get your newlines.

Accurate way to measure execution times of php scripts

You can use microtime(true) with following manners:

Put this at the start of your php file:

//place this before any script you want to calculate time
$time_start = microtime(true);

// your script code goes here

// do something

Put this at the end of your php file:

// Display Script End time
$time_end = microtime(true);

//dividing with 60 will give the execution time in minutes other wise seconds
$execution_time = ($time_end - $time_start)/60;

//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';

It will output you result in minutes.

How to make borders collapse (on a div)?

Why not use outline? it is what you want outline:1px solid red;

Programmatically Hide/Show Android Soft Keyboard

Try this code.

For showing Softkeyboard:

InputMethodManager imm = (InputMethodManager)
                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }

For Hiding SoftKeyboard -

InputMethodManager imm = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

Java Class.cast() vs. cast operator

Generally the cast operator is preferred to the Class#cast method as it's more concise and can be analyzed by the compiler to spit out blatant issues with the code.

Class#cast takes responsibility for type checking at run-time rather than during compilation.

There are certainly use-cases for Class#cast, particularly when it comes to reflective operations.

Since lambda's came to java I personally like using Class#cast with the collections/stream API if I'm working with abstract types, for example.

Dog findMyDog(String name, Breed breed) {
    return lostAnimals.stream()
                      .filter(Dog.class::isInstance)
                      .map(Dog.class::cast)
                      .filter(dog -> dog.getName().equalsIgnoreCase(name))
                      .filter(dog -> dog.getBreed() == breed)
                      .findFirst()
                      .orElse(null);
}

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

Here's an example DataFrame which show this, it has duplicate values with the same index. The question is, do you want to aggregate these or keep them as multiple rows?

In [11]: df
Out[11]:
   0  1  2      3
0  1  2  a  16.86
1  1  2  a  17.18
2  1  4  a  17.03
3  2  5  b  17.28

In [12]: df.pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')  # desired?
Out[12]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

In [13]: df1 = df.set_index([0, 1, 2])

In [14]: df1
Out[14]:
           3
0 1 2
1 2 a  16.86
    a  17.18
  4 a  17.03
2 5 b  17.28

In [15]: df1.unstack(2)
ValueError: Index contains duplicate entries, cannot reshape

One solution is to reset_index (and get back to df) and use pivot_table.

In [16]: df1.reset_index().pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')
Out[16]:
2        a      b
0 1
1 2  17.02    NaN
  4  17.03    NaN
2 5    NaN  17.28

Another option (if you don't want to aggregate) is to append a dummy level, unstack it, then drop the dummy level...

Find a class somewhere inside dozens of JAR files?

Grepj is a command line utility to search for classes within jar files. I am the author of the utility.

You can run the utility like grepj package.Class my1.jar my2.war my3.ear

Multiple jar, ear, war files can be provided. For advanced usage use find to provide a list of jars to be searched.

How to draw a graph in PHP?

There are also several graphing libraries available for PHP to make your life simpler. JPGraph is a good (non-free) one.

How to time Java program execution speed

You get the current system time, in milliseconds:

final long startTime = System.currentTimeMillis();

Then you do what you're going to do:

for (int i = 0; i < length; i++) {
  // Do something
}

Then you see how long it took:

final long elapsedTimeMillis = System.currentTimeMillis() - startTime;

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@Jk1's answer is fine, but Mockito also allows for more succinct injection using annotations:

@InjectMocks MyClass myClass; //@InjectMocks automatically instantiates too
@Mock MyInterface myInterface

But regardless of which method you use, the annotations are not being processed (not even your @Mock) unless you somehow call the static MockitoAnnotation.initMocks() or annotate the class with @RunWith(MockitoJUnitRunner.class).

How to include a Font Awesome icon in React's render()

In case you are looking to include the font awesome library without having to do module imports and npm installs, put this in the head section of your React index.html page:

public/index.html (in head section)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>

Then in your component (such as App.js) just use standard font awesome class convention. Just remember to use className instead of class:

<button className='btn'><i className='fa fa-home'></i></button>

How to delete duplicate lines in a file without sorting it in Unix?

The one-liner that Andre Miller posted above works except for recent versions of sed when the input file ends with a blank line and no chars. On my Mac my CPU just spins.

Infinite loop if last line is blank and has no chars:

sed '$!N; /^\(.*\)\n\1$/!P; D'

Doesn't hang, but you lose the last line

sed '$d;N; /^\(.*\)\n\1$/!P; D'

The explanation is at the very end of the sed FAQ:

The GNU sed maintainer felt that despite the portability problems
this would cause, changing the N command to print (rather than
delete) the pattern space was more consistent with one's intuitions
about how a command to "append the Next line" ought to behave.
Another fact favoring the change was that "{N;command;}" will
delete the last line if the file has an odd number of lines, but
print the last line if the file has an even number of lines.

To convert scripts which used the former behavior of N (deleting
the pattern space upon reaching the EOF) to scripts compatible with
all versions of sed, change a lone "N;" to "$d;N;".

File count from a folder

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; // Will Retrieve count of all files in directry and sub directries

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length; // Will Retrieve count of all files in directry but not sub directries

int fileCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length; // Will Retrieve count of files XML extension in directry and sub directries

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

How can I inspect the file system of a failed `docker build`?

Debugging build step failures is indeed very annoying.

The best solution I have found is to make sure that each step that does real work succeeds, and adding a check after those that fails. That way you get a committed layer that contains the outputs of the failed step that you can inspect.

A Dockerfile, with an example after the # Run DB2 silent installer line:

#
# DB2 10.5 Client Dockerfile (Part 1)
#
# Requires
#   - DB2 10.5 Client for 64bit Linux ibm_data_server_runtime_client_linuxx64_v10.5.tar.gz
#   - Response file for DB2 10.5 Client for 64bit Linux db2rtcl_nr.rsp 
#
#
# Using Ubuntu 14.04 base image as the starting point.
FROM ubuntu:14.04

MAINTAINER David Carew <[email protected]>

# DB2 prereqs (also installing sharutils package as we use the utility uuencode to generate password - all others are required for the DB2 Client) 
RUN dpkg --add-architecture i386 && apt-get update && apt-get install -y sharutils binutils libstdc++6:i386 libpam0g:i386 && ln -s /lib/i386-linux-gnu/libpam.so.0 /lib/libpam.so.0
RUN apt-get install -y libxml2


# Create user db2clnt
# Generate strong random password and allow sudo to root w/o password
#
RUN  \
   adduser --quiet --disabled-password -shell /bin/bash -home /home/db2clnt --gecos "DB2 Client" db2clnt && \
   echo db2clnt:`dd if=/dev/urandom bs=16 count=1 2>/dev/null | uuencode -| head -n 2 | grep -v begin | cut -b 2-10` | chgpasswd && \
   adduser db2clnt sudo && \
   echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

# Install DB2
RUN mkdir /install
# Copy DB2 tarball - ADD command will expand it automatically
ADD v10.5fp9_linuxx64_rtcl.tar.gz /install/
# Copy response file
COPY  db2rtcl_nr.rsp /install/
# Run  DB2 silent installer
RUN mkdir /logs
RUN (/install/rtcl/db2setup -t /logs/trace -l /logs/log -u /install/db2rtcl_nr.rsp && touch /install/done) || /bin/true
RUN test -f /install/done || (echo ERROR-------; echo install failed, see files in container /logs directory of the last container layer; echo run docker run '<last image id>' /bin/cat /logs/trace; echo ----------)
RUN test -f /install/done

# Clean up unwanted files
RUN rm -fr /install/rtcl

# Login as db2clnt user
CMD su - db2clnt

String.Format alternative in C++

For the sake of completeness, you may use std::stringstream:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string a = "a", b = "b", c = "c";
    // apply formatting
    std::stringstream s;
    s << a << " " << b << " > " << c;
    // assign to std::string
    std::string str = s.str();
    std::cout << str << "\n";
}

Or (in this case) std::string's very own string concatenation capabilities:

#include <iostream>
#include <string>

int main() {
    std::string a = "a", b = "b", c = "c";
    std::string str = a + " " + b + " > " + c;
    std::cout << str << "\n";
}

For reference:


If you really want to go the C way. Here you are:

#include <iostream>
#include <string>
#include <vector>
#include <cstdio>

int main() {
    std::string a = "a", b = "b", c = "c";
    const char fmt[] = "%s %s > %s";
    // use std::vector for memory management (to avoid memory leaks)
    std::vector<char>::size_type size = 256;
    std::vector<char> buf;
    do {
        // use snprintf instead of sprintf (to avoid buffer overflows)
        // snprintf returns the required size (without terminating null)
        // if buffer is too small initially: loop should run at most twice
        buf.resize(size+1);
        size = std::snprintf(
                &buf[0], buf.size(),
                fmt, a.c_str(), b.c_str(), c.c_str());
    } while (size+1 > buf.size());
    // assign to std::string
    std::string str(buf.begin(), buf.begin()+size);
    std::cout << str << "\n";
}

For reference:


Then, there's the Boost Format Library. For the sake of your example:

#include <iostream>
#include <string>
#include <boost/format.hpp>

int main() {
    std::string a = "a", b = "b", c = "c";
    // apply format
    boost::format fmt = boost::format("%s %s > %s") % a % b % c; 
    // assign to std::string
    std::string str = fmt.str();
    std::cout << str << "\n";
}

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

You don't need HttpServletResponse to set a header on the response. You can do it using javax.ws.rs.core.Response. Just make your method to return Response instead of entity:

return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()

If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:

@Path("/resource")
class MyResource {

  // one way to get HttpServletResponse
  @Context
  private HttpServletResponse anotherServletResponse;

  // another way
  Response myMethod(@Context HttpServletResponse servletResponse) {
      // ... code
  }
}

How can I specify the schema to run an sql file against in the Postgresql command line

I was facing similar problems trying to do some dat import on an intermediate schema (that later we move on to the final one). As we rely on things like extensions (for example PostGIS), the "run_insert" sql file did not fully solved the problem.

After a while, we've found that at least with Postgres 9.3 the solution is far easier... just create your SQL script always specifying the schema when refering to the table:

CREATE TABLE "my_schema"."my_table" (...); COPY "my_schema"."my_table" (...) FROM stdin;

This way using psql -f xxxxx works perfectly, and you don't need to change search_paths nor use intermediate files (and won't hit extension schema problems).

Sorting a List<int>

Sort list of int descending you could just sort first and reverse

class Program
{
    static void Main(string[] args)
    {

        List<int> myList = new List<int>();

        myList.Add(38);
        myList.Add(34);
        myList.Add(35);
        myList.Add(36);
        myList.Add(37);


        myList.Sort();
        myList.Reverse();
        myList.ForEach(Console.WriteLine);


    }



}

How can I join elements of an array in Bash?

Yet another solution:

#!/bin/bash
foo=('foo bar' 'foo baz' 'bar baz')
bar=$(printf ",%s" "${foo[@]}")
bar=${bar:1}

echo $bar

Edit: same but for multi-character variable length separator:

#!/bin/bash
separator=")|(" # e.g. constructing regex, pray it does not contain %s
foo=('foo bar' 'foo baz' 'bar baz')
regex="$( printf "${separator}%s" "${foo[@]}" )"
regex="${regex:${#separator}}" # remove leading separator
echo "${regex}"
# Prints: foo bar)|(foo baz)|(bar baz

Color Tint UIButton Image

In Swift you can do that like so:

var exampleImage = UIImage(named: "ExampleImage.png")?.imageWithRenderingMode(.AlwaysTemplate)

Then in your viewDidLoad

exampleButtonOutlet.setImage(exampleImage, forState: UIControlState.Normal)

And to modify the color

exampleButtonOutlet.tintColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1) //your color

EDIT Xcode 8 Now you can also just the rendering mode of the image in your .xcassets to Template Image and then you don't need to specifically declare it in the var exampleImage anymore

How to remove application from app listings on Android Developer Console

No, you can unpublish but once your application has been live on the market you cannot delete it. (Each package name is unique and Google remembers all package names anyway so you could use this a reminder)

The "Delete" button only works for unpublished version of your app. Once you published your app or a particular version of it, you cannot delete it from the Market. However, you can still "unpublish" it. The "Delete" button is only handy when you uploaded a new version, then you realized you goofed and want to remove that new version before publishing it.

A reference


Update, 2016

you can now filter out unpublished or draft apps from your listing.

enter image description here

Unpublish option can be found in the header area, beside PUBLISHED text. Unpublish link


UPDATE 2020

Due to changes in the new play console, the unpublish option was moved to a different location as follows.
Click All Apps in the left pane. Then click the app you want to remove.

Then under the Setup option in the left pane, Click Advanced Settings.

Then under App Availablity on the right, change the status to UnPublished and click Save Changes at the bottom.

Take a look at the image below:
New UnPublish screenshot

Draw on HTML5 Canvas using a mouse

I had to provide a simple example for this subject so I'll share here:

http://jsfiddle.net/Haelle/v6tfp2e1

_x000D_
_x000D_
class SignTool {_x000D_
  constructor() {_x000D_
    this.initVars()_x000D_
    this.initEvents()_x000D_
  }_x000D_
_x000D_
  initVars() {_x000D_
    this.canvas = $('#canvas')[0]_x000D_
    this.ctx = this.canvas.getContext("2d")_x000D_
    this.isMouseClicked = false_x000D_
    this.isMouseInCanvas = false_x000D_
    this.prevX = 0_x000D_
    this.currX = 0_x000D_
    this.prevY = 0_x000D_
    this.currY = 0_x000D_
  }_x000D_
_x000D_
  initEvents() {_x000D_
    $('#canvas').on("mousemove", (e) => this.onMouseMove(e))_x000D_
    $('#canvas').on("mousedown", (e) => this.onMouseDown(e))_x000D_
    $('#canvas').on("mouseup", () => this.onMouseUp())_x000D_
    $('#canvas').on("mouseout", () => this.onMouseOut())_x000D_
    $('#canvas').on("mouseenter", (e) => this.onMouseEnter(e))_x000D_
  }_x000D_
  _x000D_
  onMouseDown(e) {_x000D_
   this.isMouseClicked = true_x000D_
    this.updateCurrentPosition(e)_x000D_
  }_x000D_
  _x000D_
  onMouseUp() {_x000D_
   this.isMouseClicked = false_x000D_
  }_x000D_
  _x000D_
  onMouseEnter(e) {_x000D_
   this.isMouseInCanvas = true_x000D_
    this.updateCurrentPosition(e)_x000D_
  }_x000D_
  _x000D_
  onMouseOut() {_x000D_
   this.isMouseInCanvas = false_x000D_
  }_x000D_
_x000D_
  onMouseMove(e) {_x000D_
    if (this.isMouseClicked && this.isMouseInCanvas) {_x000D_
     this.updateCurrentPosition(e)_x000D_
      this.draw()_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  updateCurrentPosition(e) {_x000D_
      this.prevX = this.currX_x000D_
      this.prevY = this.currY_x000D_
      this.currX = e.clientX - this.canvas.offsetLeft_x000D_
      this.currY = e.clientY - this.canvas.offsetTop_x000D_
  }_x000D_
  _x000D_
  draw() {_x000D_
    this.ctx.beginPath()_x000D_
    this.ctx.moveTo(this.prevX, this.prevY)_x000D_
    this.ctx.lineTo(this.currX, this.currY)_x000D_
    this.ctx.strokeStyle = "black"_x000D_
    this.ctx.lineWidth = 2_x000D_
    this.ctx.stroke()_x000D_
    this.ctx.closePath()_x000D_
  }_x000D_
}_x000D_
_x000D_
var canvas = new SignTool()
_x000D_
canvas {_x000D_
  position: absolute;_x000D_
  border: 2px solid;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<canvas id="canvas" width="500" height="300"></canvas>
_x000D_
_x000D_
_x000D_

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

1. See information about the SQL server

tsql -LH SERVER_IP_ADDRESS

locale is "C"
locale charset is "646"
ServerName TITAN
InstanceName MSSQLSERVER
IsClustered No
Version 8.00.194
tcp 1433
np \\TITAN\pipe\sql\query

2. Set your freetds.conf

tsql -C    
freetds.conf directory: /usr/local/etc

[TITAN]
host = SERVER_IP_ADDRESS
port = 1433
tds version = 7.2

3 Try

tsql -S TITAN -U user -P password

OR

 'dsn' => 'dblib:host=TITAN:1433;dbname=YOURDBNAME',

See also http://www.freetds.org/userguide/confirminstall.htm (Example 3-5.)

If you get message 20009, remember you haven't connected to the machine. It's a configuration or network issue, not a protocol failure. Verify the server is up, has the name and IP address FreeTDS is using, and is listening to the configured port.

How can I add to a List's first position?

Use List<T>.Insert(0, item) or a LinkedList<T>.AddFirst().

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

How to read strings from a Scanner in a Java console application?

What you can do is use delimeter as new line. Till you press enter key you will be able to read it as string.

Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));

Hope this helps.

Setting table row height

You can remove some extra spacing as well if you place a border-collapse: collapse; CSS statement on your table.

Will iOS launch my app into the background if it was force-quit by the user?

I've been trying different variants of this for days, and I thought for a day I had it re-launching the app in the background, even when the user swiped to kill, but no I can't replicate that behavior.

It's unfortunate that the behavior is quite different than before. On iOS 6, if you killed the app from the jiggling icons, it would still get re-awoken on SLC triggers. Now, if you kill by swiping, that doesn't happen.

It's a different behavior, and the user, who would continue to get useful information from our app if they had killed it on iOS 6, now will not.

We need to nudge our users to re-open the app now if they have swiped to kill it and are still expecting some of the notification behavior that we used to give them. I'm worried this won't be obvious to users when they swipe an app away. They may, after all, be basically cleaning up or wanting to rearrange the apps that are shown minimized.

Android view pager with page indicator

Here are a few things you need to do:

1-Download the library if you haven't already done that.

2- Import into Eclipse.

3- Set you project to use the library: Project-> Properties -> Android -> Scroll down to Library section, click Add... and select viewpagerindicator.

4- Now you should be able to import com.viewpagerindicator.TitlePageIndicator.

Now about implementing this without using fragments:

In the sample that comes with viewpagerindicatior, you can see that the library is being used with a ViewPager which has a FragmentPagerAdapter.

But in fact the library itself is Fragment independant. It just needs a ViewPager. So just use a PagerAdapter instead of a FragmentPagerAdapter and you're good to go.

JavaScript open in a new window, not tab

I had this same question but found a relatively simple solution to it.

In JavaScript I was checking for window.opener !=null; to determine if the window was a pop up. If you're using some similar detection code to determine if the window you're site is being rendered in is a pop up you can easily "turn it off" when you want to open a "new" window using the new windows JavaScript.

Just put this at the top of your page you want to always be a "new" window.

<script type="text/javascript">
    window.opener=null;
</script>

I use this on the log in page of my site so users don't get pop up behavior if they use a pop up window to navigate to my site.

You could even create a simple redirect page that does this and then moves to the URL you gave it. Something like,

JavaScript on parent page:

window.open("MyRedirect.html?URL="+URL, "_blank");

And then by using a little javascript from here you can get the URL and redirect to it.

JavaScript on Redirect Page:

 <script type="text/javascript">
        window.opener=null;

    function getSearchParameters() {
          var prmstr = window.location.search.substr(1);
          return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
    }

    function transformToAssocArray( prmstr ) {
        var params = {};
        var prmarr = prmstr.split("&");
        for ( var i = 0; i < prmarr.length; i++) {
            var tmparr = prmarr[i].split("=");
            params[tmparr[0]] = tmparr[1];
        }
        return params;
    }

    var params = getSearchParameters();
    window.location = params.URL;
    </script>

How can I get a first element from a sorted list?

Using Java 8 streams, you can turn your list into a stream and get the first item in a list using the .findFirst() method.

List<String> stringsList = Arrays.asList("zordon", "alpha", "tommy");
Optional<String> optional = stringsList.stream().findFirst();
optional.get(); // "zordon"

The .findFirst() method will return an Optional that may or may not contain a string value (it may not contain a value if the stringsList is empty).

Then to unwrap the item from the Optional use the .get() method.

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

How to find out the number of CPUs using python

In Python 3.4+: os.cpu_count().

multiprocessing.cpu_count() is implemented in terms of this function but raises NotImplementedError if os.cpu_count() returns None ("can't determine number of CPUs").

Process escape sequences in a string in Python

This is a bad way of doing it, but it worked for me when trying to interpret escaped octals passed in a string argument.

input_string = eval('b"' + sys.argv[1] + '"')

It's worth mentioning that there is a difference between eval and ast.literal_eval (eval being way more unsafe). See Using python's eval() vs. ast.literal_eval()?

How to get the row number from a datatable?

Try:

int i = Convert.ToInt32(dt.Rows.Count);

I think it's the shortest, thus the simplest way.

How to get the browser viewport dimensions?

A solution that would conform to W3C standards would be to create a transparent div (for example dynamically with JavaScript), set its width and height to 100vw/100vh (Viewport units) and then get its offsetWidth and offsetHeight. After that, the element can be removed again. This will not work in older browsers because the viewport units are relatively new, but if you don't care about them but about (soon-to-be) standards instead, you could definitely go this way:

var objNode = document.createElement("div");
objNode.style.width  = "100vw";
objNode.style.height = "100vh";
document.body.appendChild(objNode);
var intViewportWidth  = objNode.offsetWidth;
var intViewportHeight = objNode.offsetHeight;
document.body.removeChild(objNode);

Of course, you could also set objNode.style.position = "fixed" and then use 100% as width/height - this should have the same effect and improve compatibility to some extent. Also, setting position to fixed might be a good idea in general, because otherwise the div will be invisible but consume some space, which will lead to scrollbars appearing etc.

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).

EDIT:

Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:

=UDF_Date(C2)

You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.

Addendum:

Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
    
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
    
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
    
        bDate = True
        bValue = True
    
        bChanged = False
    
    
        Dim sVal As String
        Dim dDate As Date
    
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
    
        sVal = CStr(inData.Value)
        dDate = Now()
    
        Set wb = inData.Worksheet.Parent
    
        Set dProps = wb.CustomDocumentProperties
    
    On Error Resume Next
    
        Set pValue = dProps.Item(sName)
    
        If Err.Number <> 0 Then
            bValue = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
        Else
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    
    On Error Resume Next
    
        Set pDate = dProps.Item(sNameDate)
    
        If Err.Number <> 0 Then
            bDate = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
    
        If bChanged Then
            pDate.Value = dDate
        Else
            dDate = pDate.Value
        End If
    
    
        UDF_Date = dDate
     End Function
    

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

How to set JVM parameters for Junit Unit Tests?

I agree with the others who said that there is no simple way to distribute these settings.

For Eclipse: ask your colleagues to set the following:

  • Windows Preferences / Java / Installed JREs:
  • Select the proper JRE/JDK (or do it for all of them)
  • Edit
  • Default VM arguments: -Xmx1024m
  • Finish, OK.

After that all test will run with -Xmx1024m but unfortunately you have set it in every Eclipse installation. Maybe you could create a custom Eclipse package which contains this setting and give it to you co-workers.

The following working process also could help: If the IDE cannot run a test the developer should check that Maven could run this test or not.

  • If Maven could run it the cause of the failure usually is the settings of the developer's IDE. The developer should check these settings.
  • If Maven also could not run the test the developer knows that the cause of the failure is not the IDE, so he/she could use the IDE to debug the test.

How to Specify Eclipse Proxy Authentication Credentials?

Here is the workaround:

In eclipse.ini write the following:

-vmargs
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors= org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyHost=*myproxyhost*
-Dhttp.proxyPort=*myproxyport*
-Dhttp.proxyUser=*proxy username*
-Dhttp.proxyPassword=*proxy password*
-Dhttp.nonProxyHosts=localhost|127.0.0.1

After starting eclipse verify, that you use the Manual proxy method.

HTH

TensorFlow: "Attempting to use uninitialized value" in variable initialization

I want to give my resolution, it work when i replace the line [session = tf.Session()] with [sess = tf.InteractiveSession()]. Hope this will be useful to others.

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

400 vs 422 response to POST of data

Firstly this is a very good question.

400 Bad Request - When a critical piece of information is missing from the request

e.g. The authorization header or content type header. Which is absolutely required by the server to understand the request. This can differ from server to server.

422 Unprocessable Entity - When the request body can't be parsed.

This is less severe than 400. The request has reached the server. The server has acknowledged the request has got the basic structure right. But the information in the request body can't be parsed or understood.

e.g. Content-Type: application/xml when request body is JSON.

Here's an article listing status codes and its use in REST APIs. https://metamug.com/article/status-codes-for-rest-api.php

How to prevent favicon.ico requests?

I will first say that having a favicon in a Web page is a good thing (normally).

However it is not always desired and sometime developers need a way to avoid the extra payload. For example an IFRAME would request a favicon without showing it. Worst yet, in Chrome and Android an IFRAME will generate 3 requests for favicons:

"GET /favicon.ico HTTP/1.1" 404 183
"GET /apple-touch-icon-precomposed.png HTTP/1.1" 404 197
"GET /apple-touch-icon.png HTTP/1.1" 404 189

The following uses data URI and can be used to avoid fake favicon requests:

<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon"> 

For references see here:

UPDATE 1:

From the comments (jpic) it looks like Firefox >= 25 doesn't like the above syntax anymore. I tested on Firefox 27 and it doesn't work while it still work on Webkit/Chrome.

So here is the new one that should cover all recent browsers. I tested Safari, Chrome and Firefox:

<link rel="icon" href="data:;base64,=">

I left out the "shortcut" name from the "rel" attribute value since that's only for older IE and versions of IE < 8 doesn't like dataURIs either. Not tested on IE8.

UPDATE 2:

If you need your document to validate against HTML5 use this instead:

<link rel="icon" href="data:;base64,iVBORw0KGgo=">

PHP array delete by value (not key)

function array_remove_by_value($array, $value)
{
    return array_values(array_diff($array, array($value)));
}

$array = array(312, 401, 1599, 3);

$newarray = array_remove_by_value($array, 401);

print_r($newarray);

Output

Array ( [0] => 312 [1] => 1599 [2] => 3 )

an htop-like tool to display disk activity in linux

It is not htop-like, but you could use atop. However, to display disk activity per process, it needs a kernel patch (available from the site). These kernel patches are now obsoleted, only to show per-process network activity an optional module is provided.

Docker: Multiple Dockerfiles in project

When working on a project that requires the use of multiple dockerfiles, simply create each dockerfile in a separate directory. For instance,

app/ db/

Each of the above directories will contain their dockerfile. When an application is being built, docker will search all directories and build all dockerfiles.

smtpclient " failure sending mail"

Five years later (I hope this developer isn't still waiting for a fix to this..)

I had the same issue, caused by the same error: I was declaring the SmtpClient inside the loop.

The fix is simple - declare it once, outside the loop...

MailAddress mail = null;
SmtpClient client = new SmtpClient();
client.Port = 25;
client.EnableSsl = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.Host = smtpAddress;       //  Enter your company's email server here!

for(int i = 0; i < number ; i++)
{
    mail = new MailMessage(iMail.from, iMail.to);
    mail.Subject = iMail.sub;
    mail.Body = iMail.body;
    mail.IsBodyHtml = true;
    mail.Priority = MailPriority.Normal;
    mail.Sender = from;
    client.Send(mail);
}
mail.Dispose();
client.Dispose();

Sum the digits of a number

It only works for three-digit numbers, but it works

a = int(input())
print(a // 100 + a // 10 % 10 + a % 10)

what is the most efficient way of counting occurrences in pandas?

Just an addition to the previous answers. Let's not forget that when dealing with real data there might be null values, so it's useful to also include those in the counting by using the option dropna=False (default is True)

An example:

>>> df['Embarked'].value_counts(dropna=False)
S      644
C      168
Q       77
NaN      2

MySQL: Grant **all** privileges on database

This is old question but I don't think the accepted answer is safe. It's good for creating a super user but not good if you want to grant privileges on a single database.

grant all privileges on mydb.* to myuser@'%' identified by 'mypasswd';
grant all privileges on mydb.* to myuser@localhost identified by 'mypasswd';

% seems to not cover socket communications, that the localhost is for. WITH GRANT OPTION is only good for the super user, otherwise it is usually a security risk.

Update for MySQL 5.7+ seems like this warns about:

Using GRANT statement to modify existing user's properties other than privileges is deprecated and will be removed in future release. Use ALTER USER statement for this operation.

So setting password should be with separate commands. Thanks to comment from @scary-wombat.

ALTER USER 'myuser'@'%' IDENTIFIED BY 'mypassword';
ALTER USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';

Hope this helps.

What is the difference between the float and integer data type when the size is the same?

Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point

Class vs. static method in JavaScript

Javascript has no actual classes rather it uses a system of prototypal inheritance in which objects 'inherit' from other objects via their prototype chain. This is best explained via code itself:

_x000D_
_x000D_
function Foo() {};_x000D_
// creates a new function object_x000D_
_x000D_
Foo.prototype.talk = function () {_x000D_
    console.log('hello~\n');_x000D_
};_x000D_
// put a new function (object) on the prototype (object) of the Foo function object_x000D_
_x000D_
var a = new Foo;_x000D_
// When foo is created using the new keyword it automatically has a reference _x000D_
// to the prototype property of the Foo function_x000D_
_x000D_
// We can show this with the following code_x000D_
console.log(Object.getPrototypeOf(a) === Foo.prototype); _x000D_
_x000D_
a.talk(); // 'hello~\n'_x000D_
// When the talk method is invoked it will first look on the object a for the talk method,_x000D_
// when this is not present it will look on the prototype of a (i.e. Foo.prototype)_x000D_
_x000D_
// When you want to call_x000D_
// Foo.talk();_x000D_
// this will not work because you haven't put the talk() property on the Foo_x000D_
// function object. Rather it is located on the prototype property of Foo._x000D_
_x000D_
// We could make it work like this:_x000D_
Foo.sayhi = function () {_x000D_
    console.log('hello there');_x000D_
};_x000D_
_x000D_
Foo.sayhi();_x000D_
// This works now. However it will not be present on the prototype chain _x000D_
// of objects we create out of Foo
_x000D_
_x000D_
_x000D_

What is the "__v" field in Mongoose

Well, I can't see Tony's solution...so I have to handle it myself...


If you don't need version_key, you can just:

var UserSchema = new mongoose.Schema({
    nickname: String,
    reg_time: {type: Date, default: Date.now}
}, {
    versionKey: false // You should be aware of the outcome after set to false
});

Setting the versionKey to false means the document is no longer versioned.

This is problematic if the document contains an array of subdocuments. One of the subdocuments could be deleted, reducing the size of the array. Later on, another operation could access the subdocument in the array at it's original position.

Since the array is now smaller, it may accidentally access the wrong subdocument in the array.

The versionKey solves this by associating the document with the a versionKey, used by mongoose internally to make sure it accesses the right collection version.

More information can be found at: http://aaronheckmann.blogspot.com/2012/06/mongoose-v3-part-1-versioning.html

How do I programmatically click a link with javascript?

Client Side JS function to automatically click a link when...

Here is an example where you check the value of a hidden form input, which holds an error passed down from the server.. your client side JS then checks the value of it and populates an error in another location that you specify..in this case a pop-up login modal.

var signUperror = document.getElementById('handleError')

if (signUperror) {
  if(signUperror.innerHTML != ""){
  var clicker = function(){
    document.getElementById('signup').click()
  }
  clicker()
  }
}

How can I easily switch between PHP versions on Mac OSX?

Example: Let us switch from php 7.4 to 7.3

brew unlink [email protected]
brew install [email protected]
brew link [email protected]

If you get Warning: [email protected] is keg-only and must be linked with --force Then try with:

brew link [email protected] --force

How can I convert a series of images to a PDF from the command line on linux?

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

Renaming columns in Pandas

Assuming you can use a regular expression, this solution removes the need of manual encoding using a regular expression:

import pandas as pd
import re

srch = re.compile(r"\w+")

data = pd.read_csv("CSV_FILE.csv")
cols = data.columns
new_cols = list(map(lambda v:v.group(), (list(map(srch.search, cols)))))
data.columns = new_cols

Android fastboot waiting for devices

Just use sudo, fast boot needs Root Permission

Custom checkbox image android

Checkboxes being children of Button you can just give your checkbox a background image with several states as described here, under "Button style":

...and exemplified here:

Why does Maven have such a bad rep?

Well I've been wasting 2 days now with maven. Using m2eclipse, I found that the dependencies reported in eclipse are missing from the repositories, just like that. When I tried IAM and wanted to generate a simple blank project for struts 2, I found that v2.0.9 had also been deleted from the repository. When I finally manually added the artifacts and stuff, the project created itself only to find out that whatever I ask IAM to do, it responds with: no maven 2 projects found..... Hey, didn't I just use the Maven 2 project wizard??? Maven has been a pain in my ass since day one. THe idea behind it is very nice. In practical terms however, it lacks discipline from all parties involved. And that makes it virtually worthless. BEcause today your project might build. ANd tomorrow, when some dumbass deleted some pom from some repo, you are screwed. As simple as that. It is NOT usable for professional enterprise develoment! Not at all. Maybe in a year or 5?

How to downgrade Node version

If you're on Windows I suggest manually uninstalling node and installing chocolatey to handle your node installation. choco is a great CLI for provisioning a ton of popular software.

Then you can just do,

choco install nodejs --version $VersionNumber

and if you already have it installed via chocolatey you can do,

choco uninstall nodejs 
choco install nodejs --version $VersionNumber

For example,

choco uninstall nodejs
choco install nodejs --version 12.9.1

How do you force a CIFS connection to unmount

I use lazy unmount: umount -l (that's a lowercase L)

Lazy unmount. Detach the filesystem from the filesystem hierarchy now, and cleanup all references to the filesystem as soon as it is not busy anymore. (Requires kernel 2.4.11 or later.)

Renaming branches remotely in Git

First checkout to the branch which you want to rename:

git branch -m old_branch new_branch
git push -u origin new_branch

To remove an old branch from remote:

git push origin :old_branch

R not finding package even after package installation

When you run

install.packages("whatever")

you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:

.libPaths()

If libPaths shows 2 locations, then paste into second one. Load library:

library(whatever)

Fixed.

Grunt watch error - Waiting...Fatal error: watch ENOSPC

Any time you need to run sudo something ... to fix something, you should be pausing to think about what's going on. While the accepted answer here is perfectly valid, it's treating the symptom rather than the problem. Sorta the equivalent of buying bigger saddlebags to solve the problem of: error, cannot load more garbage onto pony. Pony has so much garbage already loaded, that pony is fainting with exhaustion.

An alternative (perhaps comparable to taking excess garbage off of pony and placing in the dump), is to run:

npm dedupe

Then go congratulate yourself for making pony happy.

Multiple submit buttons on HTML form – designate one button as default

The first button is always the default; it can't be changed. Whilst you can try to fix it up with JavaScript, the form will behave unexpectedly in a browser without scripting, and there are some usability/accessibility corner cases to think about. For example, the code linked to by Zoran will accidentally submit the form on Enter press in a <input type="button">, which wouldn't normally happen, and won't catch IE's behaviour of submitting the form for Enter press on other non-field content in the form. So if you click on some text in a <p> in the form with that script and press Enter, the wrong button will be submitted... especially dangerous if, as given in that example, the real default button is ‘Delete’!

My advice would be to forget about using scripting hacks to reassign defaultness. Go with the flow of the browser and just put the default button first. If you can't hack the layout to give you the on-screen order you want, then you can do it by having a dummy invisible button first in the source, with the same name/value as the button you want to be default:

<input type="submit" class="defaultsink" name="COMMAND" value="Save" />

.defaultsink {
    position: absolute; left: -100%;
}

(note: positioning is used to push the button off-screen because display: none and visibility: hidden have browser-variable side-effects on whether the button is taken as default and whether it's submitted.)

When does System.gc() do something?

If you use direct memory buffers, the JVM doesn't run the GC for you even if you are running low on direct memory.

If you call ByteBuffer.allocateDirect() and you get an OutOfMemoryError you can find this call is fine after triggering a GC manually.

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

I had the exact same error. It turned out that it was something was caused by something completely, though. It was missing write permissions in a cache folder. But IIS reported error 0x8007000d which is wildly confusing.

Compute row average in pandas

I think this is what you are looking for:

df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)

Get Time from Getdate()

Let's try this

select convert(varchar, getdate(), 108) 

Just try a few moment ago

Clear form after submission with jQuery

You can reset your form with:

$("#myform")[0].reset();

HTML Text with tags to formatted text in an Excel cell

Yes it is possible :) In fact let Internet Explorer do the dirty work for you ;)

TRIED AND TESTED

MY ASSUMPTIONS

  1. I am assuming that the html text is in Cell A1 of Sheet1. You can also use a variable instead.
  2. If you have a column full of html values, then simply put the below code in a loop

CODE (See NOTE at the end)

Sub Sample()
    Dim Ie As Object
    
    Set Ie = CreateObject("InternetExplorer.Application")
    
    With Ie
        .Visible = False
        
        .Navigate "about:blank"
        
        .document.body.InnerHTML = Sheets("Sheet1").Range("A1").Value
        
        .document.body.createtextrange.execCommand "Copy"
        ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("A1")
        
        .Quit
    End With
End Sub

SNAPSHOT

enter image description here

NOTE: Thanks to @tiQu answer below. The above code will work with new IE if you replace .document.body.createtextrange.execCommand "Copy" with .ExecWB 17, 0: .ExecWB 12, 2 as suggested by him.

How to get the query string by javascript?

If you're referring to the URL in the address bar, then

window.location.search

will give you just the query string part. Note that this includes the question mark at the beginning.

If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:

url.substring(url.indexOf("?"))

That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.

CSS background-image - What is the correct usage?

just check the directory structure where exactly image is suppose you have a css folder and images folder outside css folder then you will have to use"../images/image.jpg" and it will work as it did for me just make sure the directory stucture.

enable/disable zoom in Android WebView

I've looked at the source code for WebView and I concluded that there is no elegant way to accomplish what you are asking.

What I ended up doing was subclassing WebView and overriding OnTouchEvent. In OnTouchEvent for ACTION_DOWN, I check how many pointers there are using MotionEvent.getPointerCount(). If there is more than one pointer, I call setSupportZoom(true), otherwise I call setSupportZoom(false). I then call the super.OnTouchEvent().

This will effectively disable zooming when scrolling (thus disabling the zoom controls) and enable zooming when the user is about to pinch zoom. Not a nice way of doing it, but it has worked well for me so far.

Note that getPointerCount() was introduced in 2.1 so you'll have to do some extra stuff if you support 1.6.

Two decimal places using printf( )

Try using a format like %d.%02d

int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);

Another approach is to type cast it to double before printing it using %f like this:

printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);

My 2 cents :)

store return json value in input hidden field

just set the hidden field with javascript :

document.getElementById('elementId').value = 'whatever';

or do I miss something?

Twitter-Bootstrap-2 logo image on top of navbar

You should remove navbar-fixed-top class otherwise navbar stays fixed on top of page where you want logo.


If you want to place logo inside navbar:

Navbar height (set in @navbarHeight LESS variable) is 40px by default. Your logo has to fit inside or you have to make navbar higher first.

Then use brand class:

<div class="navbar navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container">
      <a href="/" class="brand"><img alt="" src="/logo.gif" /></a>
    </div>
  </div>
</div>

If your logo is higher than 20px, you have to fix stylesheets as well.

If you do that in LESS:

.navbar .brand {
  @elementHeight: 32px;
  padding: ((@navbarHeight - @elementHeight) / 2 - 2) 20px ((@navbarHeight - @elementHeight) / 2 + 2);
}

@elementHeight should be set to your image height.

Padding calculation is taken from Twitter Bootstrap LESS - https://github.com/twitter/bootstrap/blob/v2.0.4/less/navbar.less#L51-52

Alternatively you can calculate padding values yourself and use pure CSS.

This works for Twitter Bootstrap versions 2.0.x, should work in 2.1 as well, but padding calculation was changed a bit: https://github.com/twitter/bootstrap/blob/v2.1.0/less/navbar.less#L50

How to add white spaces in HTML paragraph

If you really need then you can use i.e. &nbsp; entity to do that, but remember that fonts used to render your page are usually proportional, so "aligning" with spaces does not really work and looks ugly.

Button that refreshes the page on click

This works for me:

function refreshPage(){
    window.location.reload();
} 
<button type="submit" onClick="refreshPage()">Refresh Button</button>

jQuery show/hide not working

Demo

_x000D_
_x000D_
$( '.expand' ).click(function() {_x000D_
  $( '.img_display_content' ).toggle();_x000D_
});
_x000D_
.wrap {_x000D_
    margin-left:auto;_x000D_
    margin-right:auto;_x000D_
    width:40%;_x000D_
}_x000D_
_x000D_
.img_display_header {_x000D_
    height:20px;_x000D_
    background-color:#CCC;_x000D_
    display:block;_x000D_
    border:#333 solid 1px;_x000D_
    margin-bottom: 2px;_x000D_
}_x000D_
_x000D_
.expand {_x000D_
 float:right;_x000D_
 height: 100%;_x000D_
 padding-right:5px;_x000D_
 cursor:pointer;_x000D_
}_x000D_
_x000D_
.img_display_content {_x000D_
    width: 100%;_x000D_
    height:100px;   _x000D_
    background-color:#0F3;_x000D_
    margin-top: -2px;_x000D_
    display:none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
<div class="img_display_header">_x000D_
<div class="expand">+</div>_x000D_
</div>_x000D_
<div class="img_display_content"></div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://api.jquery.com/toggle/
"Display or hide the matched elements."

This is much shorter in code than using show() and hide() methods.

Where is the .NET Framework 4.5 directory?

.NET 4.5 is not a side-by-side version, it replaces the assemblies for 4.0. Much like .NET 3.0, 3.5 and 3.5SP1 replaced the assemblies for 2.0. And added some new ones. The CLR version is still 4.0.30319. You only care about the reference assemblies, they are in c:\program files\reference assemblies.

How to multiply values using SQL

Here it is:

select player_name, player_salary, (player_salary * 1.1) as player_newsalary
from player 
order by player_name, player_salary, player_newsalary desc

You don't need to "group by" if there is only one instance of a player in the table.

How to sync with a remote Git repository?

You have to add the original repo as an upstream.

It is all well described here: https://help.github.com/articles/fork-a-repo

git remote add upstream https://github.com/octocat/Spoon-Knife.git
git fetch upstream
git merge upstream/master
git push origin master

Find a string within a cell using VBA

I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.

Try this:

Option Explicit


Sub DoIHavePercentSymbol()
   Dim rng As Range

   Set rng = ActiveCell

   Do While rng.Value <> Empty
        If InStr(rng.Value, "%") = 0 Then
            MsgBox "I know nothing about percentages!"
            Set rng = rng.Offset(1)
            rng.Select
        Else
            MsgBox "I contain a % symbol!"
            Set rng = rng.Offset(1)
            rng.Select
        End If
   Loop

End Sub

InStr will return the number of times your search text appears in the string. I changed your if test to check for no matches first.

The message boxes and the .Selects are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.

how to add or embed CKEditor in php page

If you have downloaded the latest Version 4.3.4 then just follow these steps.

  • Download the package, unzip and place in your web directory or root folder.
  • Provide the read write permissions to that folder (preferably Ubuntu machines )
  • Create view page test.php
  • Paste the below mentioned code it should work fine.

Load the mentioned js file

<script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
<textarea class="ckeditor" name="editor"></textarea>

Meaning of "n:m" and "1:n" in database design

In a relational database all types of relationships are represented in the same way: as relations. The candidate key(s) of each relation (and possibly other constraints as well) determine what kind of relationship is being represented. 1:n and m:n are two kinds of binary relationship:

C {Employee*,Company}
B {Book*,Author*}

In each case * designates the key attribute(s). {Book,Author} is a compound key.

C is a relation where each employee works for only one company but each company may have many employees (1:n): B is a relation where a book can have many authors and an author may write many books (m:n):

Notice that the key constraints ensure that each employee can only be associated with one company whereas any combination of books and authors is permitted.

Other kinds of relationship are possible as well: n-ary (having more than two components); fixed cardinality (m:n where m and n are fixed constants or ranges); directional; and so on. William Kent in his book "Data and Reality" identifies at least 432 kinds - and that's just for binary relationships. In practice, the binary relationships 1:n and m:n are very common and are usually singled out as specially important in designing and understanding data models.

Functional style of Java 8's Optional.ifPresent and if-not-Present?

If you can use only Java 8 or lower:

1) if you don't have spring-data the best way so far is:

opt.<Runnable>map(param -> () -> System.out.println(param))
      .orElse(() -> System.out.println("no-param-specified"))
      .run();

Now I know it's not so readable and even hard to understand for someone, but looks fine for me personally and I don't see another nice fluent way for this case.

2) if you're lucky enough and you can use spring-data the best way is Optionals#ifPresentOrElse:

Optionals.ifPresentOrElse(opt, System.out::println,
      () -> System.out.println("no-param-specified"));

If you can use Java 9, you should definitely go with:

opt.ifPresentOrElse(System.out::println,
      () -> System.out.println("no-param-specified"));

Missing visible-** and hidden-** in Bootstrap v4

The user Klaro suggested to restore the old visibility classes, which is a good idea. Unfortunately, their solution did not work in my project.

I think that it is a better idea to restore the old mixin of bootstrap, because it is covering all breakpoints which can be individually defined by the user.

Here is the code:

// Restore Bootstrap 3 "hidden" utility classes.
@each $bp in map-keys($grid-breakpoints) {
  .hidden-#{$bp}-up {
    @include media-breakpoint-up($bp) {
      display: none !important;
    }
  }
  .hidden-#{$bp}-down {
    @include media-breakpoint-down($bp) {
      display: none !important;
    }
  }
  .hidden-#{$bp}-only{
    @include media-breakpoint-only($bp){
      display:none !important;
    }
  }
}

In my case, I have inserted this part in a _custom.scss file which is included at this point in the bootstrap.scss:

/*!
 * Bootstrap v4.0.0-beta (https://getbootstrap.com)
 * Copyright 2011-2017 The Bootstrap Authors
 * Copyright 2011-2017 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 */

@import "functions";
@import "variables";
@import "mixins";
@import "custom"; // <-- my custom file for overwriting default vars and adding the snippet from above
@import "print";
@import "reboot";
[..]

What is a lambda expression in C++11?

Lambda expressions are typically used to encapsulate algorithms so that they can be passed to another function. However, it is possible to execute a lambda immediately upon definition:

[&](){ ...your code... }(); // immediately executed lambda expression

is functionally equivalent to

{ ...your code... } // simple code block

This makes lambda expressions a powerful tool for refactoring complex functions. You start by wrapping a code section in a lambda function as shown above. The process of explicit parameterization can then be performed gradually with intermediate testing after each step. Once you have the code-block fully parameterized (as demonstrated by the removal of the &), you can move the code to an external location and make it a normal function.

Similarly, you can use lambda expressions to initialize variables based on the result of an algorithm...

int a = []( int b ){ int r=1; while (b>0) r*=b--; return r; }(5); // 5!

As a way of partitioning your program logic, you might even find it useful to pass a lambda expression as an argument to another lambda expression...

[&]( std::function<void()> algorithm ) // wrapper section
   {
   ...your wrapper code...
   algorithm();
   ...your wrapper code...
   }
([&]() // algorithm section
   {
   ...your algorithm code...
   });

Lambda expressions also let you create named nested functions, which can be a convenient way of avoiding duplicate logic. Using named lambdas also tends to be a little easier on the eyes (compared to anonymous inline lambdas) when passing a non-trivial function as a parameter to another function. Note: don't forget the semicolon after the closing curly brace.

auto algorithm = [&]( double x, double m, double b ) -> double
   {
   return m*x+b;
   };

int a=algorithm(1,2,3), b=algorithm(4,5,6);

If subsequent profiling reveals significant initialization overhead for the function object, you might choose to rewrite this as a normal function.

React Router with optional path parameter

For any React Router v4 users arriving here following a search, optional parameters in a <Route> are denoted with a ? suffix.

Here's the relevant documentation:

https://reacttraining.com/react-router/web/api/Route/path-string

path: string

Any valid URL path that path-to-regexp understands.

    <Route path="/users/:id" component={User}/>

https://www.npmjs.com/package/path-to-regexp#optional

Optional

Parameters can be suffixed with a question mark (?) to make the parameter optional. This will also make the prefix optional.

Simple example of a paginated section of a site that can be accessed with or without a page number.

    <Route path="/section/:page?" component={Section} />

ES6 Class Multiple inheritance

I have been using a pattern like this to program complex multi inheritance things:

var mammal = {
    lungCapacity: 200,
    breath() {return 'Breathing with ' + this.lungCapacity + ' capacity.'}
}

var dog = {
    catchTime: 2,
    bark() {return 'woof'},
    playCatch() {return 'Catched the ball in ' + this.catchTime + ' seconds!'}
}

var robot = {
    beep() {return 'Boop'}
}


var robotDogProto = Object.assign({}, robot, dog, {catchTime: 0.1})
var robotDog = Object.create(robotDogProto)


var livingDogProto = Object.assign({}, mammal, dog)
var livingDog = Object.create(livingDogProto)

This method uses very little code, and allows for things like overwriting default properties (like I do with a custom catchTime in robotDogProto)

How to receive POST data in django

You should have access to the POST dictionary on the request object.

The term 'Get-ADUser' is not recognized as the name of a cmdlet

get-windowsfeature | where name -like RSAT-AD-PowerShell | Install-WindowsFeature

What is the default username and password in Tomcat?

Look in your conf/tomcat-users.xml. If there is nothing there, you'd have to configure it.

Which characters make a URL invalid?

Most of the existing answers here are impractical because they totally ignore the real-world usage of addresses like:

First, a digression into terminology. What are these addresses? Are they valid URLs?

Historically, the answer was "no". According to RFC 3986, from 2005, such addresses are not URIs (and therefore not URLs, since URLs are a type of URIs). Per the terminology of 2005 IETF standards, we should properly call them IRIs (Internationalized Resource Identifiers), as defined in RFC 3987, which are technically not URIs but can be converted to URIs simply by percent-encoding all non-ASCII characters in the IRI.

Per modern spec, the answer is "yes". The WHATWG Living Standard simply classifies everything that would previously be called "URIs" or "IRIs" as "URLs". This aligns the specced terminology with how normal people who haven't read the spec use the word "URL", which was one of the spec's goals.

What characters are allowed under the WHATWG Living Standard?

Per this newer meaning of "URL", what characters are allowed? In many parts of the URL, such as the query string and path, we're allowed to use arbitrary "URL units", which are

URL code points and percent-encoded bytes.

What are "URL code points"?

The URL code points are ASCII alphanumeric, U+0021 (!), U+0024 ($), U+0026 (&), U+0027 ('), U+0028 LEFT PARENTHESIS, U+0029 RIGHT PARENTHESIS, U+002A (*), U+002B (+), U+002C (,), U+002D (-), U+002E (.), U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+003F (?), U+0040 (@), U+005F (_), U+007E (~), and code points in the range U+00A0 to U+10FFFD, inclusive, excluding surrogates and noncharacters.

(Note that the list of "URL code points" doesn't include %, but that %s are allowed in "URL code units" if they're part of a percent-encoding sequence.)

The only place I can spot where the spec permits the use of any character that's not in this set is in the host, where IPv6 addresses are enclosed in [ and ] characters. Everywhere else in the URL, either URL units are allowed or some even more restrictive set of characters.

What characters were allowed under the old RFCs?

For the sake of history, and since it's not explored fully elsewhere in the answers here, let's examine was allowed under the older pair of specs.

First of all, we have two types of RFC 3986 reserved characters:

  • :/?#[]@, which are part of the generic syntax for a URI defined in RFC 3986
  • !$&'()*+,;=, which aren't part of the RFC's generic syntax, but are reserved for use as syntactic components of particular URI schemes. For instance, semicolons and commas are used as part of the syntax of data URIs, and & and = are used as part of the ubiquitous ?foo=bar&qux=baz format in query strings (which isn't specified by RFC 3986).

Any of the reserved characters above can be legally used in a URI without encoding, either to serve their syntactic purpose or just as literal characters in data in some places where such use could not be misinterpreted as the character serving its syntactic purpose. (For example, although / has syntactic meaning in a URL, you can use it unencoded in a query string, because it doesn't have meaning in a query string.)

RFC 3986 also specifies some unreserved characters, which can always be used simply to represent data without any encoding:

  • abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~

Finally, the % character itself is allowed for percent-encodings.

That leaves only the following ASCII characters that are forbidden from appearing in a URL:

  • The control characters (chars 0-1F and 7F), including new line, tab, and carriage return.
  • "<>\^`{|}

Every other character from ASCII can legally feature in a URL.

Then RFC 3987 extends that set of unreserved characters with the following unicode character ranges:

  %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
/ %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
/ %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
/ %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
/ %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
/ %xD0000-DFFFD / %xE1000-EFFFD

These block choices from the old spec seem bizarre and arbitrary given the latest Unicode block definitions; this is probably because the blocks have been added to in the decade since RFC 3987 was written.


Finally, it's perhaps worth noting that simply knowing which characters can legally appear in a URL isn't sufficient to recognise whether some given string is a legal URL or not, since some characters are only legal in particular parts of the URL. For example, the reserved characters [ and ] are legal as part of an IPv6 literal host in a URL like http://[1080::8:800:200C:417A]/foo but aren't legal in any other context, so the OP's example of http://example.com/file[/].html is illegal.

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

Similar to other answers I had miss typed the query.

I had -

SELECT t.id FROM t.table LEFT JOIN table2 AS t2 ON t.id = t2.table_id

Should have been

SELECT t.id FROM table AS t LEFT JOIN table2 AS t2 ON t.id = t2.table_id

Mysql was trying to find a database called t which the user didn't have permission for.

How do I use 3DES encryption/decryption in Java?

Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the contents). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string:

import java.security.MessageDigest;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class TripleDESTest {

    public static void main(String[] args) throws Exception {

        String text = "kyle boon";

        byte[] codedtext = new TripleDESTest().encrypt(text);
        String decodedtext = new TripleDESTest().decrypt(codedtext);

        System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
        System.out.println(decodedtext); // This correctly shows "kyle boon"
    }

    public byte[] encrypt(String message) throws Exception {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        final byte[] plainTextBytes = message.getBytes("utf-8");
        final byte[] cipherText = cipher.doFinal(plainTextBytes);
        // final String encodedCipherText = new sun.misc.BASE64Encoder()
        // .encode(cipherText);

        return cipherText;
    }

    public String decrypt(byte[] message) throws Exception {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        decipher.init(Cipher.DECRYPT_MODE, key, iv);

        // final byte[] encData = new
        // sun.misc.BASE64Decoder().decodeBuffer(message);
        final byte[] plainText = decipher.doFinal(message);

        return new String(plainText, "UTF-8");
    }
}

TypeError: 'int' object is not callable

I was also facing this issue but in a little different scenario.

Scenario:

param = 1

def param():
    .....
def func():
    if param:
        var = {passing a dict here}
        param(var)

It looks simple and a stupid mistake here, but due to multiple lines of codes in the actual code, it took some time for me to figure out that the variable name I was using was same as my function name because of which I was getting this error.

Changed function name to something else and it worked.

So, basically, according to what I understood, this error means that you are trying to use an integer as a function or in more simple terms, the called function name is also used as an integer somewhere in the code. So, just try to find out all occurrences of the called function name and look if that is being used as an integer somewhere.

I struggled to find this, so, sharing it here so that someone else may save their time, in case if they get into this issue.

Hope this helps!

How do I get the current time zone of MySQL?

My PHP framework uses

SET LOCAL time_zone='Whatever'

on after connect, where 'Whatever' == date_default_timezone_get()

Not my solution, but this ensures SYSTEM timezone of MySQL server is always the same as PHP's one

So, yes, PHP is strongly envolved and can affect it

Generate a unique id

Why not just use ToString?

public string generateID()
{
    return Guid.NewGuid().ToString("N");
}

If you would like it to be based on a URL, you could simply do the following:

public string generateID(string sourceUrl)
{
    return string.Format("{0}_{1:N}", sourceUrl, Guid.NewGuid());
}

If you want to hide the URL, you could use some form of SHA1 on the sourceURL, but I'm not sure what that might achieve.

How to create an integer array in Python?

two ways:

x = [0] * 10
x = [0 for i in xrange(10)]

Edit: replaced range by xrange to avoid creating another list.

Also: as many others have noted including Pi and Ben James, this creates a list, not a Python array. While a list is in many cases sufficient and easy enough, for performance critical uses (e.g. when duplicated in thousands of objects) you could look into python arrays. Look up the array module, as explained in the other answers in this thread.

Access parent DataContext from DataTemplate

RelativeSource vs. ElementName

These two approaches can achieve the same result,

RelativeSource

Binding="{Binding Path=DataContext.MyBindingProperty, 
          RelativeSource={RelativeSource AncestorType={x:Type Window}}}"

This method looks for a control of a type Window (in this example) in the visual tree and when it finds it you basically can access it's DataContext using the Path=DataContext..... The Pros about this method is that you don't need to be tied to a name and it's kind of dynamic, however, changes made to your visual tree can affect this method and possibly break it.

ElementName

Binding="{Binding Path=DataContext.MyBindingProperty, ElementName=MyMainWindow}

This method referes to a solid static Name so as long as your scope can see it, you're fine.You should be sticking to your naming convention not to break this method of course.The approach is qute simple and all you need is to specify a Name="..." for your Window/UserControl.

Although all three types (RelativeSource, Source, ElementName) are capable of doing the same thing, but according to the following MSDN article, each one better be used in their own area of specialty.

How to: Specify the Binding Source

Find the brief description of each plus a link to a more details one in the table on the bottom of the page.

How to get difference between two rows for a column field?

SELECT
   [current].rowInt,
   [current].Value,
   ISNULL([next].Value, 0) - [current].Value
FROM
   sourceTable       AS [current]
LEFT JOIN
   sourceTable       AS [next]
      ON [next].rowInt = (SELECT MIN(rowInt) FROM sourceTable WHERE rowInt > [current].rowInt)

EDIT:

Thinking about it, using a subquery in the select (ala Quassnoi's answer) may be more efficient. I would trial different versions, and look at the execution plans to see which would perform best on the size of data set that you have...


EDIT2:

I still see this garnering votes, though it's unlikely many people still use SQL Server 2005.

If you have access to Windowed Functions such as LEAD(), then use that instead...

SELECT
  RowInt,
  Value,
  LEAD(Value, 1, 0) OVER (ORDER BY RowInt) - Value
FROM
  sourceTable

How to decrypt hash stored by bcrypt

# Maybe you search this ??
For example in my case I use Symfony 4.4 (PHP).
If you want to update User, you need to insert the User password 
encrypted and test with the current Password not encrypted to verify 
if it's the same User. 

For example :

public function updateUser(Request $req)
      {
         $entityManager = $this->getDoctrine()->getManager();
         $repository = $entityManager->getRepository(User::class);
         $user = $repository->find($req->get(id)); /// get User from your DB

         if($user == null){
            throw  $this->createNotFoundException('User don't exist!!', $user);
         }
         $password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
         $passwordToUpdate = $req->get('password'); // not encrypted yet from request.

         $passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);

          ////////////VERIFY IF IT'S THE SAME PASSWORD
         $isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );

         if($isPass === false){ // failure
            throw  $this->createNotFoundException('Your password it's not verify', null);
         }

        return $isPass; //// true!! it's the same password !!!

      }

Java escape JSON String?

If you want to simply escape a string, not an object or array, use this:

String escaped = JSONObject.valueToString(" Quotes \" ' ' \" ");

http://www.json.org/javadoc/org/json/JSONObject.html#valueToString(java.lang.Object)

Editable 'Select' element

_x000D_
_x000D_
A bit more universal <select name="env" style="width: 200px; position:absolute;" onchange="this.nextElementSibling.value=this.value">_x000D_
    <option></option>_x000D_
    <option>1</option>_x000D_
    <option>2</option>_x000D_
    <option>3</option> _x000D_
</select>_x000D_
<input style="width: 178px; margin-top: 1px; border: none; position:relative; left:1px; margin-right: 25px;" value="123456789012345678901234"/>layout ...
_x000D_
_x000D_
_x000D_

Decode Base64 data in Java

This is a late answer, but Joshua Bloch committed his Base64 class (when he was working for Sun, ahem, Oracle) under the java.util.prefs package. This class existed since JDK 1.4.

E.g.

String currentString = "Hello World";
String base64String = java.util.prefs.Base64.byteArrayToBase64(currentString.getBytes("UTF-8"));

Find duplicate characters in a String and count the number of occurances using Java

public class dublicate 
{
public static void main(String...a)
{
    System.out.print("Enter the String");
    Scanner sc=new Scanner(System.in);
    String st=sc.nextLine();
    int [] ar=new int[256];
    for(int i=0;i<st.length();i++)
    {
        ar[st.charAt(i)]=ar[st.charAt(i)]+1;
    }
    for(int i=0;i<256;i++)
    {
        char ch=(char)i;
        if(ar[i]>0)
        {
            if(ar[i]==1)
            {
                System.out.print(ch);
            }
            else
            {
                System.out.print(ch+""+ar[i]);
            }
        }
    }

}
}

laravel select where and where condition

After reading your previous comments, it's clear that you misunderstood the Hash::make function. Hash::make uses bcrypt hashing. By design, this means that every time you run Hash::make('password'), the result will be different (due to random salting). That's why you can't verify the password by simply checking the hashed password against the hashed input.

The proper way to validate a hash is by using:

Hash::check($passwordToCheck, $hashedPassword);

So, for example, your login function would be implemented like this:

public static function login($email, $password) {
    $user = User::whereEmail($email)->first();
    if ( !$user ) return null;  //check if user exists
    if ( Hash::check($password, $user->password) ) {
        return $user;
    } else return null;
}

And then you'd call it like this:

$user = User::login('[email protected]', 'password');
if ( !$user ) echo "Invalid credentials.";
else echo "First name: $user->firstName";

I recommend reviewing the Laravel security documentation, as functions already exist in Laravel to perform this type of authorization.

Furthermore, if your custom-made hashing algorithm generates the same hash every time for a given input, it's a security risk. A good one-way hashing algorithm should use random salting.

xml.LoadData - Data at the root level is invalid. Line 1, position 1

if we are using XDocument.Parse(@""). Use @ it resolves the issue.

Convert comma separated string of ints to int array

import java.util.*;
import java.io.*;
public class problem
{
public static void main(String args[])enter code here
{
  String line;
  String[] lineVector;
  int n,m,i,j;
  Scanner sc = new Scanner(System.in);
  line = sc.nextLine();
  lineVector = line.split(",");
  //enter the size of the array
  n=Integer.parseInt(lineVector[0]);
  m=Integer.parseInt(lineVector[1]);
  int arr[][]= new int[n][m];
  //enter the array here
  System.out.println("Enter the array:");
  for(i=0;i<n;i++)
  {
  line = sc.nextLine();
  lineVector = line.split(",");
  for(j=0;j<m;j++)
  {
  arr[i][j] = Integer.parseInt(lineVector[j]);
  }
  }
  sc.close();
}
}

On the first line enter the size of the array separated by a comma. Then enter the values in the array separated by a comma.The result is stored in the array arr. e.g input: 2,3 1,2,3 2,4,6 will store values as arr = {{1,2,3},{2,4,6}};

Trigger an event on `click` and `enter`

$('#usersSearch').keyup(function() { // handle keyup event on search input field

    var key = e.which || e.keyCode;  // store browser agnostic keycode

    if(key == 13) 
        $(this).closest('form').submit(); // submit parent form
}

How to check if std::map contains a key without doing insert?

Potatoswatter's answer is all right, but I prefer to use find or lower_bound instead. lower_bound is especially useful because the iterator returned can subsequently be used for a hinted insertion, should you wish to insert something with the same key.

map<K, V>::iterator iter(my_map.lower_bound(key));
if (iter == my_map.end() || key < iter->first) {    // not found
    // ...
    my_map.insert(iter, make_pair(key, value));     // hinted insertion
} else {
    // ... use iter->second here
}

Regex for quoted string with escaping quotes

A more extensive version of https://stackoverflow.com/a/10786066/1794894

/"([^"\\]{50,}(\\.[^"\\]*)*)"|\'[^\'\\]{50,}(\\.[^\'\\]*)*\'|“[^”\\]{50,}(\\.[^“\\]*)*”/   

This version also contains

  1. Minimum quote length of 50
  2. Extra type of quotes (open and close )

How do I tell Gradle to use specific JDK version?

there is a Gradle plugin that download/bootstraps a JDK automatically:

https://plugins.gradle.org/plugin/com.github.rmee.jdk-bootstrap

No IDE integration yet and a decent shell required on Windows.

How to write file in UTF-8 format?

This is quite useful question. I think that my solution on Windows 10 PHP7 is rather useful for people who have yet some UTF-8 conversion trouble.

Here are my steps. The PHP script calling the following function, here named utfsave.php must have UTF-8 encoding itself, this can be easily done by conversion on UltraEdit.

In utfsave.php, we define a function calling PHP fopen($filename, "wb"), ie, it's opened in both w write mode, and especially with b in binary mode.

<?php
//
//  UTF-8 ??:
//
// fnc001: save string as a file in UTF-8:
// The resulting file is UTF-8 only if $strContent is,
// with French accents, chinese ideograms, etc..
//
function entSaveAsUtf8($strContent, $filename) {
  $fp = fopen($filename, "wb"); 
  fwrite($fp, $strContent);
  fclose($fp);
  return True;
}

//
// 0. write UTF-8 string in fly into UTF-8 file:
//
$strContent = "My string contains UTF-8 chars ie ???? for un été en France";

$filename = "utf8text.txt";

entSaveAsUtf8($strContent, $filename);


//
// 2. convert CP936 ANSI/OEM - chinese simplified GBK file into UTF-8 file:
//
$strContent = file_get_contents("cp936gbktext.txt");
$strContent = mb_convert_encoding($strContent, "UTF-8", "CP936");


$filename = "utf8text2.txt";

entSaveAsUtf8($strContent, $filename);

?>

The source file cp936gbktext.txt file content:

>>Get-Content cp936gbktext.txt
My string contains UTF-8 chars ie ???? for un été en France 936 (ANSI/OEM - chinois simplifié GBK)

Running utf8save.php on Windows 10 PHP, thus created utf8text.txt, utf8text2.txt files will be automatically saved in UTF-8 format.

With this method, BOM char is not required. BOM solution is bad because it causes troubles when we do sourcing an sql file for MySQL for example.

It's worth noting that I failed making work file_put_contents($filename, utf8_encode($mystring)); for this purpose.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

If you don't know the encoding of the source file, you can list encodings with PHP:

print_r(mb_list_encodings());

This gives a list like this:

Array
(
  [0] => pass
  [1] => wchar
  [2] => byte2be
  [3] => byte2le
  [4] => byte4be
  [5] => byte4le
  [6] => BASE64
  [7] => UUENCODE
  [8] => HTML-ENTITIES
  [9] => Quoted-Printable
  [10] => 7bit
  [11] => 8bit
  [12] => UCS-4
  [13] => UCS-4BE
  [14] => UCS-4LE
  [15] => UCS-2
  [16] => UCS-2BE
  [17] => UCS-2LE
  [18] => UTF-32
  [19] => UTF-32BE
  [20] => UTF-32LE
  [21] => UTF-16
  [22] => UTF-16BE
  [23] => UTF-16LE
  [24] => UTF-8
  [25] => UTF-7
  [26] => UTF7-IMAP
  [27] => ASCII
  [28] => EUC-JP
  [29] => SJIS
  [30] => eucJP-win
  [31] => EUC-JP-2004
  [32] => SJIS-win
  [33] => SJIS-Mobile#DOCOMO
  [34] => SJIS-Mobile#KDDI
  [35] => SJIS-Mobile#SOFTBANK
  [36] => SJIS-mac
  [37] => SJIS-2004
  [38] => UTF-8-Mobile#DOCOMO
  [39] => UTF-8-Mobile#KDDI-A
  [40] => UTF-8-Mobile#KDDI-B
  [41] => UTF-8-Mobile#SOFTBANK
  [42] => CP932
  [43] => CP51932
  [44] => JIS
  [45] => ISO-2022-JP
  [46] => ISO-2022-JP-MS
  [47] => GB18030
  [48] => Windows-1252
  [49] => Windows-1254
  [50] => ISO-8859-1
  [51] => ISO-8859-2
  [52] => ISO-8859-3
  [53] => ISO-8859-4
  [54] => ISO-8859-5
  [55] => ISO-8859-6
  [56] => ISO-8859-7
  [57] => ISO-8859-8
  [58] => ISO-8859-9
  [59] => ISO-8859-10
  [60] => ISO-8859-13
  [61] => ISO-8859-14
  [62] => ISO-8859-15
  [63] => ISO-8859-16
  [64] => EUC-CN
  [65] => CP936
  [66] => HZ
  [67] => EUC-TW
  [68] => BIG-5
  [69] => CP950
  [70] => EUC-KR
  [71] => UHC
  [72] => ISO-2022-KR
  [73] => Windows-1251
  [74] => CP866
  [75] => KOI8-R
  [76] => KOI8-U
  [77] => ArmSCII-8
  [78] => CP850
  [79] => JIS-ms
  [80] => ISO-2022-JP-2004
  [81] => ISO-2022-JP-MOBILE#KDDI
  [82] => CP50220
  [83] => CP50220raw
  [84] => CP50221
  [85] => CP50222
)

If you cannot guess, you try one by one, as mb_detect_encoding() cannot do the job easily.

How to count check-boxes using jQuery?

There are multiple methods to do that:

Method 1:

alert($('.checkbox_class_here:checked').size());

Method 2:

alert($('input[name=checkbox_name]').attr('checked'));

Method 3:

alert($(":checkbox:checked").length);

How to generate JAXB classes from XSD?

You can download the JAXB jar files from http://jaxb.java.net/2.2.5/ You don't need to install anything, just invoke the xjc command and with classpath argument pointing to the downloaded JAXB jar files.

Load local HTML file in a C# WebBrowser

  1. Place it in the Applications setup folder or in a separte folder beneath
  2. Reference it relative to the current directory when your app runs.

NotificationCenter issue on Swift 3

Swift 3 & 4

Swift 3, and now Swift 4, have replaced many "stringly-typed" APIs with struct "wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name rather than by String. For more details see the now legacy Migrating to Swift 3 guide

Swift 2.2 usage:

// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"

// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)

Swift 3 & 4 usage:

// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")

// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)

// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)

// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)

All of the system notification types are now defined as static constants on Notification.Name; i.e. .UIApplicationDidFinishLaunching, .UITextFieldTextDidChange, etc.

You can extend Notification.Name with your own custom notifications in order to stay consistent with the system notifications:

// Definition:
extension Notification.Name {
    static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)

Swift 4.2 usage:

Same as Swift 4, except now system notifications names are part of UIApplication. So in order to stay consistent with the system notifications you can extend UIApplication with your own custom notifications instead of Notification.Name :

// Definition:
UIApplication {
    public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)

What does body-parser do with express?

Keep it simple :

  • if you used post so you will need the body of the request, so you will need body-parser.

  • No need to install body-parser with express, but you have to use it if you will receive post request.

    app.use(bodyParser.urlencoded({ extended: false }));

    { extended: false } false meaning, you do not have nested data inside your body object.

    Note that: the request data embedded within the request as a body Object.

Printing newlines with print() in R

An alternative to cat() is writeLines():

> writeLines("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename
>

An advantage is that you don't have to remember to append a "\n" to the string passed to cat() to get a newline after your message. E.g. compare the above to the same cat() output:

> cat("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename>

and

> cat("File not supplied.\nUsage: ./program F=filename","\n")
File not supplied.
Usage: ./program F=filename
>

The reason print() doesn't do what you want is that print() shows you a version of the object from the R level - in this case it is a character string. You need to use other functions like cat() and writeLines() to display the string. I say "a version" because precision may be reduced in printed numerics, and the printed object may be augmented with extra information, for example.

Is there a git-merge --dry-run option?

I made an alias for doing this and works like a charm, I do this:

 git config --global alias.mergetest '!f(){ git merge --no-commit --no-ff "$1"; git merge --abort; echo "Merge aborted"; };f '

Now I just call

git mergetest <branchname>

To find out if there are any conflicts.

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

For ChromeDriver the below worked for me:

string chromeDriverDirectory = "C:\\temp\\2.37";
 var options = new ChromeOptions();
 options.AddArgument("-no-sandbox");
 driver = new ChromeDriver(chromeDriverDirectory, options, 
 TimeSpan.FromMinutes(2));

Selenium version 3.11, ChromeDriver 2.37

Does Enter key trigger a click event?

For ENTER key, why not use (keyup.enter):

@Component({
  selector: 'key-up3',
  template: `
    <input #box (keyup.enter)="values=box.value">
    <p>{{values}}</p>
  `
})
export class KeyUpComponent_v3 {
  values = '';
}

Converting a value to 2 decimal places within jQuery

you can use just javascript for it

var total =10.8
(total).toFixed(2); 10.80


alert(total.toFixed(2))); 

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

Thanks to @felixrieseberg, you just need to install windows-build-tools npm package and you are good to go.

npm install --global --production windows-build-tools

You won't need to install Visual Studio.

You won't need to install Microsoft Build Tools.

From the repo:

After installation, npm will automatically execute this module, which downloads and installs Visual C++ Build Tools 2015, provided free of charge by Microsoft. These tools are required to compile popular native modules. It will also install Python 2.7, configuring your machine and npm appropriately.

Windows Vista / 7 requires .NET Framework 4.5.1 (Currently not installed automatically by this package)

Both installations are conflict-free, meaning that they do not mess with existing installations of Visual Studio, C++ Build Tools, or Python.

TypeError: 'float' object is not subscriptable

PriceList[0] is a float. PriceList[0][1] is trying to access the first element of a float. Instead, do

PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange

or

PriceList[0:7] = [PizzaChange]*7

How do I find out which DOM element has the focus?

Reading other answers, and trying myself, it seems document.activeElement will give you the element you need in most browsers.

If you have a browser that doesn't support document.activeElement if you have jQuery around, you should be able populate it on all focus events with something very simple like this (untested as I don't have a browser meeting those criteria to hand):

if (typeof document.activeElement === 'undefined') { // Check browser doesn't do it anyway
  $('*').live('focus', function () { // Attach to all focus events using .live()
    document.activeElement = this; // Set activeElement to the element that has been focussed
  });
}

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

Basically this error comes when you have not specified a password, it means that you have an incorrect password listed in some option file.

Read this DOC on understanding how to assign and manage Passwords to accounts.

Also , Check if the permission on the folder /var/lib/mysql/mysql is 711 or not.

Call two functions from same onclick

onclick="pay(); cls();"

however, if you're using a return statement in "pay" function the execution will stop and "cls" won't execute,

a workaround to this:

onclick="var temp = function1();function2(); return temp;"

Remove all subviews?

view.subviews.forEach { $0.removeFromSuperview() }

Changing project port number in Visual Studio 2013

Steps to resolve this:

  1. Open the solution file.
  2. Find the Port tag against your project name.
  3. Assign any different port as current.
  4. Right click on your project and select Property Pages.
  5. Click on Start Options tab and checked Start URL: option.
  6. Assign the start URL in front of Start URL option like:
    localhost:8080/login.aspx

Stack array using pop() and push()

Better solution for your Stack implementation

import java.util.List;
import java.util.ArrayList;
public class IntegerStack 

{

    private List<Integer> stack;

    public IntegerStack(int SIZE) 
    {
        stack = new ArrayList<Integer>(SIZE);
    }

    public void push(int i) 
    {

       stack.add(0,i);
     }

     public int pop() 
     { 
        if(!stack.isEmpty()){
           int i= stack.get(0);
           stack.remove(0);
           return i;
        } else{
           return -1;// Or any invalid value
        }
     }

     public int peek()
     {
        if(!stack.isEmpty()){
           return stack.get(0);
        } else{
           return -1;// Or any invalid value
        }
     }


     public boolean isEmpty() 
     {
       stack.isEmpty();
     }

 }

If you have to use Array... Here are problems in your code and possible solutions

import java.util.Arrays;
public class IntegerStack 
{

    private int stack [];
    private int top; 

    public IntegerStack(int SIZE) 
   {
    stack = new int [SIZE];
    top = -1; // top should be 0. If you keep it as -1, problems will arise when SIZE is passed as 0. 
    // In your push method -1==0 will be false and your code will try to add the invalid element to Stack .. 
     /**Solution top=0; */
    }

public void push(int i) 
{
    if (top == stack.length)
    {
        extendStack();
    }

       stack[top]= i;
        top++;

}

public int pop() 
{
    top --; // here you are reducing the top before giving the Object back 
   /*Solution 
      if(!isEmpty()){
      int value = stack[top];
       top --;
     return value; 
    } else{
      return -1;// OR invalid value
    }
   */
    return stack[top];
}

public int peek()
{
    return stack[top]; // Problem when stack is empty or size is 0
    /*Solution 
       if(!isEmpty()){
         return stack[top];
       }else{
         return -1;// Or any invalid value
       }
    */


}


public boolean isEmpty() 
{
    if ( top == -1); // problem... we changed top to 0 above so here it need to check if its 0 and there should be no semicolon after the if statement
   /* Solution if(top==0) */
    {
        return true;
    }
}

private void extendStack()
{

    int [] copy = Arrays.copyOf(stack, stack.length); // The second parameter in Arrays.copyOf has no changes, so there will be no change in array length.
  /*Solution  
    stack=Arrays.copyOf(stack, stack.length+1); 
   */
     }

     }

SQL Server: Maximum character length of object names

128 characters. This is the max length of the sysname datatype (nvarchar(128)).

Safe width in pixels for printing web pages?

A printer doesn't understand pixels, it understand dots (pt in CSS). The best solution is to write an extra CSS for printing, with all of its measures in dots.

Then, in your HTML code, in head section, put:

<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<link href="style_print.css" rel="stylesheet" type="text/css" media="print">

Convert pandas DataFrame into list of lists

EDIT: as_matrix is deprecated since version 0.23.0

You can use the built in values or to_numpy (recommended option) method on the dataframe:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist():

df.to_numpy().tolist()

Python: fastest way to create a list of n lists

To create list and list of lists use below syntax

     x = [[] for i in range(10)]

this will create 1-d list and to initialize it put number in [[number] and set length of list put length in range(length)

  • To create list of lists use below syntax.
    x = [[[0] for i in range(3)] for i in range(10)]

this will initialize list of lists with 10*3 dimension and with value 0

  • To access/manipulate element
    x[1][5]=value

how to change class name of an element by jquery

$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');

Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

Example of a strong and weak entity types

First Strong/Weak Reference types are introduced in ARC. In Non ARC assign/retain are being used. A strong reference means that you want to "own" the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you points to it with a strong reference. Only once you set the property to nil, the object get destroyed.

A weak reference means you signify that you don't want to have control over the object's lifetime or don't want to "own" object. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil. The most frequent use cases of weak references in iOS are for IBOutlets, Delegates etc.

For more info Refer : http://www.informit.com/articles/article.aspx?p=1856389&seqNum=5

How to add images to README.md on GitHub?

Just add an <img> tag to your README.md with relative src to your repository. If you're not using relative src, make sure the server supports CORS.

It works because GitHub support inline-html

<img src="/docs/logo.png" alt="My cool logo"/>
# My cool project and above is the logo of it

Observe here

How to create a file in memory for user to download, but not through server?

All of the above example works just fine in chrome and IE, but fail in Firefox. Please do consider appending an anchor to the body and removing it after click.

var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(['Test,Text'], {type: 'text/csv'}));
a.download = 'test.csv';

// Append anchor to body.
document.body.appendChild(a);
a.click();

// Remove anchor from body
document.body.removeChild(a);

What's the difference between JavaScript and Java?

One is essentially a toy, designed for writing small pieces of code, and traditionally used and abused by inexperienced programmers.

The other is a scripting language for web browsers.

Unescape HTML entities in Javascript?

The trick is to use the power of the browser to decode the special HTML characters, but not allow the browser to execute the results as if it was actual html... This function uses a regex to identify and replace encoded HTML characters, one character at a time.

function unescapeHtml(html) {
    var el = document.createElement('div');
    return html.replace(/\&[#0-9a-z]+;/gi, function (enc) {
        el.innerHTML = enc;
        return el.innerText
    });
}

Android Push Notifications: Icon not displaying in notification, white square shown instead

Finally I've got the solution for this issue.

This issue occurs only when the app is not at all running. (neither in the background nor in the foreground). When the app runs on either foreground or background the notification icon is displayed properly.(not the white square)

So what we've to set is the same configuration for notification icon in Backend APIs as that of Frontend.

In the frontend we've used React Native and for push notification we've used react-native-fcm npm package.

FCM.on("notification", notif => {
   FCM.presentLocalNotification({
       body: notif.fcm.body,
       title: notif.fcm.title,
       big_text: notif.fcm.body,
       priority: "high",
       large_icon: "notification_icon", // notification icon
       icon: "notification_icon",
       show_in_foreground: true,
       color: '#8bc34b',
       vibrate: 300,
       lights: true,
       status: notif.status
   });
});

We've used fcm-push npm package using Node.js as a backend for push notification and set the payload structure as follows.

{
  to: '/topics/user', // required
  data: {
    id:212,
    message: 'test message',
    title: 'test title'
  },
  notification: {
    title: 'test title',
    body: 'test message',
    icon : 'notification_icon', // same name as mentioned in the front end
    color : '#8bc34b',
    click_action : "BROADCAST"
  }
}

What it basically searches for the notification_icon image stored locally in our Android system.

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

I used String.prototype.match(regex) which returns a string array of all found matches of the given regex in the string (more info see here):

_x000D_
_x000D_
function getLastIndex(text, regex, limit = text.length) {_x000D_
  const matches = text.match(regex);_x000D_
_x000D_
  // no matches found_x000D_
  if (!matches) {_x000D_
    return -1;_x000D_
  }_x000D_
_x000D_
  // matches found but first index greater than limit_x000D_
  if (text.indexOf(matches[0] + matches[0].length) > limit) {_x000D_
    return -1;_x000D_
  }_x000D_
_x000D_
  // reduce index until smaller than limit_x000D_
  let i = matches.length - 1;_x000D_
  let index = text.lastIndexOf(matches[i]);_x000D_
  while (index > limit && i >= 0) {_x000D_
    i--;_x000D_
    index = text.lastIndexOf(matches[i]);_x000D_
  }_x000D_
  return index > limit ? -1 : index;_x000D_
}_x000D_
_x000D_
// expect -1 as first index === 14_x000D_
console.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\. /g, 10));_x000D_
_x000D_
// expect 29_x000D_
console.log(getLastIndex('First Sentence. Last Sentence. Unfinished', /\. /g));
_x000D_
_x000D_
_x000D_

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

This may not be the prettiest, but if you don't want to use the MessageBoxManager, (which is awesome):

 public static DialogResult DialogBox(string title, string promptText, ref string value, string button1 = "OK", string button2 = "Cancel", string button3 = null)
    {
        Form form = new Form();
        Label label = new Label();
        TextBox textBox = new TextBox();
        Button button_1 = new Button();
        Button button_2 = new Button();
        Button button_3 = new Button();

        int buttonStartPos = 228; //Standard two button position


        if (button3 != null)
            buttonStartPos = 228 - 81;
        else
        {
            button_3.Visible = false;
            button_3.Enabled = false;
        }


        form.Text = title;

        // Label
        label.Text = promptText;
        label.SetBounds(9, 20, 372, 13);
        label.Font = new Font("Microsoft Tai Le", 10, FontStyle.Regular);

        // TextBox
        if (value == null)
        {
        }
        else
        {
            textBox.Text = value;
            textBox.SetBounds(12, 36, 372, 20);
            textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
        }

        button_1.Text = button1;
        button_2.Text = button2;
        button_3.Text = button3 ?? string.Empty;
        button_1.DialogResult = DialogResult.OK;
        button_2.DialogResult = DialogResult.Cancel;
        button_3.DialogResult = DialogResult.Yes;


        button_1.SetBounds(buttonStartPos, 72, 75, 23);
        button_2.SetBounds(buttonStartPos + 81, 72, 75, 23);
        button_3.SetBounds(buttonStartPos + (2 * 81), 72, 75, 23);

        label.AutoSize = true;
        button_1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
        button_2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
        button_3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

        form.ClientSize = new Size(396, 107);
        form.Controls.AddRange(new Control[] { label, button_1, button_2 });
        if (button3 != null)
            form.Controls.Add(button_3);
        if (value != null)
            form.Controls.Add(textBox);

        form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
        form.FormBorderStyle = FormBorderStyle.FixedDialog;
        form.StartPosition = FormStartPosition.CenterScreen;
        form.MinimizeBox = false;
        form.MaximizeBox = false;
        form.AcceptButton = button_1;
        form.CancelButton = button_2;

        DialogResult dialogResult = form.ShowDialog();
        value = textBox.Text;
        return dialogResult;
    }

How to format numbers by prepending 0 to single-digit numbers?

Here is a very simple solution that worked well for me.

First declare a variable to hold your number.

var number;

Now convert the number to a string and hold it in another variable;

var numberStr = number.toString();

Now you can test the length of this string , if it is less than desired you can append a 'zero' at the beginning.

if(numberStr.length < 2){
      number = '0' + number;
}

Now use the number as desired

console.log(number);

IE prompts to open or save json result from server

Have you tried to send your ajax request using POST method ? You could also try to set content type to 'text/x-json' while returning result from the server.

Broken references in Virtualenvs

I tried the top few methods, but they didn't work, for me, which were trying to make tox work. What eventually worked was:

sudo pip install tox

even if tox was already installed. The output terminated with:

Successfully built filelock
Installing collected packages: py, pluggy, toml, filelock, tox
Successfully installed filelock-3.0.10 pluggy-0.11.0 py-1.8.0 toml-0.10.0 tox-3.9.0

How to set cornerRadius for only top-left and top-right corner of a UIView?

For SwiftUI

I found these solutions you can check from here https://stackoverflow.com/a/56763282/3716103

I highly recommend the first one

Option 1: Using Path + GeometryReader

(more info on GeometryReader: https://swiftui-lab.com/geometryreader-to-the-rescue/)

struct ContentView : View {
    var body: some View {

        Text("Hello World!")
            .foregroundColor(.white)
            .font(.largeTitle)
            .padding(20)
            .background(RoundedCorners(color: .blue, tl: 0, tr: 30, bl: 30, br: 0))
    }
}

give corner radius to text view using background

RoundedCorners

struct RoundedCorners: View {

    var color: Color = .white

    var tl: CGFloat = 0.0
    var tr: CGFloat = 0.0
    var bl: CGFloat = 0.0
    var br: CGFloat = 0.0

    var body: some View {
        GeometryReader { geometry in
            Path { path in

                let w = geometry.size.width
                let h = geometry.size.height

                // Make sure we do not exceed the size of the rectangle
                let tr = min(min(self.tr, h/2), w/2)
                let tl = min(min(self.tl, h/2), w/2)
                let bl = min(min(self.bl, h/2), w/2)
                let br = min(min(self.br, h/2), w/2)

                path.move(to: CGPoint(x: w / 2.0, y: 0))
                path.addLine(to: CGPoint(x: w - tr, y: 0))
                path.addArc(center: CGPoint(x: w - tr, y: tr), radius: tr, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false)
                path.addLine(to: CGPoint(x: w, y: h - be))
                path.addArc(center: CGPoint(x: w - br, y: h - br), radius: br, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 90), clockwise: false)
                path.addLine(to: CGPoint(x: bl, y: h))
                path.addArc(center: CGPoint(x: bl, y: h - bl), radius: bl, startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 180), clockwise: false)
                path.addLine(to: CGPoint(x: 0, y: tl))
                path.addArc(center: CGPoint(x: tl, y: tl), radius: tl, startAngle: Angle(degrees: 180), endAngle: Angle(degrees: 270), clockwise: false)
            }
            .fill(self.color)
        }
    }
}

RoundedCorners_Previews

struct RoundedCorners_Previews: PreviewProvider {
    static var previews: some View {
        RoundedCorners(color: .pink, tl: 40, tr: 40, bl: 40, br: 40)
    }
}

I give the corner radius to the top of view only

cvc-elt.1: Cannot find the declaration of element 'MyElement'

After making the change suggested above by Martin, I was still getting the same error. I had to make an additional change to my parsing code. I was parsing the XML file via a DocumentBuilder as shown in the oracle docs: https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html

// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

The problem was that DocumentBuilder is not namespace aware by default. The following additional change resolved the issue:

// parse an XML document into a DOM tree
DocumentBuilderFactory dmfactory = DocumentBuilderFactory.newInstance();
dmfactory.setNamespaceAware(true);

DocumentBuilder parser = dmfactory.newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

Cannot set some HTTP headers when using System.Net.WebRequest

I ran into this problem with a custom web client. I think people may be getting confused because of multiple ways to do this. When using WebRequest.Create() you can cast to an HttpWebRequest and use the property to add or modify a header. When using a WebHeaderCollection you may use the .Add("referer","my_url").

Ex 1

WebClient client = new WebClient();
client.Headers.Add("referer", "http://stackoverflow.com");
client.Headers.Add("user-agent", "Mozilla/5.0");

Ex 2

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Referer = "http://stackoverflow.com";
request.UserAgent = "Mozilla/5.0";
response = (HttpWebResponse)request.GetResponse();

Configure Nginx with proxy_pass

Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.

The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks

Javascript Equivalent to C# LINQ Select

Yes, Array.map() or $.map() does the same thing.

//array.map:
var ids = this.fruits.map(function(v){
    return v.Id;
});

//jQuery.map:
var ids2 = $.map(this.fruits, function (v){
    return v.Id;
});

console.log(ids, ids2);

http://jsfiddle.net/NsCXJ/1/

Since array.map isn't supported in older browsers, I suggest that you stick with the jQuery method.

If you prefer the other one for some reason you could always add a polyfill for old browser support.

You can always add custom methods to the array prototype as well:

Array.prototype.select = function(expr){
    var arr = this;
    //do custom stuff
    return arr.map(expr); //or $.map(expr);
};

var ids = this.fruits.select(function(v){
    return v.Id;
});

An extended version that uses the function constructor if you pass a string. Something to play around with perhaps:

Array.prototype.select = function(expr){
    var arr = this;

    switch(typeof expr){

        case 'function':
            return $.map(arr, expr);
            break;

        case 'string':

            try{

                var func = new Function(expr.split('.')[0], 
                                       'return ' + expr + ';');
                return $.map(arr, func);

            }catch(e){

                return null;
            }

            break;

        default:
            throw new ReferenceError('expr not defined or not supported');
            break;
    }

};

console.log(fruits.select('x.Id'));

http://jsfiddle.net/aL85j/

Update:

Since this has become such a popular answer, I'm adding similar my where() + firstOrDefault(). These could also be used with the string based function constructor approach (which is the fastest), but here is another approach using an object literal as filter:

Array.prototype.where = function (filter) {

    var collection = this;

    switch(typeof filter) { 

        case 'function': 
            return $.grep(collection, filter); 

        case 'object':
            for(var property in filter) {
              if(!filter.hasOwnProperty(property)) 
                  continue; // ignore inherited properties

              collection = $.grep(collection, function (item) {
                  return item[property] === filter[property];
              });
            }
            return collection.slice(0); // copy the array 
                                      // (in case of empty object filter)

        default: 
            throw new TypeError('func must be either a' +
                'function or an object of properties and values to filter by'); 
    }
};


Array.prototype.firstOrDefault = function(func){
    return this.where(func)[0] || null;
};

Usage:

var persons = [{ name: 'foo', age: 1 }, { name: 'bar', age: 2 }];

// returns an array with one element:
var result1 = persons.where({ age: 1, name: 'foo' });

// returns the first matching item in the array, or null if no match
var result2 = persons.firstOrDefault({ age: 1, name: 'foo' }); 

Here is a jsperf test to compare the function constructor vs object literal speed. If you decide to use the former, keep in mind to quote strings correctly.

My personal preference is to use the object literal based solutions when filtering 1-2 properties, and pass a callback function for more complex filtering.

I'll end this with 2 general tips when adding methods to native object prototypes:

  1. Check for occurrence of existing methods before overwriting e.g.:

    if(!Array.prototype.where) { Array.prototype.where = ...

  2. If you don't need to support IE8 and below, define the methods using Object.defineProperty to make them non-enumerable. If someone used for..in on an array (which is wrong in the first place) they will iterate enumerable properties as well. Just a heads up.

Stored procedure with default parameters

I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc

Option 1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Option 2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Then run exec test '2016-01-01','2016-01-25'

ssh: The authenticity of host 'hostname' can't be established

Add these to your /etc/ssh/ssh_config

Host *
UserKnownHostsFile=/dev/null
StrictHostKeyChecking=no

Why does my Spring Boot App always shutdown immediately after starting?

Just another possibility,

I replaced

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

with

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

and it started without any issues

Round up to Second Decimal Place in Python

The round funtion stated does not works for definate integers like :

a=8
round(a,3)
8.0
a=8.00
round(a,3)
8.0
a=8.000000000000000000000000
round(a,3)
8.0

but , works for :

r=400/3.0
r
133.33333333333334
round(r,3)
133.333

Morever the decimals like 2.675 are rounded as 2.67 not 2.68.
Better use the other method provided above.

How add "or" in switch statements?

Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write

switch(myvar)
{
   case 2:
   case 5:
   {
      //your code
   break;
   }

// etc... }

Extracting date from a string in Python

If the date is given in a fixed form, you can simply use a regular expression to extract the date and "datetime.datetime.strptime" to parse the date:

import re
from datetime import datetime

match = re.search(r'\d{4}-\d{2}-\d{2}', text)
date = datetime.strptime(match.group(), '%Y-%m-%d').date()

Otherwise, if the date is given in an arbitrary form, you can't extract it easily.

Why do we use __init__ in Python classes?

It seems like you need to use __init__ in Python if you want to correctly initialize mutable attributes of your instances.

See the following example:

>>> class EvilTest(object):
...     attr = []
... 
>>> evil_test1 = EvilTest()
>>> evil_test2 = EvilTest()
>>> evil_test1.attr.append('strange')
>>> 
>>> print "This is evil:", evil_test1.attr, evil_test2.attr
This is evil: ['strange'] ['strange']
>>> 
>>> 
>>> class GoodTest(object):
...     def __init__(self):
...         self.attr = []
... 
>>> good_test1 = GoodTest()
>>> good_test2 = GoodTest()
>>> good_test1.attr.append('strange')
>>> 
>>> print "This is good:", good_test1.attr, good_test2.attr
This is good: ['strange'] []

This is quite different in Java where each attribute is automatically initialized with a new value:

import java.util.ArrayList;
import java.lang.String;

class SimpleTest
{
    public ArrayList<String> attr = new ArrayList<String>();
}

class Main
{
    public static void main(String [] args)
    {
        SimpleTest t1 = new SimpleTest();
        SimpleTest t2 = new SimpleTest();

        t1.attr.add("strange");

        System.out.println(t1.attr + " " + t2.attr);
    }
}

produces an output we intuitively expect:

[strange] []

But if you declare attr as static, it will act like Python:

[strange] [strange]

Redirecting exec output to a buffer or file

After forking, use dup2(2) to duplicate the file's FD into stdout's FD, then exec.

How to open Atom editor from command line in OS X?

With conemu on windows 10 I couldn't call atom from console even after I added %USERPROFILE%\AppData\Local\atom\bin to PATH in environment variables. I just added

alias atom="C:/Users/me/AppData/local/atom/app-1.12.7/atom"

to my .bashrc file.

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Close virtual keyboard on button press

Use Below Code

your_button_id.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        try  {
            InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {

        }
    }
});

Java - Reading XML file

Reading xml the easy way:

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

.

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

          } catch (JAXBException e) {
              e.printStackTrace();
          }

    }
}

Upgrading Node.js to latest version

I had node version v7.10.0 in Ubuntu

Used below commands to upgrade

curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs

Now its upgraded to v8.2.1

or

sudo apt-get install make
sudo curl -L https://git.io/n-install | bash
. /home/$USER/.bashrc

# Below command should get the latest version of node
node --version

# Install specific version of node
n 8.2

# Check for the Node Version installed
node --version

Get Last Part of URL PHP

$id = strrchr($url,"/");
$id = substr($id,1,strlen($id));

Here is the description of the strrchr function: http://www.php.net/manual/en/function.strrchr.php

Hope that's useful!

Using grep to search for a string that has a dot in it

Escape dot. Sample command will be.

grep '0\.00'