Programs & Examples On #Html parser

0

AngularJS: Insert HTML from a string

Have a look at the example in this link :

http://docs.angularjs.org/api/ngSanitize.$sanitize

Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :

If you already have done all this :

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope) {
  var str = "HELLO!";
  $scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];

Then in your html within the scope of that controller, you could

<div ng-bind-html="htmlString"></div>

Parse an HTML string with JS

with this simple code you can do that:

let el = $('<div></div>');
$(document.body).append(el);
el.html(`<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>`);
console.log(el.find('a[href="test0"]'));

HTML-parser on Node.js

Try https://github.com/tmpvar/jsdom - you give it some HTML and it gives you a DOM.

How to find numbers from a string?

Alternative via Byte Array

If you assign a string to a Byte array you typically get the number equivalents of each character in pairs of the array elements. Use a loop for numeric check via the Like operator and return the joined array as string:

Function Nums(s$)
  Dim by() As Byte, i&, ii&
  by = s: ReDim tmp(UBound(by))                    ' assign string to byte array; prepare temp array
  For i = 0 To UBound(by) - 1 Step 2               ' check num value in byte array (0, 2, 4 ... n-1)
      If Chr(by(i)) Like "#" Then tmp(ii) = Chr(by(i)): ii = ii + 1
  Next i
  Nums = Trim(Join(tmp, vbNullString))             ' return string with numbers only
  End Function

Example call

Sub testByteApproach()
  Dim s$: s = "a12bx99y /\:3,14159"                 ' [1] define original string
  Debug.Print s & " => " & Nums(s)                  ' [2] display original string and result
End Sub

would display the original string and the result string in the immediate window:

  a12bx99y /\:3,14159 => 1299314159

How to show form input fields based on select value?

$('#dbType').change(function(){

   var selection = $(this).val();
   if(selection == 'other')
   {
      $('#otherType').show();
   }
   else
   {
      $('#otherType').hide();
   } 

});

How to view the stored procedure code in SQL Server Management Studio

Use this query:

SELECT object_definition(object_id) AS [Proc Definition]
FROM sys.objects 
WHERE type='P'

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

Returning the product of a list

I am surprised no-one has suggested using itertools.accumulate with operator.mul. This avoids using reduce, which is different for Python 2 and 3 (due to the functools import required for Python 3), and moreover is considered un-pythonic by Guido van Rossum himself:

from itertools import accumulate
from operator import mul

def prod(lst):
    for value in accumulate(lst, mul):
        pass
    return value

Example:

prod([1,5,4,3,5,6])
# 1800

How to set the env variable for PHP?

You need to put the directory that has php.exe in you WAMP installation into your PATH. It is usually something like C:\wamp\xampp\php

Is there any way to install Composer globally on Windows?

sorry to dig this up, I just want to share my idea, the easy way for me is to rename composer.phar to composer.bat and put it into my PATH.

This application has no explicit mapping for /error

By default spring boot will scan current package for bean definition. So if your current package where main class is defined and controller package is not same or controller package is not child package of your main app package it will not scan the controller. To solve this issue one can include list of packages for bean definition in main package

@SpringBootApplication(scanBasePackages = {"com.module.restapi1.controller"})

or create a hierarchy of package where child package is derived from main package

package com.module.restapi;
package com.module.restapi.controller

Can the Android layout folder contain subfolders?

Now we can easily do with JetBrains plugin called "Android File Grouping"

check out this link

Android File Grouping

enter image description here

Gson library in Android Studio

If you are going to use it with Retrofit library, I suggest you to use Square's gson library as:

implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

plot a circle with pyplot

I see plots with the use of (.circle) but based on what you might want to do you can also try this out:

import matplotlib.pyplot as plt
import numpy as np

x = list(range(1,6))
y = list(range(10, 20, 2))

print(x, y)

for i, data in enumerate(zip(x,y)):
    j, k = data
    plt.scatter(j,k, marker = "o", s = ((i+1)**4)*50, alpha = 0.3)

Simple concentric circle plot using linear progressing points

centers = np.array([[5,18], [3,14], [7,6]])
m, n = make_blobs(n_samples=20, centers=[[5,18], [3,14], [7,6]], n_features=2, 
cluster_std = 0.4)
colors = ['g', 'b', 'r', 'm']

plt.figure(num=None, figsize=(7,6), facecolor='w', edgecolor='k')
plt.scatter(m[:,0], m[:,1])

for i in range(len(centers)):

    plt.scatter(centers[i,0], centers[i,1], color = colors[i], marker = 'o', s = 13000, alpha = 0.2)
    plt.scatter(centers[i,0], centers[i,1], color = 'k', marker = 'x', s = 50)

plt.savefig('plot.png')

Circled points of a classification problem.

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

MySQL Select Query - Get only first 10 characters of a value

SELECT SUBSTRING(subject, 1, 10) FROM tbl

How do I create a MongoDB dump of my database?

take mongodb backup for particular db and delete 7 days old backup using bin sh command :-

#!/bin/bash

MONGO_DATABASE="nexgtv_16"
APP_NAME="test"
MONGO_HOST="127.0.0.1"
MONGO_PORT="27017"
TIMESTAMP=`date +%F-%H%M`
MONGODUMP_PATH="/usr/bin/mongodump"
BACKUPS_DIR="/home/mongodbbackups/backups/$APP_NAME"
BACKUP_NAME="$APP_NAME-$TIMESTAMP"
$MONGODUMP_PATH -d $MONGO_DATABASE
mkdir -p $BACKUPS_DIR
mv dump $BACKUP_NAME
tar -zcvf $BACKUPS_DIR/$BACKUP_NAME.tgz $BACKUP_NAME
rm -rf $BACKUP_NAME
find /home/mongodbbackups/backups/test/ -mindepth 1 -mtime +7 -delete

GIT clone repo across local file system in windows

Not sure if it was because of my git version (1.7.2) or what, but the approaches listed above using machine name and IP options were not working for me. An additional detail that may/may not be important is that the repo was a bare repo that I had initialized and pushed to from a different machine.

I was trying to clone project1 as advised above with commands like:

$ git clone file:////<IP_ADDRESS>/home/user/git/project1
Cloning into project1...
fatal: '//<IP_ADDRESS>/home/user/git/project1' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

and

$ git clone file:////<MACHINE_NAME>/home/user/git/project1
Cloning into project1...
fatal: '//<MACHINE_NAME>/home/user/git/project1' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

What did work for me was something simpler:

$ git clone ../git/project1
Cloning into project1...
done.

Note - even though the repo being cloned from was bare, this did produce a 'normal' clone with all the actual code/image/resource files that I was hoping for (as opposed to the internals of the git repo).

git: How to ignore all present untracked files?

As already been said, to exclude from status just use:

git status -uno  # must be "-uno" , not "-u no"

If you instead want to permanently ignore currently untracked files you can, from the root of your project, launch:

git status --porcelain | grep '^??' | cut -c4- >> .gitignore

Every subsequent call to git status will explicitly ignore those files.

UPDATE: the above command has a minor drawback: if you don't have a .gitignore file yet your gitignore will ignore itself! This happens because the file .gitignore gets created before the git status --porcelain is executed. So if you don't have a .gitignore file yet I recommend using:

echo "$(git status --porcelain | grep '^??' | cut -c4-)" > .gitignore

This creates a subshell which completes before the .gitignore file is created.

COMMAND EXPLANATION as I'm getting a lot of votes (thank you!) I think I'd better explain the command a bit:

  • git status --porcelain is used instead of git status --short because manual states "Give the output in an easy-to-parse format for scripts. This is similar to the short output, but will remain stable across git versions and regardless of user configuration." So we have both the parseability and stability;
  • grep '^??' filters only the lines starting with ??, which, according to the git status manual, correspond to the untracked files;
  • cut -c4- removes the first 3 characters of every line, which gives us just the relative path to the untracked file;
  • the | symbols are pipes, which pass the output of the previous command to the input of the following command;
  • the >> and > symbols are redirect operators, which append the output of the previous command to a file or overwrites/creates a new file, respectively.

ANOTHER VARIANT for those who prefer using sed instead of grep and cut, here's another way:

git status --porcelain | sed -n -e 's/^?? //p' >> .gitignore

JOIN two SELECT statement results

Use UNION:

SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks

Or UNION ALL if you want duplicates:

SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION ALL
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks

Can constructors be async?

Your problem is comparable to the creation of a file object and opening the file. In fact there are a lot of classes where you have to perform two steps before you can actually use the object: create + Initialize (often called something similar to Open).

The advantage of this is that the constructor can be lightweight. If desired, you can change some properties before actually initializing the object. When all properties are set, the Initialize/Open function is called to prepare the object to be used. This Initialize function can be async.

The disadvantage is that you have to trust the user of your class that he will call Initialize() before he uses any other function of your class. In fact if you want to make your class full proof (fool proof?) you have to check in every function that the Initialize() has been called.

The pattern to make this easier is to declare the constructor private and make a public static function that will construct the object and call Initialize() before returning the constructed object. This way you'll know that everyone who has access to the object has used the Initialize function.

The example shows a class that mimics your desired async constructor

public MyClass
{
    public static async Task<MyClass> CreateAsync(...)
    {
        MyClass x = new MyClass();
        await x.InitializeAsync(...)
        return x;
    }

    // make sure no one but the Create function can call the constructor:
    private MyClass(){}

    private async Task InitializeAsync(...)
    {
        // do the async things you wanted to do in your async constructor
    }

    public async Task<int> OtherFunctionAsync(int a, int b)
    {
        return await ... // return something useful
    }

Usage will be as follows:

public async Task<int> SomethingAsync()
{
    // Create and initialize a MyClass object
    MyClass myObject = await MyClass.CreateAsync(...);

    // use the created object:
    return await myObject.OtherFunctionAsync(4, 7);
}

How to merge rows in a column into one cell in excel?

I use the CONCATENATE method to take the values of a column and wrap quotes around them with columns in between in order to quickly populate the WHERE IN () clause of a SQL statement.

I always just type =CONCATENATE("'",B2,"'",",") and then select that and drag it down, which creates =CONCATENATE("'",B3,"'",","), =CONCATENATE("'",B4,"'",","), etc. then highlight that whole column, copy paste to a plain text editor and paste back if needed, thus stripping the row separation. It works, but again, just as a one time deal, this is not a good solution for someone who needs this all the time.

Passing arguments to JavaScript function from code-behind

I think you want to execute the javascript serverside and not in the browser after post-back, right?

That's not possible as far as I know

If you just want to get it execute after postback, you can do something like this:

this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx", "<script>test("+x+","+y+");</script>");

Removing single-quote from a string in php

You can substitute in HTML entitiy:

$FileName = preg_replace("/'/", "\&#39;", $UserInput);

pow (x,y) in Java

Additionally for what was said, if you want integer powers of two, then 1 << x (or 1L << x) is a faster way to calculate 2x than Math.pow(2,x) or a multiplication loop, and is guaranteed to give you an int (or long) result.

It only uses the lowest 5 (or 6) bits of x (i.e. x & 31 (or x & 63)), though, shifting between 0 and 31 (or 63) bits.

socket programming multiple client to one server

For every client you need to start separate thread. Example:

public class ThreadedEchoServer {

    static final int PORT = 1978;

    public static void main(String args[]) {
        ServerSocket serverSocket = null;
        Socket socket = null;

        try {
            serverSocket = new ServerSocket(PORT);
        } catch (IOException e) {
            e.printStackTrace();

        }
        while (true) {
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                System.out.println("I/O error: " + e);
            }
            // new thread for a client
            new EchoThread(socket).start();
        }
    }
}

and

public class EchoThread extends Thread {
    protected Socket socket;

    public EchoThread(Socket clientSocket) {
        this.socket = clientSocket;
    }

    public void run() {
        InputStream inp = null;
        BufferedReader brinp = null;
        DataOutputStream out = null;
        try {
            inp = socket.getInputStream();
            brinp = new BufferedReader(new InputStreamReader(inp));
            out = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            return;
        }
        String line;
        while (true) {
            try {
                line = brinp.readLine();
                if ((line == null) || line.equalsIgnoreCase("QUIT")) {
                    socket.close();
                    return;
                } else {
                    out.writeBytes(line + "\n\r");
                    out.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
    }
}

You can also go with more advanced solution, that uses NIO selectors, so you will not have to create thread for every client, but that's a bit more complicated.

Detect IF hovering over element with jQuery

Couple updates to add after working on this subject for a while:

  1. all solutions with .is(":hover") break on jQuery 1.9.1
  2. The most likely reason to check if the mouse is still over an element is to attempt to prevent events firing over each other. For example, we were having issues with our mouseleave being triggered and completed before our mouseenter event even completed. Of course this was because of a quick mouse movement.

We used hoverIntent https://github.com/briancherne/jquery-hoverIntent to solve the issue for us. Essentially it triggers if the mouse movement is more deliberate. (one thing to note is that it will trigger on both mouse entering an element and leaving - if you only want to use one pass the constructor an empty function )

What is the correct way to write HTML using Javascript?

I'm not particularly great at JavaScript or its best practices, but document.write() along with innerHtml() basically allows you to write out strings that may or may not be valid HTML; it's just characters. By using the DOM, you ensure proper, standards-compliant HTML that will keep your page from breaking via plainly bad HTML.

And, as Tom mentioned, JavaScript is done after the page is loaded; it'd probably be a better practice to have the initial setup for your page to be done via standard HTML (via .html files or whatever your server does [i.e. php]).

ASP.NET GridView RowIndex As CommandArgument

Here is Microsoft Suggestion for this http://msdn.microsoft.com/en-us/library/bb907626.aspx#Y800

On the gridview add a command button and convert it into a template, then give it a commandname in this case "AddToCart" and also add CommandArgument "<%# ((GridViewRow) Container).RowIndex %>"

<asp:TemplateField>
  <ItemTemplate>
    <asp:Button ID="AddButton" runat="server" 
      CommandName="AddToCart" 
      CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
      Text="Add to Cart" />
  </ItemTemplate> 
</asp:TemplateField>

Then for create on the RowCommand event of the gridview identify when the "AddToCart" command is triggered, and do whatever you want from there

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "AddToCart")
  {
    // Retrieve the row index stored in the 
    // CommandArgument property.
    int index = Convert.ToInt32(e.CommandArgument);

    // Retrieve the row that contains the button 
    // from the Rows collection.
    GridViewRow row = GridView1.Rows[index];

    // Add code here to add the item to the shopping cart.
  }
}

**One mistake I was making is that I wanted to add the actions on my template button instead of doing it directly on the RowCommand Event.

Alternative for frames in html5 using iframes

While I agree with everyone else, if you are dead set on using frames anyway, you can just do index.html in XHTML and then do the contents of the frames in HTML5.

How to get current route

To get the route segments:

import { ActivatedRoute, UrlSegment } from '@angular/router';

constructor( route: ActivatedRoute) {}

getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }

