Programs & Examples On #Localsystem

500.21 Bad module "ManagedPipelineHandler" in its module list

I had this issue in Windows 10 when I needed IIS instead of IIS Express. New Web Project failed with OP's error. Fix was

Control Panel > Turn Windows Features on or off > Internet Information Services > World Wide Web Services > Application Development Features

tick ASP.NET 4.7 (in my case)

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

How can I check if a value is of type Integer?

You can use modulus %, the solution is so simple:

import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter first number");
    Double m = scan.nextDouble();
    System.out.println("Enter second number");
    Double n= scan.nextDouble();

    if(m%n==0) 
    {
        System.out.println("Integer");
    }
    else
    {
        System.out.println("Double");
    }


}
}

How to create timer events using C++ 11?

If you are on Windows, you can use the CreateThreadpoolTimer function to schedule a callback without needing to worry about thread management and without blocking the current thread.

template<typename T>
static void __stdcall timer_fired(PTP_CALLBACK_INSTANCE, PVOID context, PTP_TIMER timer)
{
    CloseThreadpoolTimer(timer);
    std::unique_ptr<T> callable(reinterpret_cast<T*>(context));
    (*callable)();
}

template <typename T>
void call_after(T callable, long long delayInMs)
{
    auto state = std::make_unique<T>(std::move(callable));
    auto timer = CreateThreadpoolTimer(timer_fired<T>, state.get(), nullptr);
    if (!timer)
    {
        throw std::runtime_error("Timer");
    }

    ULARGE_INTEGER due;
    due.QuadPart = static_cast<ULONGLONG>(-(delayInMs * 10000LL));

    FILETIME ft;
    ft.dwHighDateTime = due.HighPart;
    ft.dwLowDateTime = due.LowPart;

    SetThreadpoolTimer(timer, &ft, 0 /*msPeriod*/, 0 /*msWindowLength*/);
    state.release();
}

int main()
{
    auto callback = []
    {
        std::cout << "in callback\n";
    };

    call_after(callback, 1000);
    std::cin.get();
}

jQuery click not working for dynamically created items

I faced this problem a few days ago - the solution for me was to use .bind() to bind the required function to the dynamically created link.

var catLink = $('<a href="#" id="' + i + '" class="lnkCat">' + category.category + '</a>');
catLink.bind("click", function(){
 $.categories.getSubCategories(this);
});

getSubCategories : function(obj) {
 //do something
}

I hope this helps.

WPF C# button style

To solve your question definitely need to use the Style and Template for the Button. But how exactly does he look like? Decisions may be several. For example, Button are two texts to better define the relevant TextBlocks? Can be directly in the template, but then use the buttons will be limited, because the template can be only one ContentPresenter. I decided to do things differently, to identify one ContentPresenter with an icon in the form of a Path, and the content is set using the buttons on the side.

The style:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="#373737" />
    <Setter Property="Foreground" Value="White" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="SnapsToDevicePixels" Value="True" />

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border CornerRadius="4" Background="{TemplateBinding Background}">
                    <Grid>
                        <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                        <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#E59400" />
                        <Setter Property="Foreground" Value="White" />
                        <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                    </Trigger>

                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="OrangeRed" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Sample of using:

<Button Width="200" Height="50" VerticalAlignment="Top" Margin="0,20,0,0" />
    <Button.Content>
        <StackPanel>
            <TextBlock Text="Watch Now" FontSize="20" />
            <TextBlock Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
        </StackPanel>
    </Button.Content>
</Button>

Output

enter image description here

It is best to StackPanel determine the Resources and set the Button so:

<Window.Resources>
    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

The question remains with setting the value for TextBlock Duration, because this value must be dynamic. I implemented it using attached DependencyProperty. Set it to the window, like that:

<Window Name="MyWindow" local:MyDependencyClass.CurrentDuration="Duration: 50m" ... />

Using in TextBlock:

<TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />

In fact, there is no difference for anyone to determine the attached DependencyProperty, because it is the predominant feature.

Example of set value:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
}

A complete listing of examples:

XAML

<Window x:Class="ButtonHelp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ButtonHelp"
    Name="MyWindow"
    Title="MainWindow" Height="350" Width="525"
    WindowStartupLocation="CenterScreen"
    local:MyDependencyClass.CurrentDuration="Duration: 50m">

<Window.Resources>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="#373737" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="FontSize" Value="15" />
        <Setter Property="FontFamily" Value="./#Segoe UI" />
        <Setter Property="SnapsToDevicePixels" Value="True" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border CornerRadius="4" Background="{TemplateBinding Background}">
                        <Grid>
                            <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                            <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                        </Grid>
                    </Border>

                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#E59400" />
                            <Setter Property="Foreground" Value="White" />
                            <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                        </Trigger>

                        <Trigger Property="IsPressed" Value="True">
                            <Setter Property="Background" Value="OrangeRed" />
                            <Setter Property="Foreground" Value="White" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Grid>        
    <Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

    <Button Content="Set some duration" Style="{x:Null}" Width="140" Height="30" VerticalAlignment="Top" HorizontalAlignment="Left" Click="Button_Click" />
</Grid>

Code behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
    }
}

public class MyDependencyClass : DependencyObject
{
    public static readonly DependencyProperty CurrentDurationProperty;        

    public static void SetCurrentDuration(DependencyObject DepObject, string value)
    {
        DepObject.SetValue(CurrentDurationProperty, value);
    }

    public static string GetCurrentDuration(DependencyObject DepObject)
    {
        return (string)DepObject.GetValue(CurrentDurationProperty);
    }

    static MyDependencyClass()
    {
        PropertyMetadata MyPropertyMetadata = new PropertyMetadata("Duration: 0m");

        CurrentDurationProperty = DependencyProperty.RegisterAttached("CurrentDuration",
                                                            typeof(string),
                                                            typeof(MyDependencyClass),
                                                            MyPropertyMetadata);
    }
}

Git: how to reverse-merge a commit?

To create a new commit that 'undoes' the changes of a past commit, use:

$ git revert <commit-hash>

It's also possible to actually remove a commit from an arbitrary point in the past by rebasing and then resetting, but you really don't want to do that if you have already pushed your commits to another repository (or someone else has pulled from you).

If your previous commit is a merge commit you can run this command

$ git revert -m 1 <commit-hash>

See schacon.github.com/git/howto/revert-a-faulty-merge.txt for proper ways to re-merge an un-merged branch

How to sum all the values in a dictionary?

I feel sum(d.values()) is the most efficient way to get the sum.

You can also try the reduce function to calculate the sum along with a lambda expression:

reduce(lambda x,y:x+y,d.values())

jQuery first child of "this"

This can be done with a simple magic like this:

$(":first-child", element).toggleClass("redClass");

Reference: http://www.snoopcode.com/jquery/jquery-first-child-selector

How to create a fix size list in python?

Python has nothing built-in to support this. Do you really need to optimize it so much as I don't think that appending will add that much overhead.

However, you can do something like l = [None] * 1000.

Alternatively, you could use a generator.

iReport not starting using JRE 8

I have installed IReport 5.6 with Java 7: not working

I tried to install Java 6 and added the path to "ireport.conf" file like the attached screenshot and it worked fine :Denter image description here

So the steps is :

 Install IReport 5.6
 Install JDK 6
 Edit "ireport.conf" file like the below image and Enjoy ;)

Prevent linebreak after </div>

div's are used to give structure to a website or to contain a lot of text or elements, but you seem to use them as label, you should use span, it will put both text next to eachother automatically and you won't need to wright css code for it.

And even if other people tell you to float the elements it's best that you just change the tags.

How can I calculate the time between 2 Dates in typescript

// TypeScript

const today = new Date();
const firstDayOfYear = new Date(today.getFullYear(), 0, 1);

// Explicitly convert Date to Number
const pastDaysOfYear = ( Number(today) - Number(firstDayOfYear) );

Using awk to print all columns from the nth to the last

This awk function returns substring of $0 that includes fields from begin to end:

function fields(begin, end,    b, e, p, i) {
    b = 0; e = 0; p = 0;
    for (i = 1; i <= NF; ++i) {
        if (begin == i) { b = p; }
        p += length($i);
        e = p;
        if (end == i) { break; }
        p += length(FS);
    }
    return substr($0, b + 1, e - b);
}

To get everything starting from field 3:

tail = fields(3);

To get section of $0 that covers fields 3 to 5:

middle = fields(3, 5);

b, e, p, i nonsense in function parameter list is just an awk way of declaring local variables.

Bulk Record Update with SQL

Your approach is OK

Maybe slightly clearer (to me anyway!)

UPDATE
  T1
SET
  [Description] = t2.[Description]
FROM
   Table1 T1
   JOIN
   [Table2] t2 ON t2.[ID] = t1.DescriptionID

Both this and your query should run the same performance wise because it is the same query, just laid out differently.

Round integers to the nearest 10

I wanted to do the same thing, but with 5 instead of 10, and came up with a simple function. Hope it's useful:

def roundToFive(num):
    remaining = num % 5
    if remaining in range(0, 3):
        return num - remaining
    return num + (5 - remaining)

Append text to file from command line without using io redirection

If you don't mind using sed then,

$ cat test 
this is line 1
$ sed -i '$ a\this is line 2 without redirection' test 
$ cat test 
this is line 1
this is line 2 without redirection

As the documentation may be a bit long to go through, some explanations :

  • -i means an inplace transformation, so all changes will occur in the file you specify
  • $ is used to specify the last line
  • a means append a line after
  • \ is simply used as a delimiter

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

Better way to cast object to int

There's also TryParse.

From MSDN:

private static void TryToParse(string value)
   {
      int number;
      bool result = Int32.TryParse(value, out number);
      if (result)
      {
         Console.WriteLine("Converted '{0}' to {1}.", value, number);         
      }
      else
      {
         if (value == null) value = ""; 
         Console.WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }

How to break line in JavaScript?

alert("I will get back to you soon\nThanks and Regards\nSaurav Kumar");

or %0D%0A in a url

How to call gesture tap on UIView programmatically in swift

Implementing tap gesture

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "touchHappen") 
view.userInteractionEnabled = true
view.addGestureRecognizer(tap)

Calls this function when the tap is recognized.

func touchHappen() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    self.view.endEditing(true)
}

Update for For Swift 3 +

let tap = UITapGestureRecognizer(target: self, action: #selector(self.touchHappen(_:)))
yourView.addGestureRecognizer(tap)
yourView.userInteractionEnabled = true

func touchHappen(_ sender: UITapGestureRecognizer) {
    print("Hello Dear you are here")
}

ReactJs: What should the PropTypes be for this.props.children?

If you want to include render prop components:

  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
    PropTypes.func
  ])

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

Set background image in CSS using jquery

Try this:

<div class="rmz-srchbg">
    <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
    <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
    <br style="clear:both;">
</div>
<script>
$(function(){
   $('#globalsearchstr').on('focus mouseenter', function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
   });
});
</script>

What is the use of GO in SQL Server Management Studio & Transact SQL?

Go means, whatever SQL statements are written before it and after any earlier GO, will go to SQL server for processing.

Select * from employees;
GO    -- GO 1

update employees set empID=21 where empCode=123;
GO    -- GO 2

In the above example, statements before GO 1 will go to sql sever in a batch and then any other statements before GO 2 will go to sql server in another batch. So as we see it has separated batches.

Parser Error when deploy ASP.NET application

Faced the same error when I had a programming error in one of the ASHX files: it was created by copying another file, and inherited its class name in the code behind statement. There was no error when all ASPX and ASHX files ran in IIS Express locally, but once deployed to the server they stopped working (all of them).

Once I found that one ASHX page and fixed the class name to reflect its own class name, all ASPX and ASHX files started working fine in IIS.

Shortcuts in Objective-C to concatenate NSStrings

NSString *label1 = @"Process Name: ";
NSString *label2 = @"Process Id: ";
NSString *processName = [[NSProcessInfo processInfo] processName];
NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
NSString *testConcat = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];

How do I get the function name inside a function in PHP?

If you are using PHP 5 you can try this:

function a() {
    $trace = debug_backtrace();
    echo $trace[0]["function"];
}

PHP: get the value of TEXTBOX then pass it to a VARIABLE

I think you should need to check for isset and not empty value, like form was submitted without input data so isset will be true This will prevent you to have any error or notice.

if((isset($_POST['name'])) && !empty($_POST['name']))
{
    $name = $_POST['name']; //note i used $_POST since you have a post form **method='post'**
    echo $name;
}

Position a div container on the right side

Is this what you wanted? - http://jsfiddle.net/jomanlk/x5vyC/3/

Floats on both sides now

#wrapper{
    background:red;
    overflow:auto;
}

#c1{
   float:left;
   background:blue;
}

#c2{
    background:green;
    float:right;
}?

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

MSVCP120d.dll missing

I downloaded msvcr120d.dll and msvcp120d.dll for 32-bit version and then, I put them into Debug folder of my project. It worked well. (My computer is 64-bit version)

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

If you are receiving this error in a WebSphere container, then make sure you set your Apps class loading policy correctly. I had to change mine from the default to 'parent last' and also ‘Single class loader for application’ for the WAR policy. This is because in my case the commons-io*.jar was packaged with in the application, so it had to be loaded first.

Read Session Id using Javascript

Yes. As the session ID is either transported over the URL (document.location.href) or via a cookie (document.cookie), you could check both for the presence of a session ID.

Char to int conversion in C

Since the ASCII codes for '0','1','2'.... are placed from 48 to 57 they are essentially continuous. Now the arithmetic operations require conversion of char datatype to int datatype.Hence what you are basically doing is: 53-48 and hence it stores the value 5 with which you can do any integer operations.Note that while converting back from int to char the compiler gives no error but just performs a modulo 256 operation to put the value in its acceptable range

Element-wise addition of 2 lists?

Use map with lambda function:

>>> map(lambda x, y: x + y, list1, list2)
[5, 7, 9]

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

team! For execute SQL-query from your Servlet you should add JDBC jar library in folder

WEB-INF/lib

After this you could call driver, example :

Class.forName("oracle.jdbc.OracleDriver");

Now Y can use connection to DB-server

==> 73!

Conditional Formatting using Excel VBA code

I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!

