Programs & Examples On #Nsmutableurlrequest

NSMutableURLRequest is a subclass of NSURLRequest provided to aid developers who may find it more convenient to mutate a single request object for a series of URL load requests instead of creating an immutable NSURLRequest for each load.

Creating NSData from NSString in Swift

To create not optional data I recommend using it:

let key = "1234567"
let keyData = Data(key.utf8)

Virtualbox "port forward" from Guest to Host

Network communication Host -> Guest

Connect to the Guest and find out the ip address:

ifconfig 

example of result (ip address is 10.0.2.15):

eth0      Link encap:Ethernet  HWaddr 08:00:27:AE:36:99
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0

Go to Vbox instance window -> Menu -> Network adapters:

  • adapter should be NAT
  • click on "port forwarding"
  • insert new record (+ icon)
    • for host ip enter 127.0.0.1, and for guest ip address you got from prev. step (in my case it is 10.0.2.15)
    • in your case port is 8000 - put it on both, but you can change host port if you prefer

Go to host system and try it in browser:

http://127.0.0.1:8000

or your network ip address (find out on the host machine by running: ipconfig).

Network communication Guest -> Host

In this case port forwarding is not needed, the communication goes over the LAN back to the host.

On the host machine - find out your netw ip address:

ipconfig

example of result:

IP Address. . . . . . . . . . . . : 192.168.5.1

On the guest machine you can communicate directly with the host, e.g. check it with ping:

# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...

Firewall issues?

@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):

sudo ufw allow 8000 

Loading basic HTML in Node.js

use ejs instead of jade

npm install ejs

app.js

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

./routes/index.js

exports.index = function(req, res){
res.render('index', { title: 'ejs' });};

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

you can use the download attribute on an a tag ...

<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>

see more: https://developer.mozilla.org/en/HTML/element/a#attr-download

Please explain the exec() function and its family

The exec family of functions make your process execute a different program, replacing the old program it was running. I.e., if you call

execl("/bin/ls", "ls", NULL);

then the ls program is executed with the process id, current working dir and user/group (access rights) of the process that called execl. Afterwards, the original program is not running anymore.

To start a new process, the fork system call is used. To execute a program without replacing the original, you need to fork, then exec.

Foreign Key to multiple tables

Another approach is to create an association table that contains columns for each potential resource type. In your example, each of the two existing owner types has their own table (which means you have something to reference). If this will always be the case you can have something like this:

CREATE TABLE dbo.Group
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)  

CREATE TABLE dbo.User
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL,
    Owner_ID int NOT NULL,
    Subject varchar(50) NULL
)

CREATE TABLE dbo.Owner
(
    ID int NOT NULL,
    User_ID int NULL,
    Group_ID int NULL,
    {{AdditionalEntity_ID}} int NOT NULL
)

With this solution, you would continue to add new columns as you add new entities to the database and you would delete and recreate the foreign key constraint pattern shown by @Nathan Skerl. This solution is very similar to @Nathan Skerl but looks different (up to preference).

If you are not going to have a new Table for each new Owner type then maybe it would be good to include an owner_type instead of a foreign key column for each potential Owner:

CREATE TABLE dbo.Group
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)  

CREATE TABLE dbo.User
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL,
    Owner_ID int NOT NULL,
    Owner_Type string NOT NULL, -- In our example, this would be "User" or "Group"
    Subject varchar(50) NULL
)

With the above method, you could add as many Owner Types as you want. Owner_ID would not have a foreign key constraint but would be used as a reference to the other tables. The downside is that you would have to look at the table to see what the owner types there are since it isn't immediately obvious based upon the schema. I would only suggest this if you don't know the owner types beforehand and they won't be linking to other tables. If you do know the owner types beforehand, I would go with a solution like @Nathan Skerl.

Sorry if I got some SQL wrong, I just threw this together.

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

This worked perfectly for me without css. I think css would put some icing on the cake though.

    <form>
        <label for="First Name" >First Name:</label>
            <input type="text" name="username" size="15" maxlength="30" />
        <label for="Last Name" >Last Name:</label>
            <input type="text" name="username" size="15" maxlength="30" />
    </form>

Concat all strings inside a List<string> using LINQ

You can simply use:

List<string> items = new List<string>() { "foo", "boo", "john", "doe" };

Console.WriteLine(string.Join(",", items));

Happy coding!

Which is a better way to check if an array has more than one element?

isset() only checks if a variable is set.. Has got nothing to do with size or what the array contains

What does "javax.naming.NoInitialContextException" mean?

It means that there is no initial context :)

But seriously folks, JNDI (javax.naming) is all about looking up objects or resources from some directory or provider. To look something up, you need somewhere to look (this is the InitialContext). NoInitialContextException means "I want to find the telephone number for John Smith, but I have no phonebook to look in".

An InitialContext can be created in any number of ways. It can be done manually, for instance creating a connection to an LDAP server. It can also be set up by an application server inside which you run your application. In this case, the container (application server) already provides you with a "phonebook", through which you can look up anything the application server makes available. This is often configurable and a common way of moving this type of configuration from the application implementation to the container, where it can be shared across all applications in the server.

UPDATE: from the code snippet you post it looks like you are trying to run code stand-alone that is meant to be run in an application server. In this case, the code attempting to get a connection to a database from the "phonebook". This is one of the resources that is often configured in the application server container. So, rather than having to manage configuration and connections to the database in your code, you can configure it in your application server and simple ask for a connection (using JNDI) in your code.

How to convert color code into media.brush?

Sorry to be so late to the party! I came across a similar issue, in WinRT. I'm not sure whether you're using WPF or WinRT, but they do differ in some ways (some better than others). Hopefully this will help people across the board, whichever situation they're in.

You could always use the code from the converter class I created to re-use and do in your C# code-behind, or wherever you're using it, to be honest:

I made it with the intention that a 6-digit (RGB), or an 8-digit (ARGB) Hex value could be used either way.

So I created a converter class:

public class StringToSolidColorBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var hexString = (value as string).Replace("#", "");

        if (string.IsNullOrWhiteSpace(hexString)) throw new FormatException();
        if (hexString.Length != 6 || hexString.Length != 8) throw new FormatException();

        try
        {
            var a = hexString.Length == 8 ? hexString.Substring(0, 2) : "255";
            var r = hexString.Length == 8 ? hexString.Substring(2, 2) : hexString.Substring(0, 2);
            var g = hexString.Length == 8 ? hexString.Substring(4, 2) : hexString.Substring(2, 2);
            var b = hexString.Length == 8 ? hexString.Substring(6, 2) : hexString.Substring(4, 2);

            return new SolidColorBrush(ColorHelper.FromArgb(
                byte.Parse(a, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(r, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(g, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(b, System.Globalization.NumberStyles.HexNumber)));
        }
        catch
        {
            throw new FormatException();
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

Added it into my App.xaml:

<ResourceDictionary>
    ...
    <converters:StringToSolidColorBrushConverter x:Key="StringToSolidColorBrushConverter" />
    ...
</ResourceDictionary>

And used it in my View's Xaml:

<Grid>
    <Rectangle Fill="{Binding RectangleColour,
               Converter={StaticResource StringToSolidColorBrushConverter}}"
               Height="20" Width="20" />
</Grid>

Works a charm!

Side note... Unfortunately, WinRT hasn't got the System.Windows.Media.BrushConverter that H.B. suggested; so I needed another way, otherwise I would have made a VM property that returned a SolidColorBrush (or similar) from the RectangleColour string property.

Object of class mysqli_result could not be converted to string in

Try with:

$row = mysqli_fetch_assoc($result);
echo "my result <a href='data/" . htmlentities($row['classtype'], ENT_QUOTES, 'UTF-8') . ".php'>My account</a>";

How do I see what character set a MySQL database / table / column is?

For databases:

Just use these commands:

USE db_name;
SELECT @@character_set_database;
-- or:
-- SELECT @@collation_database;

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

Android java.lang.NoClassDefFoundError

Edit the build path in this order, this worked for me.

Make sure the /gen is before /src

enter image description here

"Cloning" row or column vectors

I think using the broadcast in numpy is the best, and faster

I did a compare as following

import numpy as np
b = np.random.randn(1000)
In [105]: %timeit c = np.tile(b[:, newaxis], (1,100))
1000 loops, best of 3: 354 µs per loop

In [106]: %timeit c = np.repeat(b[:, newaxis], 100, axis=1)
1000 loops, best of 3: 347 µs per loop

In [107]: %timeit c = np.array([b,]*100).transpose()
100 loops, best of 3: 5.56 ms per loop

about 15 times faster using broadcast

Make the size of a heatmap bigger with seaborn

You could alter the figsize by passing a tuple showing the width, height parameters you would like to keep.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)

EDIT

I remember answering a similar question of yours where you had to set the index as TIMESTAMP. So, you could then do something like below:

df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)

For the head of the dataframe you posted, the plot would look like:

enter image description here

Mockito test a void method throws an exception

The parentheses are poorly placed.

You need to use:

doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
                                          ^

and NOT use:

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
                                                                   ^

This is explained in the documentation

How to provide shadow to Button

If you are targeting pre-Lollipop devices, you can use Shadow-Layout, since it easy and you can use it in different kind of layouts.


Add shadow-layout to your Gradle file:

dependencies {
    compile 'com.github.dmytrodanylyk.shadow-layout:library:1.0.1'
}


At the top the xml layout where you have your button, add to the top:

xmlns:app="http://schemas.android.com/apk/res-auto"

it will make available the custom attributes.


Then you put a shadow layout around you Button:

<com.dd.ShadowLayout
        android:layout_marginTop="16dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:sl_shadowRadius="4dp"
        app:sl_shadowColor="#AA000000"
        app:sl_dx="0dp"
        app:sl_dy="0dp"
        app:sl_cornerRadius="56dp"> 

       <YourButton
          .... />

</com.dd.ShadowLayout>

You can then tweak the app: settings to match your required shadow.

Hope it helps.

ExtJs Gridpanel store refresh

Try refreshing the view:

Ext.getCmp('yourGridId').getView().refresh();

EOFError: EOF when reading a line

width, height = map(int, input().split())
def rectanglePerimeter(width, height):
   return ((width + height)*2)
print(rectanglePerimeter(width, height))

Running it like this produces:

% echo "1 2" | test.py
6

I suspect IDLE is simply passing a single string to your script. The first input() is slurping the entire string. Notice what happens if you put some print statements in after the calls to input():

width = input()
print(width)
height = input()
print(height)

Running echo "1 2" | test.py produces

1 2
Traceback (most recent call last):
  File "/home/unutbu/pybin/test.py", line 5, in <module>
    height = input()
EOFError: EOF when reading a line

Notice the first print statement prints the entire string '1 2'. The second call to input() raises the EOFError (end-of-file error).

So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input() once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what

width, height = map(int, input().split())

does.

Note, there are other ways to pass input to your program. If you had run test.py in a terminal, then you could have typed 1 and 2 separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1 and 2 programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with

test.py 1 2

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

In HTML, elements containing nothing but normal whitespace characters are considered empty. A paragraph that contains just a normal space character will have zero height. A non-breaking space is a special kind of whitespace character that isn't considered to be insignificant, so it can be used as content for a non-empty paragraph.

Even if you consider CSS margins on paragraphs, since an "empty" paragraph has zero height, its vertical margins will collapse. This causes it to have no height and no margins, making it appear as if it were never there at all.

how do I strip white space when grabbing text with jQuery?

Use the replace function in js:

var emailAdd = $(this).text().replace(/ /g,'');

That will remove all the spaces

If you want to remove the leading and trailing whitespace only, use the jQuery $.trim method :

var emailAdd = $.trim($(this).text());

System.Security.SecurityException when writing to Event Log

I had this issue when running an app within VS. All I had to do was run the program as Administrator once, then I could run from within VS.

To run as Administrator, just navigate to your debug folder in windows explorer. Right-click on the program and choose Run as administrator.

How to interpolate variables in strings in JavaScript, without concatenation?

var hello = "foo";

var my_string ="I pity the";

console.log(my_string, hello)

How to get current local date and time in Kotlin

You can get current year, month, day etc from a calendar instance

val c = Calendar.getInstance()

val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)

val hour = c.get(Calendar.HOUR_OF_DAY)
val minute = c.get(Calendar.MINUTE)

If you need it as a LocalDateTime, simply create it by using the parameters you got above

val myLdt = LocalDateTime.of(year, month, day, ... )

C - function inside struct

It can't be done directly, but you can emulate the same thing using function pointers and explicitly passing the "this" parameter:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;

        pno (*AddClient)(client_t *);    
};

pno client_t_AddClient(client_t *self) { /* code */ }

int main()
{

    client_t client;
    client.AddClient = client_t_AddClient; // probably really done in some init fn

    //code ..

    client.AddClient(&client);

}

It turns out that doing this, however, doesn't really buy you an awful lot. As such, you won't see many C APIs implemented in this style, since you may as well just call your external function and pass the instance.

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

(1) check the port is in use or not, kill that process

$ lsof -i:[port]

(2) another reason is the port is used by ipv6, solution:

edit /etc/sysctl.conf

add this to the file

net.ipv6.conf.all.disable_ipv6 = 1

then make it effect