Git: How to find a deleted file in the project commit history?

Summary:

  1. Step 1

You search your file full path in history of deleted files git log --diff-filter=D --summary | grep filename

  1. Step 2

You restore your file from commit before it was deleted

restore () {
  filepath="$@"
  last_commit=$(git log --all --full-history -- $filepath | grep commit | head -1 | awk '{print $2; exit}')
  echo "Restoring file from commit before $last_commit"
  git checkout $last_commit^ -- $filepath
}

restore my/file_path

Counting number of occurrences in column?

A simpler approach to this

At the beginning of column B, type

=UNIQUE(A:A)

Then in column C, use

=COUNTIF(A:A, B1)

and copy them in all row column C.

Edit: If that doesn't work for you, try using semicolon instead of comma:

=COUNTIF(A:A; B1)

Hashmap holding different data types as values for instance Integer, String and Object

If you don't have Your own Data Class, then you can design your map as follows

Map<Integer, Object> map=new HashMap<Integer, Object>();

Here don't forget to use "instanceof" operator while retrieving the values from MAP.

If you have your own Data class then then you can design your map as follows

Map<Integer, YourClassName> map=new HashMap<Integer, YourClassName>();

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class HashMapTest {
public static void main(String[] args) {
    Map<Integer,Demo> map=new HashMap<Integer, Demo>();
    Demo d1= new Demo(1,"hi",new Date(),1,1);
    Demo d2= new Demo(2,"this",new Date(),2,1);
    Demo d3= new Demo(3,"is",new Date(),3,1);
    Demo d4= new Demo(4,"mytest",new Date(),4,1);
    //adding values to map
    map.put(d1.getKey(), d1);
    map.put(d2.getKey(), d2);
    map.put(d3.getKey(), d3);
    map.put(d4.getKey(), d4);
    //retrieving values from map
    Set<Integer> keySet= map.keySet();
    for(int i:keySet){
        System.out.println(map.get(i));
    }
    //searching key on map
    System.out.println(map.containsKey(d1.getKey()));
    //searching value on map
    System.out.println(map.containsValue(d1));
}

}
class Demo{
    private int key;
    private String message;
    private Date time;
    private int count;
    private int version;

    public Demo(int key,String message, Date time, int count, int version){
        this.key=key;
        this.message = message;
        this.time = time;
        this.count = count;
        this.version = version;
    }
    public String getMessage() {
        return message;
    }
    public Date getTime() {
        return time;
    }
    public int getCount() {
        return count;
    }
    public int getVersion() {
        return version;
    }
    public int getKey() {
        return key;
    }
    @Override
    public String toString() {
        return "Demo [message=" + message + ", time=" + time
                + ", count=" + count + ", version=" + version + "]";
    }

}

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

Calling a PHP function using the HTML button: Create an HTML form document which contains the HTML button. When the button is clicked the method POST is called. The POST method describes how to send data to the server. After clicking the button, the array_key_exists() function called.

<?php
    if(array_key_exists('button1', $_POST)) { 
        button1(); 
    } 
    else if(array_key_exists('button2', $_POST)) { 
        button2(); 
    } 
    function button1() { 
        echo "This is Button1 that is selected"; 
    } 
    function button2() { 
        echo "This is Button2 that is selected"; 
    } 
?> 

<form method="post"> 
    <input type="submit" name="button1" class="button" value="Button1" /> 
    <input type="submit" name="button2" class="button" value="Button2" /> 
</form> 

source: geeksforgeeks.org

Conversion hex string into ascii in bash command line

The echo -e must have been failing for you because of wrong escaping. The following code works fine for me on a similar output from your_program with arguments:

echo -e $(your_program with arguments | sed -e 's/0x\(..\)\.\?/\\x\1/g')

Please note however that your original hexstring consists of non-printable characters.

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

Of the options you asked about:

  • float:left;
    I dislike floats because of the need to have additional markup to clear the float. As far as I'm concerned, the whole float concept was poorly designed in the CSS specs. Nothing we can do about that now though. But the important thing is it does work, and it works in all browsers (even IE6/7), so use it if you like it.

The additional markup for clearing may not be necessary if you use the :after selector to clear the floats, but this isn't an option if you want to support IE6 or IE7.

  • display:inline;
    This shouldn't be used for layout, with the exception of IE6/7, where display:inline; zoom:1 is a fall-back hack for the broken support for inline-block.

  • display:inline-block;
    This is my favourite option. It works well and consistently across all browsers, with a caveat for IE6/7, which support it for some elements. But see above for the hacky solution to work around this.

The other big caveat with inline-block is that because of the inline aspect, the white spaces between elements are treated the same as white spaces between words of text, so you can get gaps appearing between elements. There are work-arounds to this, but none of them are ideal. (the best is simply to not have any spaces between the elements)

  • display:table-cell;
    Another one where you'll have problems with browser compatibility. Older IEs won't work with this at all. But even for other browsers, it's worth noting that table-cell is designed to be used in a context of being inside elements that are styled as table and table-row; using table-cell in isolation is not the intended way to do it, so you may experience different browsers treating it differently.

Other techniques you may have missed? Yes.

  • Since you say this is for a multi-column layout, there is a CSS Columns feature that you might want to know about. However it isn't the most well supported feature (not supported by IE even in IE9, and a vendor prefix required by all other browsers), so you may not want to use it. But it is another option, and you did ask.

  • There's also CSS FlexBox feature, which is intended to allow you to have text flowing from box to box. It's an exciting feature that will allow some complex layouts, but this is still very much in development -- see http://html5please.com/#flexbox

Hope that helps.

How to reset / remove chrome's input highlighting / focus border?

This will definitely work. Orange outline won't show up anymore.. Common for all tags:

*:focus {
    outline: none;
   }

Specific to some tag, ex: input tag

input:focus{
   outline:none;
  }

Loop through each cell in a range of cells when given a Range object

I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until loop.

Do Until Selection.Value = ""
  Rem Do things here...
Loop

Has anyone gotten HTML emails working with Twitter Bootstrap?

What about Bootstrap Email? This seems to really nice and compatible with bootstrap 4.

Delete multiple rows by selecting checkboxes using PHP

Delete Multiple checkbox using PHP Code

<input type="checkbox" name="chkbox[]  value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
 $cnt=array();
 $cnt=count($_POST['chkbox']);
 for($i=0;$i<$cnt;$i++)
  {
     $del_id=$_POST['chkbox'][$i];
     $query="delete from $tablename where Id=".$del_id;
     mysql_query($query);
  }
}

how to install gcc on windows 7 machine?

I use msysgit to install gcc on Windows, it has a nice installer which installs most everything that you might need. Most devs will need more than just the compiler, e.g. the shell, shell tools, make, git, svn, etc. msysgit comes with all of that. https://msysgit.github.io/

edit: I am now using msys2. Msys2 uses pacman from Arch Linux to install packages, and includes three environments, for building msys2 apps, 32-bit native apps, and 64-bit native apps. (You probably want to build 32-bit native apps.)

https://msys2.github.io/

You could also go full-monty and install code::blocks or some other gui editor that comes with a compiler. I prefer to use vim and make.

Plotting time-series with Date labels on x-axis

1) Since the times are dates be sure to use "Date" class, not "POSIXct" or "POSIXlt". See R News 4/1 for advice and try this where Lines is defined in the Note at the end. No packages are used here.

dm <- read.table(text = Lines, header = TRUE)
dm$Date <- as.Date(dm$Date, "%m/%d/%Y")
plot(Visits ~ Date, dm, xaxt = "n", type = "l")
axis(1, dm$Date, format(dm$Date, "%b %d"), cex.axis = .7)

The use of text = Lines is just to keep the example self-contained and in reality it would be replaced with something like "myfile.dat" . (continued after image)

screenshot

2) Since this is a time series you may wish to use a time series representation giving slightly simpler code:

library(zoo)

z <- read.zoo(text = Lines, header = TRUE, format = "%m/%d/%Y")
plot(z, xaxt = "n")
axis(1, dm$Date, format(dm$Date, "%b %d"), cex.axis = .7)

Depending on what you want the plot to look like it may be sufficient just to use plot(Visits ~ Date, dm) in the first case or plot(z) in the second case suppressing the axis command entirely. It could also be done using xyplot.zoo

library(lattice)
xyplot(z)

or autoplot.zoo:

library(ggplot2)
autoplot(z)

Note:

Lines <- "Date            Visits
11/1/2010   696537
11/2/2010   718748
11/3/2010   799355
11/4/2010   805800
11/5/2010   701262
11/6/2010   531579
11/7/2010   690068
11/8/2010   756947
11/9/2010   718757
11/10/2010  701768
11/11/2010  820113
11/12/2010  645259"

Python, Pandas : write content of DataFrame into text File

Way to get Excel data to text file in tab delimited form. Need to use Pandas as well as xlrd.

import pandas as pd
import xlrd
import os

Path="C:\downloads"
wb = pd.ExcelFile(Path+"\\input.xlsx", engine=None)
sheet2 = pd.read_excel(wb, sheet_name="Sheet1")
Excel_Filter=sheet2[sheet2['Name']=='Test']
Excel_Filter.to_excel("C:\downloads\\output.xlsx", index=None)
wb2=xlrd.open_workbook(Path+"\\output.xlsx")
df=wb2.sheet_by_name("Sheet1")
x=df.nrows
y=df.ncols

for i in range(0,x):
    for j in range(0,y):
        A=str(df.cell_value(i,j))
        f=open(Path+"\\emails.txt", "a")
        f.write(A+"\t")
        f.close()
    f=open(Path+"\\emails.txt", "a")
    f.write("\n")
    f.close()
os.remove(Path+"\\output.xlsx")
print(Excel_Filter)

We need to first generate the xlsx file with filtered data and then convert the information into a text file.

Depending on requirements, we can use \n \t for loops and type of data we want in the text file.

how to pass list as parameter in function

You should always avoid using List<T> as a parameter. Not only because this pattern reduces the opportunities of the caller to store the data in a different kind of collection, but also the caller has to convert the data into a List first.

Converting an IEnumerable into a List costs O(n) complexity which is absolutely unneccessary. And it also creates a new object.

TL;DR you should always use a proper interface like IEnumerable or IQueryable based on what do you want to do with your collection. ;)

In your case:

public void foo(IEnumerable<DateTime> dateTimes)
{
}

How to add "required" attribute to mvc razor viewmodel text input editor

You can use the required html attribute if you want:

@Html.TextBoxFor(m => m.ShortName, 
new { @class = "form-control", placeholder = "short name", required="required"})

or you can use the RequiredAttribute class in .Net. With jQuery the RequiredAttribute can Validate on the front end and server side. If you want to go the MVC route, I'd suggest reading Data annotations MVC3 Required attribute.

OR

You can get really advanced:

@{
  // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
  var attributes = new Dictionary<string, object>(
    Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix));

 attributes.Add("class", "form-control");
 attributes.Add("placeholder", "short name");

  if (ViewData.ModelMetadata.ContainerType
      .GetProperty(ViewData.ModelMetadata.PropertyName)
      .GetCustomAttributes(typeof(RequiredAttribute), true)
      .Select(a => a as RequiredAttribute)
      .Any(a => a != null))
  {
   attributes.Add("required", "required");
  }

  @Html.TextBoxFor(m => m.ShortName, attributes)

}

or if you need it for multiple editor templates:

public static class ViewPageExtensions
{
  public static IDictionary<string, object> GetAttributes(this WebViewPage instance)
  {
    // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
    var attributes = new Dictionary<string, object>(
      instance.Html.GetUnobtrusiveValidationAttributes(
         instance.ViewData.TemplateInfo.HtmlFieldPrefix));

    if (ViewData.ModelMetadata.ContainerType
      .GetProperty(ViewData.ModelMetadata.PropertyName)
      .GetCustomAttributes(typeof(RequiredAttribute), true)
      .Select(a => a as RequiredAttribute)
      .Any(a => a != null))
    {
      attributes.Add("required", "required");
    }
  }
}

then in your templates:

@{
  // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
  var attributes = this.GetAttributes();

  attributes.Add("class", "form-control");
  attributes.Add("placeholder", "short name");

  @Html.TextBoxFor(m => m.ShortName, attributes)

}

Update 1 (for Tomas who is unfamilar with ViewData).

What's the difference between ViewData and ViewBag?

Excerpt:

So basically it (ViewBag) replaces magic strings:

ViewData["Foo"]

with magic properties:

ViewBag.Foo

Skip a submodule during a Maven build

The notion of multi-module projects is there to service the needs of codependent segments of a project. Such a client depends on the services which in turn depends on say EJBs or data-access routines. You could group your continuous integration (CI) tests in this manner. I would rationalize that by saying that the CI tests need to be in lock-step with application logic changes.

Suppose your project is structured as:

project-root
  |
  + --- ci
  |
  + --- client
  |
  + --- server

The project-root/pom.xml defines modules

<modules>
  <module>ci</module>
  <module>client</module>
  <module>server</module>
</modules>

The ci/pom.xml defines profiles such as:

... 
<profiles>
  <profile>
    <id>default</id>
    <activation>
      <activeByDefault>true</activeByDefault>
    </activation>
    <plugin>
       <artifactId>maven-surefire-plugin</artifactId>
       <configuration>
         <skip>true</skip>
       </configuration>
     </plugin>
  </profile>
  <profile>
    <id>CI</id>
    <plugin>
       <artifactId>maven-surefire-plugin</artifactId>
       <configuration>
         <skip>false</skip>
       </configuration>
     </plugin>
  </profile>
</profiles>

This will result in Maven skipping tests in this module except when the profile named CI is active. Your CI server must be instructed to execute mvn clean package -P CI. The Maven web site has an in-depth explanation of the profiling mechanism.

Fatal error: Call to undefined function socket_create()

I got this error when my .env file was not set up properly. Make sure you have a .env file with valid database login credentials.

How to write a Python module/package?

Make a file named "hello.py"

If you are using Python 2.x

def func():
    print "Hello"

If you are using Python 3.x

def func():
    print("Hello")

Run the file. Then, you can try the following:

>>> import hello
>>> hello.func()
Hello

If you want a little bit hard, you can use the following:

If you are using Python 2.x

def say(text):
    print text

If you are using Python 3.x

def say(text):
    print(text)

See the one on the parenthesis beside the define? That is important. It is the one that you can use within the define.

Text - You can use it when you want the program to say what you want. According to its name, it is text. I hope you know what text means. It means "words" or "sentences".

Run the file. Then, you can try the following if you are using Python 3.x:

>>> import hello
>>> hello.say("hi")
hi
>>> from hello import say
>>> say("test")
test

For Python 2.x - I guess same thing with Python 3? No idea. Correct me if I made a mistake on Python 2.x (I know Python 2 but I am used with Python 3)

What is an unhandled promise rejection?

Try not closing the connection before you send data to your database. Remove client.close(); from your code and it'll work fine.

Ternary operator ?: vs if...else

Regardless the compiled code, They are semantically different thing. <cond>?<true expr>:<false expr> is an expression and if..else.. is a statement.

Although the syntax of conditional expression seems awkward, it is a good thing. You are forced to provide a <false expr> and the two expressions are type checked.

The equivalent to if..else.. in expression-based, functional language like Lisp, Haskell is ? : in C++, instead of if..else.. statement.

How to Force New Google Spreadsheets to refresh and recalculate?

Quick, but manual


Updating NOW(), TODAY(), RAND(), or RANDBETWEEN() formulas

Press Backspace ? or Del on any empty cell to immediately trigger a recalculation of formulas depending on NOW(), TODAY(), RAND(), or RANDBETWEEN() (in all Sheets of the whole Spreadsheet, as usual).

(If no empty cell is at hand, you can delete a filled cell instead and then undo that with Ctrl+z.)

INDIRECT() formulas are unfortunately not updated like this by default.

Updating INDIRECT() formulas

You can update a (range of) cells of INDIRECT() formulas by pasting the range on itself:

  1. Select cell/ range
  2. Ctrl+C
  3. Ctrl+V

You can use Ctrl+A to select the whole current Sheet in step 1.. But for large Sheets then the other 2 operations can take several seconds each.
A trick to know when the process of copying a large range has finished: Copy some single cell before copying your range: The single cell losing its dotted border will be your notification of the large copy finishing.

Create an array with same element repeated multiple times

You can also extend the functionality of Array like so:

Array.prototype.fill = function(val){
    for (var i = 0; i < this.length; i++){
        this[i] = val;
    }
    return this;
};
// used like:
var arry = new Array(5)?.fill(2);
// or
var arry = new Array(5);
arry.fill(2);


?console.log(arry);? //[2, 2, 2, 2, 2] 

I should note that extending the functionality of built-in objects can cause problems if you are working with 3rd-party libraries. Always weigh this into your decisions.

Sorting data based on second column of a file

Solution:

sort -k 2 -n filename

more verbosely written as:

sort --key 2 --numeric-sort filename


Example:

$ cat filename
A 12
B 48
C 3

$ sort --key 2 --numeric-sort filename 
C 3
A 12
B 48

Explanation:

  • -k # - this argument specifies the first column that will be used to sort. (note that column here is defined as a whitespace delimited field; the argument -k5 will sort starting with the fifth field in each line, not the fifth character in each line)

  • -n - this option specifies a "numeric sort" meaning that column should be interpreted as a row of numbers, instead of text.


More:

Other common options include:

  • -r - this option reverses the sorting order. It can also be written as --reverse.
  • -i - This option ignores non-printable characters. It can also be written as --ignore-nonprinting.
  • -b - This option ignores leading blank spaces, which is handy as white spaces are used to determine the number of rows. It can also be written as --ignore-leading-blanks.
  • -f - This option ignores letter case. "A"=="a". It can also be written as --ignore-case.
  • -t [new separator] - This option makes the preprocessing use a operator other than space. It can also be written as --field-separator.

There are other options, but these are the most common and helpful ones, that I use often.

IntelliJ and Tomcat.. Howto..?

Please verify that the required plug-ins are enabled in Settings | Plugins, most likely you've disabled several of them, that's why you don't see all the facet options.

For the step by step tutorial, see: Creating a simple Web application and deploying it to Tomcat.

CSS3 Transition - Fade out effect

You can use transitions instead:

.successfully-saved.hide-opacity{
    opacity: 0;
}

.successfully-saved {
    color: #FFFFFF;
    text-align: center;

    -webkit-transition: opacity 3s ease-in-out;
    -moz-transition: opacity 3s ease-in-out;
    -ms-transition: opacity 3s ease-in-out;
    -o-transition: opacity 3s ease-in-out;
     opacity: 1;
}

How do I delete everything below row X in VBA/Excel?

It sounds like something like the below will suit your needs:

With Sheets("Sheet1")
    .Rows( X & ":" & .Rows.Count).Delete
End With

Where X is a variable that = the row number ( 415 )

Edit existing excel workbooks and sheets with xlrd and xlwt

Here's another way of doing the code above using the openpyxl module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.

from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')

How to create a custom exception type in Java?

You just need to create a class which extends Exception (for a checked exception) or any subclass of Exception, or RuntimeException (for a runtime exception) or any subclass of RuntimeException.

Then, in your code, just use

if (word.contains(" "))
    throw new MyException("some message");
}

Read the Java tutorial. This is basic stuff that every Java developer should know: http://docs.oracle.com/javase/tutorial/essential/exceptions/

How do I install chkconfig on Ubuntu?

Install this package in Ubuntu:

apt install sysv-rc-conf

its a substitute for chkconfig cmd.

After install run this cmd:

sysv-rc-conf --list

It'll show all services in all the runlevels. You can also run this:

sysv-rc-conf --level (runlevel number ex:1 2 3 4 5 6 )

Now you can choose which service should be active in boot time.

javascript password generator

var createPassword = function() {
  var passAt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  var passArray = Array.from({length: 15})

  return passArray.map(function(_, index) { 
    return index % 4 == 3 ? '-' : passAt.charAt(Math.random() * passAt.length)
  }).join('')
}

result like:

L5X-La0-bN0-UQO
9eW-svG-OdS-8Xf
ick-u73-2s0-TMX
5ri-PRP-MNO-Z1j

Working with a List of Lists in Java

Here's an example that reads a list of CSV strings into a list of lists and then loops through that list of lists and prints the CSV strings back out to the console.

import java.util.ArrayList;
import java.util.List;

public class ListExample
{
    public static void main(final String[] args)
    {
        //sample CSV strings...pretend they came from a file
        String[] csvStrings = new String[] {
                "abc,def,ghi,jkl,mno",
                "pqr,stu,vwx,yz",
                "123,345,678,90"
        };

        List<List<String>> csvList = new ArrayList<List<String>>();

        //pretend you're looping through lines in a file here
        for(String line : csvStrings)
        {
            String[] linePieces = line.split(",");
            List<String> csvPieces = new ArrayList<String>(linePieces.length);
            for(String piece : linePieces)
            {
                csvPieces.add(piece);
            }
            csvList.add(csvPieces);
        }

        //write the CSV back out to the console
        for(List<String> csv : csvList)
        {
            //dumb logic to place the commas correctly
            if(!csv.isEmpty())
            {
                System.out.print(csv.get(0));
                for(int i=1; i < csv.size(); i++)
                {
                    System.out.print("," + csv.get(i));
                }
            }
            System.out.print("\n");
        }
    }
}

Pretty straightforward I think. Just a couple points to notice:

  1. I recommend using "List" instead of "ArrayList" on the left side when creating list objects. It's better to pass around the interface "List" because then if later you need to change to using something like Vector (e.g. you now need synchronized lists), you only need to change the line with the "new" statement. No matter what implementation of list you use, e.g. Vector or ArrayList, you still always just pass around List<String>.

  2. In the ArrayList constructor, you can leave the list empty and it will default to a certain size and then grow dynamically as needed. But if you know how big your list might be, you can sometimes save some performance. For instance, if you knew there were always going to be 500 lines in your file, then you could do:

List<List<String>> csvList = new ArrayList<List<String>>(500);

That way you would never waste processing time waiting for your list to grow dynamically grow. This is why I pass "linePieces.length" to the constructor. Not usually a big deal, but helpful sometimes.

Hope that helps!

how to move elasticsearch data from one server to another

There is also the _reindex option

From documentation:

Through the Elasticsearch reindex API, available in version 5.x and later, you can connect your new Elasticsearch Service deployment remotely to your old Elasticsearch cluster. This pulls the data from your old cluster and indexes it into your new one. Reindexing essentially rebuilds the index from scratch and it can be more resource intensive to run.

POST _reindex
{
  "source": {
    "remote": {
      "host": "https://REMOTE_ELASTICSEARCH_ENDPOINT:PORT",
      "username": "USER",
      "password": "PASSWORD"
    },
    "index": "INDEX_NAME",
    "query": {
      "match_all": {}
    }
  },
  "dest": {
    "index": "INDEX_NAME"
  }
}

How to check if a MySQL query using the legacy API was successful?

mysql_query function is used for executing mysql query in php. mysql_query returns false if query execution fails.Alternatively you can try using mysql_error() function For e.g

$result=mysql_query($sql)

or

die(mysql_error());

In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.

Matplotlib - global legend and title aside subplots

suptitle seems the way to go, but for what it's worth, the figure has a transFigure property that you can use:

fig=figure(1)
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center')

Access index of the parent ng-repeat from child ng-repeat

My example code was correct and the issue was something else in my actual code. Still, I know it was difficult to find examples of this so I'm answering it in case someone else is looking.

<div ng-repeat="f in foos">
  <div>
    <div ng-repeat="b in foos.bars">
      <a ng-click="addSomething($parent.$index)">Add Something</a>
    </div>
  </div>
</div>

How to add hours to current date in SQL Server?

Select JoiningDate ,Dateadd (day , 30 , JoiningDate)
from Emp

Select JoiningDate ,DateAdd (month , 10 , JoiningDate)
from Emp

Select JoiningDate ,DateAdd (year , 10 , JoiningDate )
from Emp

Select DateAdd(Hour, 10 , JoiningDate )
from emp


Select dateadd (hour , 10 , getdate()), getdate()

Select dateadd (hour , 10 , joiningDate)
from Emp


Select DateAdd (Second , 120 , JoiningDate ) , JoiningDate 
From EMP

How do I set default values for functions parameters in Matlab?

I believe I found quite a nifty way to deal with this issue, taking up only three lines of code (barring line wraps). The following is lifted directly from a function I am writing, and it seems to work as desired:

defaults = {50/6,3,true,false,[375,20,50,0]}; %set all defaults
defaults(1:nargin-numberForcedParameters) = varargin; %overload with function input
[sigma,shifts,applyDifference,loop,weights] = ...
     defaults{:}; %unfold the cell struct

Just thought I'd share it.

What to return if Spring MVC controller method doesn't return value?

You can simply return a ResponseEntity with the appropriate header:

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
public ResponseEntity updateDataThatDoesntRequireClientToBeNotified(...){
....
return new ResponseEntity(HttpStatus.OK)
}

How to change root logging level programmatically for logback

I assume you are using logback (from the configuration file).

From logback manual, I see

Logger rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);

Perhaps this can help you change the value?

How to get the current time as datetime

You can use Swift4 or Swift 5 bellow like:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let current_date = dateFormatter.string(from: date)
print("current_date-->",current_date)

output like:

2020-03-02

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

Inserting NOW() into Database with CodeIgniter's Active Record

According to the source code of codeigniter, the function set is defined as:

public function set($key, $value = '', $escape = TRUE)
{
    $key = $this->_object_to_array($key);

    if ( ! is_array($key))
    {
        $key = array($key => $value);
    }

    foreach ($key as $k => $v)
    {
        if ($escape === FALSE)
        {
            $this->ar_set[$this->_protect_identifiers($k)] = $v;
        }
        else
        {
            $this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
        }
    }

    return $this;
}

Apparently, if $key is an array, codeigniter will simply ignore the second parameter $value, but the third parameter $escape will still work throughout the iteration of $key, so in this situation, the following codes work (using the chain method):