This is my working example:

Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
'               in duplicated formatting rules that in turn will significantly slow down
'               the spreadsheet.
'               This macro is designed to reset all formatting rules to default.
' ---------------------------------------------------------------------------------------- 

On Error GoTo ErrHandler

' Make sure we are positioned in the correct sheet
WS_PROMO.Select

' Disable Events
Application.EnableEvents = False

' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete

' CREATE ALL THE CONDITIONAL FORMATTING RULES:

' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
    .Font.Bold = True
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
    .Font.Bold = True
    .Font.Color = -10092544
    .StopIfTrue = False
End With

' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
    .DupeUnique = xlDuplicate
    .Font.Color = -16383844
    .Interior.Color = 13551615
    .StopIfTrue = False
End With

' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
    .Font.Bold = True
    .Interior.Color = 13434879
    .StopIfTrue = False
End With

' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")


ErrHandler:
Application.EnableEvents = False

End Sub

Put a Delay in Javascript

If you're okay with ES2017, await is good:

const DEF_DELAY = 1000;

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}

await sleep(100);

Note that the await part needs to be in an async function:

//IIAFE (immediately invoked async function expression)
(async()=>{
  //Do some stuff
  await sleep(100);
  //Do some more stuff
})()

Deprecated Java HttpClient - How hard can it be?

For the original issue, I would request you to apply below logic:

 CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 HttpPost httpPostRequest = new HttpPost();

How do I run Google Chrome as root?

Chrome can run as root (remember to use gksu when doing so) so long as you provide it with a profile directory.

Rather than type in the profile directory every time you want to run it, create a new bash file (I'd name it something like start-chrome.sh)

#/bin/bash
google-chrome --user-data-dir="/root/chrome-profile/"

Rember to call that script with root privelages!

$ gksu /root/start-chrome.sh

Access non-numeric Object properties by index?

If you are not sure Object.keys() is going to return you the keys in the right order, you can try this logic instead

var keys = []
var obj = {
    'key1' : 'value1',
    'key2' : 'value2',
    'key3' : 'value3',
}
for (var key in obj){
    keys.push(key)
}
console.log(obj[keys[1]])
console.log(obj[keys[2]])
console.log(obj[keys[3]])

How to remove illegal characters from path and filenames?

If you have to use the method in many places in a project, you could also make an extension method and call it anywhere in the project for strings.

 public static class StringExtension
    {
        public static string RemoveInvalidChars(this string originalString)
        {            
            string finalString=string.Empty;
            if (!string.IsNullOrEmpty(originalString))
            {
                return string.Concat(originalString.Split(Path.GetInvalidFileNameChars()));
            }
            return finalString;            
        }
    }

You can call the above extension method as:

string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";
string afterIllegalChars = illegal.RemoveInvalidChars();

Conditionally hide CommandField or ButtonField in Gridview

<asp:GridView ID="gv_Document" CssClass="gridstyle" runat="server" OnRowDataBound="gv_Document_RowDataBound" AutoGenerateColumns="false" DataKeyNames="SourceGUID,Source,FilePath" ShowHeaderWhenEmpty="false" OnRowDeleting="gv_Document_RowDeleting">
   <Columns>
       <asp:BoundField HeaderText="ItemID" DataField="ItemID" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
       <asp:BoundField HeaderText="SourceGUID" DataField="SourceGUID" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
       <asp:BoundField HeaderText="Source" DataField="Source" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
           <asp:TemplateField HeaderText="">
               <ItemTemplate>
                    <asp:HyperLink ID="hyperLink" runat="server" Target="_blank" NavigateUrl='<%# Bind("FilePath")%>'
                                                                Text='<%# Bind("FileName")%>'>  </asp:HyperLink>
               </ItemTemplate>
           </asp:TemplateField>
      <asp:BoundField HeaderText="Type" DataField="FileExtension" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
      <asp:BoundField HeaderText="Content type" DataField="FileMimeType" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
      <asp:BoundField HeaderText="File Path" DataField="FilePath" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
      <asp:CommandField ShowDeleteButton="True" DeleteText="Delete" />
   </Columns>

Use this code to disable delete button in gridview from code behind.

protected void gv_Document_RowDataBound(object sender, GridViewRowEventArgs e)
{ 
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((LinkButton)e.Row.Cells[7].Controls[0]).Visible = false;            
    }
}

What does 'foo' really mean?

See: RFC 3092: Etymology of "Foo", D. Eastlake 3rd et al.

Quoting only the relevant definitions from that RFC for brevity:

  1. Used very generally as a sample name for absolutely anything, esp. programs and files (esp. scratch files).

  2. First on the standard list of metasyntactic variables used in syntax examples (bar, baz, qux, quux, corge, grault, garply, waldo, fred, plugh, xyzzy, thud). [JARGON]

PHP: How do I display the contents of a textfile on my page?

if you just want to show the file itself:

header('Content-Type: text/plain');
header('Content-Disposition: inline; filename="filename.txt"');
readfile(path);

When should I use cross apply over inner join?

The essence of the APPLY operator is to allow correlation between left and right side of the operator in the FROM clause.

In contrast to JOIN, the correlation between inputs is not allowed.

Speaking about correlation in APPLY operator, I mean on the right hand side we can put:

  • a derived table - as a correlated subquery with an alias
  • a table valued function - a conceptual view with parameters, where the parameter can refer to the left side

Both can return multiple columns and rows.

How many threads is too many?

This question has been discussed quite thoroughly and I didn't get a chance to read all the responses. But here's few things to take into consideration while looking at the upper limit on number of simultaneous threads that can co-exist peacefully in a given system.

  1. Thread Stack Size : In Linux the default thread stack size is 8MB (you can use ulimit -a to find it out).
  2. Max Virtual memory that a given OS variant supports. Linux Kernel 2.4 supports a memory address space of 2 GB. with Kernel 2.6 , I a bit bigger (3GB )
  3. [1] shows the calculations for the max number of threads per given Max VM Supported. For 2.4 it turns out to be about 255 threads. for 2.6 the number is a bit larger.
  4. What kindda kernel scheduler you have . Comparing Linux 2.4 kernel scheduler with 2.6 , the later gives you a O(1) scheduling with no dependence upon number of tasks existing in a system while first one is more of a O(n). So also the SMP Capabilities of the kernel schedule also play a good role in max number of sustainable threads in a system.

Now you can tune your stack size to incorporate more threads but then you have to take into account the overheads of thread management(creation/destruction and scheduling). You can enforce CPU Affinity to a given process as well as to a given thread to tie them down to specific CPUs to avoid thread migration overheads between the CPUs and avoid cold cash issues.

Note that one can create thousands of threads at his/her wish , but when Linux runs out of VM it just randomly starts killing processes (thus threads). This is to keep the utility profile from being maxed out. (The utility function tells about system wide utility for a given amount of resources. With a constant resources in this case CPU Cycles and Memory, the utility curve flattens out with more and more number of tasks ).

I am sure windows kernel scheduler also does something of this sort to deal with over utilization of the resources

[1] http://adywicaksono.wordpress.com/2007/07/10/i-can-not-create-more-than-255-threads-on-linux-what-is-the-solutions/

How do I iterate over an NSArray?

Here is how you declare an array of strings and iterate over them:

NSArray *langs = @[@"es", @"en", @"pt", @"it", @"fr"];

for (int i = 0; i < [langs count]; i++) {
  NSString *lang = (NSString*) [langs objectAtIndex:i];
  NSLog(@"%@, ",lang);
}

Options for initializing a string array

You have several options:

string[] items = { "Item1", "Item2", "Item3", "Item4" };

string[] items = new string[]
{
  "Item1", "Item2", "Item3", "Item4"
};

string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...

jQuery hover and class selector

Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:

HTML:

  <ul id="menu">
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
  </ul>

CSS:

#menu {
  margin: 0;
}
#menu li {
  float: left;
  list-style: none;
  margin: 0;
}
#menu li a {
  display: block;
  line-height:30px;
  width:100px;
  background-color:#000;
}
#menu li a:hover {
  background-color:#F00;
}

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Remove all html tags from php string

use strip_tags

$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);   //output Test paragraph. Other text

<?php echo substr(strip_tags($row_get_Business['business_description']),0,110) . "..."; ?>

Uploading Laravel Project onto Web Server

No, but you have a couple of options:

The easiest is to upload all the files you have into that directory you're in (i.e. the cPanel user home directory), and put the contents of public into public_html. That way your directory structure will be something like this (slightly messy but it works):

/
    .composer/
    .cpanel/
    ...
    app/                 <- your laravel app directory
    etc/
    bootstrap/           <- your laravel bootstrap directory
    mail/
    public_html/         <- your laravel public directory
    vendor/
    artisan              <- your project's root files

You may also need to edit bootstrap/paths.php to point at the correct public directory.

The other solution, if you don't like having all these files in that 'root' directory would be to put them in their own directory (maybe 'laravel') that's still in the root directory and then edit the paths to work correctly. You'll still need to put the contents of public in public_html, though, and this time edit your public_html/index.php to correctly bootstrap the application. Your folder structure will be a lot tidier this way (though there could be some headaches with paths due to messing with the framework's designed structure more):

/
    .composer/
    .cpanel/
    ...
    etc/
    laravel/      <- a directory containing all your project files except public
        app/
        bootstrap/
        vendor/
        artisan
    mail/
    public_html/  <- your laravel public directory

How should we manage jdk8 stream for null values

Stuart's answer provides a great explanation, but I'd like to provide another example.

I ran into this issue when attempting to perform a reduce on a Stream containing null values (actually it was LongStream.average(), which is a type of reduction). Since average() returns OptionalDouble, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.

So, as the OP suggests, I added a filter like so:

list.stream()
    .filter(o -> o != null)
    .reduce(..);

Or as tangens pointed out below, use the predicate provided by the Java API:

list.stream()
    .filter(Objects::nonNull)
    .reduce(..);

From the mailing list discussion Stuart linked: Brian Goetz on nulls in Streams

Do conditional INSERT with SQL?

Usually you make the thing you don't want duplicates of unique, and allow the database itself to refuse the insert.

Otherwise, you can use INSERT INTO, see How to avoid duplicates in INSERT INTO SELECT query in SQL Server?

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

Using Service to run background and create notification

Your error is in UpdaterServiceManager in onCreate and showNotification method.

You are trying to show notification from Service using Activity Context. Whereas Every Service has its own Context, just use the that. You don't need to pass a Service an Activity's Context.I don't see why you need a specific Activity's Context to show Notification.

Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.

You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference

Handling Enter Key in Vue.js

Event Modifiers

You can refer to event modifiers in vuejs to prevent form submission on enter key.

It is a very common need to call event.preventDefault() or event.stopPropagation() inside event handlers.

Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.

To address this problem, Vue provides event modifiers for v-on. Recall that modifiers are directive postfixes denoted by a dot.

<form v-on:submit.prevent="<method>">
  ...
</form>

As the documentation states, this is syntactical sugar for e.preventDefault() and will stop the unwanted form submission on press of enter key.

Here is a working fiddle.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#myApp',_x000D_
  data: {_x000D_
    emailAddress: '',_x000D_
    log: ''_x000D_
  },_x000D_
  methods: {_x000D_
    validateEmailAddress: function(e) {_x000D_
      if (e.keyCode === 13) {_x000D_
        alert('Enter was pressed');_x000D_
      } else if (e.keyCode === 50) {_x000D_
        alert('@ was pressed');_x000D_
      }      _x000D_
      this.log += e.key;_x000D_
    },_x000D_
    _x000D_
    postEmailAddress: function() {_x000D_
   this.log += '\n\nPosting';_x000D_
    },_x000D_
    noop () {_x000D_
      // do nothing ?_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
html, body, #editor {_x000D_
  margin: 0;_x000D_
  height: 100%;_x000D_
  color: #333;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="myApp" style="padding:2rem; background-color:#fff;">_x000D_
<form v-on:submit.prevent="noop">_x000D_
  <input type="text" v-model="emailAddress" v-on:keyup="validateEmailAddress" />_x000D_
  <button type="button" v-on:click="postEmailAddress" >Subscribe</button> _x000D_
  <br /><br />_x000D_
  _x000D_
  <textarea v-model="log" rows="4"></textarea>  _x000D_
</form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to include another XHTML in XHTML using JSF 2.0 Facelets?

Included page:

<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>

Including page:

<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
  • You start your included xhtml file with ui:composition as shown above.
  • You include that file with ui:include in the including xhtml file as also shown above.

Viewing my IIS hosted site on other machines on my network

After installing antivirus I faced this issue and I noticed that my firewall automatically set as on, Now I just set firewall off and it solved my issue. Hope it will help someone :)

How to add Python to Windows registry

English

In case that it serves to someone, I leave here the Windows 10 base register for Python 3.4.4 - 64 bit:

Español

Por si alguien lo necesita todavía, este es el registro base de Windows 10 para Python 3.4.4:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4]
"DisplayName"="Python 3.4 (64-bit)"
"SupportUrl"="http://www.python.org/"
"Version"="3.4.4"
"SysVersion"="3.4"
"SysArchitecture"="64bit"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help]

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Help\Main Python Documentation]
@="C:\\Python34\\Doc\\python364.chm"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\Idle]
@="C:\\Python34\\Lib\\idlelib\\idle.pyw"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\IdleShortcuts]
@=dword:00000001

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstalledFeatures]

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\InstallPath]
@="C:\\Python34\\"
"ExecutablePath"="C:\\Python34\\python.exe"
"WindowedExecutablePath"="C:\\Python34\\pythonw.exe"

[HKEY_CURRENT_USER\Software\Python\PythonCore\3.4\PythonPath]
@="C:\\Python34\\Lib\\;C:\\Python34\\DLLs\\"

Forward declaration of a typedef in C++

Like @BillKotsias, I used inheritance, and it worked for me.

I changed this mess (which required all the boost headers in my declaration *.h)

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>

typedef boost::accumulators::accumulator_set<float,
 boost::accumulators::features<
  boost::accumulators::tag::median,
  boost::accumulators::tag::mean,
  boost::accumulators::tag::min,
  boost::accumulators::tag::max
 >> VanillaAccumulator_t ;
std::unique_ptr<VanillaAccumulator_t> acc;