$ sudo sysctl -p /etc/sysctl.conf

or just reboot

Create a GUID in Java

java.util.UUID.randomUUID();

How to open the terminal in Atom?

There are a number of Atom packages which give you access to the terminal from within Atom. Try a few out to find the best option for you.

Some recommendations which work in Ubuntu (with their primary keyboard shortcuts):

Open a terminal in Atom:

Edit: recommended plugin changed as terminal-plus is no longer maintained. Thanks for the head's-up, @MorganRodgers.

If you want to open a terminal panel in Atom, try atom-ide-terminal. Use the keyboard shortcut ctrl-` to open a new terminal instance.

Open an external terminal from Atom:

If you just want a shortcut to open your external terminal from within Atom, try atom-terminal (this is what I use). You can use ctrl-shift-t to open your external terminal in the current file's directory, or alt-shift-t to open the terminal in the project's root directory.

Datagridview: How to set a cell in editing mode?

Setting the CurrentCell and then calling BeginEdit(true) works well for me.

The following code shows an eventHandler for the KeyDown event that sets a cell to be editable.

My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            e.Handled = true;
            DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
            dataGridView1.CurrentCell = cell;
            dataGridView1.BeginEdit(true);               
        }
    }

If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.

Display / print all rows of a tibble (tbl_df)

You could also use

print(tbl_df(df), n=40)

or with the help of the pipe operator

df %>% tbl_df %>% print(n=40)

To print all rows specify tbl_df %>% print(n = Inf)

MySQL with Node.js

You can also try out a newer effort known as Node.js DB that aims to provide a common framework for several database engines. It is built with C++ so performance is guaranteed.

Specifically you could use its db-mysql driver for Node.js MySQL support.

laravel collection to array

Try this:

$comments_collection = $post->comments()->get()->toArray();

see this can help you
toArray() method in Collections

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

Here is a macro that I use for that purpose. It will generate a constructor from fields and properties that have a private setter.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Collections.Generic

Public Module Temp

    Sub AddConstructorFromFields()
        DTE.UndoContext.Open("Add constructor from fields")

        Dim classElement As CodeClass, index As Integer
        GetClassAndInsertionIndex(classElement, index)

        Dim constructor As CodeFunction
        constructor = classElement.AddFunction(classElement.Name, vsCMFunction.vsCMFunctionConstructor, vsCMTypeRef.vsCMTypeRefVoid, index, vsCMAccess.vsCMAccessPublic)

        Dim visitedNames As New Dictionary(Of String, String)
        Dim element As CodeElement, parameterPosition As Integer, isFirst As Boolean = True
        For Each element In classElement.Children
            Dim fieldType As String
            Dim fieldName As String
            Dim parameterName As String

            Select Case element.Kind
                Case vsCMElement.vsCMElementVariable
                    Dim field As CodeVariable = CType(element, CodeVariable)
                    fieldType = field.Type.AsString
                    fieldName = field.Name
                    parameterName = field.Name.TrimStart("_".ToCharArray())

                Case vsCMElement.vsCMElementProperty
                    Dim field As CodeProperty = CType(element, CodeProperty)
                    If field.Setter.Access = vsCMAccess.vsCMAccessPrivate Then
                        fieldType = field.Type.AsString
                        fieldName = field.Name
                        parameterName = field.Name.Substring(0, 1).ToLower() + field.Name.Substring(1)
                    End If
            End Select

            If Not String.IsNullOrEmpty(parameterName) And Not visitedNames.ContainsKey(parameterName) Then
                visitedNames.Add(parameterName, parameterName)

                constructor.AddParameter(parameterName, fieldType, parameterPosition)

                Dim endPoint As EditPoint
                endPoint = constructor.EndPoint.CreateEditPoint()
                endPoint.LineUp()
                endPoint.EndOfLine()

                If Not isFirst Then
                    endPoint.Insert(Environment.NewLine)
                Else
                    isFirst = False
                End If

                endPoint.Insert(String.Format(MemberAssignmentFormat(constructor.Language), fieldName, parameterName))

                parameterPosition = parameterPosition + 1
            End If
        Next

        DTE.UndoContext.Close()

        Try
            ' This command fails sometimes '
            DTE.ExecuteCommand("Edit.FormatDocument")
        Catch ex As Exception
        End Try
    End Sub
    Private Sub GetClassAndInsertionIndex(ByRef classElement As CodeClass, ByRef index As Integer, Optional ByVal useStartIndex As Boolean = False)
        Dim selection As TextSelection
        selection = CType(DTE.ActiveDocument.Selection, TextSelection)

        classElement = CType(selection.ActivePoint.CodeElement(vsCMElement.vsCMElementClass), CodeClass)

        Dim childElement As CodeElement
        index = 0
        For Each childElement In classElement.Children
            Dim childOffset As Integer
            childOffset = childElement.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes).AbsoluteCharOffset
            If selection.ActivePoint.AbsoluteCharOffset < childOffset Or useStartIndex Then
                Exit For
            End If
            index = index + 1
        Next
    End Sub
    Private ReadOnly Property MemberAssignmentFormat(ByVal language As String) As String
        Get
            Select Case language
                Case CodeModelLanguageConstants.vsCMLanguageCSharp
                    Return "this.{0} = {1};"

                Case CodeModelLanguageConstants.vsCMLanguageVB
                    Return "Me.{0} = {1}"

                Case Else
                    Return ""
            End Select
        End Get
    End Property
End Module

Limit the length of a string with AngularJS

In html its used along with limitTo filter provided by angular itself as below,

    <p> {{limitTo:30 | keepDots }} </p>

filter keepDots :

     App.filter('keepDots' , keepDots)

       function keepDots() {

        return function(input,scope) {
            if(!input) return;

             if(input.length > 20)
                return input+'...';
            else
                return input;

        }


    }

Force sidebar height 100% using CSS (with a sticky bottom image)?

I was facing the same problem as Jon. TheLibzter put me on the right track, but the image that has to stay at the bottom of the sidebar was not included. So I made some adjustments...

Important:

  • Positioning of the div which contains the sidebar and the content (#bodyLayout). This should be relative.
  • Positioning of the div that has to stay at the bottom of the sidbar (#sidebarBottomDiv). This should be absolute.
  • The width of the content + the width of the sidebar must be equal to the width of the page (#container)

Here's the css:

    #container
    {
        margin: auto;
        width: 940px;
    }
    #bodyLayout
    {
        position: relative;
        width: 100%;
        padding: 0;
    }
    #header
    {
        height: 95px;
        background-color: blue;
        color: white;
    }
    #sidebar
    {
        background-color: yellow;
    }
    #sidebarTopDiv
    {
        float: left;
        width: 245px;
        color: black;
    }
    #sidebarBottomDiv
    {
        position: absolute;
        float: left;
        bottom: 0;
        width: 245px;
        height: 100px;
        background-color: green;
        color: white;
    }
    #content
    {
        float: right;
        min-height: 250px;
        width: 695px;
        background-color: White;
    }
    #footer
    {
        width: 940px;
        height: 75px;
        background-color: red;
        color: white;
    }
    .clear
    {
        clear: both;
    }

And here's the html:

<div id="container">
    <div id="header">
        This is your header!
    </div>
    <div id="bodyLayout">
        <div id="sidebar">
            <div id="sidebarTopDiv">
                This is your sidebar!                   
            </div>
            <div id="content">                  
            This is your content!<br />
            The minimum height of the content is set to 250px so the div at the bottom of
            the sidebar will not overlap the top part of the sidebar.
            </div>
            <div id="sidebarBottomDiv">
                This is the div that will stay at the bottom of your footer!
            </div>
            <div class="clear" />
        </div>
    </div>
</div>
<div id="footer">
    This is your footer!
</div>

Error in Swift class: Property not initialized at super.init call

swift enforces you to initialise every member var before it is ever/might ever be used. Since it can't be sure what happens when it is supers turn, it errors out: better safe than sorry

How to debug a stored procedure in Toad?

Basic Steps to Debug a Procedure in Toad

  1. Load your Procedure in Toad Editor.
  2. Put debug point on the line where you want to debug.See the first screenshot.
  3. Right click on the editor Execute->Execute PLSQL(Debugger).See the second screeshot.
  4. A window opens up,you need to select the procedure from the left side and pass parameters for that procedure and then click Execute.See the third screenshot.
  5. Now start your debugging check Debug-->Step Over...Add Watch etc.

Reference:Toad Debugger

Debug

Execute In Debug

parameter

A long bigger than Long.MAX_VALUE

You can't. If you have a method called isBiggerThanMaxLong(long) it should always return false.

If you were to increment the bits of Long.MAX_VALUE, the next value should be Long.MIN_VALUE. Read up on twos-complement and that should tell you why.

Check if number is decimal

another way to solve this: preg_match('/^\d+\.\d+$/',$number); :)

Append values to a set in Python

The way I like to do this is to convert both the original set and the values I'd like to add into lists, add them, and then convert them back into a set, like this:

setMenu = {"Eggs", "Bacon"}
print(setMenu)
> {'Bacon', 'Eggs'}
setMenu = set(list(setMenu) + list({"Spam"}))
print(setMenu)
> {'Bacon', 'Spam', 'Eggs'}
setAdditions = {"Lobster", "Sausage"}
setMenu = set(list(setMenu) + list(setAdditions))
print(setMenu)
> {'Lobster', 'Spam', 'Eggs', 'Sausage', 'Bacon'}

This way I can also easily add multiple sets using the same logic, which gets me an TypeError: unhashable type: 'set' if I try doing it with the .update() method.

Change the color of a bullet in a html list?

The bullet gets its color from the text. So if you want to have a different color bullet than text in your list you'll have to add some markup.

Wrap the list text in a span:

<ul>
  <li><span>item #1</span></li>
  <li><span>item #2</span></li>
  <li><span>item #3</span></li>
</ul>

Then modify your style rules slightly:

li {
  color: red; /* bullet color */
}
li span {
  color: black; /* text color */
}

"inconsistent use of tabs and spaces in indentation"

Using the autopep8 command below fixed it for me:

 autopep8 -i my_file.py

Documentation for autopep8 linked here.

Does Django scale?

You can definitely run a high-traffic site in Django. Check out this pre-Django 1.0 but still relevant post here: http://menendez.com/blog/launching-high-performance-django-site/

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

How to split a string, but also keep the delimiters?

Here's a groovy version based on some of the code above, in case it helps. It's short, anyway. Conditionally includes the head and tail (if they are not empty). The last part is a demo/test case.

List splitWithTokens(str, pat) {
    def tokens=[]
    def lastMatch=0
    def m = str=~pat
    while (m.find()) {
      if (m.start() > 0) tokens << str[lastMatch..<m.start()]
      tokens << m.group()
      lastMatch=m.end()
    }
    if (lastMatch < str.length()) tokens << str[lastMatch..<str.length()]
    tokens
}

[['<html><head><title>this is the title</title></head>',/<[^>]+>/],
 ['before<html><head><title>this is the title</title></head>after',/<[^>]+>/]
].each { 
   println splitWithTokens(*it)
}

When to use DataContract and DataMember attributes?

DataMember attribute is not mandatory to add to serialize data. When DataMember attribute is not added, old XMLSerializer serializes the data. Adding a DataMember provides useful properties like order, name, isrequired which cannot be used otherwise.

__FILE__ macro shows full path

Here's a tip if you're using cmake. From: http://public.kitware.com/pipermail/cmake/2013-January/053117.html

I'm copying the tip so it's all on this page:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__FILENAME__='\"$(subst
  ${CMAKE_SOURCE_DIR}/,,$(abspath $<))\"'")

If you're using GNU make, I see no reason you couldn't extend this to your own makefiles. For example, you might have a line like this:

CXX_FLAGS+=-D__FILENAME__='\"$(subst $(SOURCE_PREFIX)/,,$(abspath $<))\"'"

where $(SOURCE_PREFIX) is the prefix that you want to remove.

Then use __FILENAME__ in place of __FILE__.

What is middleware exactly?

Middleware stands between web applications and web services that natively can't communicate and often are written in different languages/frameworks.

One such example is OWIN middleware for .NET environment, before owin people were forced to host web apps in a microsoft hosting software called IIS. After owin was developed, it has added capacity to host both in IIS and self host, in IIS was just added support for Owin which acted as an interface. Also it become possible to host .NET web apps on Linux via Mono, which again added support for Owin.

It also added capacity to create Single Page Applications, Owin handling Http request/response context, so on top of owin you can add authentication/authorization logic via OAuth2 for example, you can configure middleware to register a class which contains logic of user authentification (for ex. OAuth2 implementation) or class which contains logic of how to manage http request/response messages, that way you can make one application communicate with other applications/services via different data format (like json, xml, etc if you are targeting web).

Regular Expression to get a string between parentheses in Javascript

_x000D_
_x000D_
let str = "Before brackets (Inside brackets) After brackets".replace(/.*\(|\).*/g, '');_x000D_
console.log(str) // Inside brackets
_x000D_
_x000D_
_x000D_

Create PostgreSQL ROLE (user) if it doesn't exist

The same solution as for Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL? should work - send a CREATE USER … to \gexec.

Workaround from within psql

SELECT 'CREATE USER my_user'
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec

Workaround from the shell

echo "SELECT 'CREATE USER my_user' WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec" | psql

See accepted answer there for more details.

How do I get the old value of a changed cell in Excel VBA?

In response to Matt Roy answer, I found this option a great response, although I couldn't post as such with my current rating. :(

However, while taking the opportunity to post my thoughts on his response, I thought I would take the opportunity to include a small modification. Just compare code to see.

So thanks to Matt Roy for bringing this code to our attention, and Chris.R for posting original code.

Dim OldValues As New Collection

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

'>> Prevent user from multiple selection before any changes:

 If Selection.Cells.Count > 1 Then
        MsgBox "Sorry, multiple selections are not allowed.", vbCritical
        ActiveCell.Select
        Exit Sub
    End If
 'Copy old values
    Set OldValues = Nothing
    Dim c As Range
    For Each c In Target
        OldValues.Add c.Value, c.Address
    Next c
End Sub


Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next

 On Local Error Resume Next  ' To avoid error if the old value of the cell address you're looking for has not been copied

Dim c As Range

    For Each c In Target
        If OldValues(c.Address) <> "" And c.Value <> "" Then 'both Oldvalue and NewValue are Not Empty
                    Debug.Print "New value of " & c.Address & " is " & c.Value & "; old value was " & OldValues(c.Address)
        ElseIf OldValues(c.Address) = "" And c.Value = "" Then 'both Oldvalue and NewValue are  Empty
                    Debug.Print "New value of " & c.Address & " is Empty " & c.Value & "; old value is Empty" & OldValues(c.Address)

        ElseIf OldValues(c.Address) <> "" And c.Value = "" Then 'Oldvalue is Empty and NewValue is Not Empty
                    Debug.Print "New value of " & c.Address & " is Empty" & c.Value & "; old value was " & OldValues(c.Address)
        ElseIf OldValues(c.Address) = "" And c.Value <> "" Then 'Oldvalue is Not Empty and NewValue is Empty
                    Debug.Print "New value of " & c.Address & " is " & c.Value & "; old value is Empty" & OldValues(c.Address)
        End If
    Next c

    'Copy old values (in case you made any changes in previous lines of code)
    Set OldValues = Nothing
    For Each c In Target
        OldValues.Add c.Value, c.Address
    Next c

Error You must specify a region when running command aws ecs list-container-instances

Just to add to answers by Mr. Dimitrov and Jason, if you are using a specific profile and you have put your region setting there,then for all the requests you need to add

"--profile" option.

For example:

Lets say you have AWS Playground profile, and the ~/.aws/config has [profile playground] which further has something like,

[profile playground] region=us-east-1

then, use something like below

aws ecs list-container-instances --cluster default --profile playground

jQuery remove special characters from string and more

Remove/Replace all special chars in Jquery :

If

str = My name is "Ghanshyam" and from "java" background

and want to remove all special chars (") then use this

str=str.replace(/"/g,' ')

result:

My name is Ghanshyam and from java background

Where g means Global

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

An issue with Gulp 4.

For solving this problem try to change your current code:

gulp.task('simpleTaskName', function() {
  // code...
});

for example into this:

gulp.task('simpleTaskName', async function() {
  // code...
});

or into this:

gulp.task('simpleTaskName', done => {
  // code...
  done();
});

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

PHP Undefined Index

I don't see php file, but that could be that -
replace in your php file:

$query_age = $_GET['query_age'];

with:

$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

Most probably, at first time you running your script without ?query_age=[something] and $_GET has no key like query_age.

How to transfer some data to another Fragment?

Use a Bundle. Here's an example:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Bundle has put methods for lots of data types. See this

Then in your Fragment, retrieve the data (e.g. in onCreate() method) with:

Bundle bundle = this.getArguments();
if (bundle != null) {
        int myInt = bundle.getInt(key, defaultValue);
}

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

How to extract an assembly from the GAC?

Copying from a command line is unnecessary. I typed in the name of the DLL from the Start Window search. I chose See More Results. The one in the GAC was returned in the search window. I right clicked on it and said open file location. It opened in normal Windows Explorer. I copied the file. I closed the window. Done.

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

How can I specify system properties in Tomcat configuration on startup?

It's also possible letting a ServletContextListener set the System properties:

import java.util.Enumeration;
import javax.servlet.*;

public class SystemPropertiesHelper implements
        javax.servlet.ServletContextListener {
    private ServletContext context = null;

    public void contextInitialized(ServletContextEvent event) {
        context = event.getServletContext();
        Enumeration<String> params = context.getInitParameterNames();

        while (params.hasMoreElements()) {
          String param = (String) params.nextElement();
          String value = 
            context.getInitParameter(param);
          if (param.startsWith("customPrefix.")) {
              System.setProperty(param, value);
          }
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
    }
}

And then put this into your web.xml (should be possible for context.xml too)

<context-param>
        <param-name>customPrefix.property</param-name>
        <param-value>value</param-value>
        <param-type>java.lang.String</param-type>
</context-param>

<listener>
    <listener-class>servletUtils.SystemPropertiesHelper</listener-class>    
</listener>

It worked for me.

Convert python long/int to fixed size byte array

With Python 3.2 and later, you can use int.to_bytes and int.from_bytes: https://docs.python.org/3/library/stdtypes.html#int.to_bytes

How to get first record in each group using Linq

var res = (from element in list)
      .OrderBy(x => x.F2).AsEnumerable()
      .GroupBy(x => x.F1)
      .Select()

Use .AsEnumerable() after OrderBy()

Return only string message from Spring MVC 3 Controller

For outputing String as text/plain use:

@RequestMapping(value="/foo", method=RequestMethod.GET, produces="text/plain")
@ResponseBody
public String foo() {
    return "bar";
}

Retrieving Property name from lambda expression

This is a general implementation to get the string name of fields/properties/indexers/methods/extension methods/delegates of struct/class/interface/delegate/array. I have tested with combinations of static/instance and non-generic/generic variants.

//involves recursion
public static string GetMemberName(this LambdaExpression memberSelector)
{
    Func<Expression, string> nameSelector = null;  //recursive func
    nameSelector = e => //or move the entire thing to a separate recursive method
    {
        switch (e.NodeType)
        {
            case ExpressionType.Parameter:
                return ((ParameterExpression)e).Name;
            case ExpressionType.MemberAccess:
                return ((MemberExpression)e).Member.Name;
            case ExpressionType.Call:
                return ((MethodCallExpression)e).Method.Name;
            case ExpressionType.Convert:
            case ExpressionType.ConvertChecked:
                return nameSelector(((UnaryExpression)e).Operand);
            case ExpressionType.Invoke:
                return nameSelector(((InvocationExpression)e).Expression);
            case ExpressionType.ArrayLength:
                return "Length";
            default:
                throw new Exception("not a proper member selector");
        }
    };

    return nameSelector(memberSelector.Body);
}

This thing can be written in a simple while loop too:

//iteration based
public static string GetMemberName(this LambdaExpression memberSelector)
{
    var currentExpression = memberSelector.Body;

    while (true)
    {
        switch (currentExpression.NodeType)
        {
            case ExpressionType.Parameter:
                return ((ParameterExpression)currentExpression).Name;
            case ExpressionType.MemberAccess:
                return ((MemberExpression)currentExpression).Member.Name;
            case ExpressionType.Call:
                return ((MethodCallExpression)currentExpression).Method.Name;
            case ExpressionType.Convert:
            case ExpressionType.ConvertChecked:
                currentExpression = ((UnaryExpression)currentExpression).Operand;
                break;
            case ExpressionType.Invoke:
                currentExpression = ((InvocationExpression)currentExpression).Expression;
                break;
            case ExpressionType.ArrayLength:
                return "Length";
            default:
                throw new Exception("not a proper member selector");
        }
    }
}

I like the recursive approach, though the second one might be easier to read. One can call it like:

someExpr = x => x.Property.ExtensionMethod()[0]; //or
someExpr = x => Static.Method().Field; //or
someExpr = x => VoidMethod(); //or
someExpr = () => localVariable; //or
someExpr = x => x; //or
someExpr = x => (Type)x; //or
someExpr = () => Array[0].Delegate(null); //etc

string name = someExpr.GetMemberName();

to print the last member.

Note:

  1. In case of chained expressions like A.B.C, "C" is returned.

  2. This doesn't work with consts, array indexers or enums (impossible to cover all cases).

Loop Through Each HTML Table Column and Get the Data using jQuery

When you create your table, put your td with class = "suma"

$(function(){   

   //funcion suma todo

   var sum = 0;
   $('.suma').each(function(x,y){
       sum += parseInt($(this).text());                                   
   })           
   $('#lblTotal').text(sum);   

   // funcion suma por check                                           

    $( "input:checkbox").change(function(){
    if($(this).is(':checked')){     
        $(this).parent().parent().find('td:last').addClass('suma2');
   }else{       
        $(this).parent().parent().find('td:last').removeClass('suma2');
   }    
   suma2Total();                                                           
   })                                                      

   function suma2Total(){
      var sum2 = 0;
      $('.suma2').each(function(x,y){
        sum2 += parseInt($(this).text());       
      })
      $('#lblTotal2').text(sum2);                                              
   }                                                                      
});

Ejemplo completo

Python/BeautifulSoup - how to remove all tags from an element?

You can use the decompose method in bs4:

soup = bs4.BeautifulSoup('<body><a href="http://example.com/">I linked to <i>example.com</i></a></body>')

for a in soup.find('a').children:
    if isinstance(a,bs4.element.Tag):
        a.decompose()

print soup

Out: <html><body><a href="http://example.com/">I linked to </a></body></html>

Twig: in_array or similar possible within if statement?

Just to clear some things up here. The answer that was accepted does not do the same as PHP in_array.

To do the same as PHP in_array use following expression:

{% if myVar in myArray %}

If you want to negate this you should use this:

{% if myVar not in myArray %}

Place API key in Headers or URL

If you want an argument that might appeal to a boss: Think about what a URL is. URLs are public. People copy and paste them. They share them, they put them on advertisements. Nothing prevents someone (knowingly or not) from mailing that URL around for other people to use. If your API key is in that URL, everybody has it.

Why does sudo change the PATH?

This seemed to work for me

sudo -i 

which takes on the non-sudo PATH

Filter element based on .data() key/value

Just for the record, you can filter on data with jquery (this question is quite old, and jQuery evolved since then, so it's right to write this solution as well):

$('.navlink[data-selected="true"]');

or, better (for performance):

$('.navlink').filter('[data-selected="true"]');

or, if you want to get all the elements with data-selected set:

$('[data-selected]')

Note that this method will only work with data that was set via html-attributes. If you set or change data with the .data() call, this method will no longer work.

Can I run CUDA on Intel's integrated graphics processor?

If you're interested in learning a language which supports massive parallelism better go for OpenCL since you don't have an NVIDIA GPU. You can run OpenCL on Intel CPUs, but at best you can learn to program SIMDs. Optimization on CPU and GPU are different. I really don't think you can use Intel card for GPGPU.

Using Mockito to mock classes with generic parameters

One other way around this is to use @Mock annotation instead. Doesn't work in all cases, but looks much sexier :)

Here's an example:

@RunWith(MockitoJUnitRunner.class)
public class FooTests {

    @Mock
    public Foo<Bar> fooMock;

    @Test
    public void testFoo() {
        when(fooMock.getValue()).thenReturn(new Bar());
    }
}

The MockitoJUnitRunner initializes the fields annotated with @Mock.

What is Func, how and when is it used

I find Func<T> very useful when I create a component that needs to be personalized "on the fly".

Take this very simple example: a PrintListToConsole<T> component.

A very simple object that prints this list of objects to the console. You want to let the developer that uses it personalize the output.

For example, you want to let him define a particular type of number format and so on.

Without Func

First, you have to create an interface for a class that takes the input and produces the string to print to the console.

interface PrintListConsoleRender<T> {
  String Render(T input);
}

Then you have to create the class PrintListToConsole<T> that takes the previously created interface and uses it over each element of the list.

class PrintListToConsole<T> {

    private PrintListConsoleRender<T> _renderer;

    public void SetRenderer(PrintListConsoleRender<T> r) {
        // this is the point where I can personalize the render mechanism
        _renderer = r;
    }

    public void PrintToConsole(List<T> list) {
        foreach (var item in list) {
            Console.Write(_renderer.Render(item));
        }
    }   
}

The developer that needs to use your component has to:

  1. implement the interface

  2. pass the real class to the PrintListToConsole

    class MyRenderer : PrintListConsoleRender<int> {
        public String Render(int input) {
            return "Number: " + input;
        }
    }
    
    class Program {
        static void Main(string[] args) {
            var list = new List<int> { 1, 2, 3 };
            var printer = new PrintListToConsole<int>();
            printer.SetRenderer(new MyRenderer());
            printer.PrintToConsole(list);
            string result = Console.ReadLine();   
        }   
    }
    

Using Func it's much simpler

Inside the component you define a parameter of type Func<T,String> that represents an interface of a function that takes an input parameter of type T and returns a string (the output for the console)

class PrintListToConsole<T> {

    private Func<T, String> _renderFunc;

    public void SetRenderFunc(Func<T, String> r) {
        // this is the point where I can set the render mechanism
        _renderFunc = r;
    }

    public void Print(List<T> list) {
        foreach (var item in list) {
            Console.Write(_renderFunc(item));
        }
    }
}

When the developer uses your component he simply passes to the component the implementation of the Func<T, String> type, that is a function that creates the output for the console.

class Program {
    static void Main(string[] args) {
        var list = new List<int> { 1, 2, 3 }; // should be a list as the method signature expects
        var printer = new PrintListToConsole<int>();
        printer.SetRenderFunc((o) => "Number:" + o);
        printer.Print(list); 
        string result = Console.ReadLine();
    }
}

Func<T> lets you define a generic method interface on the fly. You define what type the input is and what type the output is. Simple and concise.

Relative URLs in WordPress

I think this is the kind of question only a core developer could/should answer. I've researched and found the core ticket #17048: URLs delivered to the browser should be root-relative. Where we can find the reasons explained by Andrew Nacin, lead core developer. He also links to this [wp-hackers] thread. On both those links, these are the key quotes on why WP doesn't use relative URLs:

Core ticket:

  • Root-relative URLs aren't really proper. /path/ might not be WordPress, it might be outside of the install. So really it's not much different than an absolute URL.

  • Any relative URLs also make it significantly more difficult to perform transformations when the install is moved. The find-replace is going to be necessary in most situations, and having an absolute URL is ironically more portable for those reasons.

  • absolute URLs are needed in numerous other places. Needing to add these in conditionally will add to processing, as well as introduce potential bugs (and incompatibilities with plugins).

[wp-hackers] thread

  • Relative to what, I'm not sure, as WordPress is often in a subdirectory, which means we'll always need to process the content to then add in the rest of the path. This introduces overhead.

  • Keep in mind that there are two types of relative URLs, with and without the leading slash. Both have caveats that make this impossible to properly implement.

  • WordPress should (and does) store absolute URLs. This requires no pre-processing of content, no overhead, no ambiguity. If you need to relocate, it is a global find-replace in the database.


And, on a personal note, more than once I've found theme and plugins bad coded that simply break when WP_CONTENT_URL is defined.
They don't know this can be set and assume that this is true: WP.URL/wp-content/WhatEver, and it's not always the case. And something will break along the way.


The plugin Relative URLs (linked in edse's Answer), applies the function wp_make_link_relative in a series of filters in the action hook template_redirect. It's quite a simple code and seems a nice option.

How do I vertically align text in a div?

HTML

<div class="relative"><!--used as a container-->
    <!-- add content here to to make some height and width
    example:<img src="" alt=""> -->
    <div class="absolute">
        <div class="table">
            <div class="table-cell">
                Vertical contents goes here
            </div>
        </div>
    </div>
</div>

CSS

 .relative {
     position: relative;
 }
 .absolute {
     position: absolute;
     top: 0;
     bottom: 0;
     left: 0;
     right: 0;
     background: rgba(0, 0, 0, 0.5);
 }
 .table {
     display: table;
     height: 100%;
     width: 100%;
     text-align: center;
     color: #fff;
 }
 .table-cell {
     display: table-cell;
     vertical-align: middle;
 }

How to read from a file or STDIN in Bash?

I think this is the straight-forward way:

$ cat reader.sh
#!/bin/bash
while read line; do
  echo "reading: ${line}"
done < /dev/stdin

--

$ cat writer.sh
#!/bin/bash
for i in {0..5}; do
  echo "line ${i}"
done

--

$ ./writer.sh | ./reader.sh
reading: line 0
reading: line 1
reading: line 2
reading: line 3
reading: line 4
reading: line 5

Internet Explorer cache location

If you are using Dot.Net then the code you need is

Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)

Click my name if you want the code to delete these files plus FireFox temp files and Flash shared object/Flash Cookies

Enum ToString with user friendly strings

If you want something completely customizable, try out my solution here:

http://www.kevinwilliampang.com/post/Mapping-Enums-To-Strings-and-Strings-to-Enums-in-NET.aspx

Basically, the post outlines how to attach Description attributes to each of your enums and provides a generic way to map from enum to description.

C# Test if user has write access to a folder

I agree with Ash, that should be fine. Alternatively you could use declarative CAS and actually prevent the program from running in the first place if they don't have access.

I believe some of the CAS features may not be present in C# 4.0 from what I've heard, not sure if that might be an issue or not.

pytest cannot import module while python can

Install the packages into Your virtual environment.
Then start a new shell and source Your virtual environment again.

UTF-8 byte[] to String

I use this way

String strIn = new String(_bytes, 0, numBytes);

PHP mail not working for some reason

If you are using Ubuntu and it seem sendmail is not in /usr/sbin/sendmail, install sendmail using the terminal with this command:

sudo apt-get install sendmail

and then run reload the PHP page where mail() is written. Also check your spam folder.

Extracting the top 5 maximum values in excel

Put the data into a Pivot Table and do a top n filter on it

Excel Demo

Google Maps v3 - limit viewable area and zoom level

Here's my variant to solve the problem of viewable area's limitation.

        google.maps.event.addListener(this.map, 'idle', function() {
            var minLat = strictBounds.getSouthWest().lat();
            var minLon = strictBounds.getSouthWest().lng();
            var maxLat = strictBounds.getNorthEast().lat();
            var maxLon = strictBounds.getNorthEast().lng();
            var cBounds  = self.map.getBounds();
            var cMinLat = cBounds.getSouthWest().lat();
            var cMinLon = cBounds.getSouthWest().lng();
            var cMaxLat = cBounds.getNorthEast().lat();
            var cMaxLon = cBounds.getNorthEast().lng();
            var centerLat = self.map.getCenter().lat();
            var centerLon = self.map.getCenter().lng();

            if((cMaxLat - cMinLat > maxLat - minLat) || (cMaxLon - cMinLon > maxLon - minLon))
            {   //We can't position the canvas to strict borders with a current zoom level
                self.map.setZoomLevel(self.map.getZoomLevel()+1);
                return;
            }
            if(cMinLat < minLat)
                var newCenterLat = minLat + ((cMaxLat-cMinLat) / 2);
            else if(cMaxLat > maxLat)
                var newCenterLat = maxLat - ((cMaxLat-cMinLat) / 2);
            else
                var newCenterLat = centerLat;
            if(cMinLon < minLon)
                var newCenterLon = minLon + ((cMaxLon-cMinLon) / 2);
            else if(cMaxLon > maxLon)
                var newCenterLon = maxLon - ((cMaxLon-cMinLon) / 2);
            else
                var newCenterLon = centerLon;

            if(newCenterLat != centerLat || newCenterLon != centerLon)
                self.map.setCenter(new google.maps.LatLng(newCenterLat, newCenterLon));
        });

strictBounds is an object of new google.maps.LatLngBounds() type. self.gmap stores a Google Map object (new google.maps.Map()).

It really works but don't only forget to take into account the haemorrhoids with crossing 0th meridians and parallels if your bounds cover them.

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

This is one of the basic differences not mentioned in previous comments:
Readonly property will work with textbox for and it will not work with EditorFor.

@Html.TextBoxFor(model => model.DateSoldOn, new { @readonly = "readonly" })

Above code works, where as with following you can't make control to readonly.

@Html.EditorFor(model => model.DateSoldOn, new { @readonly = "readonly" })

Java JDBC connection status

The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.

Example:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}

pandas unique values multiple columns

In [5]: set(df.Col1).union(set(df.Col2))
Out[5]: {'Bill', 'Bob', 'Joe', 'Mary', 'Steve'}

Or:

set(df.Col1) | set(df.Col2)

Get last n lines of a file, similar to tail

The code I ended up using. I think this is the best so far:

def tail(f, n, offset=None):
    """Reads a n lines from f with an offset of offset lines.  The return
    value is a tuple in the form ``(lines, has_more)`` where `has_more` is
    an indicator that is `True` if there are more lines in the file.
    """
    avg_line_length = 74
    to_read = n + (offset or 0)

    while 1:
        try:
            f.seek(-(avg_line_length * to_read), 2)
        except IOError:
            # woops.  apparently file is smaller than what we want
            # to step back, go to the beginning instead
            f.seek(0)
        pos = f.tell()
        lines = f.read().splitlines()
        if len(lines) >= to_read or pos == 0:
            return lines[-to_read:offset and -offset or None], \
                   len(lines) > to_read or pos > 0
        avg_line_length *= 1.3

Android add placeholder text to EditText

If you mean the location where you will add it in the layout. You can define a container like a FrameLayout and add this EditText to it when it is created.

<LinearLayout xmlns=".."/>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/container" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

FrameLayout layout = (FrameLayout) findViewById(R.id.container);
layout.addView(name);

Makefile to compile multiple C programs?

SRC = a.cpp b.cpp
BIN = $(patsubst %.cpp,%,$(SRC))

all: $(BIN)

clean:
    rm -f $(BIN)

.PHONY: all clean

make all will do:

c++     a.cpp   -o a
c++     b.cpp   -o b

If you set CXX and CXXFLAGS variables make will use them.

In Python, how do you convert seconds since epoch to a `datetime` object?

For those that want it ISO 8601 compliant, since the other solutions do not have the T separator nor the time offset (except Meistro's answer):

from datetime import datetime, timezone
result = datetime.fromtimestamp(1463288494, timezone.utc).isoformat('T', 'microseconds')
print(result) # 2016-05-15T05:01:34.000000+00:00

Note, I use fromtimestamp because if I used utcfromtimestamp I would need to chain on .astimezone(...) anyway to get the offset.

If you don't want to go all the way to microseconds you can choose a different unit with the isoformat() method.

Difference between InvariantCulture and Ordinal string comparison

Another handy difference (in English where accents are uncommon) is that an InvariantCulture comparison compares the entire strings by case-insensitive first, and then if necessary (and requested) distinguishes by case after first comparing only on the distinct letters. (You can also do a case-insensitive comparison, of course, which won't distinguish by case.) Corrected: Accented letters are considered to be another flavor of the same letters and the string is compared first ignoring accents and then accounting for them if the general letters all match (much as with differing case except not ultimately ignored in a case-insensitive compare). This groups accented versions of the otherwise same word near each other instead of completely separate at the first accent difference. This is the sort order you would typically find in a dictionary, with capitalized words appearing right next to their lowercase equivalents, and accented letters being near the corresponding unaccented letter.

An ordinal comparison compares strictly on the numeric character values, stopping at the first difference. This sorts capitalized letters completely separate from the lowercase letters (and accented letters presumably separate from those), so capitalized words would sort nowhere near their lowercase equivalents.

InvariantCulture also considers capitals to be greater than lower case, whereas Ordinal considers capitals to be less than lowercase (a holdover of ASCII from the old days before computers had lowercase letters, the uppercase letters were allocated first and thus had lower values than the lowercase letters added later).

For example, by Ordinal: "0" < "9" < "A" < "Ab" < "Z" < "a" < "aB" < "ab" < "z" < "Á" < "Áb" < "á" < "áb"

And by InvariantCulture: "0" < "9" < "a" < "A" < "á" < "Á" < "ab" < "aB" < "Ab" < "áb" < "Áb" < "z" < "Z"

Java Embedded Databases Comparison

Java DB (Sun's distribution of Apache Derby) now ships in JDK 6!

I've been wanted to do something like Jason Cohen and have been thinking this looks like the easiest way being in the JDK distro (which of last week is now a requirement for my app). Or maybe I am just lazy that way.

in_array() and multidimensional array

If you know which column to search against, you can use array_search() and array_column():

$userdb = Array
(
    (0) => Array
        (
            ('uid') => '100',
            ('name') => 'Sandra Shush',
            ('url') => 'urlof100'
        ),

    (1) => Array
        (
            ('uid') => '5465',
            ('name') => 'Stefanie Mcmohn',
            ('url') => 'urlof5465'
        ),

    (2) => Array
        (
            ('uid') => '40489',
            ('name') => 'Michael',
            ('url') => 'urlof40489'
        )
);

if(array_search('urlof5465', array_column($userdb, 'url')) !== false) {
    echo 'value is in multidim array';
}
else {
    echo 'value is not in multidim array';
}

This idea is in the comments section for array_search() on the PHP manual;

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

Java Multithreading concept and join() method

I'm not able to understand the flow of execution of the program, And when ob1 is created then the constructor is called where t.start() is written but still run() method is not executed rather main() method continues execution. So why is this happening?

This depends on Thread Scheduler as main shares the same priority order. Calling start() doesn't mean run() will be called immediately, it depends on thread scheduler when it chooses to run your thread.

join() method is used to wait until the thread on which it is called does not terminates, but here in output we see alternate outputs of the thread why??

This is because of the Thread.sleep(1000) in your code. Remove that line and you will see ob1 finishes before ob2 which in turn finishes before ob3 (as expected with join()). Having said that it all depends on when ob1 ob2 and ob3 started. Calling sleep will pause thread execution for >= 1 second (in your code), giving scheduler a chance to call other threads waiting (same priority).

Proper use of the IDisposable interface

If MyCollection is going to be garbage collected anyway, then you shouldn't need to dispose it. Doing so will just churn the CPU more than necessary, and may even invalidate some pre-calculated analysis that the garbage collector has already performed.

I use IDisposable to do things like ensure threads are disposed correctly, along with unmanaged resources.

EDIT In response to Scott's comment:

The only time the GC performance metrics are affected is when a call the [sic] GC.Collect() is made"

Conceptually, the GC maintains a view of the object reference graph, and all references to it from the stack frames of threads. This heap can be quite large and span many pages of memory. As an optimisation, the GC caches its analysis of pages that are unlikely to change very often to avoid rescanning the page unnecessarily. The GC receives notification from the kernel when data in a page changes, so it knows that the page is dirty and requires a rescan. If the collection is in Gen0 then it's likely that other things in the page are changing too, but this is less likely in Gen1 and Gen2. Anecdotally, these hooks were not available in Mac OS X for the team who ported the GC to Mac in order to get the Silverlight plug-in working on that platform.

Another point against unnecessary disposal of resources: imagine a situation where a process is unloading. Imagine also that the process has been running for some time. Chances are that many of that process's memory pages have been swapped to disk. At the very least they're no longer in L1 or L2 cache. In such a situation there is no point for an application that's unloading to swap all those data and code pages back into memory to 'release' resources that are going to be released by the operating system anyway when the process terminates. This applies to managed and even certain unmanaged resources. Only resources that keep non-background threads alive must be disposed, otherwise the process will remain alive.

Now, during normal execution there are ephemeral resources that must be cleaned up correctly (as @fezmonkey points out database connections, sockets, window handles) to avoid unmanaged memory leaks. These are the kinds of things that have to be disposed. If you create some class that owns a thread (and by owns I mean that it created it and therefore is responsible for ensuring it stops, at least by my coding style), then that class most likely must implement IDisposable and tear down the thread during Dispose.

The .NET framework uses the IDisposable interface as a signal, even warning, to developers that the this class must be disposed. I can't think of any types in the framework that implement IDisposable (excluding explicit interface implementations) where disposal is optional.

How to run ssh-add on windows?

If you are trying to setup a key for using git with ssh, there's always an option to add a configuration for the identity file.

vi ~/.ssh/config

Host example.com
IdentityFile ~/.ssh/example_key

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

I resolved this issue by correcting an error with my Global.asax file arrangement. I had copied across the files from another project and failed to embed the Global.asax.cs within the Global.asax file (both files previously existed at the same level).

Global.asax arrangement

How to execute an external program from within Node.js?

The simplest way is:

const { exec } = require("child_process")
exec('yourApp').unref()

unref is necessary to end your process without waiting for "yourApp"

Here are the exec docs

Use Async/Await with Axios in React.js

In my experience over the past few months, I've realized that the best way to achieve this is:

class App extends React.Component{
  constructor(){
   super();
   this.state = {
    serverResponse: ''
   }
  }
  componentDidMount(){
     this.getData();
  }
  async getData(){
   const res = await axios.get('url-to-get-the-data');
   const { data } = await res;
   this.setState({serverResponse: data})
 }
 render(){
  return(
     <div>
       {this.state.serverResponse}
     </div>
  );
 }
}

If you are trying to make post request on events such as click, then call getData() function on the event and replace the content of it like so:

async getData(username, password){
 const res = await axios.post('url-to-post-the-data', {
   username,
   password
 });
 ...
}

Furthermore, if you are making any request when the component is about to load then simply replace async getData() with async componentDidMount() and change the render function like so:

render(){
 return (
  <div>{this.state.serverResponse}</div>
 )
}

How to allow only one radio button to be checked?

Just give them the same name throughout the form you are using.

<form><input type="radio" name="selection">
      <input type="radio" name="selection">
      ..
      ..
</form>

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

I had this problem on Windows 7. My situation is this through SDK Manager. I only download API 19 but I had not downloaded related Android SDK build-tools. So it occur this problem.

I went through SDK Manager download build-tools 19 to fix it. Hope to give you help.

How to load specific image from assets with Swift

You can easily pick image from asset without UIImage(named: "green-square-Retina").

Instead use the image object directly from bundle.
Start typing the image name and you will get suggestions with actual image from bundle. It is advisable practice and less prone to error.

See this Stackoverflow answer for reference.

How to use JQuery with ReactJS

Yes, we can use jQuery in ReactJs. Here I will tell how we can use it using npm.

step 1: Go to your project folder where the package.json file is present via using terminal using cd command.

step 2: Write the following command to install jquery using npm : npm install jquery --save

step 3: Now, import $ from jquery into your jsx file where you need to use.

Example:

write the below in index.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';


//   react code here


$("button").click(function(){
    $.get("demo_test.asp", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

// react code here

write the below in index.html

<!DOCTYPE html>
<html>
<head>
    <script src="index.jsx"></script>
    <!-- other scripting files -->
</head>
<body>
    <!-- other useful tags -->
    <div id="div1">
        <h2>Let jQuery AJAX Change This Text</h2>
    </div>
    <button>Get External Content</button>
</body>
</html>

Angular 2 - innerHTML styling

We pull in content frequently from our CMS as [innerHTML]="content.title". We place the necessary classes in the application's root styles.scss file rather than in the component's scss file. Our CMS purposely strips out in-line styles so we must have prepared classes that the author can use in their content. Remember using {{content.title}} in the template will not render html from the content.

Setting up FTP on Amazon Cloud Server

I've simplified clone45 steps:

Open the ports as he mentioned

sudo su
sudo yum install vsftpd
echo -n "Public IP of your instance: " && read publicip
echo -e "anonymous_enable=NO\npasv_enable=YES\npasv_min_port=1024\npasv_max_port=1048\npasv_address=$publicip\nchroot_local_user=YES" >> /etc/vsftpd/vsftpd.conf
sudo /etc/init.d/vsftpd restart

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Use the AWS EC2 console, not ElasticFox.

First Way:

  • Create a new AMI of the instance
  • Launch it

Alternative Way:

  • Make a snapshot of the disk
  • Launch a large EBS instance with the same AMI type (please note that at this point the disk will contain the data that was present when this AMI was created, not your latest changes)
  • Once is fully booted, stop the new instance
  • Detach the root volume from the stopped instance
  • Create a virtual disk from the snapshot created before in the same availability zone of the new instance
  • Attach the root volume to /dev/sda1
  • Start the new instance again

Permanently add a directory to PYTHONPATH?

Shortest path between A <-> B is a straight line;

import sys
if not 'NEW_PATH' in sys.path:
  sys.path += ['NEW_PATH']

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

try this:-

select to_char(to_date('01/10/2017','dd/mm/yyyy'),'fmMonth fmDD,YYYY') from dual;

select to_char(sysdate,'fmMonth fmDD,YYYY') from dual;

how to make a full screen div, and prevent size to be changed by content?

Or even just:

<div id="full-size">
  Your contents go here
</div>
html,body{ margin:0; padding:0; height:100%; width:100%; }
#full-size{
  height:100%;
  width:100%;
  overflow:hidden; /* or overflow:auto; if you want scrollbars */
}

(html, body can be set to like.. 95%-99% or some such to account for slight inconsistencies in margins, etc.)

Read and overwrite a file in Python

I find it easier to remember to just read it and then write it.

For example:

with open('file') as f:
    data = f.read()
with open('file', 'w') as f:
    f.write('hello')

Short description of the scoping rules?

A slightly more complete example of scope:

from __future__ import print_function  # for python 2 support

x = 100
print("1. Global x:", x)
class Test(object):
    y = x
    print("2. Enclosed y:", y)
    x = x + 1
    print("3. Enclosed x:", x)

    def method(self):
        print("4. Enclosed self.x", self.x)
        print("5. Global x", x)
        try:
            print(y)
        except NameError as e:
            print("6.", e)

    def method_local_ref(self):
        try:
            print(x)
        except UnboundLocalError as e:
            print("7.", e)
        x = 200 # causing 7 because has same name
        print("8. Local x", x)

inst = Test()
inst.method()
inst.method_local_ref()

output:

1. Global x: 100
2. Enclosed y: 100
3. Enclosed x: 101
4. Enclosed self.x 101
5. Global x 100
6. global name 'y' is not defined
7. local variable 'x' referenced before assignment
8. Local x 200

Change Orientation of Bluestack : portrait/landscape mode

I install go launcher on mine, (Windows 8)=> preferences => Screens => Screen orientation => vertical (disable QWE keyboard)

How do you delete all text above a certain line

kdgg

delete all lines above the current one.

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

How to read an entire file to a string using C#?

string content = System.IO.File.ReadAllText( @"C:\file.txt" );

Perform curl request in javascript?

curl is a command in linux (and a library in php). Curl typically makes an HTTP request.

What you really want to do is make an HTTP (or XHR) request from javascript.

Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax

Essentially you will want to call $.ajax with a few options for the header, etc.

$.ajax({
        url: 'https://api.wit.ai/message?v=20140826&q=',
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
        }, success: function(data){
            alert(data);
            //process the JSON data etc
        }
})

how to rename an index in a cluster?

For renaming your index you can use Elasticsearch Snapshot module.

First you have to take snapshot of your index.while restoring it you can rename your index.

    POST /_snapshot/my_backup/snapshot_1/_restore
    {
     "indices": "jal",
     "ignore_unavailable": "true",
     "include_global_state": false,
     "rename_pattern": "jal",
     "rename_replacement": "jal1"
     }

rename_replacement :-New indexname in which you want backup your data.

Another Repeated column in mapping for entity error

This means you are mapping a column twice in your entity class. Explaining with an example...

    @Column(name = "column1")
    private String object1;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "column1", referencedColumnName = "column1")
    private TableClass object2;

The problem in the above code snippet is we are repeating mapping...

Solution

Since mapping is an important part, you don't want to remove that. Instead, you will remove

    @Column(name = "column1")
    private String uniqueId;

You can still pass the value of object1 by creating a object of TableClass and assign the String value of Object1 in it.

This works 100%. I have tested this with Postgres and Oracle database.

Regex to match only letters

Just use \w or [:alpha:]. It is an escape sequences which matches only symbols which might appear in words.

How to change the color of a SwitchCompat from AppCompat library

Ok, so I'm sorry but most of these answers are incomplete or have some minor bug in them. The very complete answer from @austyn-mahoney is correct and the source for this answer, but it's complicated and you probably just want to style a switch. 'Styling' controls across different versions of Android is an epic pain in the ass. After pulling my hair out for days on a project with very tight design constraints I finally broke down and wrote a test app and then really dug in and tested the various solutions out there for styling switches and check-boxes, since when a design has one it frequently has the other. Here's what I found...

First: You can't actually style either of them, but you can apply a theme to all of them, or just one of them.

Second: You can do it all from XML and you don't need a second values-v21/styles.xml.

Third: when it comes to switches you have two basic choices if you want to support older versions of Android (like I'm sure you do)...

  1. You can use a SwitchCompat and you will be able to make it look the same across platforms.
  2. You can use a Switch and you will be able to theme it with the rest of your theme, or just that particular switch and on older versions of Android you'll just see an unstyled older square switch.

Ok now for the simple reference code. Again if you create a simple Hello World! and drop this code in you can play to your hearts content. All of that is boiler plate here so I'm just going to include the XML for the activity and the style...

activity_main.xml...

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="'Styled' SwitchCompat" />

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_item"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:textOff="OFF"
        android:textOn="ON"
        app:switchTextAppearance="@style/BrandedSwitch.text"
        app:theme="@style/BrandedSwitch.control"
        app:showText="true" />

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Themed SwitchCompat" />

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_item2"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false" />

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Themed Switch" />

    <Switch
        android:id="@+id/switch_item3"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:textOff="OFF"
        android:textOn="ON"/>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="'Styled' Switch" />

    <Switch
        android:id="@+id/switch_item4"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:textOff="OFF"
        android:textOn="ON"
        android:theme="@style/BrandedSwitch"/>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="'Styled' CheckBox" />

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"
        android:theme="@style/BrandedCheckBox"/>

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.kunai.switchtest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Themed CheckBox" />

    <CheckBox
        android:id="@+id/checkbox2"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="16dp"
        android:checked="true"
        android:longClickable="false"/>

</RelativeLayout>

styles.xml...

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">#3F51B5</item>
    <item name="colorPrimaryDark">#303F9F</item>
    <item name="colorAccent">#FF4081</item>
</style>

<style name="BrandedSwitch.control" parent="Theme.AppCompat.Light">
    <!-- active thumb & track color (30% transparency) -->
    <item name="colorControlActivated">#e6e600</item>
    <item name="colorSwitchThumbNormal">#cc0000</item>
</style>

<style name="BrandedSwitch.text" parent="Theme.AppCompat.Light">
    <item name="android:textColor">#ffa000</item>
    <item name="android:textSize">9dp</item>
</style>

<style name="BrandedCheckBox" parent="AppTheme">
    <item name="colorAccent">#aaf000</item>
    <item name="colorControlNormal">#ff0000</item>
</style>

<style name="BrandedSwitch" parent="AppTheme">
    <item name="colorAccent">#39ac39</item>
</style>

I know, I know, you are too lazy to build this, you just want to get your code written and check it in so you can close this pain in the ass Android compatibility nightmare bug so that the designer on your team will finally be happy. I get it. Here's what it looks like when you run it...

API_21:

API 21

API_18:

API18

How to keep keys/values in same order as declared?

Rather than explaining the theoretical part, I'll give a simple example.

>>> from collections import OrderedDict
>>> my_dictionary=OrderedDict()
>>> my_dictionary['foo']=3
>>> my_dictionary['aol']=1
>>> my_dictionary
OrderedDict([('foo', 3), ('aol', 1)])
>>> dict(my_dictionary)
{'foo': 3, 'aol': 1}

What's the difference between passing by reference vs. passing by value?

If you don't want to change the value of the original variable after passing it into a function, the function should be constructed with a "pass by value" parameter.

Then the function will have ONLY the value but not the address of the passed in variable. Without the variable's address, the code inside the function cannot change the variable value as seen from the outside of the function.

But if you want to give the function the ability to change the value of the variable as seen from the outside, you need to use pass by reference. As both the value and the address (reference) are passed in and available inside the function.

JavaScript is in array

IMHO most compatible with older browsers

Array.prototype.inArray = function( needle ){

    return Array(this).join(",").indexOf(needle) >-1;

}

var foods = ["Cheese","Onion","Pickle","Ham"];
test = foods.inArray("Lemon");
console.log( "Lemon is " + (test ? "" : "not ") + "in the list." );

By turning an Array copy in to a CSV string, you can test the string in older browsers.

How to subtract days from a plain Date?

Using Modern JavaScript function syntax

_x000D_
_x000D_
const getDaysPastDate = (daysBefore, date = new Date) => new Date(date - (1000 * 60 * 60 * 24 * daysBefore));_x000D_
_x000D_
console.log(getDaysPastDate(1)); // yesterday
_x000D_
_x000D_
_x000D_

Uint8Array to string in Javascript

This should work:

// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

/* utf.js - UTF-8 <=> UTF-16 convertion
 *
 * Copyright (C) 1999 Masanao Izumo <[email protected]>
 * Version: 1.0
 * LastModified: Dec 25 1999
 * This library is free.  You can redistribute it and/or modify it.
 */

function Utf8ArrayToStr(array) {
    var out, i, len, c;
    var char2, char3;

    out = "";
    len = array.length;
    i = 0;
    while(i < len) {
    c = array[i++];
    switch(c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                       ((char2 & 0x3F) << 6) |
                       ((char3 & 0x3F) << 0));
        break;
    }
    }

    return out;
}

It's somewhat cleaner as the other solutions because it doesn't use any hacks nor depends on Browser JS functions, e.g. works also in other JS environments.

Check out the JSFiddle demo.

Also see the related questions: here and here

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

If you are using express you can use the cors package to allow CORS like so instead of writing your middleware;

var express = require('express')
, cors = require('cors')
, app = express();

app.use(cors());

app.get(function(req,res){ 
  res.send('hello');
});

Checking on a thread / remove from list

The answer has been covered, but for simplicity...

# To filter out finished threads
threads = [t for t in threads if t.is_alive()]

# Same thing but for QThreads (if you are using PyQt)
threads = [t for t in threads if t.isRunning()]

How to perform a sum of an int[] array

int sum=0;
for(int i:A)
  sum+=i;

How to add a set path only for that batch file executing?

That's right, but it doesn't change it permanently, but just for current command prompt, if you wanna to change it permanently you have to use for example this:

setx ENV_VAR_NAME "DESIRED_PATH" /m

This will change it permanently and yes you can overwrite it by another batch script.

Can't clone a github repo on Linux via HTTPS

You can manual disable ssl verfiy, and try again. :)

git config --global http.sslverify false

How to open .dll files to see what is written inside?

you are better off with a decompiler like redgates .net reflector or jetbrains resharper decompiler. there are open source ones also like

http://www.jetbrains.com/decompiler/

http://ilspy.net/

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

First, you'll want to ensure the directory to your native library is on the java.library.path. See how to do that here. Then, you can call System.loadLibrary(nativeLibraryNameWithoutExtension) - making sure to not include the file extension in the name of your library.

Getting IP address of client

I use the following static helper method to retrieve the IP of a client:

public static String getClientIpAddr(HttpServletRequest request) {  
    String ip = request.getHeader("X-Forwarded-For");  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("WL-Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_FORWARDED");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("HTTP_VIA");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getHeader("REMOTE_ADDR");  
    }  
    if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
        ip = request.getRemoteAddr();  
    }  
    return ip;  
}

Where does the @Transactional annotation belong?

The correct answer for traditional Spring architectures is to place transactional semantics on the service classes, for the reasons that others have already described.

An emerging trend in Spring is toward domain-driven design (DDD). Spring Roo exemplifies the trend nicely. The idea is to make the domain object POJOs a lot richer than they are on typical Spring architectures (usually they are anemic), and in particular to put transaction and persistence semantics on the domain objects themselves. In cases where all that's needed is simple CRUD operations, the web controllers operate directly on the domain object POJOs (they're functioning as entities in this context), and there's no service tier. In cases where there's some kind of coordination needed between domain objects, you can have a service bean handle that, with @Transaction as per tradition. You can set the transaction propagation on the domain objects to something like REQUIRED so that the domain objects use any existing transactions, such as transactions that were started at the service bean.

Technically this technique makes use of AspectJ and <context:spring-configured />. Roo uses AspectJ inter-type definitions to separate the entity semantics (transactions and persistence) from the domain object stuff (basically fields and business methods).

How to get current date in jquery?

//convert month to 2 digits<p>
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);

var currentDate =  fullDate.getFullYear()+ "/" + twoDigitMonth + "/" + fullDate.getDate();
console.log(currentDate);<br>
//2011/05/19

Why does this CSS margin-top style not work?

try this:

#outer {
    width:500px; 
    height:200px; 
    background:#FFCCCC;
    margin:50px auto 0 auto;
    display:table;
}
#inner {
    background:#FFCC33;
    margin:50px 50px 50px 50px;
    padding:10px;
    display:block;
}?

http://jsfiddle.net/7AXTf/

Good luck

Difference between return 1, return 0, return -1 and exit?

As explained here, in the context of main both return and exit do the same thing

Q: Why do we need to return or exit?

A: To indicate execution status.

In your example even if you didnt have return or exit statements the code would run fine (Assuming everything else is syntactically,etc-ally correct. Also, if (and it should be) main returns int you need that return 0 at the end).

But, after execution you don't have a way to find out if your code worked as expected. You can use the return code of the program (In *nix environments , using $?) which gives you the code (as set by exit or return) . Since you set these codes yourself you understand at which point the code reached before terminating.

You can write return 123 where 123 indicates success in the post execution checks.

Usually, in *nix environments 0 is taken as success and non-zero codes as failures.

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

You can also use query scopes to make things a bit tidier, so you can do something like:

Invoice::where('account', 27)->notPaidAt($date)->get();

Then in your model

public function scopeNotPaidAt($query, $asAt)
{
    $query = $query->where(function ($query) use ($asAt) { 
        $query->where('paid', '=', '0000-00-00')->orWhere('paid', '>=', $asAt); 
    });
    return $query;    
}

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 [email protected]
:: - http://stackoverflow.com/questions/203090
@echo off

set _isotime=
set _now=

:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_

if not (%1)==() goto _help
SetLocal EnableDelayedExpansion

:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    IF "%%~L"=="" goto  _WMIC_done_
        set _yyyy=%%L
        set _mm=00%%J
        set _dd=00%%G
        set _hour=00%%H
        set _minute=00%%I
        set _second=00%%K
)
:_WMIC_done_

::   1    2     3       4      5      6
:: %%G  %%H    %%I     %%J    %%K    %%L
:: Day  Hour  Minute  Month  Second  Year
:: 27   9     35      4      38      2017

:: Remove excess leading zeroes
        set _mm=%_mm:~-2%
        set _dd=%_dd:~-2%
        set _hour=%_hour:~-2%
        set _minute=%_minute:~-2%
        set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%

:: Set date/time in ISO 8601 format:
        Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format

if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
    set /a _hour=1%_hour%-12
    set _hour=%_hour:~-2%
    set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
    :: -> https://ss64.com/nt/if.html
    :: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
    :: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_

EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out

:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%\System32\wbem\WMIC.exe"

:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo    %%_now%%     environment variable set to current date and time
echo    %%_isotime%% environment variable to current time in ISO format
echo    set _today=%%_isotime:~0,10%%
echo.

:_out
:: EOF: GetDate.cmd

Print second last column/field in awk

If you have many columns and want to print all but not the three cloumns in the last, then this might help

awk '{ $NF="";$(NF-1)="";$(NF-2)="" ; print $0 }'

Android SDK Manager Not Installing Components

In my case I had to specify proxy settings in Tools->Options.

Sort ArrayList of custom Objects by property

I found most if not all of these answers rely on the underlying class (Object) to implement comparable or to have a helper comparable interface.

Not with my solution! The following code lets you compare object's field by knowing their string name. You could easily modify it not to use the name, but then you need to expose it or construct one of the Objects you want to compare against.

Collections.sort(anArrayListOfSomeObjectPerhapsUsersOrSomething, new ReflectiveComparator(). new ListComparator("name"));

public class ReflectiveComparator {
    public class FieldComparator implements Comparator<Object> {
        private String fieldName;

        public FieldComparator(String fieldName){
            this.fieldName = fieldName;
        }

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public int compare(Object object1, Object object2) {
            try {
                Field field = object1.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);

                Comparable object1FieldValue = (Comparable) field.get(object1);
                Comparable object2FieldValue = (Comparable) field.get(object2);

                return object1FieldValue.compareTo(object2FieldValue);
            }catch (Exception e){}

            return 0;
        }
    }

    public class ListComparator implements Comparator<Object> {
        private String fieldName;

        public ListComparator(String fieldName) {
            this.fieldName = fieldName;
        }

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public int compare(Object object1, Object object2) {
            try {
                Field field = object1.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Comparable o1FieldValue = (Comparable) field.get(object1);
                Comparable o2FieldValue = (Comparable) field.get(object2);

                if (o1FieldValue == null){ return -1;}
                if (o2FieldValue == null){ return 1;}
                return o1FieldValue.compareTo(o2FieldValue);
            } catch (NoSuchFieldException e) {
                throw new IllegalStateException("Field doesn't exist", e);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException("Field inaccessible", e);
            }
        }
    }
}

Python Checking a string's first and last character

You are testing against the string minus the last character:

>>> '"xxx"'[:-1]
'"xxx'

Note how the last character, the ", is not part of the output of the slice.

I think you wanted just to test against the last character; use [-1:] to slice for just the last element.

However, there is no need to slice here; just use str.startswith() and str.endswith() directly.

Increase max_execution_time in PHP?

Add this to an htaccess file (and see edit notes added below):

<IfModule mod_php5.c>
   php_value post_max_size 200M
   php_value upload_max_filesize 200M
   php_value memory_limit 300M
   php_value max_execution_time 259200
   php_value max_input_time 259200
   php_value session.gc_maxlifetime 1200
</IfModule>

Additional resources and information:


2021 EDIT:

As PHP and Apache evolve and grow, I think it is important for me to take a moment to mention a few things to consider and possible "gotchas" to consider:

  • PHP can be run as a module or as CGI. It is not recommended to run as CGI as it creates a lot of opportunities for attack vectors [Read More]. Running as a module (the safer option) will trigger the settings to be used if the specific module from <IfModule is loaded.
  • The answer indicates to write mod_php5.c in the first line. If you are using PHP 7, you would replace that with mod_php7.c.
  • Sometimes after you make changes to your .htaccess file, restarting Apache or NGINX will not work. The most common reason for this is you are running PHP-FPM, which runs as a separate process. You need to restart that as well.
  • Remember these are settings that are normally defined in your php.ini config file(s). This method is usually only useful in the event your hosting provider does not give you access to change those files. In circumstances where you can edit the PHP configuration, it is recommended that you apply these settings there.
  • Finally, it's important to note that not all php.ini settings can be configured via an .htaccess file. A file list of php.ini directives can be found here, and the only ones you can change are the ones in the changeable column with the modes PHP_INI_ALL or PHP_INI_PERDIR.

Set Content-Type to application/json in jsp file

Try this piece of code, it should work too

<%
    //response.setContentType("Content-Type", "application/json"); // this will fail compilation
    response.setContentType("application/json"); //fixed
%>

mysqli_fetch_array while loop columns

Both will works perfectly in mysqli_fetch_array in while loops

while($row = mysqli_fetch_array($result,MYSQLI_BOTH)) {
    $posts[] = $row['post_id'].$row['post_title'].$row['content'];
}

(OR)

while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
    $posts[] = $row['post_id'].$row['post_title'].$row['content'];
}

mysqli_fetch_array() - has second argument $resulttype.

MYSQLI_ASSOC: Fetch associative array

MYSQLI_NUM: Fetch numeric array

MYSQLI_BOTH: Fetch both associative and numeric array.

Get 2 Digit Number For The Month

Simply can be used:

SELECT RIGHT('0' + CAST(MONTH(@Date) AS NVARCHAR(2)), 2)

Git merge two local branches

For merging first branch to second one:

on first branch: git merge secondBranch

on second branch: Move to first branch-> git checkout firstBranch-> git merge secondBranch

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
            //    relationship.DeleteBehavior = DeleteBehavior.Restrict;

            modelBuilder.Entity<User>().ToTable("Users");

            modelBuilder.Entity<IdentityRole<string>>().ToTable("Roles");
            modelBuilder.Entity<IdentityUserToken<string>>().ToTable("UserTokens");
            modelBuilder.Entity<IdentityUserClaim<string>>().ToTable("UserClaims");
            modelBuilder.Entity<IdentityUserLogin<string>>().ToTable("UserLogins");
            modelBuilder.Entity<IdentityRoleClaim<string>>().ToTable("RoleClaims");
            modelBuilder.Entity<IdentityUserRole<string>>().ToTable("UserRoles");

        }
    }

Rolling back local and remote git repository by 1 commit

If you only want to remove the last commit from the remote repository without messing up with your local repository, here's a one-liner:

git push origin +origin/master~:master

This uses the following syntax:

git push <remote> <refspec>

Here, <remote> is origin, and <refspec> has the following structure:

+origin/master~:master

Details can be found in git-push(1). The preceding + means "force push this ref", and the other part means "from origin/master~ to master (of remote origin)". It isn't hard to know that origin/master~ is the last commit before origin/master, right?

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

I use ".hpp" for C++ headers and ".h" for C language headers. The ".hpp" reminds me that the file contains statements for the C++ language which are not valid for the C language, such as "class" declarations.

Carriage return and Line feed... Are both required in C#?

System.Environment.NewLine is the constant you are looking for - http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx which will provide environment specific combination that most programs on given OS will consider "next line of text".

In practice most of the text tools treat all variations that include \n as "new line" and you can just use it in your text "foo\nbar". Especially if you are trying to construct multi-line format strings like $"V1 = {value1}\nV2 = {value2}\n". If you are building text with string concatenation consider using NewLine. In any case make sure tools you are using understand output the way you want and you may need for example always use \r\n irrespective of platform if editor of your choice can't correctly open files otherwise.

Note that WriteLine methods use NewLine so if you plan to write text with one these methods avoid using just \n as resulting text may contain mix of \r\n and just \n which may confuse some tools and definitely does not look neat.

For historical background see Difference between \n and \r?

Java converting int to hex and back again

It overflows, because the number is negative.

Try this and it will work:

int n = (int) Long.parseLong("ffff8000", 16);

How to update all MySQL table rows at the same time?

The default null value for a field is "not null". So you must set it to "null" before you can set that field value for any record to null. Then you can:

UPDATE `myTable` SET `myField` = null

Android Studio - No JVM Installation found

This is tested on my Windows 7 64Bit machine.

Quite strange... I had the same issue - WHILE IntelliJ Idea (including the Android Plug-in) was working perfectly.

However, here is what I did to get Android Studio 1.0 working (no step missing -> maybe it will help programming beginners).

Just set up a new environment variable by...

  1. pressing Windows-Key and typing env... you'll see "Edit the system environment variables". Click!
  2. Now click "Environment Variables..."
  3. Under System variables (NOT "User variables") add a new entry named JAVA_HOME and set the value to your Java folder (like C:\Program Files\Java\jdk1.8.0_25)
  4. apply and you are good to go.

PS: I don't know why some people writing about nuclear science when they want to explain how to set the Java path..

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

The accepted answer from @harlequin might work, but I spend 2 hours and could not build git package from source code.

However, Check the below link as this works for me.

The remote end hung up unexpectedly while git cloning

just update the http post buffer value

git config --global http.postBuffer 1048576000

How to add jQuery in JS file

I believe what you want to do is still to incude this js file in you html dom, if so then this apporach will work.

  1. Write your jquery code in your javascript file as you would in your html dom
  2. Include jquery framework before closing body tag
  3. Include javascript file after including jqyery file

Example: //js file

     $(document).ready(function(){
     alert("jquery in js file");
     });

//html dom

    <body>
   <!--some divs content--->

   <script src=/path/to/jquery.js ></script>
   <script src=/path/to/js.js ></script>
   </body>

Multiple models in a view

Another way is to use:

@model Tuple<LoginViewModel,RegisterViewModel>

I have explained how to use this method both in the view and controller for another example: Two models in one view in ASP MVC 3

In your case you could implement it using the following code:

In the view:

@using YourProjectNamespace.Models;
@model Tuple<LoginViewModel,RegisterViewModel>

@using (Html.BeginForm("Login1", "Auth", FormMethod.Post))
{
        @Html.TextBoxFor(tuple => tuple.Item2.Name, new {@Name="Name"})
        @Html.TextBoxFor(tuple => tuple.Item2.Email, new {@Name="Email"})
        @Html.PasswordFor(tuple => tuple.Item2.Password, new {@Name="Password"})
}

@using (Html.BeginForm("Login2", "Auth", FormMethod.Post))
{
        @Html.TextBoxFor(tuple => tuple.Item1.Email, new {@Name="Email"})
        @Html.PasswordFor(tuple => tuple.Item1.Password, new {@Name="Password"})
}

Note that I have manually changed the Name attributes for each property when building the form. This needs to be done, otherwise it wouldn't get properly mapped to the method's parameter of type model when values are sent to the associated method for processing. I would suggest using separate methods to process these forms separately, for this example I used Login1 and Login2 methods. Login1 method requires to have a parameter of type RegisterViewModel and Login2 requires a parameter of type LoginViewModel.

if an actionlink is required you can use:

@Html.ActionLink("Edit", "Edit", new { id=Model.Item1.Id })

in the controller's method for the view, a variable of type Tuple needs to be created and then passed to the view.

Example:

public ActionResult Details()
{
    var tuple = new Tuple<LoginViewModel, RegisterViewModel>(new LoginViewModel(),new RegisterViewModel());
    return View(tuple);
}

or you can fill the two instances of LoginViewModel and RegisterViewModel with values and then pass it to the view.

Convert Difference between 2 times into Milliseconds?

DateTime dt1 = DateTime.Parse(maskedTextBox1.Text);
DateTime dt2 = DateTime.Parse(maskedTextBox2.Text);
TimeSpan span = dt2 - dt1;
int ms = (int)span.TotalMilliseconds;

Get login username in java

The 'set Username="Username" ' is a temporary override that only exists as long as the cmd windows is still up, once it is killed off, the variable loses value. So i think the

System.getProperty("user.name");

is still a short and precise code to use.

Install specific branch from github using Npm

The Doc of the npm defines that only tag/version can be specified after repo_url.

Here is the Doc: https://docs.npmjs.com/cli/install

showing that a date is greater than current date

For SQL Server

select *
from YourTable
where DateCol between getdate() and dateadd(d, 90, getdate())

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Works in 2020

$response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization'=> 'key='. $token,
        ])->post($url, [
            'notification' => [
                'body' => $request->summary,
                'title' => $request->title,
                'image' => 'http://'.request()->getHttpHost().$path,
                
            ],
            'priority'=> 'high',
            'data' => [
                'click_action'=> 'FLUTTER_NOTIFICATION_CLICK',
                
                'status'=> 'done',
                
            ],
            'to' => '/topics/all'
        ]);

Remove all classes that begin with a certain string

Prestaul's answer was helpful, but it didn't quite work for me. The jQuery way to select an object by id didn't work. I had to use

document.getElementById("a").className

instead of

$("#a").className

How to pass prepareForSegue: an object

Sometimes it is helpful to avoid creating a compile-time dependency between two view controllers. Here's how you can do it without caring about the type of the destination view controller:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.destinationViewController respondsToSelector:@selector(setMyData:)]) {
        [segue.destinationViewController performSelector:@selector(setMyData:) 
                                              withObject:myData];
    } 
}

So as long as your destination view controller declares a public property, e.g.:

@property (nonatomic, strong) MyData *myData;

you can set this property in the previous view controller as I described above.

How to request Location Permission at runtime

This code work for me. I also handled case "Never Ask Me"

In AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

In build.gradle (Module: app)

dependencies {
    ....
    implementation "com.google.android.gms:play-services-location:16.0.0"
}

This is CurrentLocationManager.kt

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.IntentSender
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.CountDownTimer
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.CommonStatusCodes
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.LocationSettingsRequest
import com.google.android.gms.location.LocationSettingsStatusCodes
import java.lang.ref.WeakReference


object CurrentLocationManager : LocationListener {

    const val REQUEST_CODE_ACCESS_LOCATION = 123

    fun checkLocationPermission(activity: Activity) {
        if (ContextCompat.checkSelfPermission(
                activity,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                activity,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                REQUEST_CODE_ACCESS_LOCATION
            )
        } else {
            Thread(Runnable {
                // Moves the current Thread into the background
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
                //
                requestLocationUpdates(activity)
            }).start()
        }
    }

    /**
     * be used in HomeActivity.
     */
    const val REQUEST_CHECK_SETTINGS = 55
    /**
     * The number of millis in the future from the call to start().
     * until the countdown is done and onFinish() is called.
     *
     *
     * It is also the interval along the way to receive onTick(long) callbacks.
     */
    private const val TWENTY_SECS: Long = 20000
    /**
     * Timer to get location from history when requestLocationUpdates don't return result.
     */
    private var mCountDownTimer: CountDownTimer? = null
    /**
     * WeakReference of current activity.
     */
    private var mWeakReferenceActivity: WeakReference<Activity>? = null
    /**
     * user's location.
     */
    var currentLocation: Location? = null

    @Synchronized
    fun requestLocationUpdates(activity: Activity) {
        if (mWeakReferenceActivity == null) {
            mWeakReferenceActivity = WeakReference(activity)
        } else {
            mWeakReferenceActivity?.clear()
            mWeakReferenceActivity = WeakReference(activity)
        }
        //create location request: https://developer.android.com/training/location/change-location-settings.html#prompt
        val mLocationRequest = LocationRequest()
        // Which your app prefers to receive location updates. Note that the location updates may be
        // faster than this rate, or slower than this rate, or there may be no updates at all
        // (if the device has no connectivity)
        mLocationRequest.interval = 20000
        //This method sets the fastest rate in milliseconds at which your app can handle location updates.
        // You need to set this rate because other apps also affect the rate at which updates are sent
        mLocationRequest.fastestInterval = 10000
        mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

        //Get Current Location Settings
        val builder = LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest)
        //Next check whether the current location settings are satisfied
        val client = LocationServices.getSettingsClient(activity)
        val task = client.checkLocationSettings(builder.build())
        //Prompt the User to Change Location Settings
        task.addOnSuccessListener(activity) {
            Log.d("CurrentLocationManager", "OnSuccessListener")
            // All location settings are satisfied. The client can initialize location requests here.
            // If it's failed, the result after user updated setting is sent to onActivityResult of HomeActivity.
            val activity1 = mWeakReferenceActivity?.get()
            if (activity1 != null) {
                startRequestLocationUpdate(activity1.applicationContext)
            }
        }

        task.addOnFailureListener(activity) { e ->
            Log.d("CurrentLocationManager", "addOnFailureListener")
            val statusCode = (e as ApiException).statusCode
            when (statusCode) {
                CommonStatusCodes.RESOLUTION_REQUIRED ->
                    // Location settings are not satisfied, but this can be fixed
                    // by showing the user a dialog.
                    try {
                        val activity1 = mWeakReferenceActivity?.get()
                        if (activity1 != null) {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            val resolvable = e as ResolvableApiException
                            resolvable.startResolutionForResult(
                                activity1, REQUEST_CHECK_SETTINGS
                            )
                        }
                    } catch (sendEx: IntentSender.SendIntentException) {
                        // Ignore the error.
                        sendEx.printStackTrace()
                    }

                LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
                    // Location settings are not satisfied. However, we have no way
                    // to fix the settings so we won't show the dialog.
                }
            }
        }
    }

    fun startRequestLocationUpdate(appContext: Context) {
        val mLocationManager = appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (ActivityCompat.checkSelfPermission(
                appContext.applicationContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            //Utilities.showProgressDialog(mWeakReferenceActivity.get());
            if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 10000, 0f, this
                )
            } else {
                mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 10000, 0f, this
                )
            }
        }

        /*Timer to call getLastKnownLocation() when requestLocationUpdates don 't return result*/
        countDownUpdateLocation()
    }

    override fun onLocationChanged(location: Location?) {
        if (location != null) {
            stopRequestLocationUpdates()
            currentLocation = location
        }
    }

    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {

    }

    override fun onProviderEnabled(provider: String) {

    }

    override fun onProviderDisabled(provider: String) {

    }

    /**
     * Init CountDownTimer to to get location from history when requestLocationUpdates don't return result.
     */
    @Synchronized
    private fun countDownUpdateLocation() {
        mCountDownTimer?.cancel()
        mCountDownTimer = object : CountDownTimer(TWENTY_SECS, TWENTY_SECS) {
            override fun onTick(millisUntilFinished: Long) {}

            override fun onFinish() {
                if (mWeakReferenceActivity != null) {
                    val activity = mWeakReferenceActivity?.get()
                    if (activity != null && ActivityCompat.checkSelfPermission(
                            activity,
                            Manifest.permission.ACCESS_FINE_LOCATION
                        ) == PackageManager.PERMISSION_GRANTED
                    ) {
                        val location = (activity.applicationContext
                            .getSystemService(Context.LOCATION_SERVICE) as LocationManager)
                            .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)
                        stopRequestLocationUpdates()
                        onLocationChanged(location)
                    } else {
                        stopRequestLocationUpdates()
                    }
                } else {
                    mCountDownTimer?.cancel()
                    mCountDownTimer = null
                }
            }
        }.start()
    }

    /**
     * The method must be called in onDestroy() of activity to
     * removeUpdateLocation and cancel CountDownTimer.
     */
    fun stopRequestLocationUpdates() {
        val activity = mWeakReferenceActivity?.get()
        if (activity != null) {
            /*if (ActivityCompat.checkSelfPermission(activity,
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {*/
            (activity.applicationContext
                .getSystemService(Context.LOCATION_SERVICE) as LocationManager).removeUpdates(this)
            /*}*/
        }
        mCountDownTimer?.cancel()
        mCountDownTimer = null
    }
}

In MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
...
CurrentLocationManager.checkLocationPermission(this@LoginActivity)
}

override fun onDestroy() {
        CurrentLocationManager.stopRequestLocationUpdates()
        super.onDestroy()
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CurrentLocationManager.REQUEST_CODE_ACCESS_LOCATION) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                //denied
                val builder = AlertDialog.Builder(this)
                builder.setMessage("We need permission to use your location for the purpose of finding friends near you.")
                    .setTitle("Device Location Required")
                    .setIcon(com.eswapp.R.drawable.ic_info)
                    .setPositiveButton("OK") { _, _ ->
                        if (ActivityCompat.shouldShowRequestPermissionRationale(
                                this,
                                Manifest.permission.ACCESS_FINE_LOCATION
                            )
                        ) {
                            //only deny
                            CurrentLocationManager.checkLocationPermission(this@LoginActivity)
                        } else {
                            //never ask again
                            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                            val uri = Uri.fromParts("package", packageName, null)
                            intent.data = uri
                            startActivityForResult(intent, CurrentLocationManager.REQUEST_CHECK_SETTINGS)
                        }
                    }
                    .setNegativeButton("Ask Me Later") { _, _ ->

                    }
                // Create the AlertDialog object and return it
                val dialog = builder.create()
                dialog.show()
            } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                CurrentLocationManager.requestLocationUpdates(this)
            }
        }
    }

    //Forward Login result to the CallBackManager in OnActivityResult()
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            //case 1. After you allow the app access device location, Another dialog will be displayed to request you to turn on device location
            //case 2. Or You chosen Never Ask Again, you open device Setting and enable location permission
            CurrentLocationManager.REQUEST_CHECK_SETTINGS -> when (resultCode) {
                RESULT_OK -> {
                    Log.d("REQUEST_CHECK_SETTINGS", "RESULT_OK")
                    //case 1. You choose OK
                    CurrentLocationManager.startRequestLocationUpdate(applicationContext)
                }
                RESULT_CANCELED -> {
                    Log.d("REQUEST_CHECK_SETTINGS", "RESULT_CANCELED")
                    //case 1. You choose NO THANKS
                    //CurrentLocationManager.requestLocationUpdates(this)

                    //case 2. In device Setting screen: user can enable or not enable location permission,
                    // so when user back to this activity, we should re-call checkLocationPermission()
                    CurrentLocationManager.checkLocationPermission(this@LoginActivity)
                }
                else -> {
                    //do nothing
                }
            }
            else -> {
                super.onActivityResult(requestCode, resultCode, data)
            }
        }
    }

Returning an array using C

In your case, you are creating an array on the stack and once you leave the function scope, the array will be deallocated. Instead, create a dynamically allocated array and return a pointer to it.

char * returnArray(char *arr, int size) {
    char *new_arr = malloc(sizeof(char) * size);
    for(int i = 0; i < size; ++i) {
        new_arr[i] = arr[i];
    }
    return new_arr;
}

int main() {

    char arr[7]= {1,0,0,0,0,1,1};
    char *new_arr = returnArray(arr, 7);

    // don't forget to free the memory after you're done with the array
    free(new_arr);

}

How to catch all exceptions in c# using try and catch?

Note that besides all other comments there is a small difference, which should be mentioned here for completeness!

With the empty catch clause you can catch non-CLSCompliant Exceptions when the assembly is marked with "RuntimeCompatibility(WrapNonExceptionThrows = false)" (which is true by default since CLR2). [1][2][3]

[1] http://msdn.microsoft.com/en-us/library/bb264489.aspx

[2] http://blogs.msdn.com/b/pedram/archive/2007/01/07/non-cls-exceptions.aspx

[3] Will CLR handle both CLS-Complaint and non-CLS complaint exceptions?

Unique on a dataframe with only selected columns

Using unique():

dat <- data.frame(id=c(1,1,3),id2=c(1,1,4),somevalue=c("x","y","z"))    
dat[row.names(unique(dat[,c("id", "id2")])),]

ActiveRecord OR query

You could do it like:

Person.where("name = ? OR age = ?", 'Pearl', 24)

or more elegant, install rails_or gem and do it like:

Person.where(:name => 'Pearl').or(:age => 24)

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

Just do it like this:

if(!document.getElementById("someId") { /Some code. Note the NOT (!) in the expresion/ };

If element with id "someId" does not exist expresion will return TRUE (NOT FALSE === TRUE) or !false === true;

try this code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="format-detection" content="telephone-no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, minimum-scale=1, maximum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi">
        <title>Test</title>
    </head>
    <body>
      <script>
var createPerson = function (name) {
    var person;
    if (!document.getElementById(name)) {
        alert("Element does not exist. Let's create it.");
      person = document.createElement("div");
//add argument name as the ID of the element
      person.id = name;
//append element to the body of the document
      document.body.appendChild(person);
    } else {
        alert("Element exists. Lets get it by ID!");
      person = document.getElementById(name);
    }
    person.innerHTML = "HI THERE!";

};
//run the function.
createPerson("someid");
          </script>
       </body>
</html>

Try this in your browser and it should alert "Element does not exist. Let's create it."

Now add

<div id="someid"></div>

to the body of the page and try again. Voila! :)

How do I get the title of the current active window using c#?

If it happens that you need the Current Active Form from your MDI application: (MDI- Multi Document Interface).

Form activForm;
activForm = Form.ActiveForm.ActiveMdiChild;

How can I get the DateTime for the start of the week?

Did it for Monday but similar logic for Sunday.

public static DateTime GetStartOfWeekDate()
{
    // Get today's date
    DateTime today = DateTime.Today;
    // Get the value for today. DayOfWeek is an enum with 0 being Sunday, 1 Monday, etc
    var todayDayOfWeek = (int)today.DayOfWeek;

    var dateStartOfWeek = today;
    // If today is not Monday, then get the date for Monday
    if (todayDayOfWeek != 1)
    {
        // How many days to get back to Monday from today
        var daysToStartOfWeek = (todayDayOfWeek - 1);
        // Subtract from today's date the number of days to get to Monday
        dateStartOfWeek = today.AddDays(-daysToStartOfWeek);
    }

    return dateStartOfWeek;

}

How to use executables from a package installed locally in node_modules?

For Windows use this:

/* cmd into "node_modules" folder */
"%CD%\.bin\grunt" --version

Upload files from Java client to a HTTP server

Here is how you would do it with Apache HttpClient (this solution is for those who don't mind using a 3rd party library):

    HttpEntity entity = MultipartEntityBuilder.create()
                       .addPart("file", new FileBody(file))
                       .build();

    HttpPost request = new HttpPost(url);
    request.setEntity(entity);

    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(request);

Get the Selected value from the Drop down box in PHP

Couldn't you just pass the a name attribute and wrap it in a form?

<form id="form" action="do_stuff.php" method="post">
    <select id="select_catalog" name="select_catalog_query">
    <?php <<<INSERT THE SELECT OPTION LOOP>>> ?>
    </select>
</form>

And then look for $_POST['select_catalog_query'] ?

How do I keep Python print from adding newlines or spaces?

print('''first line \
second line''')

it will produce

first line second line

Not able to pip install pickle in python 3.6

import pickle

intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()

Test your pickle quickly. pickle is a part of standard python library and available by default.

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

What is Persistence Context?

  1. Entities are managed by javax.persistence.EntityManager instance using persistence context.
  2. Each EntityManager instance is associated with a persistence context.
  3. Within the persistence context, the entity instances and their lifecycle are managed.
  4. Persistence context defines a scope under which particular entity instances are created, persisted, and removed.
  5. A persistence context is like a cache which contains a set of persistent entities , So once the transaction is finished, all persistent objects are detached from the EntityManager's persistence context and are no longer managed.

How do I concatenate two text files in PowerShell?

You can do something like:

get-content input_file1 > output_file
get-content input_file2 >> output_file

Where > is an alias for "out-file", and >> is an alias for "out-file -append".

How to change status bar color in Flutter?

to Make it Like your App Bar Color

import 'package:flutter/material.dart';

 Widget build(BuildContext context) {
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      systemNavigationBarColor: Colors.transparent,
  ));
 }

What does "where T : class, new()" mean?

What comes after the "Where" is a constraint on the generic type T you declared, so:

  • class means that the T should be a class and not a value type or a struct.

  • new() indicates that the T class should have a public parameter-free default constructor defined.

PHP: trying to create a new line with "\n"

If you want a new line character to be inserted into a plain text stream then you could use the OS independent global PHP_EOL

echo "foo";
echo PHP_EOL ;
echo "bar";

In HTML terms you would see a newline between foo and bar if you looked at the source code of the page.

ergo, it is useful if you are outputting say, a loop of values for a select box and you value having html source code which is "prettier" or easier to read for yourself later. e.g.

foreach( $dogs as $dog )
echo "<option>$dog</option>" . PHP_EOL ;

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

Even i had same problem,this solution helped me so it might help you

check build version is matching with compile sdk version and add below code inside android block of build.gradle

buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

How to add and get Header values in WebApi

In case someone is using ASP.NET Core for model binding,

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

There's is built in support for retrieving values from the header using the [FromHeader] attribute

public string Test([FromHeader]string Host, [FromHeader]string Content-Type )
{
     return $"Host: {Host} Content-Type: {Content-Type}";
}

How to get EditText value and display it on screen through TextView?

yesButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        eiteText=(EditText)findViewById(R.id.nameET);
        String result=eiteText.getText().toString();
        Log.d("TAG",result);
    }
});

Gson - convert from Json to a typed ArrayList<T>

I am not sure about gson but this is how you do it with Jon.sample hope there must be similar way using gson

{ "Players": [ "player 1", "player 2", "player 3", "player 4", "player 5" ] }

===============================================

import java.io.FileReader;
import java.util.List;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JosnFileDemo {

    public static void main(String[] args) throws Exception
    {
        String jsonfile ="fileloaction/fileName.json";


                FileReader reader = null;
                JSONObject jsb = null;
                try {
                    reader = new FileReader(jsonfile);
                    JSONParser jsonParser = new JSONParser();
                     jsb = (JSONObject) jsonParser.parse(reader);
                } catch (Exception e) {
                    throw new Exception(e);
                } finally {
                    if (reader != null)
                        reader.close();
                }
                List<String> Players=(List<String>) jsb.get("Players");
                for (String player : Players) {
                    System.out.println(player);
                }           
    }
}

.trim() in JavaScript not working in IE

jQuery:

$.trim( $("#mycomment").val() );

Someone uses $("#mycomment").val().trim(); but this will not work on IE.

Working Soap client example

String send = 
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n" +
    "        <soap:Body>\n" +
    "        </soap:Body>\n" +
    "</soap:Envelope>";

private static String getResponse(String send) throws Exception {
    String url = "https://api.comscore.com/KeyMeasures.asmx"; //endpoint
    String result = "";
    String username="user_name";
    String password="pass_word";
    String[] command = {"curl", "-u", username+":"+password ,"-X", "POST", "-H", "Content-Type: text/xml", "-d", send, url};
    ProcessBuilder process = new ProcessBuilder(command); 
    Process p;
    try {
        p = process.start();
        BufferedReader reader =  new BufferedReader(new InputStreamReader(p.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ( (line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
        }
        result = builder.toString();
    }
    catch (IOException e)
    {   System.out.print("error");
        e.printStackTrace();
    }

    return result;
}

Where are logs located?

In Laravel 6, by default the logs are in:

storage/logs/laravel.log

Maven 3 warnings about build.plugins.plugin.version

Search "maven-jar-plugin" in pom.xml and add version tag maven version

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

Is there a built-in function to print all the current properties and values of an object?

You can try the Flask Debug Toolbar.
https://pypi.python.org/pypi/Flask-DebugToolbar

from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__)

# the toolbar is only enabled in debug mode:
app.debug = True

# set a 'SECRET_KEY' to enable the Flask session cookies
app.config['SECRET_KEY'] = '<replace with a secret key>'

toolbar = DebugToolbarExtension(app)

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

After reading several of these answers, I used a combination of several in Aug of 2018 to retrieve the query string params through lambda for python 3.6.

First, I went to API Gateway -> My API -> resources (on the left) -> Integration Request. Down at the bottom, select Mapping Templates then for content type enter application/json.

Next, select the Method Request Passthrough template that Amazon provides and select save and deploy your API.

Then in, lambda event['params'] is how you access all of your parameters. For query string: event['params']['querystring']