$this->db->set(array(
    'name' => $name ,
    'email' => $email,
    'time' => 'NOW()'), '', FALSE)->insert('mytable');

However, this will unescape all the data, so you can break your data into two parts:

$this->db->set(array(
    'name' => $name ,
    'email' => $email))->set(array('time' => 'NOW()'), '', FALSE)->insert('mytable');

How to get the html of a div on another page with jQuery ajax?

Ok, You should "construct" the html and find the .content div.

like this:

$.ajax({
   url:href,
   type:'GET',
   success: function(data){
       $('#content').html($(data).find('#content').html());
   }
});

Simple!

Regex, every non-alphanumeric character except white space or colon

No alphanumeric, white space or '_'.

var reg = /[^\w\s)]|[_]/g;

Programmatically change the height and width of a UIImageView Xcode Swift

u can use this code

var imageView = UIImageView(image: UIImage(name:"imageName"));
imageView.frame = CGrectMake(x,y imageView.frame.width*0.2,50);

or

var imageView = UIImageView(frame:CGrectMake(x,y, self.view.frame.size.width *0.2, 50)

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

I had a similar problem recently, and needed to change the permissions of my vendor folder

By running following commands :

  1. php artisan cache:clear
  2. chmod -R 777 storage vendor
  3. composer dump-autoload

I need to give all the permissions required to open and write vendor files to solve this issue

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

Access denied for root user in MySQL command-line

this might help on Ubuntu:

go to /etc/mysql/my.cnf and comment this line:

bind-address           = 127.0.0.1

Hope this helps someone, I've been searching for this a while too

Cheers

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

This is due to locking of Mongodb
sudo rm /var/lib/mongodb/mongod.lock
sudo service mongodb restart

How to set JAVA_HOME in Linux for all users

For all users, I would recommend placing the following line in /etc/profile

export JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:/bin/javac::")

This will update dynamically and works well with the alternatives system. Do note though that the update will only take place in a new login shell.

Remove ':hover' CSS behavior from element

You want to keep the selector, so adding/removing it won't work. Instead of writing a hard and fast CSS selectors (or two), perhaps you can just use the original selector to apply new CSS rule to that element based on some criterion:

$(".test").hover(
  if(some evaluation) {
    $(this).css('border':0);
  }
);

Android Studio SDK location

C:\Users\username\AppData\Local\Android\sdk

This is the right path, if you looking up for sdkmanager.

Invert match with regexp

Build an expression that matches, and use !match()... (logical negation) That's probably how grep does anyway...

Using WGET to run a cronjob PHP

You could tell wget to not download the contents in a couple of different ways:

wget --spider http://www.example.com/cronit.php

which will just perform a HEAD request but probably do what you want

wget -O /dev/null http://www.example.com/cronit.php

which will save the output to /dev/null (a black hole)

You might want to look at wget's -q switch too which prevents it from creating output

I think that the best option would probably be:

wget -q --spider http://www.example.com/cronit.php

that's unless you have some special logic checking the HTTP method used to request the page

Download image with JavaScript

The problem is that jQuery doesn't trigger the native click event for <a> elements so that navigation doesn't happen (the normal behavior of an <a>), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).

To trigger it manually, try:

var a = $("<a>")
    .attr("href", "http://i.stack.imgur.com/L8rHf.png")
    .attr("download", "img.png")
    .appendTo("body");

a[0].click();

a.remove();

DEMO: http://jsfiddle.net/HTggQ/

Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332