into this declaration (*.h)

class VanillaAccumulator;
std::unique_ptr<VanillaAccumulator> acc;

and the implementation (*.cpp) was

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>

class VanillaAccumulator : public
  boost::accumulators::accumulator_set<float,
    boost::accumulators::features<
      boost::accumulators::tag::median,
      boost::accumulators::tag::mean,
      boost::accumulators::tag::min,
      boost::accumulators::tag::max
>>
{
};

How do I escape special characters in MySQL?

For strings like that, for me the most comfortable way to do it is doubling the ' or ", as explained in the MySQL manual:

There are several ways to include quote characters within a string:

A “'” inside a string quoted with “'” may be written as “''”.

A “"” inside a string quoted with “"” may be written as “""”.

Precede the quote character by an escape character (“\”).

A “'” inside a string quoted with “"” needs no special treatment and need not be doubled or escaped. In the same way, “"” inside a

Strings quoted with “'” need no special treatment.

It is from http://dev.mysql.com/doc/refman/5.0/en/string-literals.html.

Xcode process launch failed: Security

I have the same issue. I click ok in xcode and when launching the app on my iPhone I'm asked if I want to trust this application. Doing it, the app runs and further build-and-run from xcode went without any issue until deleting the app from the iPhone and reinstalling it. Then goto first line ;-)

"Specified argument was out of the range of valid values"

I was also getting same issue as i tried using value 0 in non-based indexing,i.e starting with 1, not with zero

Running Java Program from Command Line Linux

(This is the KISS answer.)

Let's say you have several .java files in the current directory:

$ ls -1 *.java
javaFileName1.java
javaFileName2.java

Let's say each of them have a main() method (so they are programs, not libs), then to compile them do:

javac *.java -d .

This will generate as many subfolders as "packages" the .java files are associated to. In my case all java files where inside under the same package name packageName, so only one folder was generated with that name, so to execute each of them:

java -cp . packageName.javaFileName1
java -cp . packageName.javaFileName2

How can I combine two HashMap objects containing the same types?

If you know you don't have duplicate keys, or you want values in map2 to overwrite values from map1 for duplicate keys, you can just write

map3 = new HashMap<>(map1);
map3.putAll(map2);

If you need more control over how values are combined, you can use Map.merge, added in Java 8, which uses a user-provided BiFunction to merge values for duplicate keys. merge operates on individual keys and values, so you'll need to use a loop or Map.forEach. Here we concatenate strings for duplicate keys:

map3 = new HashMap<>(map1);
for (Map.Entry<String, String> e : map2.entrySet())
    map3.merge(e.getKey(), e.getValue(), String::concat);
//or instead of the above loop
map2.forEach((k, v) -> map3.merge(k, v, String::concat));

If you know you don't have duplicate keys and want to enforce it, you can use a merge function that throws an AssertionError:

map2.forEach((k, v) ->
    map3.merge(k, v, (v1, v2) ->
        {throw new AssertionError("duplicate values for key: "+k);}));

Taking a step back from this specific question, the Java 8 streams library provides toMap and groupingBy Collectors. If you're repeatedly merging maps in a loop, you may be able to restructure your computation to use streams, which can both clarify your code and enable easy parallelism using a parallel stream and concurrent collector.

ASP.NET Display "Loading..." message while update panel is updating

You can use code as below when

using Image as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

using Text as Loading

<asp:UpdateProgress id="updateProgress" runat="server">
    <ProgressTemplate>
        <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
            <span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
        </div>
    </ProgressTemplate>
</asp:UpdateProgress>

True/False vs 0/1 in MySQL

Bit is also an option if tinyint isn't to your liking. A few links:

Not surprisingly, more info about numeric types is available in the manual.

One more link: http://blog.mclaughlinsoftware.com/2010/02/26/mysql-boolean-data-type/

And a quote from the comment section of the article above:

  • TINYINT(1) isn’t a synonym for bit(1).
  • TINYINT(1) can store -9 to 9.
  • TINYINT(1) UNSIGNED: 0-9
  • BIT(1): 0, 1. (Bit, literally).

Edit: This edit (and answer) is only remotely related to the original question...

Additional quotes by Justin Rovang and the author maclochlainn (comment section of the linked article).

Excuse me, seems I’ve fallen victim to substr-ism: TINYINT(1): -128-+127 TINYINT(1) UNSIGNED: 0-255 (Justin Rovang 25 Aug 11 at 4:32 pm)

True enough, but the post was about what PHPMyAdmin listed as a Boolean, and there it only uses 0 or 1 from the entire wide range of 256 possibilities. (maclochlainn 25 Aug 11 at 11:35 pm)

how to convert String into Date time format in JAVA?

With SimpleDateFormat. And steps are -

  1. Create your date pattern string
  2. Create SimpleDateFormat Object
  3. And parse with it.
  4. It will return Date Object.

Entity Framework rollback and remove bad migration

You can also use

Remove-Migration -Force

This will revert and remove the last applied migration

How to comment out a block of code in Python

The only cure I know for this is a good editor. Sorry.

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

Get attribute name value of <input>

You need to write a selector which selects the correct <input> first. Ideally you use the element's ID $('#element_id'), failing that the ID of it's container $('#container_id input'), or the element's class $('input.class_name').

Your element has none of these and no context, so it's hard to tell you how to select it.

Once you have figured out the proper selector, you'd use the attr method to access the element's attributes. To get the name, you'd use $(selector).attr('name') which would return (in your example) 'xxxxx'.

A url resource that is a dot (%2E)

It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of . or .. is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments . and ..”, without clarifying whether they match . and .. before or after pct-encoding.

Personally I find Firefox's interpretation that %2E does not mean . most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only . or ...

I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F, %00 and %5C sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.

NSString property: copy or retain?

If the string is very large then copy will affect performance and two copies of the large string will use more memory.

Why do I get "MismatchSenderId" from GCM server side?

This happens when the Server key and Sender ID parameters HTTP request do not match each other. Basically both server ID and Server key must belong to the same firebase project. Please refer to the below image. In case of mixing these parameters from deferent Firebase projects will cause error MismatchSenderId enter image description here

pypi UserWarning: Unknown distribution option: 'install_requires'

It works fine if you follow the official documentation:

import setuptools
setuptools.setup(...)

Source: https://packaging.python.org/tutorials/packaging-projects/#creating-setup-py

How do I set cell value to Date and apply default Excel date format?

I am writing my answer here because it may be helpful to other readers, who might have a slightly different requirement than the questioner here.

I prepare an .xlsx template; all the cells which will be populated with dates, are already formatted as date cells (using Excel).

I open the .xlsx template using Apache POI and then just write the date to the cell, and it works.

In the example below, cell A1 is already formatted from within Excel with the format [$-409]mmm yyyy, and the Java code is used only to populate the cell.

FileInputStream inputStream = new FileInputStream(new File("Path to .xlsx template"));
Workbook wb = new XSSFWorkbook(inputStream);
Date date1=new Date();
Sheet xlsMainTable = (Sheet) wb.getSheetAt(0);
Row myRow= CellUtil.getRow(0, xlsMainTable);
CellUtil.getCell(myRow, 0).setCellValue(date1);

WHen the Excel is opened, the date is formatted correctly.

Set order of columns in pandas dataframe

You can use this:

columnsTitles = ['onething', 'secondthing', 'otherthing']

frame = frame.reindex(columns=columnsTitles)

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

write() versus writelines() and concatenated strings

if you just want to save and load a list try Pickle

Pickle saving:

with open("yourFile","wb")as file:
 pickle.dump(YourList,file)

and loading:

with open("yourFile","rb")as file:
 YourList=pickle.load(file)

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

Same here on Ubuntu 18.04

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

  1. mysqld.sock= actually resides under folder /run/mysqld/
  2. ?> / ll /var/run
    lrwxrwxrwx 1 root root 4 Nov 1 2018 /var/run -> /run/

hmmm... Does that mean a symbolic link won't work? That's weird...

Reading a cell value in Excel vba and write in another Cell

surely you can do this with worksheet formulas, avoiding VBA entirely:

so for this value in say, column AV S:1 P:0 K:1 Q:1

you put this formula in column BC:

=MID(AV:AV,FIND("S",AV:AV)+2,1)

then these formulas in columns BD, BE...

=MID(AV:AV,FIND("P",AV:AV)+2,1)
=MID(AV:AV,FIND("K",AV:AV)+2,1)
=MID(AV:AV,FIND("Q",AV:AV)+2,1)