if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
        jQuery.acceptData( elem ) ) {

Illegal string offset Warning PHP

In my case i change mysql_fetch_assoc to mysql_fetch_array and solve. It takes 3 days to solve :-( and the other versions of my proyect run with fetch assoc.

Send data through routing paths in Angular

Best I found on internet for this is ngx-navigation-with-data. It is very simple and good for navigation the data from one component to another component. You have to just import the component class and use it in very simple way. Suppose you have home and about component and want to send data then

HOME COMPONENT

import { Component, OnInit } from '@angular/core';
import { NgxNavigationWithDataComponent } from 'ngx-navigation-with-data';

@Component({
 selector: 'app-home',
 templateUrl: './home.component.html',
 styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

constructor(public navCtrl: NgxNavigationWithDataComponent) { }

 ngOnInit() {
 }

 navigateToABout() {
  this.navCtrl.navigate('about', {name:"virendta"});
 }

}

ABOUT COMPONENT

import { Component, OnInit } from '@angular/core';
import { NgxNavigationWithDataComponent } from 'ngx-navigation-with-data';

@Component({
 selector: 'app-about',
 templateUrl: './about.component.html',
 styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {

 constructor(public navCtrl: NgxNavigationWithDataComponent) {
  console.log(this.navCtrl.get('name')); // it will console Virendra
  console.log(this.navCtrl.data); // it will console whole data object here
 }

 ngOnInit() {
 }

}

For any query follow https://www.npmjs.com/package/ngx-navigation-with-data

Comment down for help.

jQuery : select all element with custom attribute

Use the "has attribute" selector:

$('p[MyTag]')

Or to select one where that attribute has a specific value:

$('p[MyTag="Sara"]')

There are other selectors for "attribute value starts with", "attribute value contains", etc.

How to enable MySQL Query Log?

On Windows you can simply go to

C:\wamp\bin\mysql\mysql5.1.53\my.ini

Insert this line in my.ini

general_log_file = c:/wamp/logs/mysql_query_log.log

The my.ini file finally looks like this

...
...
...    
socket      = /tmp/mysql.sock
skip-locking
key_buffer = 16M
max_allowed_packet = 1M
table_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
basedir=c:/wamp/bin/mysql/mysql5.1.53
log = c:/wamp/logs/mysql_query_log.log        #dump query logs in this file
log-error=c:/wamp/logs/mysql.log
datadir=c:/wamp/bin/mysql/mysql5.1.53/data
...
...
...
...

textarea character limit

... onkeydown="if(value.length>500)value=value.substr(0,500); if(value.length==500)return false;" ...

It ought to work.

Combine two or more columns in a dataframe into a new column with a new name

Use paste.

 df$x <- paste(df$n,df$s)
 df
#   n  s     b    x
# 1 2 aa  TRUE 2 aa
# 2 3 bb FALSE 3 bb
# 3 5 cc  TRUE 5 cc

Can anyone explain what JSONP is, in layman terms?

JSONP is a way of getting around the browser's same-origin policy. How? Like this:

enter image description here

The goal here is to make a request to otherdomain.com and alert the name in the response. Normally we'd make an AJAX request:

$.get('otherdomain.com', function (response) {
  var name = response.name;
  alert(name);
});

However, since the request is going out to a different domain, it won't work.

We can make the request using a <script> tag though. Both <script src="otherdomain.com"></script> and $.get('otherdomain.com') will result in the same request being made:

GET otherdomain.com

Q: But if we use the <script> tag, how could we access the response? We need to access it if we want to alert it.

A: Uh, we can't. But here's what we could do - define a function that uses the response, and then tell the server to respond with JavaScript that calls our function with the response as its argument.

Q: But what if the server won't do this for us, and is only willing to return JSON to us?

A: Then we won't be able to use it. JSONP requires the server to cooperate.

Q: Having to use a <script> tag is ugly.

A: Libraries like jQuery make it nicer. Ex:

$.ajax({
    url: "http://otherdomain.com",
    jsonp: "callback",
    dataType: "jsonp",
    success: function( response ) {
        console.log( response );
    }
});

It works by dynamically creating the <script> tag DOM element.

Q: <script> tags only make GET requests - what if we want to make a POST request?

A: Then JSONP won't work for us.

Q: That's ok, I just want to make a GET request. JSONP is awesome and I'm going to go use it - thanks!

A: Actually, it isn't that awesome. It's really just a hack. And it isn't the safest thing to use. Now that CORS is available, you should use it whenever possible.

How to convert a date to milliseconds

You don't have a Date, you have a String representation of a date. You should convert the String into a Date and then obtain the milliseconds. To convert a String into a Date and vice versa you should use SimpleDateFormat class.

Here's an example of what you want/need to do (assuming time zone is not involved here):

String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();

Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.


Using the new Date/Time API available since Java 8:

String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
    DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
  With this new Date/Time API, when using a date, you need to
  specify the Zone where the date/time will be used. For your case,
  seems that you want/need to use the default zone of your system.
  Check which zone you need to use for specific behaviour e.g.
  CET or America/Lima
*/
long millis = localDateTime
    .atZone(ZoneId.systemDefault())
    .toInstant().toEpochMilli();

Get protocol, domain, and port from URL

Try use a regular expression (Regex), which will be quite useful when you want to validate / extract stuff or even do some simple parsing in javascript.

The regex is :

/([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/

Demonstration:

function breakURL(url){

     matches = /([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/.exec(url);

     foo = new Array();

     if(matches){
          for( i = 1; i < matches.length ; i++){ foo.push(matches[i]); }
     }

     return foo
}

url = "https://www.google.co.uk:55699/search?q=http%3A%2F%2F&oq=http%3A%2F%2F&aqs=chrome..69i57j69i60l3j69i65l2.2342j0j4&sourceid=chrome&ie=UTF-8"


breakURL(url);       // [https, www.google.co.uk, 55699] 
breakURL();          // []
breakURL("asf");     // []
breakURL("asd://");  // []
breakURL("asd://a"); // [asd, a, undefined]

Now you can do validation as well.

Disabling browser caching for all browsers from ASP.NET

See also How to prevent google chrome from caching my inputs, esp hidden ones when user click back? without which Chrome might reload but preserve the previous content of <input> elements -- in other words, use autocomplete="off".

Set Colorbar Range in matplotlib

Using figure environment and .set_clim()

Could be easier and safer this alternative if you have multiple plots:

import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np

cdict = {
  'red'  :  ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
  'green':  ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
  'blue' :  ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}

cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)

data = 2*( np.sin(X) + np.sin(3*Y) )
data1 = np.clip(data,0,6)
data2 = np.clip(data,-6,0)
vmin = np.min(np.array([data,data1,data2]))
vmax = np.max(np.array([data,data1,data2]))

fig = plt.figure()
ax = fig.add_subplot(131)
mesh = ax.pcolormesh(data, cmap = cm)
mesh.set_clim(vmin,vmax)
ax1 = fig.add_subplot(132)
mesh1 = ax1.pcolormesh(data1, cmap = cm)
mesh1.set_clim(vmin,vmax)
ax2 = fig.add_subplot(133)
mesh2 = ax2.pcolormesh(data2, cmap = cm)
mesh2.set_clim(vmin,vmax)
# Visualizing colorbar part -start
fig.colorbar(mesh,ax=ax)
fig.colorbar(mesh1,ax=ax1)
fig.colorbar(mesh2,ax=ax2)
fig.tight_layout()
# Visualizing colorbar part -end

plt.show()

enter image description here

A single colorbar

The best alternative is then to use a single color bar for the entire plot. There are different ways to do that, this tutorial is very useful for understanding the best option. I prefer this solution that you can simply copy and paste instead of the previous visualizing colorbar part of the code.

fig.subplots_adjust(bottom=0.1, top=0.9, left=0.1, right=0.8,
                    wspace=0.4, hspace=0.1)
cb_ax = fig.add_axes([0.83, 0.1, 0.02, 0.8])
cbar = fig.colorbar(mesh, cax=cb_ax)

enter image description here

P.S.

I would suggest using pcolormesh instead of pcolor because it is faster (more infos here ).

Count number of iterations in a foreach loop

If you just want to find out the number of elements in an array, use count. Now, to answer your question...

How to calculate how many items in a foreach?

$i = 0;
foreach ($Contents as $item) {
    $item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
    $i++;
}

If you only need the index inside the loop, you could use

foreach($Contents as $index=>$item) {
    // $index goes from 0 up to count($Contents) - 1
    // $item iterates over the elements
}

How to get the date from the DatePicker widget in Android?

The DatePicker class has methods for getting the month, year, day of month. Or you can use an OnDateChangedListener.

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

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

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

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

model.addRow(list.toArray());

table.setModel(model);

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

How to force garbage collection in Java?

On OracleJDK 10 with G1 GC, a single call to System.gc() will cause GC to clean up the Old Collection. I am not sure if GC runs immediately. However, GC will not clean up the Young Collection even if System.gc() is called many times in a loop. To get GC to clean up the Young Collection, you must allocate in a loop (e.g. new byte[1024]) without calling System.gc(). Calling System.gc() for some reason prevents GC from cleaning up the Young Collection.

CSS: background image on background color

And if you want Generate a Black Shadow in the background, you can use the following:

background:linear-gradient( rgba(0, 0, 0, 0.5) 100%, rgba(0, 0, 0, 0.5)100%),url("logo/header-background.png");

Insert Update trigger how to determine if insert or update

Try this..

ALTER TRIGGER ImportacionesGS ON dbo.Compra 
    AFTER INSERT, UPDATE, DELETE
AS
BEGIN
  -- idCompra is PK
  DECLARE @vIdCompra_Ins INT,@vIdCompra_Del INT
  SELECT @vIdCompra_Ins=Inserted.idCompra FROM Inserted
  SELECT @vIdCompra_Del=Deleted.idCompra FROM Deleted
  IF (@vIdCompra_Ins IS NOT NULL AND @vIdCompra_Del IS NULL)  
  Begin
     -- Todo Insert
  End
  IF (@vIdCompra_Ins IS NOT NULL AND @vIdCompra_Del IS NOT NULL)
  Begin
     -- Todo Update
  End
  IF (@vIdCompra_Ins IS NULL AND @vIdCompra_Del IS NOT NULL)
  Begin
     -- Todo Delete
  End
END

SQL Server String or binary data would be truncated

Yes,I am also face these kind of problem.

REMARKS VARCHAR(500)
to
REMARKS VARCHAR(1000)

Here, I've change REMARKS filed length from 500 to 1000

PHP - Indirect modification of overloaded property

I was receiving this notice for doing this:

$var = reset($myClass->my_magic_property);

This fixed it:

$tmp = $myClass->my_magic_property;
$var = reset($tmp);

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

How do I use a PriorityQueue?

As an alternative to using Comparator, you can also have the class you're using in your PriorityQueue implement Comparable (and correspondingly override the compareTo method).

Note that it's generally best to only use Comparable instead of Comparator if that ordering is the intuitive ordering of the object - if, for example, you have a use case to sort Person objects by age, it's probably best to just use Comparator instead.

import java.lang.Comparable;
import java.util.PriorityQueue;

class Test
{
    public static void main(String[] args)
    {
        PriorityQueue<MyClass> queue = new PriorityQueue<MyClass>();
        queue.add(new MyClass(2, "short"));
        queue.add(new MyClass(2, "very long indeed"));
        queue.add(new MyClass(1, "medium"));
        queue.add(new MyClass(1, "very long indeed"));
        queue.add(new MyClass(2, "medium"));
        queue.add(new MyClass(1, "short"));
        while (queue.size() != 0)
            System.out.println(queue.remove());
    }
}
class MyClass implements Comparable<MyClass>
{
    int sortFirst;
    String sortByLength;

    public MyClass(int sortFirst, String sortByLength)
    {
        this.sortFirst = sortFirst;
        this.sortByLength = sortByLength;
    }

    @Override
    public int compareTo(MyClass other)
    {
        if (sortFirst != other.sortFirst)
            return Integer.compare(sortFirst, other.sortFirst);
        else
            return Integer.compare(sortByLength.length(), other.sortByLength.length());
    }

    public String toString()
    {
        return sortFirst + ", " + sortByLength;
    }
}

Output:

1, short
1, medium
1, very long indeed
2, short
2, medium
2, very long indeed

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

Route.get() requires callback functions but got a "object Undefined"

This thing also happened with my code, but somehow I solved my problem. I checked my routes folder (where my all endpoints are their). I would recommend you check your routes folder file and check whether you forgot to add your particular router link.

file_put_contents - failed to open stream: Permission denied

Here the solution. To copy an img from an URL. this URL: http://url/img.jpg

$image_Url=file_get_contents('http://url/img.jpg');

create the desired path finish the name with .jpg

$file_destino_path="imagenes/my_image.jpg";

file_put_contents($file_destino_path, $image_Url)

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

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

Try this:

rdd = df.rdd.map(tuple)

or

rdd = df.rdd.map(list)

Intersect Two Lists in C#

If you have objects, not structs (or strings), then you'll have to intersect their keys first, and then select objects by those keys:

var ids = list1.Select(x => x.Id).Intersect(list2.Select(x => x.Id));
var result = list1.Where(x => ids.Contains(x.Id));

How to write log base(2) in c/c++

#define M_LOG2E 1.44269504088896340736 // log2(e)

inline long double log2(const long double x){
    return log(x) * M_LOG2E;
}

(multiplication may be faster than division)

java.lang.ClassNotFoundException on working app

I recently invested some time in a similar error report that reached me through the play store error reports.

An overview of some possible causes.

Missing Library

Since my app is tested before release and the issue only occurs approx. once a week I'm pretty sure mine isn’t a library issue. You should think in this direction if a build on your system fails and installing the app using ADB results in error on launch.

Cleaning and building your project could help if this is a local issue and make sure you have the latest version of both SDK and IDE.

In these cases it’s one class of your app or a library used in your app that triggers the error. This is an important difference with the next point where the entry point (Activity with MAIN intent or your custom service/Application object) of your app is not found.

If so look into the following questions & answers I’ve selected. They all have an accepted answer.

unable to instantiate application - ClassNotFoundException Android Activity ClassNotFoundException - tried everything Android ClassNotFoundException

Main Activity or Application not found

Misconfiguration of AndroidManifest.xml

More like a beginners mistake was quoted here before in one of the answers talking about the android manifest file.

Important here is that this error would always block your app from loading. It should build though but crash on the first use.

I’ve edited that answer, this is the important part:

Do not use the android:name attribute! unless you've implemented a custom Application object.

The application:name attribute has nothing to do with the name of your app. This is the name of a specific class to load as your Application instance. That's why you would get the ClassNotFoundException if that class wouldn't exist.

For the name of the app use the android:label attribute on this same application node instead.

Suppressed: java.io.IOException: unable to open DEX file

Now it’s getting interesting! This was part of the stack trace logged in my case through the playstore. So I can create a build and execute that on my device without errors (whereas all previous errors would prevent any run).

An important comment was made to the following SO question Android Application ClassNotFoundException, Unable to instantiate application

Looks like the system has trouble opening your application dex file java.io.IOException: unable to open DEX file, this is before any of your classes are loaded, so it doesn't have anything to do with how you define your application class in the Manifest. – user2046264 Feb 27 '14 at 2:25

The important part here is the suppressed IOException. This indicates that an IO operation failed. Examples of IO operations are network and storage calls.

Another error report that goes into that direction is listed at Android to Unable to instantiate Application java.lang.ClassNotFoundException: where the role of the external storage provided by an sdcard is mentioned.

Some other similar questions indicate that this can be a user error. "/mnt/asec/..." indicates that the app is running from the sdcard. If the sdcard is removed it could cause this error. 3rd party apps or rooted devices can probably move an app to the sdcard even if its not allowed by the manifest.

If you’re desperate read all the answers to that question since there are some other paths listed also. Think of full package specification, use of singletons and more.

The point here is that both network and storage are IO.

For my specific case I checked all the devices that reported this error and found that they all have external storage support. So a user could install the app and move it to external storage, have the SD card removed and get this error (just a theory, not tested).

For more info on the installLocation options see http://developer.android.com/guide/topics/data/install-location.html

I also considered the network. On top of the stack trace detail page at the play store reports you get an overview of the occurrences of the error over time.

It appeared to me that the error occurred more around the times an update was released. This could support the theory that the user gets an update of the app, downloads this update that somehow gets corrupted. The installation goes fine but the first execution of the app results in the error (again just a theory, not tested).

Other resources

Finally 2 non SO resources that might help you:

https://groups.google.com/forum/#!topic/android-developers/JC7_qqwBRjo https://code.google.com/p/android/issues/detail?id=72121

Multiple inputs with same name through POST in php

Change the names of your inputs:

<input name="xyz[]" value="Lorem" />
<input name="xyz[]" value="ipsum"  />
<input name="xyz[]" value="dolor" />
<input name="xyz[]" value="sit" />
<input name="xyz[]" value="amet" />

Then:

$_POST['xyz'][0] == 'Lorem'
$_POST['xyz'][4] == 'amet'

If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "xyz".

Note that this is probably the wrong solution. Obviously, it depends on the data you are sending.

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

Use:

((Long) userService.getAttendanceList(currentUser)).intValue();

instead.

The .intValue() method is defined in class Number, which Long extends.

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

The application that you are running is blocked because the application does not comply with security guidelines implemented in Java 7 Update 51

How to create a box when mouse over text in pure CSS?

This is a small tweak on the other answers. If you have nested divs you can include more exciting content such as H1s in your popup.

CSS

div.appear {
    width: 250px; 
    border: #000 2px solid;
    background:#F8F8F8;
    position: relative;
    top: 5px;
    left:15px;
    display:none;
    padding: 0 20px 20px 20px;
    z-index: 1000000;
}
div.hover  {
    cursor:pointer;
    width: 5px;
}
div.hover:hover div.appear {
    display:block;
}

HTML

<div class="hover">
<img src="questionmark.png"/>
    <div class="appear">
       <h1>My popup</h1>Hitherto and whenceforth.
    </div>
</div>

The problem with these solutions is that everything after this in the page gets shifted when the popup is displayed, ie, the rest of the page jumps downwards to 'make space'. The only way I could fix this was by making position:absolute and removing the top and left CSS tags.

Using grep and sed to find and replace a string

I have taken Vlad's idea and changed it a little bit. Instead of

grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null

Which yields

sed: couldn't edit /dev/null: not a regular file

I'm doing in 3 different connections to the remote server

touch deleteme
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' ./deleteme
rm deleteme

Although this is less elegant and requires 2 more connections to the server (maybe there's a way to do it all in one line) it does the job efficiently as well

get list of packages installed in Anaconda

To check if a specific package is installed:

conda list html5lib

which outputs something like this if installed:

# packages in environment at C:\ProgramData\Anaconda3:
#
# Name                    Version                   Build  Channel
html5lib                  1.0.1                    py37_0

or something like this if not installed:

# packages in environment at C:\ProgramData\Anaconda3:
#
# Name                    Version                   Build  Channel

you don't need to type the exact package name. Partial matches are supported:

conda list html

This outputs all installed packages containing 'html':

# packages in environment at C:\ProgramData\Anaconda3:
#
# Name                    Version                   Build  Channel
html5lib                  1.0.1                    py37_0
sphinxcontrib-htmlhelp    1.0.2                      py_0
sphinxcontrib-serializinghtml 1.1.3                      py_0

How to format string to money

Parse to your string to a decimal first.

Difference between window.location.href=window.location.href and window.location.reload()

As said, modifying the href when there is a hash (#) in the url would not reload the page. Thus, I use this to reload it instead of regular expressions:

if (!window.location.hash) {
    window.location.href = window.location.href;
} else {
    window.location.reload();
}

Best data type to store money values in MySQL

Storing money as BIGINT multiplied by 100 or more with the reason to use less storage space makes no sense in all "normal" situations.

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try this:

import matplotlib as plt

after importing the file we can use matplotlib library but remember to use it as plt

df.plt(kind='line',figsize=(10,5))

after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

An absolute xpath in HTML DOM starts with /html e.g.

/html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]

and a relative xpath finds the closed id to the dom element and generates xpath starting from that element e.g.

.//*[@id='answers']/h2[1]/a[1]

You can use firepath (firebug) for generating both types of xpaths

It won't make any difference which xpath you use in selenium, the former may be faster than the later one (but it won't be observable)

Absolute xpaths are prone to more regression as slight change in DOM makes them invalid or refer to a wrong element

How to verify that a specific method was not called using Mockito?

Even more meaningful :

import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

// ...

verify(dependency, never()).someMethod();

The documentation of this feature is there §4 "Verifying exact number of invocations / at least x / never", and the never javadoc is here.

AttributeError: Module Pip has no attribute 'main'

My solution is to check the version number of pip and use the import the correct main function correctly

    import pip

    if int(pip.__version__.split('.')[0])>9:
        from pip._internal import main
    else:
        from pip import main
    def install(package):
        main(['install', package])

Adding calculated column(s) to a dataframe in pandas

The first four functions you list will work on vectors as well, with the exception that lower_wick needs to be adapted. Something like this,

def lower_wick_vec(o, l, c):
    min_oc = numpy.where(o > c, c, o)
    return min_oc - l

where o, l and c are vectors. You could do it this way instead which just takes the df as input and avoid using numpy, although it will be much slower:

def lower_wick_df(df):
    min_oc = df[['Open', 'Close']].min(axis=1)
    return min_oc - l

The other three will work on columns or vectors just as they are. Then you can finish off with

def is_hammer(df):
    lw = lower_wick_at_least_twice_real_body(df["Open"], df["Low"], df["Close"]) 
    cl = closed_in_top_half_of_range(df["High"], df["Low"], df["Close"])
    return cl & lw

Bit operators can perform set logic on boolean vectors, & for and, | for or etc. This is enough to completely vectorize the sample calculations you gave and should be relatively fast. You could probably speed up even more by temporarily working with the numpy arrays underlying the data while performing these calculations.

For the second part, I would recommend introducing a column indicating the pattern for each row and writing a family of functions which deal with each pattern. Then groupby the pattern and apply the appropriate function to each group.

Clear android application user data

This command worked for me:

adb shell pm clear packageName

How to detect Windows 64-bit platform with .NET?

I found this to be the best way to check for the platform of the system and the process:

bool 64BitSystem = Environment.Is64BitOperatingSystem;
bool 64BitProcess = Environment.Is64BitProcess;

The first property returns true for 64-bit system, and false for 32-bit. The second property returns true for 64-bit process, and false for 32-bit.

The need for these two properties is because you can run 32-bit processes on 64-bit system, so you will need to check for both the system and the process.

How to embed fonts in CSS?

When I went to Google fonts all they gave me were true type font files .ttf and didn't explain at all how to use the @font-face to include them into my document. I tried the web font generator from font squirrel too, which just kept running the loading gif and not working... I then found this site -

https://transfonter.org/

I had great success using the following method:

I selected the Add Fonts button, leaving the default options, added all of my .ttf that Google gave me for Open Sans (which was like 10, I chose a lot of options...).

Then I selected the Convert button.

Heres the best part!

They gave me a zip file with all the font format files I selected, .ttf, .woff and .eot. Inside that zip file they had a demo.html file that I just double clicked on and it opened up a web page in my browser showing me example usages of all the different css font options, how to implement them, and what they looked like etc.

@font-face

I still didn't know at this point how to include the fonts into my stylesheet properly using @font-face but then I noticed that this demo.html came with it's own stylesheet in the zip as well. I opened the stylesheet and it showed how to bring in all of the fonts using @font-face so I was able to quickly, and easily, copy paste this into my project -

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-BoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-BoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-BoldItalic.ttf') format('truetype');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-LightItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-LightItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-LightItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-LightItalic.ttf') format('truetype');
    font-weight: 300;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-SemiBold.eot');
    src: url('fonts/Open_Sans/OpenSans-SemiBold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-SemiBold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-SemiBold.ttf') format('truetype');
    font-weight: 600;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Regular.eot');
    src: url('fonts/Open_Sans/OpenSans-Regular.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Regular.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Light.eot');
    src: url('fonts/Open_Sans/OpenSans-Light.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Light.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Light.ttf') format('truetype');
    font-weight: 300;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Italic.eot');
    src: url('fonts/Open_Sans/OpenSans-Italic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Italic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Italic.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-SemiBoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-SemiBoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-SemiBoldItalic.ttf') format('truetype');
    font-weight: 600;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot');
    src: url('fonts/Open_Sans/OpenSans-ExtraBold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-ExtraBold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-ExtraBold.ttf') format('truetype');
    font-weight: 800;
    font-style: normal;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot');
    src: url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-ExtraBoldItalic.ttf') format('truetype');
    font-weight: 800;
    font-style: italic;
}

@font-face {
    font-family: 'Open Sans';
    src: url('fonts/Open_Sans/OpenSans-Bold.eot');
    src: url('fonts/Open_Sans/OpenSans-Bold.eot?#iefix') format('embedded-opentype'),
        url('fonts/Open_Sans/OpenSans-Bold.woff') format('woff'),
        url('fonts/Open_Sans/OpenSans-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}

The demo.html also had it's own inline stylesheet that was interesting to take a look at, though I am familiar with working with font weights and styles once they are included so I didn't need it much. For an example of how to implement a font style onto an html element for reference purposes you could use the following method in a similar case to mine after @font-face has been used properly -

html, body{
    margin: 0;
    font-family: 'Open Sans';
}
.banner h1{
    font-size: 43px;
    font-weight: 700;
}
.banner p{
    font-size: 24px;
    font-weight: 300;
    font-style: italic;
}

Bash command line and input limit

There is a buffer limit of something like 1024. The read will simply hang mid paste or input. To solve this use the -e option.

http://linuxcommand.org/lc3_man_pages/readh.html

-e use Readline to obtain the line in an interactive shell

Change your read to read -e and annoying line input hang goes away.

Rails: update_attribute vs update_attributes

Recently I ran into update_attribute vs. update_attributes and validation issue, so similar names, so different behavior, so confusing.

In order to pass hash to update_attribute and bypass validation you can do:

object = Object.new
object.attributes = {
  field1: 'value',
  field2: 'value2',
  field3: 'value3'
}
object.save!(validate: false)

How to restart a single container with docker-compose

The answer's here are talking about the reflection of the change on the docker-compose.yml file.

But what if I want to incorporate the changes I have done in my code, and I believe that will be only possible by rebuilding the image and that I do with following commands

1. docker container stop

docker stop container-id

2. docker container removal

docker rm container-id

3. docker image removal

docker rmi image-id

4. compose the container again

docker-compose up container-name

How can you get the first digit in an int (C#)?

If you think Keltex's answer is ugly, try this one, it's REALLY ugly, and even faster. It does unrolled binary search to determine the length.

 ... leading code along the same lines
/* i<10000 */
if (i >= 100){
  if (i >= 1000){
    return i/1000;
  }
  else /* i<1000 */{
    return i/100;
  }
}
else /* i<100*/ {
  if (i >= 10){
    return i/10;
  }
  else /* i<10 */{
    return i;
  }
}

P.S. MartinStettner had the same idea.

Error: Execution failed for task ':app:clean'. Unable to delete file

I am using Android Studio 3.0 Beta 7. Clean Project, Invalidate caches, restart studio did not work but Updating Kotlin version to 1.1.51 and restart studio solved this issue for me.

How to get Last record from Sqlite?

If you have already got the cursor, then this is how you may get the last record from cursor:

cursor.moveToPosition(cursor.getCount() - 1);
//then use cursor to read values

Install Application programmatically on Android

Just an extension, if anyone need a library then this might help. Thanks to Raghav

Comparing two arrays & get the values which are not common

This should help, uses simple hash table.

$a1=@(1,2,3,4,5) $b1=@(1,2,3,4,5,6)


$hash= @{}

#storing elements of $a1 in hash
foreach ($i in $a1)
{$hash.Add($i, "present")}

#define blank array $c
$c = @()

#adding uncommon ones in second array to $c and removing common ones from hash
foreach($j in $b1)
{
if(!$hash.ContainsKey($j)){$c = $c+$j}
else {hash.Remove($j)}
}

#now hash is left with uncommon ones in first array, so add them to $c
foreach($k in $hash.keys)
{
$c = $c + $k
}

git: How to diff changed files versus previous versions after a pull?

I like to use:

git diff HEAD^

Or if I only want to diff a specific file:

git diff HEAD^ -- /foo/bar/baz.txt

Is there a quick change tabs function in Visual Studio Code?

Windows

When using Visual Studio Code on Windows, you can use CTRL + PAGE_UP to switch to the previous tab, and CTRL + PAGE_DN to switch to the next tab.

You also have the ability to switch to tabs based on their (non-zero relative) index. You can do so, by pressing and holding ALT, followed by a number (1 through 9).

macOS

To quickly navigate between tabs, press and hold the CMD key, followed by the number (1 through 9) of the tab you want to switch to.

You also have the ability to switch between the previous/next tab via the CMD + ALT + LEFT/RIGHT keyboard shortcut.

Please note that in order to switch to a tab that is in a different editor group, you must first switch to the desired editor group.

Pro Tip: If you aren't comfortable with any of the key bindings, you can change them to whatever you feel more comfortable with!

If conditions in a Makefile, inside a target

There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)

You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.

UNAME := $(shell uname -m)

all:
    $(info Checking if custom header is needed)
    ifeq ($(UNAME), x86_64)
    ... do some things to build unistd_32.h
    endif

    @make -C $(KDIR) M=$(PWD) modules

So you want unistd_32.h built (maybe) before you invoke the second make, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:

ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif

all:
    @make -C $(KDIR) M=$(PWD) modules

unistd_32.h:
    ... do some things to build unistd_32.h

Now for building unistd_32.h:

F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
    $(info Copying custom header)
    $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else    
    F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
    ifeq ($(F2_EXISTS), 1)
        $(info Copying custom header)
        $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
    else
        $(error asm/unistd_32.h and asm-386/unistd.h does not exist)
    endif
endif

You are trying to build unistd.h from unistd_32.h; the only trick is that unistd_32.h could be in either of two places. The simplest way to clean this up is to use a vpath directive:

vpath unistd.h /usr/include/asm /usr/include/asm-i386

unistd_32.h: unistd.h
    sed -e 's/__NR_/__NR32_/g' $< > $@

How can I reconcile detached HEAD with master/origin?

Just do this:

git checkout master

Or, if you have changes that you want to keep, do this:

git checkout -b temp
git checkout -B master temp

How to create query parameters in Javascript?

If you are using Prototype there is Form.serialize

If you are using jQuery there is Ajax/serialize

I do not know of any independent functions to accomplish this, though, but a google search for it turned up some promising options if you aren't currently using a library. If you're not, though, you really should because they are heaven.

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

Look no more for IP addresses not being set in the expected header. Just do the following to inspect the whole server variables and figure out which one is suitable for your case:

print_r($_SERVER);

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

A solution that accept exceptions(passed by parameters):

Copy the below code and use it like this: $('myselector').maskOwnName(['of', 'on', 'a', 'as', 'at', 'for', 'in', 'to']);

(function($) {
    $.fn.maskOwnName = function(not_capitalize) {
            not_capitalize = !(not_capitalize instanceof Array)? []: not_capitalize;

        $(this).keypress(function(e){
            if(e.altKey || e.ctrlKey)
                return;

            var new_char = String.fromCharCode(e.which).toLowerCase();

            if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
                var start = this.selectionStart,
                    end = this.selectionEnd;

                if(e.keyCode == 8){
                    if(start == end)
                        start--;

                    new_char = '';
                }

                var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
                var maxlength = this.getAttribute('maxlength');
                var words = new_value.split(' ');
                start += new_char.length;
                end = start;

                if(maxlength === null || new_value.length <= maxlength)
                    e.preventDefault();
                else
                    return;

                for (var i = 0; i < words.length; i++){
                    words[i] = words[i].toLowerCase();

                    if(not_capitalize.indexOf(words[i]) == -1)
                        words[i] = words[i].substring(0,1).toUpperCase() + words[i].substring(1,words[i].length).toLowerCase();
                }

                this.value = words.join(' ');
                this.setSelectionRange(start, end);
            }
        });
    }

    $.fn.maskLowerName = function(pos) {
        $(this).css('text-transform', 'lowercase').bind('blur change', function(){
            this.value = this.value.toLowerCase();
        });
    }

    $.fn.maskUpperName = function(pos) {
        $(this).css('text-transform', 'uppercase').bind('blur change', function(){
            this.value = this.value.toUpperCase();
        });
    }
})(jQuery);

How to insert tab character when expandtab option is on in Vim

From the documentation on expandtab:

To insert a real tab when expandtab is on, use CTRL-V<Tab>. See also :retab and ins-expandtab.
This option is reset when the paste option is set and restored when the paste option is reset.

So if you have a mapping for toggling the paste option, e.g.

set pastetoggle=<F2>

you could also do <F2>Tab<F2>.

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

Get data from php array - AJAX - jQuery

you cannot access array (php array) from js try

<?php
$array = array(1,2,3,4,5,6);
echo implode('~',$array);
?>

and js

$(document).ready( function() {
$('#prev').click(function() {
  $.ajax({
  type: 'POST',
  url: 'ajax.php',
  data: 'id=testdata',
  cache: false,
  success: function(data) {
    result=data.split('~');
    $('#content1').html(result[0]);
  },
  });
});
});

Rename a file in C#

None of the answers mention writing a unit testable solution. You could use System.IO.Abstractions as it provides a testable wrapper around FileSystem operations, using which you can create a mocked file system objects and write unit tests.

using System.IO.Abstractions;

IFileInfo fileInfo = _fileSystem.FileInfo.FromFileName("filePathAndName");
fileInfo.MoveTo(Path.Combine(fileInfo.DirectoryName, newName));

It was tested, and it is working code to rename a file.

HTML/CSS font color vs span style

Use style. The font tag is deprecated (W3C Wiki).

Android Studio - Auto complete and other features not working

i have this problem many times until now ,i suggest thees approach :

1-as said check power saveing mode

2-create new project with same application id and package name and copy all source and resource from older project to new one,

jQuery UI Accordion Expand/Collapse All

I don't believe you can do this with an accordion since it's specifically designed preserve the property that at most one item will be opened. However, even though you say you don't want to re-implement accordion, you might be over estimating the complexity involved.

Consider the following scenario where you have a vertical stack of elements,

++++++++++++++++++++
+     Header 1     +
++++++++++++++++++++
+                  +
+      Item 1      +
+                  +
++++++++++++++++++++
+     Header 2     +
++++++++++++++++++++
+                  +
+      Item 2      +
+                  +
++++++++++++++++++++

If you're lazy you could build this using a table, otherwise, suitably styled DIVs will also work.

Each of the item blocks can have a class of itemBlock. Clicking on a header will cause all elements of class itemBlock to be hidden ($(".itemBlock").hide()). You can then use the jquery slideDown() function to expand the item below the header. Now you've pretty much implemented accordion.

To expand all items, just use $(".itemBlock").show() or if you want it animated, $(".itemBlock").slideDown(500). To hide all items, just use $(".itemBlock").hide().

Combining "LIKE" and "IN" for SQL Server

You need multiple LIKE clauses connected by OR.

SELECT * FROM table WHERE 
column LIKE 'Text%' OR 
column LIKE 'Link%' OR 
column LIKE 'Hello%' OR 
column LIKE '%World%' OR 

Read text file into string array (and write)

You can use os.File (which implements the io.Reader interface) with the bufio package for that. However, those packages are build with fixed memory usage in mind (no matter how large the file is) and are quite fast.

Unfortunately this makes reading the whole file into the memory a bit more complicated. You can use a bytes.Buffer to join the parts of the line if they exceed the line limit. Anyway, I recommend you to try to use the line reader directly in your project (especially if do not know how large the text file is!). But if the file is small, the following example might be sufficient for you:

package main

import (
    "os"
    "bufio"
    "bytes"
    "fmt"
)

// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err os.Error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 1024))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == os.EOF {
        err = nil
    }
    return
}

func main() {
    lines, err := readLines("foo.txt")
    if err != nil {
        fmt.Println("Error: %s\n", err)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }
}

Another alternative might be to use io.ioutil.ReadAll to read in the complete file at once and do the slicing by line afterwards. I don't give you an explicit example of how to write the lines back to the file, but that's basically an os.Create() followed by a loop similar to that one in the example (see main()).

jQuery: How can I show an image popup onclick of the thumbnail?

I was in the same situation and found this one,

WOWslider

What are the safe characters for making URLs?

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

What is the default boolean value in C#?

The default value is indeed false.

However you can't use a local variable is it's not been assigned first.

You can use the default keyword to verify:

bool foo = default(bool);
if (!foo) { Console.WriteLine("Default is false"); }

File opens instead of downloading in internet explorer in a href link

It should be fixed on server side. Your server should return this headers for this file types:

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"

Back to previous page with header( "Location: " ); in PHP

Just a little addition: I believe it's a common and known thing to add exit; after the header function in case we don't want the rest of the code to load or execute...

header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;

how to have two headings on the same line in html

You should only need to do one of:

  • Make them both inline (or inline-block)
  • Set them to float left or right

You should be able to adjust the height, padding, or margin properties of the smaller heading to compensate for its positioning. I recommend setting both headings to have the same height.

See this live jsFiddle for an example.

(code of the jsFiddle):

CSS

h2 {
  font-size: 50px;
}

h3 {
  font-size: 30px;
}

h2, h3 {
  width: 50%;
  height: 60px;
  margin: 0;
  padding: 0;
  display: inline;
}?

HTML

<h2>Big Heading</h2>
<h3>Small(er) Heading</h3>
<hr />?

SQL DATEPART(dw,date) need monday = 1 and sunday = 7

Another solution is the following:

ISNULL(NULLIF(DATEPART(dw,DateField)-1,0),7)

Gradle, Android and the ANDROID_HOME SDK location

How to do it on MAC OSX:

1) Open up Terminal, and Edit: vi ~/.bash_profile If there is no file there, just add it.

2) Add (Change to YOUR USER NAME and add this):

#Java var home: JAVA_HOME="/usr/libexec/java_home" ANDROID_HOME="/Users/<YOUR USER NAME>/Library/Android/sdk"

3) Run source ~/.bash_profile.

4) Run echo $JAVA_HOME; echo $ANDROID_HOME;

5) If your output is:

/usr/libexec/java_home /Users/<YOUR USER NAME>/Library/Android/sdk

So you are good.

and RESTART android studio!

And, Make sure that you have java :)

java -version

And gradle :)

gradle --version

Define a global variable in a JavaScript function

If you read the comments there's a nice discussion around this particular naming convention.

It seems that since my answer has been posted the naming convention has gotten more formal. People who teach, write books, etc. speak about var declaration, and function declaration.

Here is the additional Wikipedia post that supports my point: Declarations and definitions ...and to answer the main question. Declare variable before your function. This will work and it will comply to the good practice of declaring your variables at the top of the scope :)

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Looks like the question has been long ago answered but the solution did not work for me. When I was getting that error, I was able to fix the problem by downloading PyWin32

oracle.jdbc.driver.OracleDriver ClassNotFoundException

In Eclipse,

When you use JDBC in your servlet, the driver jar must be placed in the WEB-INF/lib directory of your project.

C++ calling base class constructors

The default class constructor is called unless you explicitly call another constructor in the derived class. the language specifies this.

Rectangle(int h,int w):
   Shape(h,w)
  {...}

Will call the other base class constructor.

How to print float to n decimal places including trailing 0s?

For Python versions in 2.6+ and 3.x

You can use the str.format method. Examples:

>>> print('{0:.16f}'.format(1.6))
1.6000000000000001

>>> print('{0:.15f}'.format(1.6))
1.600000000000000

Note the 1 at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.

For Python versions prior to 2.6 (at least back to 2.0)

You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):

>>> print '%.16f' % 1.6
1.6000000000000001

>>> print '%.15f' % 1.6
1.600000000000000

Javascript to set hidden form value on drop down change

Plain old Javascript:

<script type="text/javascript">

function changeHiddenInput (objDropDown)
{
    var objHidden = document.getElementById("hiddenInput");
    objHidden.value = objDropDown.value; 
}

</script>
<form>
    <select id="dropdown" name="dropdown" onchange="changeHiddenInput(this)">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
    </select>

    <input type="hidden" name="hiddenInput" id="hiddenInput" value="" />
</form>

Difference between maven scope compile and provided for JAR packaging

If jar file is like executable spring boot jar file then scope of all dependencies must be compile to include all jar files.

But if jar file used in other packages or applications then it does not need to include all dependencies in jar file because these packages or applications can provide other dependencies themselves.

Iframe transparent background

Why not just load the frame off screen or hidden and then display it once it has finished loading. You could show a loading icon in its place to begin with to give the user immediate feedback that it's loading.

How can I declare dynamic String array in Java

no, there is no way to make array length dynamic in java. you can use ArrayList or other List implementations instead.

C# Checking if button was clicked

These helped me a lot: I wanted to save values from my gridview, and it was reloading my gridview /overriding my new values, as i have IsPostBack inside my PageLoad.

if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{
   //Do not reload the gridview.

}
else
{
   reload my gridview.
}

SOURCE: http://bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked

How does GPS in a mobile phone work exactly?

There's 3 satellites at least that you must be able to receive from of the 24-32 out there, and they each broadcast a time from a synchronized atomic clock. The differences in those times that you receive at any one time tell you how long the broadcast took to reach you, and thus where you are in relation to the satellites. So, it sort of reads from something, but it doesn't connect to that thing. Note that this doesn't tell you your orientation, many GPSes fake that (and speed) by interpolating data points.

If you don't count the cost of the receiver, it's a free service. Apparently there's higher resolution services out there that are restricted to military use. Those are likely a fixed cost for a license to decrypt the signals along with a confidentiality agreement.

Now your device may support GPS tracking, in which case it might communicate, say via GPRS, to a database which will store the location the device has found itself to be at, so that multiple devices may be tracked. That would require some kind of connection.

Maps are either stored on the device or received over a connection. Navigation is computed based on those maps' databases. These likely are a licensed item with a cost associated, though if you use a service like Google Maps they have the license with NAVTEQ and others.

How to execute only one test spec with angular-cli

I solved this problem for myself using grunt. I have the grunt script below. What the script does is takes the command line parameter of the specific test to run and creates a copy of test.ts and puts this specific test name in there.

To run this, first install grunt-cli using:

npm install -g grunt-cli

Put the below grunt dependencies in your package.json:

"grunt": "^1.0.1",
"grunt-contrib-clean": "^1.0.0",
"grunt-contrib-copy": "^1.0.0",
"grunt-exec": "^2.0.0",
"grunt-string-replace": "^1.3.1"

To run it save the below grunt file as Gruntfile.js in your root folder. Then from command line run it as:

grunt --target=app.component

This will run app.component.spec.ts.

Grunt file is as below:

/*
This gruntfile is used to run a specific test in watch mode. Example: To run app.component.spec.ts , the Command is: 
grunt --target=app.component
Do not specific .spec.ts. If no target is specified it will run all tests.
*/
module.exports = function(grunt) {
var target = grunt.option('target') || '';
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    clean: ['temp.conf.js','src/temp-test.ts'],
    copy: {
      main: {
        files: [
             {expand: false, cwd: '.', src: ['karma.conf.js'], dest: 'temp.conf.js'},
             {expand: false, cwd: '.', src: ['src/test.ts'], dest: 'src/temp-test.ts'}
             ],
      }
    },
    'string-replace': {
          dist: {
            files: {
              'temp.conf.js': 'temp.conf.js',
              'src/temp-test.ts': 'src/temp-test.ts'
            },
            options: {
              replacements: [{
                pattern: /test.ts/ig,
                replacement: 'temp-test.ts'
              },
              {
                pattern: /const context =.*/ig,
                replacement: 'const context = require.context(\'./\', true, /'+target+'\\\.spec\\\.ts$/);'
              }]
            }
        }
    },
    'exec': {
        sleep: {
          //The sleep command is needed here, else webpack compile fails since it seems like the files in the previous step were touched too recently
          command: 'ping 127.0.0.1 -n 4 > nul',
          stdout: true,
          stderr: true
        },
        ng_test: {
          command: 'ng test --config=temp.conf.js',
          stdout: true,
          stderr: true
        }
    }
  });

  // Load the plugin that provides the "uglify" task.
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-string-replace');
    grunt.loadNpmTasks('grunt-exec');
  // Default task(s).
  grunt.registerTask('default', ['clean','copy','string-replace','exec']);

};

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

building '_mysql' extension
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
C:\Users\TimHuang\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\python27\include -Ic:\python27\PC /Tc_mysql.c /Fobuild\temp.win-amd64-2.7\Release\_mysql.obj /Zl
_mysql.c
_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory

If you see this when you try pip install mysql-python, the easiest way is to copy

C:\Program Files\MySQL\MySQL Connector C 6.0.2 to C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2

I tried to create the symbolic link but Windows keeps throwing me C:\WINDOWS\system32>mklink /d "C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" "C:\Program Files\MySQL\MySQL Connector C 6.0.2\include" The system cannot find the path specified.

The remote host closed the connection. The error code is 0x800704CD

I get this one all the time. It means that the user started to download a file, and then it either failed, or they cancelled it.

To reproduce the exception try do this yourself - however I'm unaware of any ways to prevent it (except for handling this specific exception only).

You need to decide what the best way forward is depending on your app.

Getting The ASCII Value of a character in a C# string

This example might help you. by using simple casting you can get code behind urdu character.

string str = "?????";
        char ch = ' ';
        int number = 0;
        for (int i = 0; i < str.Length; i++)
        {
            ch = str[i];
            number = (int)ch;
            Console.WriteLine(number);
        }

mongo - couldn't connect to server 127.0.0.1:27017

Steps to solve this issue on Windows OS:

  1. Delete mongod.lock file from C:\Program Files\MongoDB\Server\4.0\data
  2. Click on mongod in C:\Program Files\MongoDB\Server\4.0\bin
  3. Click on mongo in C:\Program Files\MongoDB\Server\4.0\bin to start the mongodb shell

Accessing UI (Main) Thread safely in WPF

Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.

Step 1. Use the following namespaces

using System.Windows;
using System.Threading;
using System.Windows.Threading;

Step 2. Put the following line where you need to update UI

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
    //Update UI here
}));

Syntax

[BrowsableAttribute(false)]
public object Invoke(
  DispatcherPriority priority,
  Delegate method
)

Parameters

priority

Type: System.Windows.Threading.DispatcherPriority

The priority, relative to the other pending operations in the Dispatcher event queue, the specified method is invoked.

method

Type: System.Delegate

A delegate to a method that takes no arguments, which is pushed onto the Dispatcher event queue.

Return Value

Type: System.Object

The return value from the delegate being invoked or null if the delegate has no return value.

Version Information

Available since .NET Framework 3.0

How to change the color of winform DataGridview header?

If you want to change a color to single column try this:

 dataGridView1.EnableHeadersVisualStyles = false;
 dataGridView1.Columns[0].HeaderCell.Style.BackColor = Color.Magenta;
 dataGridView1.Columns[1].HeaderCell.Style.BackColor = Color.Yellow;

How do I launch the Android emulator from the command line?

Run the first emulator available:

~/Library/Android/sdk/tools/emulator -avd `~/Library/Android/sdk/tools/emulator -list-avds | awk '{print $1}'`

What is com.sun.proxy.$Proxy

What are they?

Nothing special. Just as same as common Java Class Instance.

But those class are Synthetic proxy classes created by java.lang.reflect.Proxy#newProxyInstance

What is there relationship to the JVM? Are they JVM implementation specific?

Introduced in 1.3

http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection

It is a part of Java. so each JVM should support it.

How are they created (Openjdk7 source)?

In short : they are created using JVM ASM tech ( defining javabyte code at runtime )

something using same tech:

What happens after calling java.lang.reflect.Proxy#newProxyInstance

  1. reading the source you can see newProxyInstance call getProxyClass0 to obtain a `Class

    `

  2. after lots of cache or sth it calls the magic ProxyGenerator.generateProxyClass which return a byte[]
  3. call ClassLoader define class to load the generated $Proxy Class (the classname you have seen)
  4. just instance it and ready for use

What happens in magic sun.misc.ProxyGenerator

  1. draw a class(bytecode) combining all methods in the interfaces into one
  2. each method is build with same bytecode like

    1. get calling Method meth info (stored while generating)
    2. pass info into invocation handler's invoke()
    3. get return value from invocation handler's invoke()
    4. just return it
  3. the class(bytecode) represent in form of byte[]

How to draw a class

Thinking your java codes are compiled into bytecodes, just do this at runtime

Talk is cheap show you the code

core method in sun/misc/ProxyGenerator.java

generateClassFile

/**
 * Generate a class file for the proxy class.  This method drives the
 * class file generation process.
 */