so these formulas look for the values S:1, P:1 etc in column AV. If the FIND function returns an error, then 0 is returned by the formula, else 1 (like an IF, THEN, ELSE

Then you would just copy down the formulas for all the rows in column AV.

HTH Philip

Using LIMIT within GROUP BY to get N results per group?

You could use GROUP_CONCAT aggregated function to get all years into a single column, grouped by id and ordered by rate:

SELECT   id, GROUP_CONCAT(year ORDER BY rate DESC) grouped_year
FROM     yourtable
GROUP BY id

Result:

-----------------------------------------------------------
|  ID | GROUPED_YEAR                                      |
-----------------------------------------------------------
| p01 | 2006,2003,2008,2001,2007,2009,2002,2004,2005,2000 |
| p02 | 2001,2004,2002,2003,2000,2006,2007                |
-----------------------------------------------------------

And then you could use FIND_IN_SET, that returns the position of the first argument inside the second one, eg.

SELECT FIND_IN_SET('2006', '2006,2003,2008,2001,2007,2009,2002,2004,2005,2000');
1

SELECT FIND_IN_SET('2009', '2006,2003,2008,2001,2007,2009,2002,2004,2005,2000');
6

Using a combination of GROUP_CONCAT and FIND_IN_SET, and filtering by the position returned by find_in_set, you could then use this query that returns only the first 5 years for every id:

SELECT
  yourtable.*
FROM
  yourtable INNER JOIN (
    SELECT
      id,
      GROUP_CONCAT(year ORDER BY rate DESC) grouped_year
    FROM
      yourtable
    GROUP BY id) group_max
  ON yourtable.id = group_max.id
     AND FIND_IN_SET(year, grouped_year) BETWEEN 1 AND 5
ORDER BY
  yourtable.id, yourtable.year DESC;

Please see fiddle here.

Please note that if more than one row can have the same rate, you should consider using GROUP_CONCAT(DISTINCT rate ORDER BY rate) on the rate column instead of the year column.

The maximum length of the string returned by GROUP_CONCAT is limited, so this works well if you need to select a few records for every group.

Reading the selected value from asp:RadioButtonList using jQuery

I found a simple solution, try this:

var Ocasiao = "";    
$('#ctl00_rdlOcasioesMarcas input').each(function() { if (this.checked) { Ocasiao = this.value } });

WARNING: Can't verify CSRF token authenticity rails

I'm using Rails 4.2.4 and couldn't work out why I was getting:

Can't verify CSRF token authenticity

I have in the layout:

<%= csrf_meta_tags %>

In the controller:

protect_from_forgery with: :exception

Invoking tcpdump -A -s 999 -i lo port 3000 was showing the header being set ( despite not needing to set the headers with ajaxSetup - it was done already):

X-CSRF-Token: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
DNT: 1
Content-Length: 125
authenticity_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

In the end it was failing because I had cookies switched off. CSRF doesn't work without cookies being enabled, so this is another possible cause if you're seeing this error.

Display only 10 characters of a long string?

Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:

.no-overflow {
    white-space: no-wrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.

how to read all files inside particular folder

If you are looking to copy all the text files in one folder to merge and copy to another folder, you can do this to achieve that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace HowToCopyTextFiles
{
  class Program
  {
    static void Main(string[] args)
    {
      string mydocpath=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);     
      StringBuilder sb = new StringBuilder();
      foreach (string txtName in Directory.GetFiles(@"D:\Links","*.txt"))
      {
        using (StreamReader sr = new StreamReader(txtName))
        {
          sb.AppendLine(txtName.ToString());
          sb.AppendLine("= = = = = =");
          sb.Append(sr.ReadToEnd());
          sb.AppendLine();
          sb.AppendLine();   
        }
      }
      using (StreamWriter outfile=new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
      {    
        outfile.Write(sb.ToString());
      }   
    }
  }
}

How do I keep a label centered in WinForms?

The accepted answer didn't work for me for two reasons:

  1. I had BackColor set so setting AutoSize = false and Dock = Fill causes the background color to fill the whole form
  2. I couldn't have AutoSize set to false anyway because my label text was dynamic

Instead, I simply used the form's width and the width of the label to calculate the left offset:

MyLabel.Left = (this.Width - MyLabel.Width) / 2;

jQuery 'if .change() or .keyup()'

Write a single function and call it for both of them.

function yourHandler(e){
    alert( 'something happened!' );        
}
jQuery(':input').change(yourHandler).keyup(yourHandler);

The change() and keyup() event registration functions return the original set, so they can be chained.

jQuery / Javascript code check, if not undefined

$.fn.attr(attributeName) returns the attribute value as string, or undefined when the attribute is not present.

Since "", and undefined are both falsy (evaluates to false when coerced to boolean) values in JavaScript, in this case I would write the check as below:

if (wlocation) { ... }

Regex for string not ending with given suffix

Try this

/.*[^a]$/

The [] denotes a character class, and the ^ inverts the character class to match everything but an a.

HttpContext.Current.User.Identity.Name is Empty

In addition to "answered Mar 28 '11 at 12:27Bryan Bedard"

In case that the solution doesn't work, you have to enable Windows Authentication in iss manager. How to do that:

1.To start IIS Manager from the Run dialog box: On the Start menu, click All Programs, click Accessories, and then click Run. In the Open box, type inetmgr and then click OK.

2.In the Connections pane, expand the server name, expand Sites, and go to the level in the hierarchy pane that you want to configure, and then click the Web site or Web application. 3. Scroll to the IIS section in the Home pane, and then double-click Authentication.

4.In the Authentication pane, select Anonymous Authentication, and then click Disable. enter image description here

  1. In the Authentication pane, select Windows Authentication, and then click Enable.

Reference

LPCSTR, LPCTSTR and LPTSTR

Quick and dirty:

LP == Long Pointer. Just think pointer or char*

C = Const, in this case, I think they mean the character string is a const, not the pointer being const.

STR is string

the T is for a wide character or char (TCHAR) depending on compile options.

How to fix date format in ASP .NET BoundField (DataFormatString)?

The following links will help you:

In Client side design page you can try this: {0:G}

OR

You can convert that datetime format inside the query itself from the database:

Python extract pattern matches

You could use something like this:

import re
s = #that big string
# the parenthesis create a group with what was matched
# and '\w' matches only alphanumeric charactes
p = re.compile("name +(\w+) +is valid", re.flags)
# use search(), so the match doesn't have to happen 
# at the beginning of "big string"
m = p.search(s)
# search() returns a Match object with information about what was matched
if m:
    name = m.group(1)
else:
    raise Exception('name not found')

Copy filtered data to another sheet using VBA

I suggest you do it a different way.

In the following code I set as a Range the column with the sports name F and loop through each cell of it, check if it is "hockey" and if yes I insert the values in the other sheet one by one, by using Offset.

I do not think it is very complicated and even if you are just learning VBA, you should probably be able to understand every step. Please let me know if you need some clarification

Sub TestThat()

'Declare the variables
Dim DataSh As Worksheet
Dim HokySh As Worksheet
Dim SportsRange As Range
Dim rCell As Range
Dim i As Long

'Set the variables
Set DataSh = ThisWorkbook.Sheets("Data")
Set HokySh = ThisWorkbook.Sheets("Hoky")

Set SportsRange = DataSh.Range(DataSh.Cells(3, 6), DataSh.Cells(Rows.Count, 6).End(xlUp))
    'I went from the cell row3/column6 (or F3) and go down until the last non empty cell

    i = 2

    For Each rCell In SportsRange 'loop through each cell in the range

        If rCell = "hockey" Then 'check if the cell is equal to "hockey"

            i = i + 1                                'Row number (+1 everytime I found another "hockey")
            HokySh.Cells(i, 2) = i - 2               'S No.
            HokySh.Cells(i, 3) = rCell.Offset(0, -1) 'School
            HokySh.Cells(i, 4) = rCell.Offset(0, -2) 'Background
            HokySh.Cells(i, 5) = rCell.Offset(0, -3) 'Age

        End If

    Next rCell

End Sub

OR condition in Regex

Try

\d \w |\d

or add a positive lookahead if you don't want to include the trailing space in the match

\d \w(?= )|\d

When you have two alternatives where one is an extension of the other, put the longer one first, otherwise it will have no opportunity to be matched.

Android Room - simple select query - Cannot access database on the main thread

With lambda its easy to run with AsyncTask

 AsyncTask.execute(() -> //run your query here );

WordPress asking for my FTP credentials to install plugins

I did a local install of WordPress on Ubuntu 14.04 following the steps outlined here and simply running:

sudo chown -R www-data:www-data {path_to_your_project_directory}

solved my issue with downloading plugins. The only reason I'm leaving this post here is because when I googled my issue, this was one of the first results and it led me to the solution to my problem.

Hope this one helps to anyone!

Java Class.cast() vs. cast operator

First, you are strongly discouraged to do almost any cast, so you should limit it as much as possible! You lose the benefits of Java's compile-time strongly-typed features.

In any case, Class.cast() should be used mainly when you retrieve the Class token via reflection. It's more idiomatic to write

MyObject myObject = (MyObject) object

rather than

MyObject myObject = MyObject.class.cast(object)

EDIT: Errors at compile time

Over all, Java performs cast checks at run time only. However, the compiler can issue an error if it can prove that such casts can never succeed (e.g. cast a class to another class that's not a supertype and cast a final class type to class/interface that's not in its type hierarchy). Here since Foo and Bar are classes that aren't in each other hierarchy, the cast can never succeed.

Javascript "Uncaught TypeError: object is not a function" associativity question

JavaScript does require semicolons, it's just that the interpreter will insert them for you on line breaks where possible*.

Unfortunately, the code

var a = new B(args)(stuff)()

does not result in a syntax error, so no ; will be inserted. (An example which can run is

var answer = new Function("x", "return x")(function(){return 42;})();

To avoid surprises like this, train yourself to always end a statement with ;.


* This is just a rule of thumb and not always true. The insertion rule is much more complicated. This blog page about semicolon insertion has more detail.

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

What's the difference between event.stopPropagation and event.preventDefault?

event.preventDefault(); Stops the default action of an element from happening.

event.stopPropagation(); Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

Remove all special characters, punctuation and spaces from string

Removing Punctuations, Numbers, and Special Characters

Example :-

enter image description here

Code

combi['tidy_tweet'] = combi['tidy_tweet'].str.replace("[^a-zA-Z#]", " ") 

Result:- enter image description here

Thanks :)

The infamous java.sql.SQLException: No suitable driver found

I faced the similar issue. My Project in context is Dynamic Web Project(Java 8 + Tomcat 8) and error is for PostgreSQL Driver exception: No suitable driver found

It got resolved by adding Class.forName("org.postgresql.Driver") before calling getConnection() method

Here is my Sample Code:

try {
            Connection conn = null;
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/?preferQueryMode="
                    + sql_auth,sql_user , sql_password);
        } catch (Exception e) {
            System.out.println("Failed to create JDBC db connection " + e.toString() + e.getMessage());
        }

how to kill the tty in unix

You can use killall command as well .

-o, --older-than Match only processes that are older (started before) the time specified. The time is specified as a float then a unit. The units are s,m,h,d,w,M,y for seconds, minutes, hours, days,

-e, --exact Require an exact match for very long names.

-r, --regexp Interpret process name pattern as an extended regular expression.

This worked like a charm.

What are the different types of indexes, what are the benefits of each?

PostgreSQL allows partial indexes, where only rows that match a predicate are indexed. For instance, you might want to index the customer table for only those records which are active. This might look something like:

create index i on customers (id, name, whatever) where is_active is true;

If your index many columns, and you have many inactive customers, this can be a big win in terms of space (the index will be stored in fewer disk pages) and thus performance. To hit the index you need to, at a minimum, specify the predicate:

select name from customers where is_active is true;

NULL values inside NOT IN clause

SQL uses three-valued logic for truth values. The IN query produces the expected result:

SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE col IN (NULL, 1)
-- returns first row

But adding a NOT does not invert the results:

SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE NOT col IN (NULL, 1)
-- returns zero rows

This is because the above query is equivalent of the following:

SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE NOT (col = NULL OR col = 1)

Here is how the where clause is evaluated:

| col | col = NULL?¹?  | col = 1 | col = NULL OR col = 1 | NOT (col = NULL OR col = 1) |
|-----|----------------|---------|-----------------------|-----------------------------|
| 1   | UNKNOWN        | TRUE    | TRUE                  | FALSE                       |
| 2   | UNKNOWN        | FALSE   | UNKNOWN?²?            | UNKNOWN?³?                  |

Notice that:

  1. The comparison involving NULL yields UNKNOWN
  2. The OR expression where none of the operands are TRUE and at least one operand is UNKNOWN yields UNKNOWN (ref)
  3. The NOT of UNKNOWN yields UNKNOWN (ref)

You can extend the above example to more than two values (e.g. NULL, 1 and 2) but the result will be same: if one of the values is NULL then no row will match.

Set start value for column with autoincrement

In the Table Designer on SQL Server Management Studio you can set the where the auto increment will start. Right-click on the table in Object Explorer and choose Design, then go to the Column Properties for the relevant column:

Here the autoincrement will start at 760

How to set encoding in .getJSON jQuery

I think that you'll probably have to use $.ajax() if you want to change the encoding, see the contentType param below (the success and error callbacks assume you have <div id="success"></div> and <div id="error"></div> in the html):

$.ajax({
    type: "POST",
    url: "SomePage.aspx/GetSomeObjects",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: "{id: '" + someId + "'}",
    success: function(json) {
        $("#success").html("json.length=" + json.length);
        itemAddCallback(json);
    },
    error: function (xhr, textStatus, errorThrown) {
        $("#error").html(xhr.responseText);
    }
});

I actually just had to do this about an hour ago, what a coincidence!

Return number of rows affected by UPDATE statements

You might need to collect the stats as you go, but @@ROWCOUNT captures this:

declare @Fish table (
Name varchar(32)
)

insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT  --gives 1

update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3

Make a Bash alias that takes a parameter?

Respectfully to all those saying you can't insert a parameter in the middle of an alias I just tested it and found that it did work.

alias mycommand = "python3 "$1" script.py --folderoutput RESULTS/"

when I then ran mycommand foobar it worked exactly as if I had typed the command out longhand.

CSV parsing in Java - working example..?

You might want to have a look at this specification for CSV. Bear in mind that there is no official recognized specification.

If you do not now the delimiter it will not be possible to do this so you have to find out somehow. If you can do a manual inspection of the file you should quickly be able to see what it is and hard code it in your program. If the delimiter can vary your only hope is to be able to deduce if from the formatting of the known data. When Excel imports CSV files it lets the user choose the delimiter and this is a solution you could use as well.

What are the differences between git branch, fork, fetch, merge, rebase and clone?

Git

This answer includes GitHub as many folks have asked about that too.

Local repositories

Git (locally) has a directory (.git) which you commit your files to and this is your 'local repository'. This is different from systems like SVN where you add and commit to the remote repository immediately.

Git stores each version of a file that changes by saving the entire file. It is also different from SVN in this respect as you could go to any individual version without 'recreating' it through delta changes.

Git doesn't 'lock' files at all and thus avoids the 'exclusive lock' functionality for an edit (older systems like pvcs come to mind), so all files can always be edited, even when off-line. It actually does an amazing job of merging file changes (within the same file!) together during pulls or fetches/pushes to a remote repository such as GitHub. The only time you need to do manual changes (actually editing a file) is if two changes involve the same line(s) of code.


Branches

Branches allow you to preserve the main code (the 'master' branch), make a copy (a new branch) and then work within that new branch. If the work takes a while or master gets a lot of updates since the branch was made then merging or rebasing (often preferred for better history and easier to resolve conflicts) against the master branch should be done. When you've finished, you merge the changes made in the branch back in to the master repository. Many organizations use branches for each piece of work whether it is a feature, bug or chore item. Other organizations only use branches for major changes such as version upgrades.

Fork: With a branch you control and manage the branch, whereas with a fork someone else controls accepting the code back in.

Broadly speaking, there are two main approaches to doing branches. The first is to keep most changes on the master branch, only using branches for larger and longer-running things like version changes where you want to have two branches available for different needs. The second is whereby you basically make a branch for every feature request, bug fix or chore and then manually decide when to actually merge those branches into the main master branch. Though this sounds tedious, this is a common approach and is the one that I currently use and recommend because this keeps the master branch cleaner and it's the master that we promote to production, so we only want completed, tested code, via the rebasing and merging of branches.

The standard way to bring a branch 'in' to master is to do a merge. Branches can also be "rebased" to 'clean up' history. It doesn't affect the current state and is done to give a 'cleaner' history.

Basically, the idea is that you branched from a certain point (usually from master). Since you branched, 'master' itself has since moved forward from that branching point. It will be 'cleaner' (easier to resolve issues and the history will be easier to understand) if all the changes you have done in a branch are played against the current state of master with all of its latest changes. So, the process is: save the changes; get the 'new' master, and then reapply (this is the rebase part) the changes again against that. Be aware that rebase, just like merge, can result in conflicts that you have to manually resolve (i.e. edit and fix).

One guideline to note:
Only rebase if the branch is local and you haven't pushed it to remote yet!
This is mainly because rebasing can alter the history that other people see which may include their own commits.

Tracking branches

These are the branches that are named origin/branch_name (as opposed to just branch_name). When you are pushing and pulling the code to/from remote repositories this is actually the mechanism through which that happens. For example, when you git push a branch called building_groups, your branch goes first to origin/building_groups and then that goes to the remote repository. Similarly, if you do a git fetch building_groups, the file that is retrieved is placed in your origin/building_groups branch. You can then choose to merge this branch into your local copy. Our practice is to always do a git fetch and a manual merge rather than just a git pull (which does both of the above in one step).

Fetching new branches.

Getting new branches: At the initial point of a clone you will have all the branches. However, if other developers add branches and push them to the remote there needs to be a way to 'know' about those branches and their names in order to be able to pull them down locally. This is done via a git fetch which will get all new and changed branches into the locally repository using the tracking branches (e.g., origin/). Once fetched, one can git branch --remote to list the tracking branches and git checkout [branch] to actually switch to any given one.

Merging

Merging is the process of combining code changes from different branches, or from different versions of the same branch (for example when a local branch and remote are out of sync). If one has developed work in a branch and the work is complete, ready and tested, then it can be merged into the master branch. This is done by git checkout master to switch to the master branch, then git merge your_branch. The merge will bring all the different files and even different changes to the same files together. This means that it will actually change the code inside files to merge all the changes.

When doing the checkout of master it's also recommended to do a git pull origin master to get the very latest version of the remote master merged into your local master. If the remote master changed, i.e., moved forward, you will see information that reflects that during that git pull. If that is the case (master changed) you are advised to git checkout your_branch and then rebase it to master so that your changes actually get 'replayed' on top of the 'new' master. Then you would continue with getting master up-to-date as shown in the next paragraph.

If there are no conflicts, then master will have the new changes added in. If there are conflicts, this means that the same files have changes around similar lines of code that it cannot automatically merge. In this case git merge new_branch will report that there's conflict(s) to resolve. You 'resolve' them by editing the files (which will have both changes in them), selecting the changes you want, literally deleting the lines of the changes you don't want and then saving the file. The changes are marked with separators such as ======== and <<<<<<<<.

Once you have resolved any conflicts you will once again git add and git commit those changes to continue the merge (you'll get feedback from git during this process to guide you).

When the process doesn't work well you will find that git merge --abort is very handy to reset things.

Interactive rebasing and squashing / reordering / removing commits

If you have done work in a lot of small steps, e.g., you commit code as 'work-in-progress' every day, you may want to 'squash' those many small commits into a few larger commits. This can be particularly useful when you want to do code reviews with colleagues. You don't want to replay all the 'steps' you took (via commits), you want to just say here is the end effect (diff) of all of my changes for this work in one commit.

The key factor to evaluate when considering whether to do this is whether the multiple commits are against the same file or files more than once (better to squash commits in that case). This is done with the interactive rebasing tool. This tool lets you squash commits, delete commits, reword messages, etc. For example, git rebase -i HEAD~10 (note: that's a ~, not a -) brings up the following:

interactive rebasing in Git

Be careful though and use this tool 'gingerly'. Do one squash/delete/reorder at a time, exit and save that commit, then reenter the tool. If commits are not contiguous you can reorder them (and then squash as needed). You can actually delete commits here too, but you really need to be sure of what you are doing when you do that!

Forks

There are two main approaches to collaboration in Git repositories. The first, detailed above, is directly via branches that people pull and push from/to. These collaborators have their SSH keys registered with the remote repository. This will let them push directly to that repository. The downside is that you have to maintain the list of users. The other approach - forking - allows anybody to 'fork' the repository, basically making a local copy in their own Git repository account. They can then make changes and when finished send a 'pull request' (really it's more of a 'push' from them and a 'pull' request for the actual repository maintainer) to get the code accepted.

This second method, using forks, does not require someone to maintain a list of users for the repository.


GitHub

GitHub (a remote repository) is a remote source that you normally push and pull those committed changes to if you have (or are added to) such a repository, so local and remote are actually quite distinct. Another way to think of a remote repository is that it is a .git directory structure that lives on a remote server.

When you 'fork' - in the GitHub web browser GUI you can click on this button Image of fork button - you create a copy ('clone') of the code in your GitHub account. It can be a little subtle first time you do it, so keep making sure you look at whose repository a code base is listed under - either the original owner or 'forked from' and you, e.g., like this:

Image of name of forked repository

Once you have the local copy, you can make changes as you wish (by pulling and pushing them to a local machine). When you are done then you submit a 'pull request' to the original repository owner/admin (sounds fancy but actually you just click on this: Image of pull request button) and they 'pull' it in.

More common for a team working on code together is to 'clone' the repository (click on the 'copy' icon on the repository's main screen). Then, locally type git clone and paste. This will set you up locally and you can also push and pull to the (shared) GitHub location.

Clones

As indicated in the section on GitHub, a clone is a copy of a repository. When you have a remote repository you issue the git clone command against its URL and you then end up with a local copy, or clone, of the repository. This clone has everything, the files, the master branch, the other branches, all the existing commits, the whole shebang. It is this clone that you do your adds and commits against and then the remote repository itself is what you push those commits to. It's this local/remote concept that makes Git (and systems similar to it such as Mercurial) a DVCS (Distributed Version Control System) as opposed to the more traditional CVSs (Code Versioning Systems) such as SVN, PVCS, CVS, etc. where you commit directly to the remote repository.

Visualization

Visualization of the core concepts can be seen at
http://marklodato.github.com/visual-git-guide/index-en.html and
http://ndpsoftware.com/git-cheatsheet.html#loc=index

If you want a visual display of how the changes are working, you can't beat the visual tool gitg (gitx for macOS) with a GUI that I call 'the subway map' (esp. London Underground), great for showing who did what, how things changes, diverged and merged, etc.

You can also use it to add, commit and manage your changes!

Image of gitg/gitx interface

Although gitg/gitx is fairly minimal, the number of GUI tools continues to expand. Many Mac users use brotherbard's fork of gitx and for Linux, a great option is smart-git with an intuitive yet powerful interface:

Image of smart-git GUI

Note that even with a GUI tool, you will probably do a lot of commands at the command line.

For this, I have the following aliases in my ~/.bash_aliases file (which is called from my ~/.bashrc file for each terminal session):

# git
alias g='git status'
alias gcob='git checkout -b '
alias gcom='git checkout master'
alias gd='git diff'
alias gf='git fetch'
alias gfrm='git fetch; git reset --hard origin/master'
alias gg='git grep '
alias gits='alias | grep "^alias g.*git.*$"'
alias gl='git log'
alias gl1='git log --oneline'
alias glf='git log --name-status'
alias glp='git log -p'
alias gpull='git pull '
alias gpush='git push '

AND I have the following "git aliases" in my ~/.gitconfig file - why have these ?
So that branch completion (with the TAB key) works !

So these are:

[alias]
  co = checkout
  cob = checkout -b

Example usage: git co [branch] <- tab completion for branches will work.

GUI Learning Tool

You may find https://learngitbranching.js.org/ useful in learning some of the base concepts. Screen shot: enter image description here
Video: https://youtu.be/23JqqcLPss0

Finally, 7 key lifesavers!

  1. You make changes, add and commit them (but don't push) and then oh! you realize you are in master!

    git reset [filename(s)]
    git checkout -b [name_for_a_new_branch]
    git add [file(s)]
    git commit -m "A useful message"
    
    Voila!  You've moved that 'master' commit to its own branch !
    
  2. You mess up some files while working in a local branch and simply want to go back to what you had the last time you did a git pull:

    git reset --hard origin/master  # You will need to be comfortable doing this!
    
  3. You start making changes locally, you edit half a dozen files and then, oh crap, you're still in the master (or another) branch:

    git checkout -b new_branch_name  # just create a new branch
    git add .                      # add the changes files
    git commit -m"your message"    # and commit them
    
  4. You mess up one particular file in your current branch and want to basically 'reset' that file (lose changes) to how it was the the last time you pulled it from the remote repository:

    git checkout your/directories/filename
    

    This actually resets the file (like many Git commands it is not well named for what it is doing here).

  5. You make some changes locally, you want to make sure you don't lose them while you do a git reset or rebase: I often make a manual copy of the entire project (cp -r ../my_project ~/) when I am not sure if I might mess up in Git or lose important changes.

  6. You are rebasing but things gets messed up:

    git rebase --abort # To abandon interactive rebase and merge issues
    
  7. Add your Git branch to your PS1 prompt (see https://unix.stackexchange.com/a/127800/10043), e.g.

    Image of prompt

    The branch is selenium_rspec_conversion.

Excel: replace part of cell's string value

What you need to do is as follows:

  1. List item
  2. Select the entire column by clicking once on the corresponding letter or by simply selecting the cells with your mouse.
  3. Press Ctrl+H.
  4. You are now in the "Find and Replace" dialog. Write "Author" in the "Find what" text box.
  5. Write "Authoring" in the "Replace with" text box.
  6. Click the "Replace All" button.

That's it!

How to enable PHP short tags?

This can be done by enabling short_open_tag in php.ini:

short_open_tag = on

If you don't have access to the php.ini you can try to enable them trough the .htaccess file but it's possible the hosting company disabled this if you are on shared hosting:

php_value short_open_tag 1

For the people thinking that short_open_tags are bad practice as of php 5.4 the <?= ... ?> shorttag will supported everywhere, regardless of the settings so there is no reason not to use them if you can control the settings on the server. Also said in this link: short_open_tag

What does "#pragma comment" mean?

Pragma directives specify operating system or machine specific (x86 or x64 etc) compiler options. There are several options available. Details can be found in https://msdn.microsoft.com/en-us/library/d9x1s805.aspx

#pragma comment( comment-type [,"commentstring"] ) has this format.

Refer https://msdn.microsoft.com/en-us/library/7f0aews7.aspx for details about different comment-type.

#pragma comment(lib, "kernel32") #pragma comment(lib, "user32")

The above lines of code includes the library names (or path) that need to be searched by the linker. These details are included as part of the library-search record in the object file.

So, in this case kernel.lib and user32.lib are searched by the linker and included in the final executable.

How do I convert from a string to an integer in Visual Basic?

You can use the following to convert string to int:

  • CInt(String) for ints
  • CDec(String) for decimals

For details refer to Type Conversion Functions (Visual Basic).

Fixing broken UTF-8 encoding

It looks like your utf-8 is being interpreted as iso8859-1 or Win-1250 at some point.

When you say "In my database I have a few instances of bad encodings" - how did you check this? Through your app, phpmyadmin or the command line client? Are all utf-8 encodings showing up like this or only some? Is it possible you had the encodings wrong and it has been incorrectly converted from iso8859-1 to utf-8 when it was utf-8 already?

How to show PIL Image in ipython notebook

If you are using the pylab extension, you could convert the image to a numpy array and use matplotlib's imshow.

%pylab # only if not started with the --pylab option
imshow(array(pil_im))

EDIT: As mentioned in the comments, the pylab module is deprecated, so use the matplotlib magic instead and import the function explicitly:

%matplotlib
from matplotlib.pyplot import imshow 
imshow(array(pil_im))

Convert from MySQL datetime to another format with PHP

To correctly format a DateTime object in PHP for storing in MySQL use the standardised format that MySQL uses, which is ISO 8601.

PHP has had this format stored as a constant since version 5.1.1, and I highly recommend using it rather than manually typing the string each time.

$dtNow = new DateTime();
$mysqlDateTime = $dtNow->format(DateTime::ISO8601);

This, and a list of other PHP DateTime constants are available at http://php.net/manual/en/class.datetime.php#datetime.constants.types

Oracle insert if not exists statement

Another approach would be to leverage the INSERT ALL syntax from oracle,

INSERT ALL 
    INTO table1(email, campaign_id) VALUES (email, campaign_id)
WITH source_data AS
 (SELECT '[email protected]' email,100 campaign_id
  FROM   dual
  UNION ALL
  SELECT '[email protected]' email,200 campaign_id
  FROM   dual)      
SELECT email
      ,campaign_id
FROM   source_data src
WHERE  NOT EXISTS (SELECT 1
        FROM   table1 dest
        WHERE  src.email = dest.email
        AND    src.campaign_id = dest.campaign_id);

INSERT ALL also allow us to perform a conditional insert into multiple tables based on a sub query as source.

There are some really clean and nice examples are there to refer.

  1. oracletutorial.com
  2. oracle-base.com/

Is SMTP based on TCP or UDP?

In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.

As defined in RFC 821, RFC 2821, and RFC 5321:

SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.

In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.

In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.


The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.

Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.

Java Convert GMT/UTC to Local time doesn't work as expected

tl;dr

Instant.now()                           // Capture the current moment in UTC.
.atZone( ZoneId.systemDefault() )       // Adjust into the JVM's current default time zone. Same moment, different wall-clock time. Produces a `ZonedDateTime` object.
.toInstant()                            // Extract a `Instant` (always in UTC) object from the `ZonedDateTime` object.
.atZone( ZoneId.of( "Europe/Paris" ) )  // Adjust the `Instant` into a specific time zone. Renders a `ZonedDateTime` object. Same moment, different wall-clock time.
.toInstant()                            // And back to UTC again.

java.time

The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes (Date, Calendar, etc.).

Your use of the word "local" contradicts the usage in the java.time class. In java.time, "local" means any locality or all localities, but not any one particular locality. The java.time classes with names starting with "Local…" all lack any concept of time zone or offset-from-UTC. So they do not represent a specific moment, they are not a point on the timeline, whereas your Question is all about moments, points on the timeline viewed through various wall-clock times.

Get the current system time (local time)

If you want to capture the current moment in UTC, use Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now() ;  // Capture the current moment in UTC.

Adjust into a time zone by applying a ZoneId to get a ZonedDateTime. Same moment, same point on the timeline, different wall-clock time.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment, different wall-clock time.

As a shortcut, you can skip the usage of Instant to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

Convert Local time to UTC // Works Fine Till here

You can adjust from the zoned date-time to UTC by extracting an Instant from a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Instant instant = zdt.toInstant() ;

Reverse the UTC time, back to local time.

As shown above, apply a ZoneId to adjust the same moment into another wall-clock time used by the people of a certain region (a time zone).

Instant instant = Instant.now() ;  // Capture current moment in UTC.

ZoneId zDefault = ZoneId.systemDefault() ;  // The JVM's current default time zone.
ZonedDateTime zdtDefault = instant.atZone( zDefault ) ;

ZoneId zTunis = ZoneId.of( "Africa/Tunis" ) ;  // The JVM's current default time zone.
ZonedDateTime zdtTunis = instant.atZone( zTunis ) ;

ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ;  // The JVM's current default time zone.
ZonedDateTime zdtAuckland = instant.atZone( zAuckland ) ;

Going back to UTC from a zoned date-time, call ZonedDateTime::toInstant. Think of it conceptually as: ZonedDateTime = Instant + ZoneId.

Instant instant = zdtAuckland.toInstant() ;

All of these objects, the Instant and the three ZonedDateTime objects all represent the very same simultaneous moment, the same point in history.

Followed 3 different approaches (listed below) but all the 3 approaches retains the time in UTC only.

Forget about trying to fix code using those awful Date, Calendar, and GregorianCalendar classes. They are a wretched mess of bad design and flaws. You need never touch them again. If you must interface with old code not yet updated to java.time, you can convert back-and-forth via new conversion methods added to the old classes.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Re-enabling window.alert in Chrome

Close and re-open the tab. That should do the trick.

How to fix Cannot find module 'typescript' in Angular 4?

For me just running the below command is not enough (though a valid first step):

npm install -g typescript

The following command is what you need (I think deleting node_modules works too, but the below command is quicker)

npm link typescript

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

I was facing this issue while deploying my ear to my local weblogic instance. Clearing the local repository and building the ear again resolved the issue for me.

How do I find the version of Apache running without access to the command line?

Simply use something like the following - the string should be there already:

<?php
   if(isset($_SERVER['SERVER_SOFTWARE'])){
      echo $_SERVER['SERVER_SOFTWARE'];
   }
?>

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Add this code to the beginning:

    Application.ScreenUpdating = False
     With ThisWorkbook
      Dim ws As Worksheet
       For Each ws In Worksheets: ws.Visible = True: Next ws
     End With

Add this code to the end:

    With ThisWorkbook
     Dim ws As Worksheet
      For Each ws In Worksheets: ws.Visible = False: Next ws
    End With
     Application.ScreenUpdating = True

Adjust Code at the end if you want more than the first sheet to be active and visible. Such as the following:

     Dim ws As Worksheet
      For Each ws In Worksheets
       If ws.Name = "_DataRecords" Then

         Else: ws.Visible = False
       End If
      Next ws

To ensure the new sheet is the one renamed, adjust your code similar to the following:

     Sheets(Me.cmbxSheetCopy.value).Copy After:=Sheets(Sheets.Count)
     Sheets(Me.cmbxSheetCopy.value & " (2)").Select
     Sheets(Me.cmbxSheetCopy.value & " (2)").Name = txtbxNewSheetName.value

This code is from my user form that allows me to copy a particular sheet (chosen from a dropdown box) with the formatting and formula's that I want to a new sheet and then rename new sheet with the user Input. Note that every time a sheet is copied it is automatically given the old sheet name with the designation of " (2)". Example "OldSheet" becomes "OldSheet (2)" after the copy and before the renaming. So you must select the Copied sheet with the programs naming before renaming.

Round to at most 2 decimal places (only if necessary)

Here is a simple way to do it:

Math.round(value * 100) / 100

You might want to go ahead and make a separate function to do it for you though:

function roundToTwo(value) {
    return(Math.round(value * 100) / 100);
}

Then you would simply pass in the value.

You could enhance it to round to any arbitrary number of decimals by adding a second parameter.

function myRound(value, places) {
    var multiplier = Math.pow(10, places);

    return (Math.round(value * multiplier) / multiplier);
}

Key hash for Android-Facebook app

The simplest solution:

  1. Don't add the hash key, implement everything else
  2. When facebook login is pressed, you will get an error saying "Invalid key hash. The key hash "xxx" does not match any stored key. ..."
  3. Open the facebook app dashboard and add the hash "xxx=" ("xxx" hash from the error + "=" sign)

How to delete files/subfolders in a specific directory at the command prompt in Windows

To delete file:

del PATH_TO_FILE

To delete folder with all files in it:

rmdir /s /q PATH_TO_FOLDER

To delete all files from specific folder (not deleting folder itself) is a little bit complicated. del /s *.* cannot delete folders, but removes files from all subfolder. So two commands are needed:

del /q PATH_TO_FOLDER\*.*
for /d %i in (PATH_TO_FOLDER\*.*) do @rmdir /s /q "%i"

How do I select a random value from an enumeration?

You can also cast a random value:

using System;

enum Test {
  Value1,
  Value2,
  Value3
}

class Program {
  public static void Main (string[] args) {
    var max = Enum.GetValues(typeof(Test)).Length;
    var value = (Test)new Random().Next(0, max - 1);
    Console.WriteLine(value);
  }
}

But you should use a better randomizer like the one in this library of mine.

Getting coordinates of marker in Google Maps API

var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();

See the google.maps.LatLng docs and google.maps.Marker getPosition().

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}

Spring doc about Aggregating @Configuration classes with @Import: link

How to determine whether code is running in DEBUG / RELEASE build?

Most answers said that how to set #ifdef DEBUG and none of them saying how to determinate debug/release build.

My opinion:

  1. Edit scheme -> run -> build configuration :choose debug / release . It can control the simulator and your test iPhone's code status.

  2. Edit scheme -> archive -> build configuration :choose debug / release . It can control the test package app and App Store app 's code status. enter image description here

How to switch from POST to GET in PHP CURL

Make sure that you're putting your query string at the end of your URL when doing a GET request.

$qry_str = "?x=10&y=20";
$ch = curl_init();

// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php' . $qry_str); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
With a POST you pass the data via the CURLOPT_POSTFIELDS option instead 
of passing it in the CURLOPT__URL.
-------------------------------------------------------------------------

$qry_str = "x=10&y=20";
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php');  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);

// Set request method to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Set query data here with CURLOPT_POSTFIELDS
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str);

$content = trim(curl_exec($ch));
curl_close($ch);
print $content;

Note from the curl_setopt() docs for CURLOPT_HTTPGET (emphasis added):

[Set CURLOPT_HTTPGET equal to] TRUE to reset the HTTP request method to GET.
Since GET is the default, this is only necessary if the request method has been changed.

Package opencv was not found in the pkg-config search path

I got the same error when trying to compile a Go package on Debian 9.8:

# pkg-config --cflags  -- libssl libcrypto
Package libssl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libssl.pc'

The thing is that pkg-config searches for package meta-information in .pc files. Such files come from the dev package. So, even though I had libssl installed, I still got the error. It was resolved by running:

sudo apt-get install libssl-dev

WSDL/SOAP Test With soapui

definitions is a root element of WSDL so it looks like you are not loading WSDL.

Edit:

I tested it and it looks like the whole problem is with your web server. Your web server returns WSDL to browser but it doesn't return it to any tool because these tools are using very minimalistic HTTP requests without many HTTP headers. One of missing headers is Accept. Once this header is not included in the request your server throws HTTP 400 Bad request.

The easy approach to continue is opening WSDL in the browser, save the wsdl to a file and import that file to soapUI instead of the WSDL from URL.

How do you determine what SQL Tables have an identity column programmatically

Another way (for 2000 / 2005/2012/2014):

IF ((SELECT OBJECTPROPERTY( OBJECT_ID(N'table_name_here'), 'TableHasIdentity')) = 1)
    PRINT 'Yes'
ELSE
    PRINT 'No'

NOTE: table_name_here should be schema.table, unless the schema is dbo.

Notify ObservableCollection when Item changes

You could use an extension method to get notified about changed property of an item in a collection in a generic way.

public static class ObservableCollectionExtension
{
    public static void NotifyPropertyChanged<T>(this ObservableCollection<T> observableCollection, Action<T, PropertyChangedEventArgs> callBackAction)
        where T : INotifyPropertyChanged
    {
        observableCollection.CollectionChanged += (sender, args) =>
        {
            //Does not prevent garbage collection says: http://stackoverflow.com/questions/298261/do-event-handlers-stop-garbage-collection-from-occuring
            //publisher.SomeEvent += target.SomeHandler;
            //then "publisher" will keep "target" alive, but "target" will not keep "publisher" alive.
            if (args.NewItems == null) return;
            foreach (T item in args.NewItems)
            {
                item.PropertyChanged += (obj, eventArgs) =>
                {
                    callBackAction((T)obj, eventArgs);
                };
            }
        };
    }
}

public void ExampleUsage()
{
    var myObservableCollection = new ObservableCollection<MyTypeWithNotifyPropertyChanged>();
    myObservableCollection.NotifyPropertyChanged((obj, notifyPropertyChangedEventArgs) =>
    {
        //DO here what you want when a property of an item in the collection has changed.
    });
}

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used "view" and I used "webview", for the rest is the same

No, it is not.

The one that is new to the N Developer Preview has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)

The one that is supported by all Android versions, including N, has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, String url)

So why should I do to make it work on all versions?

Override the deprecated one, the one that takes a String as the second parameter.

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

Inside a Fragment subclass you have to use getFragmentManager in place of getSupportFragmentManager. You will get the support one if the import are from the support library.

How to get single value from this multi-dimensional PHP array

I think you want this:

foreach ($myarray as $key => $value) {
    echo "$key = $value\n";
}

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

May be this can help you- Add the system variable _JAVA_OPTIONS and in the "new variable value" add "-Xmx1024M" Xmx sets the maximum heap memory size

Change image source in code behind - Wpf

None of the above solutions worked for me. But this did:

myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));

How to export plots from matplotlib with transparent background?

Png files can handle transparency. So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png file.

And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?

If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.

Convert numpy array to tuple

If you like long cuts, here is another way tuple(tuple(a_m.tolist()) for a_m in a )

from numpy import array
a = array([[1, 2],
           [3, 4]])
tuple(tuple(a_m.tolist()) for a_m in a )

The output is ((1, 2), (3, 4))

Note just (tuple(a_m.tolist()) for a_m in a ) will give a generator expresssion. Sort of inspired by @norok2's comment to Greg von Winckel's answer

IndentationError: unexpected indent error

import urllib.request
import requests
from bs4 import BeautifulSoup

        r = requests.get('https://icons8.com/icons/set/favicon')

If you try to connect to such a site, you will get an indent error.

import urllib.request
import requests
from bs4 import BeautifulSoup


r = requests.get('https://icons8.com/icons/set/favicon')

Python cares about indents

How to Select Every Row Where Column Value is NOT Distinct

select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

How to add a column in TSQL after a specific column?

You should be able to do this if you create the column using the GUI in Management Studio. I believe Management studio is actually completely recreating the table, which is why this appears to happen.

As others have mentioned, the order of columns in a table doesn't matter, and if it does there is something wrong with your code.

How to change the status bar color in Android?

Just add these lines in your styles.xml file

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- This is used for statusbar color. -->
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <!-- This is used for statusbar content color. If statusbarColor is light, use "true" otherwise use "false"-->
    <item name="android:windowLightStatusBar">false</item>
</style>

Compiling a java program into an executable

You can convert .jar file to .exe on these ways:
alt text
(source: viralpatel.net)

1- JSmooth .exe wrapper:
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a web site.

JSmooth provides a variety of wrappers for your java application, each of them having their own behaviour: Choose your flavour!

Download: http://jsmooth.sourceforge.net/

2- JarToExe 1.8
Jar2Exe is a tool to convert jar files into exe files. Following are the main features as describe in their website:

  • Can generate “Console”, “Windows GUI”, “Windows Service” three types of exe files.
  • Generated exe files can add program icons and version information.
  • Generated exe files can encrypt and protect java programs, no temporary files will be generated when program runs.
  • Generated exe files provide system tray icon support.
  • Generated exe files provide record system event log support.
  • Generated windows service exe files are able to install/uninstall itself, and support service pause/continue.
  • New release of x64 version, can create 64 bits executives. (May 18, 2008)
  • Both wizard mode and command line mode supported. (May 18, 2008)

Download: http://www.brothersoft.com/jartoexe-75019.html

3- Executor
Package your Java application as a jar, and Executor will turn the jar into a Windows exe file, indistinguishable from a native application. Simply double-clicking the exe file will invoke the Java Runtime Environment and launch your application.

Download: http://mpowers.net/executor/

EDIT: The above link is broken, but here is the page (with working download) from the Internet Archive. http://web.archive.org/web/20090316092154/http://mpowers.net/executor/

4- Advanced Installer
Advanced Installer lets you create Windows MSI installs in minutes. This also has Windows Vista support and also helps to create MSI packages in other languages.
Download: http://www.advancedinstaller.com/ Let me know other tools that you have used to convert JAR to EXE.

JavaScript string with new line - but not using \n

UPDATE: I just came across a wonderful syntax design in JavaScript-ES6 called Template literals. What you want to do can be literally be done using ` (backtick or grave accent character).

var foo = `Bob
is
cool`;

In which case, foo === "Bob\nis\ncool" is true.

Why the designers decided that ` ... ` can be left unterminated, but the " ... " and ' ... ' are illegal to have newline characters in them is beyond me.

Just be sure that the targeting browser supports ES6-specified Javascript implementation.

 


P. S. This syntax has a pretty cool feature that is similar to PHP and many more scripting languages, namely "Tagged template literals" in which you can have a string like this:

var a = 'Hello', b = 'World';
console.log(`The computer says ${ a.toUpperCase() }, ${b}!`);
// Prints "The computer says HELLO, World!"

How to add an image in the title bar using html?

W3C says:

<!DOCTYPE html 
      PUBLIC "-//W3C//DTD HTML 4.01//EN"
      "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" 
      type="image/png" 
      href="http://example.com/myicon.png">
[…]
</head>
[…]
</html>

See http://www.w3.org/2005/10/howto-favicon

But keep in mind: Some browser need a while to recognize that there is a favicon - try to delete the cookies and reopen your site! (And be sure the icon is at the path :) )

Import an existing git project into GitLab?

I was able to fully export my project along with all commits, branches and tags to gitlab via following commands run locally on my computer:

To illustrate my example, I will be using https://github.com/raveren/kint as the source repository that I want to import into gitlab. I created an empty project named Kint (under namespace raveren) in gitlab beforehand and it told me the http git url of the newly created project there is http://gitlab.example.com/raveren/kint.git

The commands are OS agnostic.

In a new directory:

git clone --mirror https://github.com/raveren/kint
cd kint.git
git remote add gitlab http://gitlab.example.com/raveren/kint.git
git push gitlab --mirror

Now if you have a locally cloned repository that you want to keep using with the new remote, just run the following commands* there:

git remote remove origin
git remote add origin http://gitlab.example.com/raveren/kint.git
git fetch --all

*This assumes that you did not rename your remote master from origin, otherwise, change the first two lines to reflect it.

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

Well, I'm not sure that merge would be the way to go. Personally I would build a new data frame by creating an index of the dates and then constructing the columns using list comprehensions. Possibly not the most pythonic way, but it seems to work for me!

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )

# Create an index list from the set of dates in both data frames
Index = list(set(list(df1.index) + list(df2.index)))
Index.sort()

df3 = pd.DataFrame({'df1': [df1.loc[Date, 'c'] if Date in df1.index else np.nan for Date in Index],\
                'df2': [df2.loc[Date, 'c'] if Date in df2.index else np.nan for Date in Index],},\
                index = Index)

df3

Dynamically access object property using variable

You should use JSON.parse, take a look at https://www.w3schools.com/js/js_json_parse.asp

const obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}')
console.log(obj.name)
console.log(obj.age)

Dictionary text file

What about /usr/share/dict/words on any Unix system? How many words are we talking about? Like OED-Unabridged?

Calculate difference between two datetimes in MySQL

my two cents about logic:

syntax is "old date" - :"new date", so:

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:00', '2018-11-15 15:00:30')

gives 30,

SELECT TIMESTAMPDIFF(SECOND, '2018-11-15 15:00:55', '2018-11-15 15:00:15')

gives: -40

tmux status bar configuration

The man page has very detailed descriptions of all of the various options (the status bar is highly configurable). Your best bet is to read through man tmux and pay particular attention to those options that begin with status-.

So, for example, status-bg red would set the background colour of the bar.

The three components of the bar, the left and right sections and the window-list in the middle, can all be configured to suit your preferences. status-left and status-right, in addition to having their own variables (like #S to list the session name) can also call custom scripts to display, for example, system information like load average or battery time.

The option to rename windows or panes based on what is currently running in them is automatic-rename. You can set, or disable it globally with:

setw -g automatic-rename [on | off]

The most straightforward way to become comfortable with building your own status bar is to start with a vanilla one and then add changes incrementally, reloading the config as you go.1

You might also want to have a look around on github or bitbucket for other people's conf files to provide some inspiration. You can see mine here2.



1 You can automate this by including this line in your .tmux.conf:

bind R source-file ~/.tmux.conf \; display-message "Config reloaded..."

You can then test your new functionality with Ctrlb,Shiftr. tmux will print a helpful error message—including a line number of the offending snippet—if you misconfigure an option.

2 Note: I call a different status bar depending on whether I am in X or the console - I find this quite useful.

How do I set up the database.yml file in Rails?

The database.yml is the file where you set up all the information to connect to the database. It differs depending on the kind of DB you use. You can find more information about this in the Rails Guide or any tutorial explaining how to setup a rails project.

The information in the database.yml file is scoped by environment, allowing you to get a different setting for testing, development or production. It is important that you keep those distinct if you don't want the data you use for development deleted by mistake while running your test suite.

Regarding source control, you should not commit this file but instead create a template file for other developers (called database.yml.template). When deploying, the convention is to create this database.yml file in /shared/config directly on the server.

With SVN: svn propset svn:ignore config "database.yml"

With Git: Add config/database.yml to the .gitignore file or with git-extra git ignore config/database.yml


... and now, some examples:

SQLite

adapter: sqlite3
database: db/db_dev_db.sqlite3
pool: 5
timeout: 5000

MYSQL

adapter: mysql
database: my_db
hostname: 127.0.0.1
username: root
password: 
socket: /tmp/mysql.sock
pool: 5
timeout: 5000

MongoDB with MongoID (called mongoid.yml, but basically the same thing)

host: <%= ENV['MONGOID_HOST'] %>
port: <%= ENV['MONGOID_PORT'] %>
username: <%= ENV['MONGOID_USERNAME'] %>
password: <%= ENV['MONGOID_PASSWORD'] %>
database: <%= ENV['MONGOID_DATABASE'] %>
# slaves:
#   - host: slave1.local
#     port: 27018
#   - host: slave2.local
#     port: 27019

Sqlite in chrome

You might be able to make use of sql.js.

sql.js is a port of SQLite to JavaScript, by compiling the SQLite C code with Emscripten. no C bindings or node-gyp compilation here.

<script src='js/sql.js'></script>
<script>
    //Create the database
    var db = new SQL.Database();
    // Run a query without reading the results
    db.run("CREATE TABLE test (col1, col2);");
    // Insert two rows: (1,111) and (2,222)
    db.run("INSERT INTO test VALUES (?,?), (?,?)", [1,111,2,222]);

    // Prepare a statement
    var stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
    stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111}

    // Bind new values
    stmt.bind({$start:1, $end:2});
    while(stmt.step()) { //
        var row = stmt.getAsObject();
        // [...] do something with the row of result
    }
</script>

sql.js is a single JavaScript file and is about 1.5MiB in size currently. While this could be a problem in a web-page, the size is probably acceptable for an extension.

Generate PDF from HTML using pdfMake in Angularjs

this is what it worked for me I'm using html2pdf from an Angular2 app, so I made a reference to this function in the controller

var html2pdf = (function(html2canvas, jsPDF) {

declared in html2pdf.js.

So I added just after the import declarations in my angular-controller this declaration:

declare function html2pdf(html2canvas, jsPDF): any;

then, from a method of my angular controller I'm calling this function:

generate_pdf(){
    this.someService.loadContent().subscribe(
      pdfContent => {
        html2pdf(pdfContent, {
          margin:       1,
          filename:     'myfile.pdf',
          image:        { type: 'jpeg', quality: 0.98 },
          html2canvas:  { dpi: 192, letterRendering: true },
          jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
        });
      }
    );
  }

Hope it helps

How to set custom header in Volley Request

Looking for solution to this problem as well. see something here: http://developer.android.com/training/volley/request.html

is it a good idea to directly use ImageRequest instead of ImageLoader? Seems ImageLoader uses it internally anyway. Does it miss anything important other than ImageLoader's cache support?

ImageView mImageView;
String url = "http://i.imgur.com/7spzG.png";
mImageView = (ImageView) findViewById(R.id.myImage);
...

// Retrieves an image specified by the URL, displays it in the UI.
mRequestQueue = Volley.newRequestQueue(context);;
ImageRequest request = new ImageRequest(url,
  new Response.Listener() {
      @Override
      public void onResponse(Bitmap bitmap) {
          mImageView.setImageBitmap(bitmap);
      }
  }, 0, 0, null,
  new Response.ErrorListener() {
      public void onErrorResponse(VolleyError error) {
          mImageView.setImageResource(R.drawable.image_load_error);
      }
  })   {
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new Map<String, String>();
        params.put("User-Agent", "one");
        params.put("header22", "two");

        return params;
    };
mRequestQueue.add(request);

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

It's been a while, but last time I had something similar:

ROLLBACK TRAN

or trying to

COMMIT

what had allready been done free'd everything up so I was able to clear things out and start again.

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

My picture size is only 14Kb but the problem is that the designer gave me 1011px x 1819px (resolution too high hence causing the InflateException)

How to get first character of string?

Example of all method

First : string.charAt(index)

Return the caract at the index index

_x000D_
_x000D_
var str = "Stack overflow";_x000D_
_x000D_
console.log(str.charAt(0));
_x000D_
_x000D_
_x000D_

Second : string.substring(start,length);

Return the substring in the string who start at the index start and stop after the length length

Here you only want the first caract so : start = 0 and length = 1

_x000D_
_x000D_
var str = "Stack overflow";_x000D_
_x000D_
console.log(str.substring(0,1));
_x000D_
_x000D_
_x000D_

Alternative : string[index]

A string is an array of caract. So you can get the first caract like the first cell of an array.

Return the caract at the index index of the string

_x000D_
_x000D_
var str = "Stack overflow";_x000D_
_x000D_
console.log(str[0]);
_x000D_
_x000D_
_x000D_

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

In my case just run the command and worked like charm.

php artisan route:clear

Python calling method in class

Let's say you have a shiny Foo class. Well you have 3 options:

1) You want to use the method (or attribute) of a class inside the definition of that class:

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class:

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

The process cannot access the file because it is being used by another process (File is created but contains nothing)

Try This

string path = @"c:\mytext.txt";

if (File.Exists(path))
{
    File.Delete(path);
}

{ // Consider File Operation 1
    FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
    StreamWriter str = new StreamWriter(fs);
    str.BaseStream.Seek(0, SeekOrigin.End);
    str.Write("mytext.txt.........................");
    str.WriteLine(DateTime.Now.ToLongTimeString() + " " + 
                  DateTime.Now.ToLongDateString());
    string addtext = "this line is added" + Environment.NewLine;
    str.Flush();
    str.Close();
    fs.Close();
    // Close the Stream then Individually you can access the file.
}

File.AppendAllText(path, addtext);  // File Operation 2

string readtext = File.ReadAllText(path); // File Operation 3

Console.WriteLine(readtext);

In every File Operation, The File will be Opened and must be Closed prior Opened. Like wise in the Operation 1 you must Close the File Stream for the Further Operations.

curl Failed to connect to localhost port 80

Since you have a ::1 localhost line in your hosts file, it would seem that curl is attempting to use IPv6 to contact your local web server.

Since the web server is not listening on IPv6, the connection fails.

You could try to use the --ipv4 option to curl, which should force an IPv4 connection when both are available.

Calculate MD5 checksum for a file

And if you need to calculate the MD5 to see whether it matches the MD5 of an Azure blob, then this SO question and answer might be helpful: MD5 hash of blob uploaded on Azure doesnt match with same file on local machine

WebAPI Multiple Put/Post parameters

We passed Json object by HttpPost method, and parse it in dynamic object. it works fine. this is sample code:

webapi:

[HttpPost]
public string DoJson2(dynamic data)
{
   //whole:
   var c = JsonConvert.DeserializeObject<YourObjectTypeHere>(data.ToString()); 

   //or 
   var c1 = JsonConvert.DeserializeObject< ComplexObject1 >(data.c1.ToString());

   var c2 = JsonConvert.DeserializeObject< ComplexObject2 >(data.c2.ToString());

   string appName = data.AppName;
   int appInstanceID = data.AppInstanceID;
   string processGUID = data.ProcessGUID;
   int userID = data.UserID;
   string userName = data.UserName;
   var performer = JsonConvert.DeserializeObject< NextActivityPerformers >(data.NextActivityPerformers.ToString());

   ...
}

The complex object type could be object, array and dictionary.

ajaxPost:
...
Content-Type: application/json,
data: {"AppName":"SamplePrice",
       "AppInstanceID":"100",
       "ProcessGUID":"072af8c3-482a-4b1c??-890b-685ce2fcc75d",
       "UserID":"20",
       "UserName":"Jack",
       "NextActivityPerformers":{
           "39??c71004-d822-4c15-9ff2-94ca1068d745":[{
                 "UserID":10,
                 "UserName":"Smith"
           }]
       }}
...

How to jump back to NERDTree from file in tab?

All The Shortcuts And Functionality is At

press CTRL-?

How to Bulk Insert from XLSX file extension?

Create a linked server to your document

http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm

Then use ordinary INSERT or SELECT INTO. If you want to get fancy, you can use ADO.NET's SqlBulkCopy, which takes just about any data source that you can get a DataReader from and is pretty quick on insert, although the reading of the data won't be esp fast.

You could also take the time to transform an excel spreadsheet into a text delimited file or other bcp supported format and then use BCP.

How can a web application send push notifications to iOS devices?

No, there is no way for an webapp to receive push notification. What you could do is to wrap your webapp into a native app which has push notifications.

What does the C++ standard state the size of int, long type to be?

As you mentioned - it largely depends upon the compiler and the platform. For this, check the ANSI standard, http://home.att.net/~jackklein/c/inttypes.html

Here is the one for the Microsoft compiler: Data Type Ranges.

removeEventListener on anonymous functions in JavaScript

I know this is a fairly old thread, but thought I might put in my two cents for those who find it useful.

The script (apologies about the uncreative method names):

window.Listener = {
    _Active: [],
    remove: function(attached, on, callback, capture){
        for(var i = 0; i < this._Active.length; i++){
            var current = this._Active[i];
            if(current[0] === attached && current[1] === on && current[2] === callback){
                attached.removeEventListener(on, callback, (capture || false));
                return this._Active.splice(i, 1);
            }
        }
    }, removeAtIndex(i){
        if(this._Active[i]){
            var remove = this._Active[i];
            var attached = remove[0], on = remove[1], callback = remove[2];
            attached.removeEventListener(on, callback, false);
            return this._Active.splice(i, 1);
        }
    }, purge: function(){
        for(var i = 0; i < this._Active.length; i++){
            var current = this._Active[i];
            current[0].removeEventListener(current[1], current[2]);
            this._Active.splice(i, 1);
        }
    }, declare: function(attached, on, callback, capture){
        attached.addEventListener(on, callback, (capture || false));
        if(this._Active.push([attached, on, callback])){
            return this._Active.length - 1;
        }
    }
};

And you can use it like so:

// declare a new onclick listener attached to the document
var clickListener = Listener.declare(document, "click" function(e){
    // on click, remove the listener and log the clicked element
    console.log(e.target);
    Listener.removeAtIndex(clickListener);
});

// completely remove all active listeners 
// (at least, ones declared via the Listener object)
Listener.purge();

// works exactly like removeEventListener
Listener.remove(element, on, callback);

How can I make PHP display the error instead of giving me 500 Internal Server Error

Use "php -l <filename>" (that's an 'L') from the command line to output the syntax error that could be causing PHP to throw the status 500 error. It'll output something like:

PHP Parse error: syntax error, unexpected '}' in <filename> on line 18

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

SQL Server query to find all permissions/access for all users in a database

The GetPermissions Stored Procedure above is good however it uses Sp_msforeachdb which means that it will break if your SQL Instance has any databases names that include spaces or dashes and other non-best-practices characters. I have created a version that avoids the use of Sp_msforeachdb and also includes two columns that indicate 1 - if the Login is a sysadmin login (IsSysAdminLogin) and 2 - if the login is an orphan user (IsEmptyRow).

USE [master] ;
GO
IF EXISTS
(
    SELECT * FROM sys.objects
    WHERE object_id = OBJECT_ID(N'dbo.uspGetPermissionsOfAllLogins_DBsOnColumns')
    AND [type] in (N'P',N'PC')
)
BEGIN
    DROP PROCEDURE dbo.uspGetPermissionsOfAllLogins_DBsOnColumns ;
END
GO
CREATE PROCEDURE dbo.uspGetPermissionsOfAllLogins_DBsOnColumns
AS
SET NOCOUNT ON
;
BEGIN TRY
    IF EXISTS
    (
        SELECT * FROM tempdb.dbo.sysobjects
        WHERE id = object_id(N'[tempdb].dbo.[#permission]')
    )
    DROP TABLE #permission
    ;
    IF EXISTS
    (
        SELECT * FROM tempdb.dbo.sysobjects
        WHERE id = object_id(N'[tempdb].dbo.[#userroles_kk]')
    )
    DROP TABLE #userroles_kk
    ;
    IF EXISTS
    (
        SELECT * FROM tempdb.dbo.sysobjects
        WHERE id = object_id(N'[tempdb].dbo.[#rolemember_kk]')
    )
    DROP TABLE #rolemember_kk
    ;
    IF EXISTS
    (
        SELECT * FROM tempdb.dbo.sysobjects
        WHERE id = object_id(N'[tempdb].dbo.[##db_name]')
    )
    DROP TABLE ##db_name
    ;
    DECLARE
    @db_name VARCHAR(255)
    ,@sql_text VARCHAR(MAX) 
    ;
    SET @sql_text =
    'CREATE TABLE ##db_name
    (
        LoginUserName VARCHAR(MAX)
        ,' 
    ;
    DECLARE cursDBs CURSOR FOR 
        SELECT [name]
        FROM sys.databases
        ORDER BY [name]
    ;
    OPEN cursDBs 
    ;
    FETCH NEXT FROM cursDBs INTO @db_name 
    WHILE @@FETCH_STATUS = 0 
        BEGIN 
                SET @sql_text =
        @sql_text + QUOTENAME(@db_name) + ' VARCHAR(MAX)
        ,' 
                FETCH NEXT FROM cursDBs INTO @db_name 
        END 
    CLOSE cursDBs 
    ;
    SET @sql_text =
        @sql_text + 'IsSysAdminLogin CHAR(1)
        ,IsEmptyRow CHAR(1)
    )' 

    --PRINT @sql_text
    EXEC (@sql_text)
    ;
    DEALLOCATE cursDBs 
    ;
    DECLARE
    @RoleName VARCHAR(255) 
    ,@UserName VARCHAR(255) 
    ;
    CREATE TABLE #permission 
    (
     LoginUserName VARCHAR(255)
     ,databasename VARCHAR(255)
     ,[role] VARCHAR(255)
    ) 
    ;
    DECLARE cursSysSrvPrinName CURSOR FOR 
        SELECT [name]
        FROM sys.server_principals 
        WHERE
        [type] IN ( 'S', 'U', 'G' )
        AND principal_id > 4
        AND [name] NOT LIKE '##%'
        ORDER BY [name]
    ;
    OPEN cursSysSrvPrinName
    ;
    FETCH NEXT FROM cursSysSrvPrinName INTO @UserName 
    WHILE @@FETCH_STATUS = 0 
    BEGIN 
        CREATE TABLE #userroles_kk 
        ( 
             databasename VARCHAR(255)
             ,[role] VARCHAR(255)
        ) 
        ;
        CREATE TABLE #rolemember_kk 
        ( 
             dbrole VARCHAR(255)
             ,membername VARCHAR(255)
             ,membersid VARBINARY(2048)
        ) 
        ;
        DECLARE cursDatabases CURSOR FAST_FORWARD LOCAL FOR
        SELECT [name]
        FROM sys.databases
        ORDER BY [name]
        ;
        OPEN cursDatabases
        ;
        DECLARE 
        @DBN VARCHAR(255)
        ,@sqlText NVARCHAR(4000)
        ;
        FETCH NEXT FROM cursDatabases INTO @DBN
        WHILE @@FETCH_STATUS = 0
        BEGIN
            SET @sqlText =
    N'USE ' + QUOTENAME(@DBN) + ';
    TRUNCATE TABLE #RoleMember_kk 
    INSERT INTO #RoleMember_kk 
    EXEC sp_helprolemember 
    INSERT INTO #UserRoles_kk
    (DatabaseName,[Role])
    SELECT db_name(),dbRole
    FROM #RoleMember_kk
    WHERE MemberName = ''' + @UserName + '''
    '

            --PRINT @sqlText ;
            EXEC sp_executesql @sqlText ;
        FETCH NEXT FROM cursDatabases INTO @DBN
        END
        CLOSE cursDatabases
        ;
        DEALLOCATE cursDatabases
        ;
        INSERT INTO #permission 
        SELECT
        @UserName 'user'
        ,b.name
        ,u.[role]
        FROM
        sys.sysdatabases b
        LEFT JOIN
        #userroles_kk u 
            ON QUOTENAME(u.databasename) = QUOTENAME(b.name)
        ORDER  BY 1 
        ;
        DROP TABLE #userroles_kk
        ; 
        DROP TABLE #rolemember_kk
        ;
        FETCH NEXT FROM cursSysSrvPrinName INTO @UserName 
    END 
    CLOSE cursSysSrvPrinName 
    ;
    DEALLOCATE cursSysSrvPrinName 
    ;
    TRUNCATE TABLE ##db_name 
    ;
    DECLARE
    @d1 VARCHAR(MAX)
    ,@d2 VARCHAR(MAX)
    ,@d3 VARCHAR(MAX)
    ,@ss VARCHAR(MAX)
    ;
    DECLARE cursPermisTable CURSOR FOR
        SELECT * FROM #permission 
        ORDER BY 2 DESC 
    ;
    OPEN cursPermisTable
    ;
    FETCH NEXT FROM cursPermisTable INTO @d1,@d2,@d3
    WHILE @@FETCH_STATUS = 0 
    BEGIN 
        IF NOT EXISTS
        (
            SELECT 1 FROM ##db_name WHERE LoginUserName = @d1
        )
        BEGIN 
            SET @ss =
            'INSERT INTO ##db_name(LoginUserName) VALUES (''' + @d1 + ''')' 
            EXEC (@ss) 
            ;
            SET @ss =
            'UPDATE ##db_name SET ' + @d2 + ' = ''' + @d3 + ''' WHERE LoginUserName = ''' + @d1 + '''' 
            EXEC (@ss)
            ;
        END 
        ELSE 
        BEGIN 
            DECLARE
            @var NVARCHAR(MAX)
            ,@ParmDefinition NVARCHAR(MAX)
            ,@var1 NVARCHAR(MAX)
            ;
            SET @var =
            N'SELECT @var1 = ' + QUOTENAME(@d2) + ' FROM ##db_name WHERE LoginUserName = ''' + @d1 + ''''
            ; 
            SET @ParmDefinition =
            N'@var1 NVARCHAR(600) OUTPUT '
            ; 
            EXECUTE Sp_executesql @var,@ParmDefinition,@var1 = @var1 OUTPUT
            ;
            SET @var1 =
            ISNULL(@var1, ' ')
            ;
            SET @var =
            '  UPDATE ##db_name SET ' + @d2 + '=''' + @var1 + ' ' + @d3 + ''' WHERE LoginUserName = ''' + @d1 + '''  '
            ;
            EXEC (@var)
            ;
        END
        FETCH NEXT FROM cursPermisTable INTO @d1,@d2,@d3
    END 
    CLOSE cursPermisTable
    ;
    DEALLOCATE cursPermisTable 
    ;
    UPDATE ##db_name SET
    IsSysAdminLogin = 'Y'
    FROM
    ##db_name TT
    INNER JOIN
    dbo.syslogins SL
        ON TT.LoginUserName = SL.[name]
    WHERE
    SL.sysadmin = 1
    ;
    DECLARE cursDNamesAsColumns CURSOR FAST_FORWARD LOCAL FOR
    SELECT [name]
    FROM tempdb.sys.columns
    WHERE
    OBJECT_ID = OBJECT_ID('tempdb..##db_name')
    AND [name] NOT IN ('LoginUserName','IsEmptyRow')
    ORDER BY [name]
    ;
    OPEN cursDNamesAsColumns
    ;
    DECLARE 
    @ColN VARCHAR(255)
    ,@tSQLText NVARCHAR(4000)
    ;
    FETCH NEXT FROM cursDNamesAsColumns INTO @ColN
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @tSQLText =
N'UPDATE ##db_name SET
IsEmptyRow = ''N''
WHERE IsEmptyRow IS NULL
AND ' + QUOTENAME(@ColN) + ' IS NOT NULL
;
'

        --PRINT @tSQLText ;
        EXEC sp_executesql @tSQLText ;
    FETCH NEXT FROM cursDNamesAsColumns INTO @ColN
    END
    CLOSE cursDNamesAsColumns
    ;
    DEALLOCATE cursDNamesAsColumns
    ;
    UPDATE ##db_name SET
    IsEmptyRow = 'Y'
    WHERE IsEmptyRow IS NULL
    ;
    UPDATE ##db_name SET
    IsSysAdminLogin = 'N'
    FROM
    ##db_name TT
    INNER JOIN
    dbo.syslogins SL
        ON TT.LoginUserName = SL.[name]
    WHERE
    SL.sysadmin = 0
    ;
    SELECT * FROM ##db_name
    ;
    DROP TABLE ##db_name
    ;
    DROP TABLE #permission
    ;
END TRY
BEGIN CATCH
    DECLARE
    @cursDBs_Status INT
    ,@cursSysSrvPrinName_Status INT
    ,@cursDatabases_Status INT
    ,@cursPermisTable_Status INT
    ,@cursDNamesAsColumns_Status INT
    ;
    SELECT
    @cursDBs_Status = CURSOR_STATUS('GLOBAL','cursDBs')
    ,@cursSysSrvPrinName_Status = CURSOR_STATUS('GLOBAL','cursSysSrvPrinName')
    ,@cursDatabases_Status = CURSOR_STATUS('GLOBAL','cursDatabases')
    ,@cursPermisTable_Status = CURSOR_STATUS('GLOBAL','cursPermisTable')
    ,@cursDNamesAsColumns_Status = CURSOR_STATUS('GLOBAL','cursPermisTable')
    ;
    IF @cursDBs_Status > -2
        BEGIN
            CLOSE cursDBs ;
            DEALLOCATE cursDBs ;
        END
    IF @cursSysSrvPrinName_Status > -2
        BEGIN
            CLOSE cursSysSrvPrinName ;
            DEALLOCATE cursSysSrvPrinName ;
        END
    IF @cursDatabases_Status > -2
        BEGIN
            CLOSE cursDatabases ;
            DEALLOCATE cursDatabases ;
        END
    IF @cursPermisTable_Status > -2
        BEGIN
            CLOSE cursPermisTable ;
            DEALLOCATE cursPermisTable ;
        END
    IF @cursDNamesAsColumns_Status > -2
        BEGIN
            CLOSE cursDNamesAsColumns ;
            DEALLOCATE cursDNamesAsColumns ;
        END
    SELECT ErrorNum = ERROR_NUMBER(),ErrorMsg = ERROR_MESSAGE() ;
END CATCH
GO
/*
EXEC [master].dbo.uspGetPermissionsOfAllLogins_DBsOnColumns ;
*/

Is it possible to read the value of a annotation in java?

In common case you have private access for fields, so you CAN'T use getFields in reflection. Instead of this you should use getDeclaredFields

So, firstly, you should be aware if your Column annotation has the runtime retention:

@Retention(RetentionPolicy.RUNTIME)
@interface Column {
}

After that you can do something like this:

for (Field f: MyClass.class.getDeclaredFields()) {
   Column column = f.getAnnotation(Column.class);
       // ...
}

Obviously, you would like to do something with field - set new value using annotation value:

Column annotation = f.getAnnotation(Column.class);
if (annotation != null) {
    new PropertyDescriptor(f.getName(), Column.class).getWriteMethod().invoke(
        object,
        myCoolProcessing(
            annotation.value()
        )
    );
}

So, full code can be looked like this:

for (Field f : MyClass.class.getDeclaredFields()) {
    Column annotation = f.getAnnotation(Column.class);
    if (annotation != null)
        new PropertyDescriptor(f.getName(), Column.class).getWriteMethod().invoke(
                object,
                myCoolProcessing(
                        annotation.value()
                )
        );
}

Django request get parameters

You may also use:

request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137] 
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]

Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).

What is the difference between sscanf or atoi to convert a string to an integer?

If user enters 34abc and you pass them to atoi it will return 34. If you want to validate the value entered then you have to use isdigit on the entered string iteratively

Javascript Iframe innerHTML

You can use the contentDocument or contentWindow property for that purpose. Here is the sample code.

function gethtml() {
  const x = document.getElementById("myframe")
  const y = x.contentWindow || x.contentDocument
  const z = y.document ? y.document : y
  alert(z.body.innerHTML)
}

here, myframe is the id of your iframe. Note: You can't extract the content out of an iframe from a src outside you domain.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

I got this error because I did not have the correct line in my build.gradle. I am using the org.apache.http.legacy.jar library, which requires this:

android{
   useLibrary 'org.apache.http.legacy'

   ...
}

So check that you have everything in your gradle file that is required.

Attributes / member variables in interfaces?

Fields in interfaces are implicitly public static final. (Also methods are implicitly public, so you can drop the public keyword.) Even if you use an abstract class instead of an interface, I strongly suggest making all non-constant (public static final of a primitive or immutable object reference) private. More generally "prefer composition to inheritance" - a Tile is-not-a Rectangle (of course, you can play word games with "is-a" and "has-a").

Python: How to get values of an array at certain index positions?

The one liner "no imports" version

a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [1,5,7]
[ a[i] for i in ind_pos ]

How to schedule a periodic task in Java?

If you want to stick with java.util.Timer, you can use it to schedule at large time intervals. You simply pass in the period you are shooting for. Check the documentation here.

How to align an image dead center with bootstrap

The correct way of doing this is

<div class="row text-center">
  <img ...>
</div>

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

This explains better: Postman docs

Request body

While constructing requests, you would be dealing with the request body editor a lot. Postman lets you send almost any kind of HTTP request (If you can't send something, let us know!). The body editor is divided into 4 areas and has different controls depending on the body type.

form-data

multipart/form-data is the default encoding a web form uses to transfer data. This simulates filling a form on a website, and submitting it. The form-data editor lets you set key/value pairs (using the key-value editor) for your data. You can attach files to a key as well. Do note that due to restrictions of the HTML5 spec, files are not stored in history or collections. You would have to select the file again at the time of sending a request.

urlencoded

This encoding is the same as the one used in URL parameters. You just need to enter key/value pairs and Postman will encode the keys and values properly. Note that you can not upload files through this encoding mode. There might be some confusion between form-data and urlencoded so make sure to check with your API first.

raw

A raw request can contain anything. Postman doesn't touch the string entered in the raw editor except replacing environment variables. Whatever you put in the text area gets sent with the request. The raw editor lets you set the formatting type along with the correct header that you should send with the raw body. You can set the Content-Type header manually as well. Normally, you would be sending XML or JSON data here.

binary

binary data allows you to send things which you can not enter in Postman. For example, image, audio or video files. You can send text files as well. As mentioned earlier in the form-data section, you would have to reattach a file if you are loading a request through the history or the collection.

UPDATE

As pointed out by VKK, the WHATWG spec say urlencoded is the default encoding type for forms.

The invalid value default for these attributes is the application/x-www-form-urlencoded state. The missing value default for the enctype attribute is also the application/x-www-form-urlencoded state.

Vim: How to insert in visual block mode?

Try this

After selecting a block of text, press Shift+i or capital I.

Lowercase i will not work.

Then type the things you want and finally to apply it to all lines, press Esc twice.




If this doesn't work...

Check if you have +visualextra enabled in your version of Vim.

You can do this by typing in :ver and scrolling through the list of features. (You might want to copy and paste it into a buffer and do incremental search because the format is odd.)

Enabling it is outside the scope of this question but I'm sure you can find it somewhere.