private byte[] generateClassFile() {

    /* ============================================================
     * Step 1: Assemble ProxyMethod objects for all methods to
     * generate proxy dispatching code for.
     */

    /*
     * Record that proxy methods are needed for the hashCode, equals,
     * and toString methods of java.lang.Object.  This is done before
     * the methods from the proxy interfaces so that the methods from
     * java.lang.Object take precedence over duplicate methods in the
     * proxy interfaces.
     */
    addProxyMethod(hashCodeMethod, Object.class);
    addProxyMethod(equalsMethod, Object.class);
    addProxyMethod(toStringMethod, Object.class);

    /*
     * Now record all of the methods from the proxy interfaces, giving
     * earlier interfaces precedence over later ones with duplicate
     * methods.
     */
    for (int i = 0; i < interfaces.length; i++) {
        Method[] methods = interfaces[i].getMethods();
        for (int j = 0; j < methods.length; j++) {
            addProxyMethod(methods[j], interfaces[i]);
        }
    }

    /*
     * For each set of proxy methods with the same signature,
     * verify that the methods' return types are compatible.
     */
    for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
        checkReturnTypes(sigmethods);
    }

    /* ============================================================
     * Step 2: Assemble FieldInfo and MethodInfo structs for all of
     * fields and methods in the class we are generating.
     */
    try {
        methods.add(generateConstructor());

        for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
            for (ProxyMethod pm : sigmethods) {

                // add static field for method's Method object
                fields.add(new FieldInfo(pm.methodFieldName,
                    "Ljava/lang/reflect/Method;",
                     ACC_PRIVATE | ACC_STATIC));

                // generate code for proxy method and add it
                methods.add(pm.generateMethod());
            }
        }

        methods.add(generateStaticInitializer());

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    if (methods.size() > 65535) {
        throw new IllegalArgumentException("method limit exceeded");
    }
    if (fields.size() > 65535) {
        throw new IllegalArgumentException("field limit exceeded");
    }

    /* ============================================================
     * Step 3: Write the final class file.
     */

    /*
     * Make sure that constant pool indexes are reserved for the
     * following items before starting to write the final class file.
     */
    cp.getClass(dotToSlash(className));
    cp.getClass(superclassName);
    for (int i = 0; i < interfaces.length; i++) {
        cp.getClass(dotToSlash(interfaces[i].getName()));
    }

    /*
     * Disallow new constant pool additions beyond this point, since
     * we are about to write the final constant pool table.
     */
    cp.setReadOnly();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
        /*
         * Write all the items of the "ClassFile" structure.
         * See JVMS section 4.1.
         */
                                    // u4 magic;
        dout.writeInt(0xCAFEBABE);
                                    // u2 minor_version;
        dout.writeShort(CLASSFILE_MINOR_VERSION);
                                    // u2 major_version;
        dout.writeShort(CLASSFILE_MAJOR_VERSION);

        cp.write(dout);             // (write constant pool)

                                    // u2 access_flags;
        dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);
                                    // u2 this_class;
        dout.writeShort(cp.getClass(dotToSlash(className)));
                                    // u2 super_class;
        dout.writeShort(cp.getClass(superclassName));

                                    // u2 interfaces_count;
        dout.writeShort(interfaces.length);
                                    // u2 interfaces[interfaces_count];
        for (int i = 0; i < interfaces.length; i++) {
            dout.writeShort(cp.getClass(
                dotToSlash(interfaces[i].getName())));
        }

                                    // u2 fields_count;
        dout.writeShort(fields.size());
                                    // field_info fields[fields_count];
        for (FieldInfo f : fields) {
            f.write(dout);
        }

                                    // u2 methods_count;
        dout.writeShort(methods.size());
                                    // method_info methods[methods_count];
        for (MethodInfo m : methods) {
            m.write(dout);
        }

                                     // u2 attributes_count;
        dout.writeShort(0); // (no ClassFile attributes for proxy classes)

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    return bout.toByteArray();
}

addProxyMethod

/**
 * Add another method to be proxied, either by creating a new
 * ProxyMethod object or augmenting an old one for a duplicate
 * method.
 *
 * "fromClass" indicates the proxy interface that the method was
 * found through, which may be different from (a subinterface of)
 * the method's "declaring class".  Note that the first Method
 * object passed for a given name and descriptor identifies the
 * Method object (and thus the declaring class) that will be
 * passed to the invocation handler's "invoke" method for a given
 * set of duplicate methods.
 */
private void addProxyMethod(Method m, Class fromClass) {
    String name = m.getName();
    Class[] parameterTypes = m.getParameterTypes();
    Class returnType = m.getReturnType();
    Class[] exceptionTypes = m.getExceptionTypes();

    String sig = name + getParameterDescriptors(parameterTypes);
    List<ProxyMethod> sigmethods = proxyMethods.get(sig);
    if (sigmethods != null) {
        for (ProxyMethod pm : sigmethods) {
            if (returnType == pm.returnType) {
                /*
                 * Found a match: reduce exception types to the
                 * greatest set of exceptions that can thrown
                 * compatibly with the throws clauses of both
                 * overridden methods.
                 */
                List<Class<?>> legalExceptions = new ArrayList<Class<?>>();
                collectCompatibleTypes(
                    exceptionTypes, pm.exceptionTypes, legalExceptions);
                collectCompatibleTypes(
                    pm.exceptionTypes, exceptionTypes, legalExceptions);
                pm.exceptionTypes = new Class[legalExceptions.size()];
                pm.exceptionTypes =
                    legalExceptions.toArray(pm.exceptionTypes);
                return;
            }
        }
    } else {
        sigmethods = new ArrayList<ProxyMethod>(3);
        proxyMethods.put(sig, sigmethods);
    }
    sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                   exceptionTypes, fromClass));
}

Full code about gen the proxy method

    private MethodInfo generateMethod() throws IOException {
        String desc = getMethodDescriptor(parameterTypes, returnType);
        MethodInfo minfo = new MethodInfo(methodName, desc,
            ACC_PUBLIC | ACC_FINAL);

        int[] parameterSlot = new int[parameterTypes.length];
        int nextSlot = 1;
        for (int i = 0; i < parameterSlot.length; i++) {
            parameterSlot[i] = nextSlot;
            nextSlot += getWordsPerType(parameterTypes[i]);
        }
        int localSlot0 = nextSlot;
        short pc, tryBegin = 0, tryEnd;

        DataOutputStream out = new DataOutputStream(minfo.code);

        code_aload(0, out);

        out.writeByte(opc_getfield);
        out.writeShort(cp.getFieldRef(
            superclassName,
            handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));

        code_aload(0, out);

        out.writeByte(opc_getstatic);
        out.writeShort(cp.getFieldRef(
            dotToSlash(className),
            methodFieldName, "Ljava/lang/reflect/Method;"));

        if (parameterTypes.length > 0) {

            code_ipush(parameterTypes.length, out);

            out.writeByte(opc_anewarray);
            out.writeShort(cp.getClass("java/lang/Object"));

            for (int i = 0; i < parameterTypes.length; i++) {

                out.writeByte(opc_dup);

                code_ipush(i, out);

                codeWrapArgument(parameterTypes[i], parameterSlot[i], out);

                out.writeByte(opc_aastore);
            }
        } else {

            out.writeByte(opc_aconst_null);
        }

        out.writeByte(opc_invokeinterface);
        out.writeShort(cp.getInterfaceMethodRef(
            "java/lang/reflect/InvocationHandler",
            "invoke",
            "(Ljava/lang/Object;Ljava/lang/reflect/Method;" +
                "[Ljava/lang/Object;)Ljava/lang/Object;"));
        out.writeByte(4);
        out.writeByte(0);

        if (returnType == void.class) {

            out.writeByte(opc_pop);

            out.writeByte(opc_return);

        } else {

            codeUnwrapReturnValue(returnType, out);
        }

        tryEnd = pc = (short) minfo.code.size();

        List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
        if (catchList.size() > 0) {

            for (Class<?> ex : catchList) {
                minfo.exceptionTable.add(new ExceptionTableEntry(
                    tryBegin, tryEnd, pc,
                    cp.getClass(dotToSlash(ex.getName()))));
            }

            out.writeByte(opc_athrow);

            pc = (short) minfo.code.size();

            minfo.exceptionTable.add(new ExceptionTableEntry(
                tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));

            code_astore(localSlot0, out);

            out.writeByte(opc_new);
            out.writeShort(cp.getClass(
                "java/lang/reflect/UndeclaredThrowableException"));

            out.writeByte(opc_dup);

            code_aload(localSlot0, out);

            out.writeByte(opc_invokespecial);

            out.writeShort(cp.getMethodRef(
                "java/lang/reflect/UndeclaredThrowableException",
                "<init>", "(Ljava/lang/Throwable;)V"));

            out.writeByte(opc_athrow);
        }

Add JavaScript object to JavaScript object

var jsonIssues = [
 {ID:'1',Name:'Some name',Notes:'NOTES'},
 {ID:'2',Name:'Some name 2',Notes:'NOTES 2'}
];

If you want to add to the array then you can do this

jsonIssues[jsonIssues.length] = {ID:'3',Name:'Some name 3',Notes:'NOTES 3'};

Or you can use the push technique that the other guy posted, which is also good.

Cordova app not displaying correctly on iPhone X (Simulator)

Just a note that the constant keyword use for safe-area margins has been updated to env for 11.2 beta+

https://webkit.org/blog/7929/designing-websites-for-iphone-x/

Combining multiple condition in single case statement in Sql Server

select ROUND(CASE 

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))!='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))!='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

else CONVERT( float, REPLACE(isnull( value1,''),',','')) end,0)  from Tablename where    ID="123" 

Do fragments really need an empty constructor?

As noted by CommonsWare in this question https://stackoverflow.com/a/16064418/1319061, this error can also occur if you are creating an anonymous subclass of a Fragment, since anonymous classes cannot have constructors.

Don't make anonymous subclasses of Fragment :-)

How can I make a div stick to the top of the screen once it's been scrolled to?

The info provided to answer this other question may be of help to you, Evan:

Check if element is visible after scrolling

You basically want to modify the style of the element to set it to fixed only after having verified that the document.body.scrollTop value is equal to or greater than the top of your element.

versionCode vs versionName in Android Manifest

It is indeed based on versionCode and not on versionName. However, I noticed that changing the versionCode in AndroidManifest.xml wasn't enough with Android Studio - Gradle build system. I needed to change it in the build.gradle.

Using pip behind a proxy with CNTLM

If you are using Linux, as root:

env https_proxy=http://$web_proxy_ip:$web_proxy_port pip install something

When you use env it exports the variable https_proxy for the current execution of the command pip install.

$web_proxy_ip is the hostname or IP of your Proxy $web_proxy_port is the Port

Reading Space separated input in python

If you have it in a string, you can use .split() to separate them.

>>> for string in ('Mike 18', 'Kevin 35', 'Angel 56'):
...   l = string.split()
...   print repr(l[0]), repr(int(l[1]))
...
'Mike' 18
'Kevin' 35
'Angel' 56
>>>

How to get the return value from a thread in python?

In Python 3.2+, stdlib concurrent.futures module provides a higher level API to threading, including passing return values or exceptions from a worker thread back to the main thread:

import concurrent.futures

def foo(bar):
    print('hello {}'.format(bar))
    return 'foo'

with concurrent.futures.ThreadPoolExecutor() as executor:
    future = executor.submit(foo, 'world!')
    return_value = future.result()
    print(return_value)

REST API error code 500 handling

You suggested "Catching any unexpected errors and return some error code signaling "unexpected situation" " but couldn't find an appropriate error code.

Guess what: That's what 5xx is there for.

How to install pip for Python 3 on Mac OS X?

UPDATE: This is no longer necessary with Python3.4. It installs pip3 as part of the stock install.

I ended up posting this same question on the python mailing list, and got the following answer:

# download and install setuptools
curl -O https://bootstrap.pypa.io/ez_setup.py
python3 ez_setup.py
# download and install pip
curl -O https://bootstrap.pypa.io/get-pip.py
python3 get-pip.py

Which solved my question perfectly. After adding the following for my own:

cd /usr/local/bin
ln -s ../../../Library/Frameworks/Python.framework/Versions/3.3/bin/pip pip

So that I could run pip directly, I was able to:

# use pip to install
pip install pyserial

or:

# Don't want it?
pip uninstall pyserial

Difference between View and ViewGroup in Android

  1. A ViewGroup is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers. This class also defines the ViewGroup.LayoutParams class which serves as the base class for layouts parameters.

    View class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.).

  2. Example : ViewGroup (LinearLayout), View (TextView)

Reference

How do I redirect users after submit button click?

Using jquery you can do it this way

$("#order").click(function(e){
    e.preventDefault();
    window.location="login.php";
});

Also in HMTL you can do it this way

<form name="frm" action="login.php" method="POST">
...
</form>

Hope this helps

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

Header set Access-Control-Allow-Origin in .htaccess doesn't work

I activated the Apache module headers a2enmod headers, and the issue has been solved.

Open youtube video in Fancybox jquery

THIS IS BROKEN, SEE EDIT

<script type="text/javascript">
$("a.more").fancybox({
                    'titleShow'     : false,
                    'transitionIn'  : 'elastic',
                    'transitionOut' : 'elastic',
            'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'      : 'swf',
            'swf'       : {'wmode':'transparent','allowfullscreen':'true'}
        });
</script>

This way if the user javascript is enabled it opens a fancybox with the youtube embed video, if javascript is disabled it opens the video's youtube page. If you want you can add

target="_blank"

to each of your links, it won't validate on most doctypes, but it will open the link in a new window if fancybox doesn't pick it up.

EDIT

this, above, isn't referenced correctly, so the code won't find href under this. You have to call it like this:

$("a.more").click(function() {
    $.fancybox({
            'padding'       : 0,
            'autoScale'     : false,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'title'         : this.title,
            'width'     : 680,
            'height'        : 495,
            'href'          : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'          : 'swf',
            'swf'           : {
                 'wmode'        : 'transparent',
                'allowfullscreen'   : 'true'
            }
        });

    return false;
});

as covered at http://fancybox.net/blog #4, replicated above

MySQL connection not working: 2002 No such file or directory

Not that it helps you much, but in the recent versions (and even less recent) of MySQL, error code 2002 means “Can't connect to local MySQL server through socket [name-of-socket]”, so that might tell you a bit more.

creating json object with variables

It's called on Object Literal

I'm not sure what you want your structure to be, but according to what you have above, where you put the values in variables try this.

var formObject =  {"formObject": [
                {"firstName": firstName, "lastName": lastName},
                {"phoneNumber": phone},
                {"address": address},
                ]}

Although this seems to make more sense (Why do you have an array in the above literal?):

var formObject = {
   firstName: firstName
   ...
}

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Most of the answers here have dealt with how to mange EOFError exceptions, which is really handy if you're unsure about whether the pickled object is empty or not.

However, if you're surprised that the pickle file is empty, it could be because you opened the filename through 'wb' or some other mode that could have over-written the file.

for example:

filename = 'cd.pkl'
with open(filename, 'wb') as f:
    classification_dict = pickle.load(f)

This will over-write the pickled file. You might have done this by mistake before using:

...
open(filename, 'rb') as f:

And then got the EOFError because the previous block of code over-wrote the cd.pkl file.

When working in Jupyter, or in the console (Spyder) I usually write a wrapper over the reading/writing code, and call the wrapper subsequently. This avoids common read-write mistakes, and saves a bit of time if you're going to be reading the same file multiple times through your travails