Programs & Examples On #Mysql error 1292

MySQL error when trying to compare numeric and non-numeric data

error code 1292 incorrect date value mysql

An update. Dates of the form '2019-08-00' will trigger the same error. Adding the lines:

[mysqld]

sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" 

to mysql.cnf fixes this too. Inserting malformed dates now generates warnings for values out of range but does insert the data.

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

In my case it was a view (highly nested, view in view) insertion causing the error in :

CREATE TABLE tablename AS
  SELECT * FROM highly_nested_viewname
;

The workaround we ended up doing was simulating a materialized view (which is really a table) and periodically insert/update it using stored procedures.

What is the difference between primary, unique and foreign key constraints, and indexes?

Key/index : A key is an aspect of a LOGICAL database design, an index is an aspect of a PHYSICAL database design. A key corresponds to an integrity constraint, an index is a technique of physically recording values that can be usefully applied when enforcing those constraints.

Primary/foreign : A "primary" key is a set of attributes whose values must form a combination that is unique in the entire table. There can be more than one such set (> 1 key), and the word "primary" is a remnant from the earlier days when the designer was then forced to choose one of those multiple keys as being "the most important/relevant one". The reason for this was primarily in combination with foreign keys :

Like a "primary" key, a "foreign" key is also a set of attributes. The values of these attributes must form a combination that is an existing primary key value in the referenced table. I don't know exactly how strict this rule still applies in SQL today. The terminology has remained anyway.

Unique : keyword used to indicate that an index cannot accept duplicate entries. Unique indexes are obviously an excellent means to enforce primary keys. To the extent that the word 'unique' is used in contexts of LOGICAL design, it is superfluous, sloppy, unnecessary and confusing. Keys (primary keys, that is) are unique by definition.

Capturing count from an SQL query

Complementing in C# with SQL:

SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = Convert.ToInt32(comm.ExecuteScalar());
if (count > 0)
{
    lblCount.Text = Convert.ToString(count.ToString()); //For example a Label
}
else
{
    lblCount.Text = "0";
}
conn.Close(); //Remember close the connection

Javascript: Setting location.href versus location

You might set location directly because it's slightly shorter. If you're trying to be terse, you can usually omit the window. too.

URL assignments to both location.href and location are defined to work in JavaScript 1.0, back in Netscape 2, and have been implemented in every browser since. So take your pick and use whichever you find clearest.

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

vuetify center items into v-flex

<v-layout justify-center>
  <v-card-actions>
    <v-btn primary>
     <span>SignUp</span>
    </v-btn>`enter code here`
  </v-card-actions>
</v-layout>

How to make a JFrame Modal in Swing java

The most simple way is to use pack() method before visualizing the JFrame object. here is an example:

myFrame frm = new myFrame();
frm.pack();
frm.setVisible(true);

How to specify names of columns for x and y when joining in dplyr?

This is more a workaround than a real solution. You can create a new object test_data with another column name:

left_join("names<-"(test_data, "name"), kantrowitz, by = "name")

     name gender
1    john      M
2    bill either
3 madison      M
4    abby either
5     zzz   <NA>

Send JavaScript variable to PHP variable

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

How to copy directories in OS X 10.7.3?

tl;dr

cp -R "/src/project 1/App" "/src/project 2"

Explanation:

Using quotes will cater for spaces in the directory names

cp -R "/src/project 1/App" "/src/project 2"

If the App directory is specified in the destination directory:

cp -R "/src/project 1/App" "/src/project 2/App"

and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"

Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.

Inside a bash script:

cp -R "${1}/App" "${2}"

How to make HTML table cell editable?

Add <input> to <td> when it is clicked. Change <input> to <span> when it is blurred.

Meaning of = delete after function declaration

This excerpt from The C++ Programming Language [4th Edition] - Bjarne Stroustrup book talks about the real purpose behind using =delete:

3.3.4 Suppressing Operations

Using the default copy or move for a class in a hierarchy is typically a disaster: given only a pointer to a base, we simply don’t know what members the derived class has, so we can’t know how to copy them. So, the best thing to do is usually to delete the default copy and move operations, that is, to eliminate the default definitions of those two operations:

class Shape {
public:
  Shape(const Shape&) =delete; // no copy operations
  Shape& operator=(const Shape&) =delete;

  Shape(Shape&&) =delete; // no move operations
  Shape& operator=(Shape&&) =delete;
  ˜Shape();
    // ...
};

Now an attempt to copy a Shape will be caught by the compiler.

The =delete mechanism is general, that is, it can be used to suppress any operation

How to show first commit by 'git log'?

git log --format="%h" | tail -1 gives you the commit hash (ie 0dd89fb), which you can feed into other commands, by doing something like

git diff `git log --format="%h" --after="1 day"| tail -1`..HEAD to view all the commits in the last day.

Get current date in DD-Mon-YYY format in JavaScript/Jquery

Use date format dd-MM-yy . It will output like: 16-December-2014.

Android: How to get a custom View's height and width?

Well getheight gets the height, and getwidth gets the width. But you're calling those methods too soon. If you're calling them in oncreate or onresume, the view isn't drawn yet. You have to call it after the view has been drawn.

Change the encoding of a file in Visual Studio Code

The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:

File > Preferences > Settings > Encoding > Choose your option

This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.

Changing the text on a label

Here is another one, I think. Just for reference. Let's set a variable to be an instantance of class StringVar

If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.

There’s no way to track changes to Python variables, but Tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.

text = StringVar()
self.depositLabel = Label(self.__mainWindow, text = self.labelText, textvariable = text)
                                                                    ^^^^^^^^^^^^^^^^^
  def depositCallBack(self,event):
      text.set('change the value')

How to open remote files in sublime text 3

Base on this.

Step by step:

  • On your local workstation: On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub
  • On your local workstation: Add RemoteForward 52698 127.0.0.1:52698 to your .ssh/config file, or -R 52698:localhost:52698 if you prefer command line
  • On your remote server:

    sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
    sudo chmod a+x /usr/local/bin/rsub
    

Just keep your ST3 editor open, and you can easily edit remote files with

rsub myfile.txt

EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:

echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc

Now just log off, log back in, and you'll be all set.

How to open child forms positioned within MDI parent in VB.NET?

You will want to set the MdiParent property of your new form to the name of the MDI parent form, as follows:

dim form as new yourform
form.show()
form.MdiParent = nameParent

Putting HTML inside Html.ActionLink(), plus No Link Text?

Instead of using Html.ActionLink you can render a url via Url.Action

<a href="<%= Url.Action("Index", "Home") %>"><span>Text</span></a>
<a href="@Url.Action("Index", "Home")"><span>Text</span></a>

And to do a blank url you could have

<a href="<%= Url.Action("Index", "Home") %>"></a>
<a href="@Url.Action("Index", "Home")"></a>

Negative list index?

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

Can I get Unix's pthread.h to compile in Windows?

There are, as i recall, two distributions of the gnu toolchain for windows: mingw and cygwin.

I'd expect cygwin work - a lot of effort has been made to make that a "stadard" posix environment.

The mingw toolchain uses msvcrt.dll for its runtime and thus will probably expose msvcrt's "thread" api: _beginthread which is defined in <process.h>

how to run a winform from console application?

The easiest option is to start a windows forms project, then change the output-type to Console Application. Alternatively, just add a reference to System.Windows.Forms.dll, and start coding:

using System.Windows.Forms;

[STAThread]
static void Main() {
    Application.EnableVisualStyles();
    Application.Run(new Form()); // or whatever
}

The important bit is the [STAThread] on your Main() method, required for full COM support.

How to include a class in PHP

I suggest you also take a look at __autoload.
This will clean up the code of requires and includes.

How can I replace the deprecated set_magic_quotes_runtime in php?

In PHP 7 we can use:

ini_set('magic_quotes_runtime', 0);

instead of set_magic_quotes_runtime(0);

How to: Install Plugin in Android Studio

1) Launch Android Studio application

2) Choose File -> Settings (For Mac Preference )

3) Search for Plugins

enter image description here

In Android Studio 3.4.2

enter image description here

How to get start and end of previous month in VB

Just to add something to what @Fionnuala Said, The below functions can be used. These even work for leap years.

'If you pass #2016/20/01# you get #2016/31/01#
Public Function GetLastDate(tempDate As Date) As Date
    GetLastDate = DateSerial(Year(tempDate), Month(tempDate) + 1, 0)
End Function

'If you pass #2016/20/01# you get 31
Public Function GetLastDay(tempDate As Date) As Integer
    GetLastDay = Day(DateSerial(Year(tempDate), Month(tempDate) + 1, 0))
End Function

What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

Another poster provided a lookup-table using a byte-wide lookup. In case you want to eke out a bit more performance (at the cost of 32K of memory instead of just 256 lookup entries) here is a solution using a 15-bit lookup table, in C# 7 for .NET.

The interesting part is initializing the table. Since it's a relatively small block that we want for the lifetime of the process, I allocate unmanaged memory for this by using Marshal.AllocHGlobal. As you can see, for maximum performance, the whole example is written as native:

readonly static byte[] msb_tab_15;

// Initialize a table of 32768 bytes with the bit position (counting from LSB=0)
// of the highest 'set' (non-zero) bit of its corresponding 16-bit index value.
// The table is compressed by half, so use (value >> 1) for indexing.
static MyStaticInit()
{
    var p = new byte[0x8000];

    for (byte n = 0; n < 16; n++)
        for (int c = (1 << n) >> 1, i = 0; i < c; i++)
            p[c + i] = n;

    msb_tab_15 = p;
}

The table requires one-time initialization via the code above. It is read-only so a single global copy can be shared for concurrent access. With this table you can quickly look up the integer log2, which is what we're looking for here, for all the various integer widths (8, 16, 32, and 64 bits).

Notice that the table entry for 0, the sole integer for which the notion of 'highest set bit' is undefined, is given the value -1. This distinction is necessary for proper handling of 0-valued upper words in the code below. Without further ado, here is the code for each of the various integer primitives:

ulong (64-bit) Version

/// <summary> Index of the highest set bit in 'v', or -1 for value '0' </summary>
public static int HighestOne(this ulong v)
{
    if ((long)v <= 0)
        return (int)((v >> 57) & 0x40) - 1;      // handles cases v==0 and MSB==63

    int j = /**/ (int)((0xFFFFFFFFU - v /****/) >> 58) & 0x20;
    j |= /*****/ (int)((0x0000FFFFU - (v >> j)) >> 59) & 0x10;
    return j + msb_tab_15[v >> (j + 1)];
}

uint (32-bit) Version

/// <summary> Index of the highest set bit in 'v', or -1 for value '0' </summary>
public static int HighestOne(uint v)
{
    if ((int)v <= 0)
        return (int)((v >> 26) & 0x20) - 1;     // handles cases v==0 and MSB==31

    int j = (int)((0x0000FFFFU - v) >> 27) & 0x10;
    return j + msb_tab_15[v >> (j + 1)];
}

Various overloads for the above

public static int HighestOne(long v) => HighestOne((ulong)v);
public static int HighestOne(int v) => HighestOne((uint)v);
public static int HighestOne(ushort v) => msb_tab_15[v >> 1];
public static int HighestOne(short v) => msb_tab_15[(ushort)v >> 1];
public static int HighestOne(char ch) => msb_tab_15[ch >> 1];
public static int HighestOne(sbyte v) => msb_tab_15[(byte)v >> 1];
public static int HighestOne(byte v) => msb_tab_15[v >> 1];

This is a complete, working solution which represents the best performance on .NET 4.7.2 for numerous alternatives that I compared with a specialized performance test harness. Some of these are mentioned below. The test parameters were a uniform density of all 65 bit positions, i.e., 0 ... 31/63 plus value 0 (which produces result -1). The bits below the target index position were filled randomly. The tests were x64 only, release mode, with JIT-optimizations enabled.




That's the end of my formal answer here; what follows are some casual notes and links to source code for alternative test candidates associated with the testing I ran to validate the performance and correctness of the above code.


The version provided above above, coded as Tab16A was a consistent winner over many runs. These various candidates, in active working/scratch form, can be found here, here, and here.

 1  candidates.HighestOne_Tab16A               622,496
 2  candidates.HighestOne_Tab16C               628,234
 3  candidates.HighestOne_Tab8A                649,146
 4  candidates.HighestOne_Tab8B                656,847
 5  candidates.HighestOne_Tab16B               657,147
 6  candidates.HighestOne_Tab16D               659,650
 7  _highest_one_bit_UNMANAGED.HighestOne_U    702,900
 8  de_Bruijn.IndexOfMSB                       709,672
 9  _old_2.HighestOne_Old2                     715,810
10  _test_A.HighestOne8                        757,188
11  _old_1.HighestOne_Old1                     757,925
12  _test_A.HighestOne5  (unsafe)              760,387
13  _test_B.HighestOne8  (unsafe)              763,904
14  _test_A.HighestOne3  (unsafe)              766,433
15  _test_A.HighestOne1  (unsafe)              767,321
16  _test_A.HighestOne4  (unsafe)              771,702
17  _test_B.HighestOne2  (unsafe)              772,136
18  _test_B.HighestOne1  (unsafe)              772,527
19  _test_B.HighestOne3  (unsafe)              774,140
20  _test_A.HighestOne7  (unsafe)              774,581
21  _test_B.HighestOne7  (unsafe)              775,463
22  _test_A.HighestOne2  (unsafe)              776,865
23  candidates.HighestOne_NoTab                777,698
24  _test_B.HighestOne6  (unsafe)              779,481
25  _test_A.HighestOne6  (unsafe)              781,553
26  _test_B.HighestOne4  (unsafe)              785,504
27  _test_B.HighestOne5  (unsafe)              789,797
28  _test_A.HighestOne0  (unsafe)              809,566
29  _test_B.HighestOne0  (unsafe)              814,990
30  _highest_one_bit.HighestOne                824,345
30  _bitarray_ext.RtlFindMostSignificantBit    894,069
31  candidates.HighestOne_Naive                898,865

Notable is that the terrible performance of ntdll.dll!RtlFindMostSignificantBit via P/Invoke:

[DllImport("ntdll.dll"), SuppressUnmanagedCodeSecurity, SecuritySafeCritical]
public static extern int RtlFindMostSignificantBit(ulong ul);

It's really too bad, because here's the entire actual function:

    RtlFindMostSignificantBit:
        bsr rdx, rcx  
        mov eax,0FFFFFFFFh  
        movzx ecx, dl  
        cmovne      eax,ecx  
        ret

I can't imagine the poor performance originating with these five lines, so the managed/native transition penalties must be to blame. I was also surprised that the testing really favored the 32KB (and 64KB) short (16-bit) direct-lookup tables over the 128-byte (and 256-byte) byte (8-bit) lookup tables. I thought the following would be more competitive with the 16-bit lookups, but the latter consistently outperformed this:

public static int HighestOne_Tab8A(ulong v)
{
    if ((long)v <= 0)
        return (int)((v >> 57) & 64) - 1;

    int j;
    j =  /**/ (int)((0xFFFFFFFFU - v) >> 58) & 32;
    j += /**/ (int)((0x0000FFFFU - (v >> j)) >> 59) & 16;
    j += /**/ (int)((0x000000FFU - (v >> j)) >> 60) & 8;
    return j + msb_tab_8[v >> j];
}

The last thing I'll point out is that I was quite shocked that my deBruijn method didn't fare better. This is the method that I had previously been using pervasively:

const ulong N_bsf64 = 0x07EDD5E59A4E28C2,
            N_bsr64 = 0x03F79D71B4CB0A89;

readonly public static sbyte[]
bsf64 =
{
    63,  0, 58,  1, 59, 47, 53,  2, 60, 39, 48, 27, 54, 33, 42,  3,
    61, 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22,  4,
    62, 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21,
    56, 45, 25, 31, 35, 16,  9, 12, 44, 24, 15,  8, 23,  7,  6,  5,
},
bsr64 =
{
     0, 47,  1, 56, 48, 27,  2, 60, 57, 49, 41, 37, 28, 16,  3, 61,
    54, 58, 35, 52, 50, 42, 21, 44, 38, 32, 29, 23, 17, 11,  4, 62,
    46, 55, 26, 59, 40, 36, 15, 53, 34, 51, 20, 43, 31, 22, 10, 45,
    25, 39, 14, 33, 19, 30,  9, 24, 13, 18,  8, 12,  7,  6,  5, 63,
};

public static int IndexOfLSB(ulong v) =>
    v != 0 ? bsf64[((v & (ulong)-(long)v) * N_bsf64) >> 58] : -1;

public static int IndexOfMSB(ulong v)
{
    if ((long)v <= 0)
        return (int)((v >> 57) & 64) - 1;

    v |= v >> 1; v |= v >> 2;  v |= v >> 4;   // does anybody know a better
    v |= v >> 8; v |= v >> 16; v |= v >> 32;  // way than these 12 ops?
    return bsr64[(v * N_bsr64) >> 58];
}

There's much discussion of how superior and great deBruijn methods at this SO question, and I had tended to agree. My speculation is that, while both the deBruijn and direct lookup table methods (that I found to be fastest) both have to do a table lookup, and both have very minimal branching, only the deBruijn has a 64-bit multiply operation. I only tested the IndexOfMSB functions here--not the deBruijn IndexOfLSB--but I expect the latter to fare much better chance since it has so many fewer operations (see above), and I'll likely continue to use it for LSB.

How to add an element to the beginning of an OrderedDict?

You may want to use a different structure altogether, but there are ways to do it in python 2.7.

d1 = OrderedDict([('a', '1'), ('b', '2')])
d2 = OrderedDict(c='3')
d2.update(d1)

d2 will then contain

>>> d2
OrderedDict([('c', '3'), ('a', '1'), ('b', '2')])

As mentioned by others, in python 3.2 you can use OrderedDict.move_to_end('c', last=False) to move a given key after insertion.

Note: Take into consideration that the first option is slower for large datasets due to creation of a new OrderedDict and copying of old values.

What are best practices for REST nested resources?

I've moved what I've done from the question to an answer where more people are likely to see it.

What I've done is to have the creation endpoints at the nested endpoint, The canonical endpoint for modifying or querying an item is not at the nested resource.

So in this example (just listing the endpoints that change a resource)

  • POST /companies/ creates a new company returns a link to the created company.
  • POST /companies/{companyId}/departments when a department is put creates the new department returns a link to /departments/{departmentId}
  • PUT /departments/{departmentId} modifies a department
  • POST /departments/{deparmentId}/employees creates a new employee returns a link to /employees/{employeeId}

So there are root level resources for each of the collections. However the create is in the owning object.

Pass Hidden parameters using response.sendRedirect()

Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.

RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);

The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue. Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.

How to force browser to download file?

Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.

How to parse JSON without JSON.NET library?

You can use the classes found in the System.Json Namespace which were added in .NET 4.5. You need to add a reference to the System.Runtime.Serialization assembly

The JsonValue.Parse() Method parses JSON text and returns a JsonValue:

JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");

If you pass a string with a JSON object, you should be able to cast the value to a JsonObject:

using System.Json;


JsonObject result = value as JsonObject;

Console.WriteLine("Name .... {0}", (string)result["name"]);
Console.WriteLine("Artist .. {0}", (string)result["artist"]);
Console.WriteLine("Genre ... {0}", (string)result["genre"]);
Console.WriteLine("Album ... {0}", (string)result["album"]);

The classes are quite similar to those found in the System.Xml.Linq Namespace.

How do I declare class-level properties in Objective-C?

Properties have values only in objects, not classes.

If you need to store something for all objects of a class, you have to use a global variable. You can hide it by declaring it static in the implementation file.

You may also consider using specific relations between your objects: you attribute a role of master to a specific object of your class and link others objects to this master. The master will hold the dictionary as a simple property. I think of a tree like the one used for the view hierarchy in Cocoa applications.

Another option is to create an object of a dedicated class that is composed of both your 'class' dictionary and a set of all the objects related to this dictionary. This is something like NSAutoreleasePool in Cocoa.

How do I properly 'printf' an integer and a string in C?

scanf("%s",str) scans only until it finds a whitespace character. With the input "A 1", it will scan only the first character, hence s2 points at the garbage that happened to be in str, since that array wasn't initialised.

How to keep one variable constant with other one changing with row in excel

Use this form:

=(B0+4)/$A$0

The $ tells excel not to adjust that address while pasting the formula into new cells.

Since you are dragging across rows, you really only need to freeze the row part:

=(B0+4)/A$0

Keyboard Shortcuts

Commenters helpfully pointed out that you can toggle relative addressing for a formula in the currently selected cells with these keyboard shortcuts:

  • Windows: f4
  • Mac: CommandT

How to set locale in DatePipe in Angular 2?

As of Angular2 RC6, you can set default locale in your app module, by adding a provider:

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: "en-US" }, //replace "en-US" with your locale
    //otherProviders...
  ]
})

The Currency/Date/Number pipes should pick up the locale. LOCALE_ID is an OpaqueToken, to be imported from angular/core.

import { LOCALE_ID } from '@angular/core';

For a more advanced use case, you may want to pick up locale from a service. Locale will be resolved (once) when component using date pipe is created:

{
  provide: LOCALE_ID,
  deps: [SettingsService],      //some service handling global settings
  useFactory: (settingsService) => settingsService.getLanguage()  //returns locale string
}

Hope it works for you.

Setting transparent images background in IrfanView

You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.

You just need to re-open the image with IrfanView after changing the view color to white.

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

Navigation Drawer (Google+ vs. YouTube)

There is a great implementation of NavigationDrawer that follows the Google Material Design Guidelines (and compatible down to API 10) - The MaterialDrawer library (link to GitHub). As of time of writing, May 2017, it's actively supported.

It's available in Maven Central repo. Gradle dependency setup:

compile 'com.mikepenz:materialdrawer:5.9.1'

Maven dependency setup:

<dependency>
    <groupId>com.mikepenz</groupId>
    <artifactId>materialdrawer</artifactId>
    <version>5.9.1</version>
</dependency>

enter image description here enter image description here

Visual Studio opens the default browser instead of Internet Explorer

Your project might not have aspx files since it might be another kind of web project.

However, if it has a ClientApp folder:

  1. go to the standard view of the Solution Explorer (Ctrl+Alt+L) where you can find your-project name solution (click on the folders icon at the top to be sure (saying "Solutions and Folders"))
  2. right-click on the ClientApp folder itself
  3. Browse with... will show up near the top (near View in Browser option), click on it and the browsers dialog shows up
  4. click on your preferred browser
  5. click on Set as Default
  6. click on Browse to confirm (this will open the browser you just chose on that folder)

How to implement a binary search tree in Python?

class Node: 
    rChild,lChild,data = None,None,None

This is wrong - it makes your variables class variables - that is, every instance of Node uses the same values (changing rChild of any node changes it for all nodes!). This is clearly not what you want; try

class Node: 
    def __init__(self, key):
        self.rChild = None
        self.lChild = None
        self.data = key

now each node has its own set of variables. The same applies to your definition of Tree,

class Tree:
    root,size = None,0    # <- lose this line!
    def __init__(self):
        self.root = None
        self.size = 0

Further, each class should be a "new-style" class derived from the "object" class and should chain back to object.__init__():

class Node(object): 
    def __init__(self, data, rChild=None, lChild=None):
        super(Node,self).__init__()
        self.data   = data
        self.rChild = rChild
        self.lChild = lChild

class Tree(object):
    def __init__(self):
        super(Tree,self).__init__()
        self.root = None
        self.size = 0

Also, main() is indented too far - as shown, it is a method of Tree which is uncallable because it does not accept a self argument.

Also, you are modifying the object's data directly (t.root = Node(4)) which kind of destroys encapsulation (the whole point of having classes in the first place); you should be doing something more like

def main():
    t = Tree()
    t.add(4)    # <- let the tree create a data Node and insert it
    t.add(5)

How to make MySQL handle UTF-8 properly

SET NAMES UTF8

This is does the trick

Where value in column containing comma delimited values

DECLARE @search VARCHAR(10);
SET @search = 'Cat';

WITH T(C)
AS
(
SELECT 'Cat, Dog, Sparrow, Trout, Cow, Seahorse'
)
SELECT *
FROM T 
WHERE ', ' + C + ',' LIKE '%, ' + @search + ',%'

This will of course require a full table scan for every search.

How to get Maven project version to the bash command line

mvn org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version | grep -v '\['

How to have Java method return generic list of any type?

You can simply cast to List and then check if every element can be casted to T.

public <T> List<T> asList(final Class<T> clazz) {
    List<T> values = (List<T>) this.value;
    values.forEach(clazz::cast);
    return values;
}

WCF Exception: Could not find a base address that matches scheme http for the endpoint

Your configuration should look similar to that. You may have to change <transport clientCredentialType="None" proxyCredentialType="None" /> depending on your needs for authentication. The config below doesn't require any authentication.

<bindings>
    <basicHttpBinding>
        <binding name="basicHttpBindingConfiguration">
            <security mode="Transport">
                <transport clientCredentialType="None" proxyCredentialType="None" />
            </security>
        </binding>       
    </basicHttpBinding>
</bindings>

<services>
    <service name="XXX">
        <endpoint
            name="AAA"
            address=""
            binding="basicHttpBinding"
            bindingConfiguration="basicHttpBindingConfiguration"
            contract="YourContract" />
    </service>
<services>

That will allow a WCF service with basicHttpBinding to use HTTPS.

Fetch API request timeout?

EDIT: The fetch request will still be running in the background and will most likely log an error in your console.

Indeed the Promise.race approach is better.

See this link for reference Promise.race()

Race means that all Promises will run at the same time, and the race will stop as soon as one of the promises returns a value. Therefore, only one value will be returned. You could also pass a function to call if the fetch times out.

fetchWithTimeout(url, {
  method: 'POST',
  body: formData,
  credentials: 'include',
}, 5000, () => { /* do stuff here */ });

If this piques your interest, a possible implementation would be :

function fetchWithTimeout(url, options, delay, onTimeout) {
  const timer = new Promise((resolve) => {
    setTimeout(resolve, delay, {
      timeout: true,
    });
  });
  return Promise.race([
    fetch(url, options),
    timer
  ]).then(response => {
    if (response.timeout) {
      onTimeout();
    }
    return response;
  });
}

Is there a way to return a list of all the image file names from a folder using only Javascript?

Although you can run FTP commands using WebSockets, the simpler solution is listing your files using opendir in server side (PHP), and "spitting" it into the HTML source-code, so it will be available to client side.

The following code will do just that,

Optionally -

  • use <a> tag to present a link.
  • query for more information using server side (PHP),

    for example a file size,

PHP filesize TIP:   also you can easily overcome the 2GB limit of PHP's filesize using: AJAX + HEAD request + .htaccess rule to allow Content-Length access from client-side.

<?php
  /* taken from: https://github.com/eladkarako/download.eladkarako.com */

  $path = 'resources';
  $files = [];
  $handle = @opendir('./' . $path . '/');

  while ($file = @readdir($handle)) 
    ("." !== $file && ".." !== $file) && array_push($files, $file);
  @closedir($handle);
  sort($files); //uksort($files, "strnatcasecmp");

  $files = json_encode($files);

  unset($handle,$ext,$file,$path);
?>
<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <div data-container></div>
  <script>
    /* you will see (for example): 'var files = ["1.bat","1.exe","1.txt"];' if your folder containes those 1.bat 1.exe 1.txt files, it will be sorted too! :) */

    var files = <?php echo $files; ?>;

    files = files.map(function(file){
      return '<a data-ext="##EXT##" download="##FILE##" href="http://download.eladkarako.com/resources/##FILE##">##FILE##</a>'
        .replace(/##FILE##/g,       file)
        .replace(/##EXT##/g,        file.split('.').slice(-1) )
        ;
    }).join("\n<br/>\n");

    document.querySelector('[data-container]').innerHTML = files;
  </script>

</body>
</html>

DOM result will look like that:

<html lang="en-US" dir="ltr"><head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <div data-container="">
    <a data-ext="bat" download="1.bat" href="http://download.eladkarako.com/resources/1.bat">1.bat</a>
    <br/>
    <a data-ext="exe" download="1.exe" href="http://download.eladkarako.com/resources/1.exe">1.exe</a>
    <br/>
    <a data-ext="txt" download="1.txt" href="http://download.eladkarako.com/resources/1.txt">1.txt</a>
    <br/>
  </div>
  <script>
    var files = ["1.bat","1.exe","1.txt"];

    files = files.map(function(file){
      return '<a data-ext="##EXT##" download="##FILE##" href="http://download.eladkarako.com/resources/##FILE##">##FILE##</a>'
        .replace(/##FILE##/g,       file)
        .replace(/##EXT##/g,        file.split('.').slice(-1) )
        ;
    }).join("\n<br/>\n");

    document.querySelector('[data-container').innerHTML = files;
  </script>


</body></html>

How to check if cursor exists (open status)

Just Small change to what Gary W mentioned, adding 'SELECT':

IF (SELECT CURSOR_STATUS('global','myCursor')) >= -1
BEGIN
 DEALLOCATE myCursor
END

http://social.msdn.microsoft.com/Forums/en/sqlgetstarted/thread/eb268010-75fd-4c04-9fe8-0bc33ccf9357

Defining Z order of views of RelativeLayout in Android

Check if you have any elevation on one of the Views in XML. If so, add elevation to the other item or remove the elevation to solve the issue. From there, it's the order of the views that dictates what comes above the other.

Android Service needs to run always (Never pause or stop)

"Is it possible to run this service always as when the application pause and anything else?"

Yes.

  1. In the service onStartCommand method return START_STICKY.

    public int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY;
    }
    
  2. Start the service in the background using startService(MyService) so that it always stays active regardless of the number of bound clients.

    Intent intent = new Intent(this, PowerMeterService.class);
    startService(intent);
    
  3. Create the binder.

    public class MyBinder extends Binder {
            public MyService getService() {
                    return MyService.this;
            }
    }
    
  4. Define a service connection.

    private ServiceConnection m_serviceConnection = new ServiceConnection() {
            public void onServiceConnected(ComponentName className, IBinder service) {
                    m_service = ((MyService.MyBinder)service).getService();
            }
    
            public void onServiceDisconnected(ComponentName className) {
                    m_service = null;
            }
    };
    
  5. Bind to the service using bindService.

            Intent intent = new Intent(this, MyService.class);
            bindService(intent, m_serviceConnection, BIND_AUTO_CREATE);
    
  6. For your service you may want a notification to launch the appropriate activity once it has been closed.

    private void addNotification() {
            // create the notification
            Notification.Builder m_notificationBuilder = new Notification.Builder(this)
                    .setContentTitle(getText(R.string.service_name))
                    .setContentText(getResources().getText(R.string.service_status_monitor))
                    .setSmallIcon(R.drawable.notification_small_icon);
    
            // create the pending intent and add to the notification
            Intent intent = new Intent(this, MyService.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
            m_notificationBuilder.setContentIntent(pendingIntent);
    
            // send the notification
            m_notificationManager.notify(NOTIFICATION_ID, m_notificationBuilder.build());
    }
    
  7. You need to modify the manifest to launch the activity in single top mode.

              android:launchMode="singleTop"
    
  8. Note that if the system needs the resources and your service is not very active it may be killed. If this is unacceptable bring the service to the foreground using startForeground.

            startForeground(NOTIFICATION_ID, m_notificationBuilder.build());
    

jQuery AJAX Character Encoding

I DONT AGREE everything must be UTF-8, you can make it work perfectly with ISO 8859, I did, please read my response here.

my response in stackoverflow

How to check if number is divisible by a certain number?

package lecture3;

import java.util.Scanner;

public class divisibleBy2and5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Enter an integer number:");
        Scanner input = new Scanner(System.in);
        int x;
        x = input.nextInt();
         if (x % 2==0){
             System.out.println("The integer number you entered is divisible by 2");
         }
         else{
             System.out.println("The integer number you entered is not divisible by 2");
             if(x % 5==0){
                 System.out.println("The integer number you entered is divisible by 5");
             } 
             else{
                 System.out.println("The interger number you entered is not divisible by 5");
             }
        }

    }
}

Generate war file from tomcat webapp folder

There is a way to create war file of your project from eclipse.

First a create an xml file with the following code,

Replace HistoryCheck with your project name.

<?xml version="1.0" encoding="UTF-8"?>
<project name="HistoryCheck" basedir="." default="default">
    <target name="default" depends="buildwar,deploy"></target>
    <target name="buildwar">
        <war basedir="war" destfile="HistoryCheck.war" webxml="war/WEB-INF/web.xml">
            <exclude name="WEB-INF/**" />
            <webinf dir="war/WEB-INF/">
                <include name="**/*.jar" />
            </webinf>
        </war>
    </target>
    <target name="deploy">
        <copy file="HistoryCheck.war" todir="." />
    </target>
</project>

Now, In project explorer right click on that xml file and Run as-> ant build

You can see the war file of your project in your project folder.

Programmatic equivalent of default(Type)

  • In case of a value type use Activator.CreateInstance and it should work fine.
  • When using reference type just return null
public static object GetDefault(Type type)
{
   if(type.IsValueType)
   {
      return Activator.CreateInstance(type);
   }
   return null;
}

In the newer version of .net such as .net standard, type.IsValueType needs to be written as type.GetTypeInfo().IsValueType

Where to place JavaScript in an HTML file?

Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.

You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.

How to install mysql-connector via pip

If loading via pip install mysql-connector and leads an error Unable to find Protobuf include directory then this would be useful pip install mysql-connector==2.1.4

mysql-connector is obsolete, so use pip install mysql-connector-python. Same here

How can I find the current OS in Python?

import os
print os.name

This gives you the essential information you will usually need. To distinguish between, say, different editions of Windows, you will have to use a platform-specific method.

How do I assign ls to an array in Linux Bash?

It would be this

array=($(ls -d */))

EDIT: See Gordon Davisson's solution for a more general answer (i.e. if your filenames contain special characters). This answer is merely a syntax correction.

Multiple contexts with the same path error running web service in Eclipse using Tomcat

Go to server.xml and Search for "Context" tag with a property name "docBase".

Remove the duplicate lines here. Then try to restart the server.

How to change Android usb connect mode to charge only?

Nothing worked until I went this way: Settings>Developer options>Default USB configuration now you can choose your default USB connection purpose.

Getting Serial Port Information

There is a post about this same issue on MSDN:

Getting more information about a serial port in C#

Hi Ravenb,

We can't get the information through the SerialPort type. I don't know why you need this info in your application. However, there's a solved thread with the same question as you. You can check out the code there, and see if it can help you.

If you have any further problem, please feel free to let me know.

Best regards, Bruce Zhou

The link in that post goes to this one:

How to get more info about port using System.IO.Ports.SerialPort

You can probably get this info from a WMI query. Check out this tool to help you find the right code. Why would you care though? This is just a detail for a USB emulator, normal serial ports won't have this. A serial port is simply know by "COMx", nothing more.

1064 error in CREATE TABLE ... TYPE=MYISAM

A complementary note about CREATE TABLE .. TYPE="" syntax in SQL dump files

TLDR: If you still get CREATE TABLE ... TYPE="..." statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode of MYSQL40 or MYSQL323.

Long story

As it was said by others, the TYPE argument to CREATE TABLE has been deprecated for a long time in MySQL. mysqldump correctly uses the ENGINE argument, unless you specifically ask it to generate a backward compatible dump (for example using --compatible=mysql40 in versions of mysqldump up to 5.7).

However, many external SQL dump tools (for example, those integrated in MySQL clients such as phpmyadmin, Navicat and DBVisualizer, as well as those used by external automated backup services such as iControlWP) are not specifically aware of this change, and instead rely on the SHOW CREATE TABLE ... command to provide table creation statements for each tables (and just to it make it clear: this is actually a good thing). However, the SHOW CREATE TABLE will actually produce outdated syntax, including the TYPE argument, if the sqlmode variable is set to MYSQL40 or MYSQL323.

Therefore, if you still get CREATE TABLE ... TYPE="..." statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode of MYSQL40 or MYSQL323.

These sqlmodes basically configure MySQL to retain some backward compatible behaviours, and using them by default was largely recommended a few years ago. It is however highly improbable that you still have any code that wouldn't work correctly without these modes. Anyway, MYSQL40, MYSQL323 and several other similar sqlmodes have themselves been deprecated and are not supported in MySQL 8.0 and higher.

If your server is still configured with these sqlmodes and you are worried that some legacy program might fail if you change these, then one possibility is to set the sqlmode locally for that program, by executing SET SESSION sql_mode = 'MYSQL40'; immediately after connection. Note that this should only be considered as a temporary patch, and will not work in MySQL 8.0 and higher.

A more future-proof solution that do not involve rewriting your SQL queries would be to determine exactly which compatibility features need to be enable, and to enable only those, on a per-program basis (as described previously). The default sqlmode (that is, in server's configuration) should ideally be left unset (which will use official MySQL defaults for your current version). The full list of sqlmode (as of MySQL 5.7) is described here: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html.

PHP: Inserting Values from the Form into MySQL

There are two problems in your code.

  1. No action found in form.
  2. You have not executed the query mysqli_query()

dbConfig.php

<?php

$conn=mysqli_connect("localhost","root","password","testDB");

if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}

?>

index.php

 include('dbConfig.php');

<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="$1">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" type="text/css" href="style.css">

<title>test</title>


</head>
<body>

 <?php

  if(isset($_POST['save']))
{
    $sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

    $result = mysqli_query($conn,$sql);
}

?>

<form action="index.php" method="post"> 
<label id="first"> First name:</label><br/>
<input type="text" name="username"><br/>

<label id="first">Password</label><br/>
<input type="password" name="password"><br/>

<label id="first">Email</label><br/>
<input type="text" name="email"><br/>

<button type="submit" name="save">save</button>

</form>

</body>
</html>

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

Slash is a date delimiter, so that will use the current culture date delimiter.

If you want to hard-code it to always use slash, you can do something like this:

DateTime.ToString("dd'/'MM'/'yyyy")

How to decrease prod bundle size?

If you have run ng build --prod - you shouldn't have vendor files at all.

If I run just ng build - I get these files:

enter image description here

The total size of the folder is ~14MB. Waat! :D

But if I run ng build --prod - I get these files:

enter image description here

The total size of the folder is 584K.

One and the same code. I have enabled Ivy in both cases. Angular is 8.2.13.

So - I guess you didn't add --prod to your build command?

Difference between Fact table and Dimension table?

In the simplest form, I think a dimension table is something like a 'Master' table - that keeps a list of all 'items', so to say.

A fact table is a transaction table which describes all the transactions. In addition, aggregated (grouped) data like total sales by sales person, total sales by branch - such kinds of tables also might exist as independent fact tables.

Download a file from NodeJS Server using Express

Update

Express has a helper for this to make life easier.

app.get('/download', function(req, res){
  const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
  res.download(file); // Set disposition and send it.
});

Old Answer

As far as your browser is concerned, the file's name is just 'download', so you need to give it more info by using another HTTP header.

res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');

You may also want to send a mime-type such as this:

res.setHeader('Content-type', 'video/quicktime');

If you want something more in-depth, here ya go.

var path = require('path');
var mime = require('mime');
var fs = require('fs');

app.get('/download', function(req, res){

  var file = __dirname + '/upload-folder/dramaticpenguin.MOV';

  var filename = path.basename(file);
  var mimetype = mime.lookup(file);

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);
  filestream.pipe(res);
});

You can set the header value to whatever you like. In this case, I am using a mime-type library - node-mime, to check what the mime-type of the file is.

Another important thing to note here is that I have changed your code to use a readStream. This is a much better way to do things because using any method with 'Sync' in the name is frowned upon because node is meant to be asynchronous.

Generating random strings with T-SQL

Using a guid

SELECT @randomString = CONVERT(varchar(255), NEWID())

very short ...

How to generate a QR Code for an Android application?

with zxing this is my code for create QR

 QRCodeWriter writer = new QRCodeWriter();
    try {
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 512, 512);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bmp.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
            }
        }
        ((ImageView) findViewById(R.id.img_result_qr)).setImageBitmap(bmp);

    } catch (WriterException e) {
        e.printStackTrace();
    }

Can't get Python to import from a different folder

After going through the answers given by these contributors above - Zorglub29, Tom, Mark, Aaron McMillin, lucasamaral, JoeyZhao, Kjeld Flarup, Procyclinsur, martin.zaenker, tooty44 and debugging the issue that I was facing I found out a different use case due to which I was facing this issue. Hence adding my observations below for anybody's reference.

In my code I had a cyclic import of classes. For example:

src
 |-- utilities.py (has Utilities class that uses Event class)  
 |-- consume_utilities.py (has Event class that uses Utilities class)
 |-- tests
      |-- test_consume_utilities.py (executes test cases that involves Event class)

I got following error when I tried to execute python -m pytest tests/test_utilities.py for executing UTs written in test_utilities.py.

ImportError while importing test module '/Users/.../src/tests/test_utilities.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_utilities.py:1: in <module>
    from utilities import Utilities
...
...
E   ImportError: cannot import name 'Utilities'

The way I resolved the error was by re-factoring my code to move the functionality in cyclic import class so that I could remove the cyclic import of classes.

Note, I have __init__.py file in my 'src' folder as well as 'tests' folder and still was able to get rid of the 'ImportError' just by re-factoring the code.

Following stackoverflow link provides much more details on Circular dependency in Python.

Socket accept - "Too many open files"

For future reference, I ran into a similar problem; I was creating too many file descriptors (FDs) by creating too many files and sockets (on Unix OSs, everything is a FD). My solution was to increase FDs at runtime with setrlimit().

First I got the FD limits, with the following code:

// This goes somewhere in your code
struct rlimit rlim;

if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) {
    std::cout << "Soft limit: " << rlim.rlim_cur << std::endl;
    std::cout << "Hard limit: " << rlim.rlim_max << std::endl;
} else {
    std::cout << "Unable to get file descriptor limits" << std::endl;
}

After running getrlimit(), I could confirm that on my system, the soft limit is 256 FDs, and the hard limit is infinite FDs (this is different depending on your distro and specs). Since I was creating > 300 FDs between files and sockets, my code was crashing.

In my case I couldn't decrease the number of FDs, so I decided to increase the FD soft limit instead, with this code:

// This goes somewhere in your code
struct rlimit rlim;

rlim.rlim_cur = NEW_SOFT_LIMIT;
rlim.rlim_max = NEW_HARD_LIMIT;

if (setrlimit(RLIMIT_NOFILE, &rlim) == -1) {
    std::cout << "Unable to set file descriptor limits" << std::endl;
}

Note that you can also get the number of FDs that you are using, and the source of these FDs, with this code.

Also you can find more information on gettrlimit() and setrlimit() here and here.

Scanner is never closed

I am assuming you are using java 7, thus you get a compiler warning, when you don't close the resource you should close your scanner usually in a finally block.

Scanner scanner = null;
try {
    scanner = new Scanner(System.in);
    //rest of the code
}
finally {
    if(scanner!=null)
        scanner.close();
}

Or even better: use the new Try with resource statement:

try(Scanner scanner = new Scanner(System.in)){
    //rest of your code
}

How to set environment variables from within package.json?

For a larger set of environment variables or when you want to reuse them you can use env-cmd.

./.env file:

# This is a comment
ENV1=THANKS
ENV2=FOR ALL
ENV3=THE FISH

./package.json:

{
  "scripts": {
    "test": "env-cmd mocha -R spec"
  }
}

Convert a number to 2 decimal places in Java

Try

DecimalFormat df = new DecimalFormat("#,##0.00");

Sqlite or MySql? How to decide?

The sqlite team published an article explaining when to use sqlite that is great read. Basically, you want to avoid using sqlite when you have a lot of write concurrency or need to scale to terabytes of data. In many other cases, sqlite is a surprisingly good alternative to a "traditional" database such as MySQL.

how to open Jupyter notebook in chrome on windows

If you haven't already, create a notebook config file by running

jupyter notebook --generate-config

Then, edit the file jupyter_notebook_config.py found in the .jupyter folder of your home directory.

You need to change the line # c.NotebookApp.browser = '' to c.NotebookApp.browser = 'C:/path/to/your/chrome.exe %s'

On windows 10, Chrome should be located C:/Program Files (x86)/Google/Chrome/Application/chrome.exe but check on your system to be sure.

Unit tests vs Functional tests

My vision is

  • Unit testing. In Procedural programming unit is a procedure, in Object oriented programming unit is a class. Unit is isolated and reflects a developer perspective
  • Functional testing - more than Unit. User perspective, which describes a feature, use case, story...
    • Integration testing - check if all separately developed components work together. It can be other application, service, library, database, network etc.
      • Narrow integration test - double[About] is used. The main purpose is to check if component is configured in a right way
      • Broad integration test (End to End test, System test) - live version. The main purpose is to check if all components are configured in a right way
    • UI testing - checks if user input triggers a correct action and the UI is changed when some actions are happened
    • ...
  • Non functional testing - other cases
    • Performance testing - calculate a speed and other metrics
    • Usability testing - UX
    • ...

Create a rounded button / button with border-radius in Flutter

You can use the RaisedButton Widget. Raised Button Widget has shape property which you can utilise as shown in below snippet.

 RaisedButton(
          child: Text("Press Me"),
          onPressed: null,
          shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0))
        )

How to create EditText with rounded corners?

Thanks for Norfeldt's answer. I slightly changed its gradient for a better inner shadow effect.

<item android:state_pressed="false" android:state_focused="false">
    <shape>
        <gradient
            android:centerY="0.2"
            android:startColor="#D3D3D3"
            android:centerColor="#65FFFFFF"
            android:endColor="#00FFFFFF"
            android:angle="270"
            />
        <stroke
            android:width="0.7dp"
            android:color="#BDBDBD" />
        <corners
            android:radius="15dp" />
    </shape>
</item>

Looks great in a light backgrounded layout..

enter image description here

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

As was said you need to remove the FKs before. On Mysql do it like this:

ALTER TABLE `table_name` DROP FOREIGN KEY `id_name_fk`;

ALTER TABLE `table_name` DROP INDEX `id_name_fk`;

android on Text Change Listener

You can add a check to only clear when the text in the field is not empty (i.e when the length is different than 0).

field1.addTextChangedListener(new TextWatcher() {

   @Override
   public void afterTextChanged(Editable s) {}

   @Override    
   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   @Override    
   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
      if(s.length() != 0)
        field2.setText("");
   }
  });

field2.addTextChangedListener(new TextWatcher() {

   @Override
   public void afterTextChanged(Editable s) {}

   @Override
   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   @Override
   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
      if(s.length() != 0)
         field1.setText("");
   }
  });

Documentation for TextWatcher here.

Also please respect naming conventions.

Item frequency count in Python

Standard approach:

from collections import defaultdict

words = "apple banana apple strawberry banana lemon"
words = words.split()
result = defaultdict(int)
for word in words:
    result[word] += 1

print result

Groupby oneliner:

from itertools import groupby

words = "apple banana apple strawberry banana lemon"
words = words.split()

result = dict((key, len(list(group))) for key, group in groupby(sorted(words)))
print result

Interface/enum listing standard mime-type constants

I solved this with a static class:

@SuppressWarnings("serial")
public class MimeTypes {

    private static final HashMap<String, String> mimeTypes;

    static {
        mimeTypes = new HashMap<String, String>() {
            {
                put(".323", "text/h323");
                put(".3g2", "video/3gpp2");
                put(".3gp", "video/3gpp");
                put(".3gp2", "video/3gpp2");
                put(".3gpp", "video/3gpp");
                put(".7z", "application/x-7z-compressed");
                put(".aa", "audio/audible");
                put(".AAC", "audio/aac");
                put(".aaf", "application/octet-stream");
                put(".aax", "audio/vnd.audible.aax");
                put(".ac3", "audio/ac3");
                put(".aca", "application/octet-stream");
                put(".accda", "application/msaccess.addin");
                put(".accdb", "application/msaccess");
                put(".accdc", "application/msaccess.cab");
                put(".accde", "application/msaccess");
                put(".accdr", "application/msaccess.runtime");
                put(".accdt", "application/msaccess");
                put(".accdw", "application/msaccess.webapplication");
                put(".accft", "application/msaccess.ftemplate");
                put(".acx", "application/internet-property-stream");
                put(".AddIn", "text/xml");
                put(".ade", "application/msaccess");
                put(".adobebridge", "application/x-bridge-url");
                put(".adp", "application/msaccess");
                put(".ADT", "audio/vnd.dlna.adts");
                put(".ADTS", "audio/aac");
                put(".afm", "application/octet-stream");
                put(".ai", "application/postscript");
                put(".aif", "audio/x-aiff");
                put(".aifc", "audio/aiff");
                put(".aiff", "audio/aiff");
                put(".air", "application/vnd.adobe.air-application-installer-package+zip");
                put(".amc", "application/x-mpeg");
                put(".application", "application/x-ms-application");
                put(".art", "image/x-jg");
                put(".asa", "application/xml");
                put(".asax", "application/xml");
                put(".ascx", "application/xml");
                put(".asd", "application/octet-stream");
                put(".asf", "video/x-ms-asf");
                put(".ashx", "application/xml");
                put(".asi", "application/octet-stream");
                put(".asm", "text/plain");
                put(".asmx", "application/xml");
                put(".aspx", "application/xml");
                put(".asr", "video/x-ms-asf");
                put(".asx", "video/x-ms-asf");
                put(".atom", "application/atom+xml");
                put(".au", "audio/basic");
                put(".avi", "video/x-msvideo");
                put(".axs", "application/olescript");
                put(".bas", "text/plain");
                put(".bcpio", "application/x-bcpio");
                put(".bin", "application/octet-stream");
                put(".bmp", "image/bmp");
                put(".c", "text/plain");
                put(".cab", "application/octet-stream");
                put(".caf", "audio/x-caf");
                put(".calx", "application/vnd.ms-office.calx");
                put(".cat", "application/vnd.ms-pki.seccat");
                put(".cc", "text/plain");
                put(".cd", "text/plain");
                put(".cdda", "audio/aiff");
                put(".cdf", "application/x-cdf");
                put(".cer", "application/x-x509-ca-cert");
                put(".chm", "application/octet-stream");
                put(".class", "application/x-java-applet");
                put(".clp", "application/x-msclip");
                put(".cmx", "image/x-cmx");
                put(".cnf", "text/plain");
                put(".cod", "image/cis-cod");
                put(".config", "application/xml");
                put(".contact", "text/x-ms-contact");
                put(".coverage", "application/xml");
                put(".cpio", "application/x-cpio");
                put(".cpp", "text/plain");
                put(".crd", "application/x-mscardfile");
                put(".crl", "application/pkix-crl");
                put(".crt", "application/x-x509-ca-cert");
                put(".cs", "text/plain");
                put(".csdproj", "text/plain");
                put(".csh", "application/x-csh");
                put(".csproj", "text/plain");
                put(".css", "text/css");
                put(".csv", "text/csv");
                put(".cur", "application/octet-stream");
                put(".cxx", "text/plain");
                put(".dat", "application/octet-stream");
                put(".datasource", "application/xml");
                put(".dbproj", "text/plain");
                put(".dcr", "application/x-director");
                put(".def", "text/plain");
                put(".deploy", "application/octet-stream");
                put(".der", "application/x-x509-ca-cert");
                put(".dgml", "application/xml");
                put(".dib", "image/bmp");
                put(".dif", "video/x-dv");
                put(".dir", "application/x-director");
                put(".disco", "text/xml");
                put(".dll", "application/x-msdownload");
                put(".dll.config", "text/xml");
                put(".dlm", "text/dlm");
                put(".doc", "application/msword");
                put(".docm", "application/vnd.ms-word.document.macroEnabled.12");
                put(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                put(".dot", "application/msword");
                put(".dotm", "application/vnd.ms-word.template.macroEnabled.12");
                put(".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");
                put(".dsp", "application/octet-stream");
                put(".dsw", "text/plain");
                put(".dtd", "text/xml");
                put(".dtsConfig", "text/xml");
                put(".dv", "video/x-dv");
                put(".dvi", "application/x-dvi");
                put(".dwf", "drawing/x-dwf");
                put(".dwp", "application/octet-stream");
                put(".dxr", "application/x-director");
                put(".eml", "message/rfc822");
                put(".emz", "application/octet-stream");
                put(".eot", "application/octet-stream");
                put(".eps", "application/postscript");
                put(".etl", "application/etl");
                put(".etx", "text/x-setext");
                put(".evy", "application/envoy");
                put(".exe", "application/octet-stream");
                put(".exe.config", "text/xml");
                put(".fdf", "application/vnd.fdf");
                put(".fif", "application/fractals");
                put(".filters", "Application/xml");
                put(".fla", "application/octet-stream");
                put(".flr", "x-world/x-vrml");
                put(".flv", "video/x-flv");
                put(".fsscript", "application/fsharp-script");
                put(".fsx", "application/fsharp-script");
                put(".generictest", "application/xml");
                put(".gif", "image/gif");
                put(".group", "text/x-ms-group");
                put(".gsm", "audio/x-gsm");
                put(".gtar", "application/x-gtar");
                put(".gz", "application/x-gzip");
                put(".h", "text/plain");
                put(".hdf", "application/x-hdf");
                put(".hdml", "text/x-hdml");
                put(".hhc", "application/x-oleobject");
                put(".hhk", "application/octet-stream");
                put(".hhp", "application/octet-stream");
                put(".hlp", "application/winhlp");
                put(".hpp", "text/plain");
                put(".hqx", "application/mac-binhex40");
                put(".hta", "application/hta");
                put(".htc", "text/x-component");
                put(".htm", "text/html");
                put(".html", "text/html");
                put(".htt", "text/webviewhtml");
                put(".hxa", "application/xml");
                put(".hxc", "application/xml");
                put(".hxd", "application/octet-stream");
                put(".hxe", "application/xml");
                put(".hxf", "application/xml");
                put(".hxh", "application/octet-stream");
                put(".hxi", "application/octet-stream");
                put(".hxk", "application/xml");
                put(".hxq", "application/octet-stream");
                put(".hxr", "application/octet-stream");
                put(".hxs", "application/octet-stream");
                put(".hxt", "text/html");
                put(".hxv", "application/xml");
                put(".hxw", "application/octet-stream");
                put(".hxx", "text/plain");
                put(".i", "text/plain");
                put(".ico", "image/x-icon");
                put(".ics", "application/octet-stream");
                put(".idl", "text/plain");
                put(".ief", "image/ief");
                put(".iii", "application/x-iphone");
                put(".inc", "text/plain");
                put(".inf", "application/octet-stream");
                put(".inl", "text/plain");
                put(".ins", "application/x-internet-signup");
                put(".ipa", "application/x-itunes-ipa");
                put(".ipg", "application/x-itunes-ipg");
                put(".ipproj", "text/plain");
                put(".ipsw", "application/x-itunes-ipsw");
                put(".iqy", "text/x-ms-iqy");
                put(".isp", "application/x-internet-signup");
                put(".ite", "application/x-itunes-ite");
                put(".itlp", "application/x-itunes-itlp");
                put(".itms", "application/x-itunes-itms");
                put(".itpc", "application/x-itunes-itpc");
                put(".IVF", "video/x-ivf");
                put(".jar", "application/java-archive");
                put(".java", "application/octet-stream");
                put(".jck", "application/liquidmotion");
                put(".jcz", "application/liquidmotion");
                put(".jfif", "image/pjpeg");
                put(".jnlp", "application/x-java-jnlp-file");
                put(".jpb", "application/octet-stream");
                put(".jpe", "image/jpeg");
                put(".jpeg", "image/jpeg");
                put(".jpg", "image/jpeg");
                put(".js", "application/x-javascript");
                put(".json", "application/json");
                put(".jsx", "text/jscript");
                put(".jsxbin", "text/plain");
                put(".latex", "application/x-latex");
                put(".library-ms", "application/windows-library+xml");
                put(".lit", "application/x-ms-reader");
                put(".loadtest", "application/xml");
                put(".lpk", "application/octet-stream");
                put(".lsf", "video/x-la-asf");
                put(".lst", "text/plain");
                put(".lsx", "video/x-la-asf");
                put(".lzh", "application/octet-stream");
                put(".m13", "application/x-msmediaview");
                put(".m14", "application/x-msmediaview");
                put(".m1v", "video/mpeg");
                put(".m2t", "video/vnd.dlna.mpeg-tts");
                put(".m2ts", "video/vnd.dlna.mpeg-tts");
                put(".m2v", "video/mpeg");
                put(".m3u", "audio/x-mpegurl");
                put(".m3u8", "audio/x-mpegurl");
                put(".m4a", "audio/m4a");
                put(".m4b", "audio/m4b");
                put(".m4p", "audio/m4p");
                put(".m4r", "audio/x-m4r");
                put(".m4v", "video/x-m4v");
                put(".mac", "image/x-macpaint");
                put(".mak", "text/plain");
                put(".man", "application/x-troff-man");
                put(".manifest", "application/x-ms-manifest");
                put(".map", "text/plain");
                put(".master", "application/xml");
                put(".mda", "application/msaccess");
                put(".mdb", "application/x-msaccess");
                put(".mde", "application/msaccess");
                put(".mdp", "application/octet-stream");
                put(".me", "application/x-troff-me");
                put(".mfp", "application/x-shockwave-flash");
                put(".mht", "message/rfc822");
                put(".mhtml", "message/rfc822");
                put(".mid", "audio/mid");
                put(".midi", "audio/mid");
                put(".mix", "application/octet-stream");
                put(".mk", "text/plain");
                put(".mmf", "application/x-smaf");
                put(".mno", "text/xml");
                put(".mny", "application/x-msmoney");
                put(".mod", "video/mpeg");
                put(".mov", "video/quicktime");
                put(".movie", "video/x-sgi-movie");
                put(".mp2", "video/mpeg");
                put(".mp2v", "video/mpeg");
                put(".mp3", "audio/mpeg");
                put(".mp4", "video/mp4");
                put(".mp4v", "video/mp4");
                put(".mpa", "video/mpeg");
                put(".mpe", "video/mpeg");
                put(".mpeg", "video/mpeg");
                put(".mpf", "application/vnd.ms-mediapackage");
                put(".mpg", "video/mpeg");
                put(".mpp", "application/vnd.ms-project");
                put(".mpv2", "video/mpeg");
                put(".mqv", "video/quicktime");
                put(".ms", "application/x-troff-ms");
                put(".msi", "application/octet-stream");
                put(".mso", "application/octet-stream");
                put(".mts", "video/vnd.dlna.mpeg-tts");
                put(".mtx", "application/xml");
                put(".mvb", "application/x-msmediaview");
                put(".mvc", "application/x-miva-compiled");
                put(".mxp", "application/x-mmxp");
                put(".nc", "application/x-netcdf");
                put(".nsc", "video/x-ms-asf");
                put(".nws", "message/rfc822");
                put(".ocx", "application/octet-stream");
                put(".oda", "application/oda");
                put(".odc", "text/x-ms-odc");
                put(".odh", "text/plain");
                put(".odl", "text/plain");
                put(".odp", "application/vnd.oasis.opendocument.presentation");
                put(".ods", "application/oleobject");
                put(".odt", "application/vnd.oasis.opendocument.text");
                put(".one", "application/onenote");
                put(".onea", "application/onenote");
                put(".onepkg", "application/onenote");
                put(".onetmp", "application/onenote");
                put(".onetoc", "application/onenote");
                put(".onetoc2", "application/onenote");
                put(".orderedtest", "application/xml");
                put(".osdx", "application/opensearchdescription+xml");
                put(".p10", "application/pkcs10");
                put(".p12", "application/x-pkcs12");
                put(".p7b", "application/x-pkcs7-certificates");
                put(".p7c", "application/pkcs7-mime");
                put(".p7m", "application/pkcs7-mime");
                put(".p7r", "application/x-pkcs7-certreqresp");
                put(".p7s", "application/pkcs7-signature");
                put(".pbm", "image/x-portable-bitmap");
                put(".pcast", "application/x-podcast");
                put(".pct", "image/pict");
                put(".pcx", "application/octet-stream");
                put(".pcz", "application/octet-stream");
                put(".pdf", "application/pdf");
                put(".pfb", "application/octet-stream");
                put(".pfm", "application/octet-stream");
                put(".pfx", "application/x-pkcs12");
                put(".pgm", "image/x-portable-graymap");
                put(".pic", "image/pict");
                put(".pict", "image/pict");
                put(".pkgdef", "text/plain");
                put(".pkgundef", "text/plain");
                put(".pko", "application/vnd.ms-pki.pko");
                put(".pls", "audio/scpls");
                put(".pma", "application/x-perfmon");
                put(".pmc", "application/x-perfmon");
                put(".pml", "application/x-perfmon");
                put(".pmr", "application/x-perfmon");
                put(".pmw", "application/x-perfmon");
                put(".png", "image/png");
                put(".pnm", "image/x-portable-anymap");
                put(".pnt", "image/x-macpaint");
                put(".pntg", "image/x-macpaint");
                put(".pnz", "image/png");
                put(".pot", "application/vnd.ms-powerpoint");
                put(".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12");
                put(".potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
                put(".ppa", "application/vnd.ms-powerpoint");
                put(".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12");
                put(".ppm", "image/x-portable-pixmap");
                put(".pps", "application/vnd.ms-powerpoint");
                put(".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12");
                put(".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
                put(".ppt", "application/vnd.ms-powerpoint");
                put(".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12");
                put(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
                put(".prf", "application/pics-rules");
                put(".prm", "application/octet-stream");
                put(".prx", "application/octet-stream");
                put(".ps", "application/postscript");
                put(".psc1", "application/PowerShell");
                put(".psd", "application/octet-stream");
                put(".psess", "application/xml");
                put(".psm", "application/octet-stream");
                put(".psp", "application/octet-stream");
                put(".pub", "application/x-mspublisher");
                put(".pwz", "application/vnd.ms-powerpoint");
                put(".qht", "text/x-html-insertion");
                put(".qhtm", "text/x-html-insertion");
                put(".qt", "video/quicktime");
                put(".qti", "image/x-quicktime");
                put(".qtif", "image/x-quicktime");
                put(".qtl", "application/x-quicktimeplayer");
                put(".qxd", "application/octet-stream");
                put(".ra", "audio/x-pn-realaudio");
                put(".ram", "audio/x-pn-realaudio");
                put(".rar", "application/octet-stream");
                put(".ras", "image/x-cmu-raster");
                put(".rat", "application/rat-file");
                put(".rc", "text/plain");
                put(".rc2", "text/plain");
                put(".rct", "text/plain");
                put(".rdlc", "application/xml");
                put(".resx", "application/xml");
                put(".rf", "image/vnd.rn-realflash");
                put(".rgb", "image/x-rgb");
                put(".rgs", "text/plain");
                put(".rm", "application/vnd.rn-realmedia");
                put(".rmi", "audio/mid");
                put(".rmp", "application/vnd.rn-rn_music_package");
                put(".roff", "application/x-troff");
                put(".rpm", "audio/x-pn-realaudio-plugin");
                put(".rqy", "text/x-ms-rqy");
                put(".rtf", "application/rtf");
                put(".rtx", "text/richtext");
                put(".ruleset", "application/xml");
                put(".s", "text/plain");
                put(".safariextz", "application/x-safari-safariextz");
                put(".scd", "application/x-msschedule");
                put(".sct", "text/scriptlet");
                put(".sd2", "audio/x-sd2");
                put(".sdp", "application/sdp");
                put(".sea", "application/octet-stream");
                put(".searchConnector-ms", "application/windows-search-connector+xml");
                put(".setpay", "application/set-payment-initiation");
                put(".setreg", "application/set-registration-initiation");
                put(".settings", "application/xml");
                put(".sgimb", "application/x-sgimb");
                put(".sgml", "text/sgml");
                put(".sh", "application/x-sh");
                put(".shar", "application/x-shar");
                put(".shtml", "text/html");
                put(".sit", "application/x-stuffit");
                put(".sitemap", "application/xml");
                put(".skin", "application/xml");
                put(".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12");
                put(".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide");
                put(".slk", "application/vnd.ms-excel");
                put(".sln", "text/plain");
                put(".slupkg-ms", "application/x-ms-license");
                put(".smd", "audio/x-smd");
                put(".smi", "application/octet-stream");
                put(".smx", "audio/x-smd");
                put(".smz", "audio/x-smd");
                put(".snd", "audio/basic");
                put(".snippet", "application/xml");
                put(".snp", "application/octet-stream");
                put(".sol", "text/plain");
                put(".sor", "text/plain");
                put(".spc", "application/x-pkcs7-certificates");
                put(".spl", "application/futuresplash");
                put(".src", "application/x-wais-source");
                put(".srf", "text/plain");
                put(".SSISDeploymentManifest", "text/xml");
                put(".ssm", "application/streamingmedia");
                put(".sst", "application/vnd.ms-pki.certstore");
                put(".stl", "application/vnd.ms-pki.stl");
                put(".sv4cpio", "application/x-sv4cpio");
                put(".sv4crc", "application/x-sv4crc");
                put(".svc", "application/xml");
                put(".swf", "application/x-shockwave-flash");
                put(".t", "application/x-troff");
                put(".tar", "application/x-tar");
                put(".tcl", "application/x-tcl");
                put(".testrunconfig", "application/xml");
                put(".testsettings", "application/xml");
                put(".tex", "application/x-tex");
                put(".texi", "application/x-texinfo");
                put(".texinfo", "application/x-texinfo");
                put(".tgz", "application/x-compressed");
                put(".thmx", "application/vnd.ms-officetheme");
                put(".thn", "application/octet-stream");
                put(".tif", "image/tiff");
                put(".tiff", "image/tiff");
                put(".tlh", "text/plain");
                put(".tli", "text/plain");
                put(".toc", "application/octet-stream");
                put(".tr", "application/x-troff");
                put(".trm", "application/x-msterminal");
                put(".trx", "application/xml");
                put(".ts", "video/vnd.dlna.mpeg-tts");
                put(".tsv", "text/tab-separated-values");
                put(".ttf", "application/octet-stream");
                put(".tts", "video/vnd.dlna.mpeg-tts");
                put(".txt", "text/plain");
                put(".u32", "application/octet-stream");
                put(".uls", "text/iuls");
                put(".user", "text/plain");
                put(".ustar", "application/x-ustar");
                put(".vb", "text/plain");
                put(".vbdproj", "text/plain");
                put(".vbk", "video/mpeg");
                put(".vbproj", "text/plain");
                put(".vbs", "text/vbscript");
                put(".vcf", "text/x-vcard");
                put(".vcproj", "Application/xml");
                put(".vcs", "text/plain");
                put(".vcxproj", "Application/xml");
                put(".vddproj", "text/plain");
                put(".vdp", "text/plain");
                put(".vdproj", "text/plain");
                put(".vdx", "application/vnd.ms-visio.viewer");
                put(".vml", "text/xml");
                put(".vscontent", "application/xml");
                put(".vsct", "text/xml");
                put(".vsd", "application/vnd.visio");
                put(".vsi", "application/ms-vsi");
                put(".vsix", "application/vsix");
                put(".vsixlangpack", "text/xml");
                put(".vsixmanifest", "text/xml");
                put(".vsmdi", "application/xml");
                put(".vspscc", "text/plain");
                put(".vss", "application/vnd.visio");
                put(".vsscc", "text/plain");
                put(".vssettings", "text/xml");
                put(".vssscc", "text/plain");
                put(".vst", "application/vnd.visio");
                put(".vstemplate", "text/xml");
                put(".vsto", "application/x-ms-vsto");
                put(".vsw", "application/vnd.visio");
                put(".vsx", "application/vnd.visio");
                put(".vtx", "application/vnd.visio");
                put(".wav", "audio/wav");
                put(".wave", "audio/wav");
                put(".wax", "audio/x-ms-wax");
                put(".wbk", "application/msword");
                put(".wbmp", "image/vnd.wap.wbmp");
                put(".wcm", "application/vnd.ms-works");
                put(".wdb", "application/vnd.ms-works");
                put(".wdp", "image/vnd.ms-photo");
                put(".webarchive", "application/x-safari-webarchive");
                put(".webtest", "application/xml");
                put(".wiq", "application/xml");
                put(".wiz", "application/msword");
                put(".wks", "application/vnd.ms-works");
                put(".WLMP", "application/wlmoviemaker");
                put(".wlpginstall", "application/x-wlpg-detect");
                put(".wlpginstall3", "application/x-wlpg3-detect");
                put(".wm", "video/x-ms-wm");
                put(".wma", "audio/x-ms-wma");
                put(".wmd", "application/x-ms-wmd");
                put(".wmf", "application/x-msmetafile");
                put(".wml", "text/vnd.wap.wml");
                put(".wmlc", "application/vnd.wap.wmlc");
                put(".wmls", "text/vnd.wap.wmlscript");
                put(".wmlsc", "application/vnd.wap.wmlscriptc");
                put(".wmp", "video/x-ms-wmp");
                put(".wmv", "video/x-ms-wmv");
                put(".wmx", "video/x-ms-wmx");
                put(".wmz", "application/x-ms-wmz");
                put(".wpl", "application/vnd.ms-wpl");
                put(".wps", "application/vnd.ms-works");
                put(".wri", "application/x-mswrite");
                put(".wrl", "x-world/x-vrml");
                put(".wrz", "x-world/x-vrml");
                put(".wsc", "text/scriptlet");
                put(".wsdl", "text/xml");
                put(".wvx", "video/x-ms-wvx");
                put(".x", "application/directx");
                put(".xaf", "x-world/x-vrml");
                put(".xaml", "application/xaml+xml");
                put(".xap", "application/x-silverlight-app");
                put(".xbap", "application/x-ms-xbap");
                put(".xbm", "image/x-xbitmap");
                put(".xdr", "text/plain");
                put(".xht", "application/xhtml+xml");
                put(".xhtml", "application/xhtml+xml");
                put(".xla", "application/vnd.ms-excel");
                put(".xlam", "application/vnd.ms-excel.addin.macroEnabled.12");
                put(".xlc", "application/vnd.ms-excel");
                put(".xld", "application/vnd.ms-excel");
                put(".xlk", "application/vnd.ms-excel");
                put(".xll", "application/vnd.ms-excel");
                put(".xlm", "application/vnd.ms-excel");
                put(".xls", "application/vnd.ms-excel");
                put(".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12");
                put(".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12");
                put(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                put(".xlt", "application/vnd.ms-excel");
                put(".xltm", "application/vnd.ms-excel.template.macroEnabled.12");
                put(".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");
                put(".xlw", "application/vnd.ms-excel");
                put(".xml", "text/xml");
                put(".xmta", "application/xml");
                put(".xof", "x-world/x-vrml");
                put(".XOML", "text/plain");
                put(".xpm", "image/x-xpixmap");
                put(".xps", "application/vnd.ms-xpsdocument");
                put(".xrm-ms", "text/xml");
                put(".xsc", "application/xml");
                put(".xsd", "text/xml");
                put(".xsf", "text/xml");
                put(".xsl", "text/xml");
                put(".xslt", "text/xml");
                put(".xsn", "application/octet-stream");
                put(".xss", "application/xml");
                put(".xtp", "application/octet-stream");
                put(".xwd", "image/x-xwindowdump");
                put(".z", "application/x-compress");
                put(".zip", "application/x-zip-compressed");
            }
        };
    }

    public static String getMimeType(String extension) {
        if (extension == null) {
            return null;
        }

        if (!extension.startsWith(".")) {
            extension = "." + extension.toLowerCase(Locale.getDefault());
        }

        String mime = mimeTypes.get(extension);

        return mime != null ? mime : "application/octet-stream";
    }
}

How do I make JavaScript beep?

Here's how I get it to beep using HTML5: First I copy and convert the windows wav file to mp3, then I use this code:

var _beep = window.Audio("Content/Custom/Beep.mp3")

function playBeep() { _beep.play()};

It's faster to declare the sound file globally and refer to it as needed.

Android Recyclerview vs ListView with Viewholder

More from Bill Phillip's article (go read it!) but i thought it was important to point out the following.

In ListView, there was some ambiguity about how to handle click events: Should the individual views handle those events, or should the ListView handle them through OnItemClickListener? In RecyclerView, though, the ViewHolder is in a clear position to act as a row-level controller object that handles those kinds of details.

We saw earlier that LayoutManager handled positioning views, and ItemAnimator handled animating them. ViewHolder is the last piece: it’s responsible for handling any events that occur on a specific item that RecyclerView displays.

How to install python3 version of package via pip on Ubuntu?

Another way to install python3 is using wget. Below are the steps for installation.

wget http://www.python.org/ftp/python/3.3.5/Python-3.3.5.tar.xz
tar xJf ./Python-3.3.5.tar.xz
cd ./Python-3.3.5
./configure --prefix=/opt/python3.3
make && sudo make install

Also,one can create an alias for the same using

echo 'alias py="/opt/python3.3/bin/python3.3"' >> ~/.bashrc

Now open a new terminal and type py and press Enter.

jQuery `.is(":visible")` not working in Chrome

I added next style on the parent and .is(":visible") worked.

display: inline-block;

React - clearing an input value after form submit

This is the value that i want to clear and create it in state 1st STEP

state={
TemplateCode:"",
}

craete submitHandler function for Button or what you want 3rd STEP

submitHandler=()=>{
this.clear();//this is function i made
}

This is clear function Final STEP

clear = () =>{
  this.setState({
    TemplateCode: ""//simply you can clear Templatecode
  });
}

when click button Templatecode is clear 2nd STEP

<div class="col-md-12" align="right">
  <button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save 
  </button>
</div>

How to echo out the values of this array?

foreach ($array as $key => $val) {
   echo $val;
}

How can I check if a string is null or empty in PowerShell?

An extension of the answer from Keith Hill (to account for whitespace):

$str = "     "
if ($str -and $version.Trim()) { Write-Host "Not Empty" } else { Write-Host "Empty" }

This returns "Empty" for nulls, empty strings, and strings with whitespace, and "Not Empty" for everything else.

Getting the document object of an iframe

Try the following

var doc=document.getElementById("frame").contentDocument;

// Earlier versions of IE or IE8+ where !DOCTYPE is not specified
var doc=document.getElementById("frame").contentWindow.document;

Note: AndyE pointed out that contentWindow is supported by all major browsers so this may be the best way to go.

Note2: In this sample you won't be able to access the document via any means. The reason is you can't access the document of an iframe with a different origin because it violates the "Same Origin" security policy

Call javascript from MVC controller action

For those that just used a standard form submit (non-AJAX), there's another way to fire some Javascript/JQuery code upon completion of your action.

First, create a string property on your Model.

public class MyModel 
{
    public string JavascriptToRun { get; set;}
}

Now, bind to your new model property in the Javascript of your view:

<script type="text/javascript">
     @Model.JavascriptToRun
</script>

Now, also in your view, create a Javascript function that does whatever you need to do:

<script type="text/javascript">
     @Model.JavascriptToRun

     function ShowErrorPopup() {
          alert('Sorry, we could not process your order.');
     }

</script>

Finally, in your controller action, you need to call this new Javascript function:

[HttpPost]
public ActionResult PurchaseCart(MyModel model)
{
    // Do something useful
    ...

    if (success == false)
    {
        model.JavascriptToRun= "ShowErrorPopup()";
        return View(model);
    }
    else
        return RedirectToAction("Success");
}

How do I analyze a .hprof file?

I personally prefer VisualVM. One of the features I like in VisualVM is heap dump comparison. When you are doing a heap dump analysis there are various ways to go about figuring out what caused the crash. One of the ways I have found useful is doing a comparison of healthy vs unhealthy heap dumps.

Following are the steps you can follow for it :

  1. Getting a heap dump of OutOfMemoryError let's call it "oome.hprof". You can get this via JVM parameter HeapDumpOnOutOfMemoryError.
  2. Restart the application let it run for a big (minutes/hours) depending on your application. Get another heap dump while the application is still running. Let's call it "healthy.hprof".
  3. You can open both these dumps in VisualVM and do a heap dump comparison. You can do it on class or package level. This can often point you into the direction of the issue.

link : https://visualvm.github.io

Change Image of ImageView programmatically in Android

Short answer

Just copy an image into your res/drawable folder and use

imageView.setImageResource(R.drawable.my_image);

Details

The variety of answers can cause a little confusion. We have

The methods with Background in their name all belong to the View class, not to ImageView specifically. But since ImageView inherits from View you can use them, too. The methods with Image in their name belong specifically to ImageView.

The View methods all do the same thing as each other (though setBackgroundDrawable() is deprecated), so we will just focus on setBackgroundResource(). Similarly, the ImageView methods all do the same thing, so we will just focus on setImageResource(). The only difference between the methods is they type of parameter you pass in.

Setup

Here is a FrameLayout that contains an ImageView. The ImageView initially doesn't have any image in it. (I only added the FrameLayout so that I could put a border around it. That way you can see the edge of the ImageView.)

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:background="@drawable/border"
        android:layout_centerInParent="true">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </FrameLayout>
</RelativeLayout>

Below we will compare the different methods.

setImageResource()

If you use ImageView's setImageResource(), then the image keeps its aspect ratio and is resized to fit. Here are two different image examples.

  • imageView.setImageResource(R.drawable.sky);
  • imageView.setImageResource(R.drawable.balloons);

enter image description here

setBackgroundResource()

Using View's setBackgroundResource(), on the other hand, causes the image resource to be stretched to fill the view.

  • imageView.setBackgroundResource(R.drawable.sky);
  • imageView.setBackgroundResource(R.drawable.balloons);

enter image description here

Both

The View's background image and the ImageView's image are drawn separately, so you can set them both.

imageView.setBackgroundResource(R.drawable.sky);
imageView.setImageResource(R.drawable.balloons);

enter image description here

How to find event listeners on a DOM node when debugging or from the JavaScript code?

Fully working solution based on answer by Jan Turon - behaves like getEventListeners() from console:

(There is a little bug with duplicates. It doesn't break much anyway.)

(function() {
  Element.prototype._addEventListener = Element.prototype.addEventListener;
  Element.prototype.addEventListener = function(a,b,c) {
    if(c==undefined)
      c=false;
    this._addEventListener(a,b,c);
    if(!this.eventListenerList)
      this.eventListenerList = {};
    if(!this.eventListenerList[a])
      this.eventListenerList[a] = [];
    //this.removeEventListener(a,b,c); // TODO - handle duplicates..
    this.eventListenerList[a].push({listener:b,useCapture:c});
  };

  Element.prototype.getEventListeners = function(a){
    if(!this.eventListenerList)
      this.eventListenerList = {};
    if(a==undefined)
      return this.eventListenerList;
    return this.eventListenerList[a];
  };
  Element.prototype.clearEventListeners = function(a){
    if(!this.eventListenerList)
      this.eventListenerList = {};
    if(a==undefined){
      for(var x in (this.getEventListeners())) this.clearEventListeners(x);
        return;
    }
    var el = this.getEventListeners(a);
    if(el==undefined)
      return;
    for(var i = el.length - 1; i >= 0; --i) {
      var ev = el[i];
      this.removeEventListener(a, ev.listener, ev.useCapture);
    }
  };

  Element.prototype._removeEventListener = Element.prototype.removeEventListener;
  Element.prototype.removeEventListener = function(a,b,c) {
    if(c==undefined)
      c=false;
    this._removeEventListener(a,b,c);
      if(!this.eventListenerList)
        this.eventListenerList = {};
      if(!this.eventListenerList[a])
        this.eventListenerList[a] = [];

      // Find the event in the list
      for(var i=0;i<this.eventListenerList[a].length;i++){
          if(this.eventListenerList[a][i].listener==b, this.eventListenerList[a][i].useCapture==c){ // Hmm..
              this.eventListenerList[a].splice(i, 1);
              break;
          }
      }
    if(this.eventListenerList[a].length==0)
      delete this.eventListenerList[a];
  };
})();

Usage:

someElement.getEventListeners([name]) - return list of event listeners, if name is set return array of listeners for that event

someElement.clearEventListeners([name]) - remove all event listeners, if name is set only remove listeners for that event

How do I start my app on startup?

The Sean's solution didn't work for me initially (Android 4.2.2). I had to add a dummy activity to the same Android project and run the activity manually on the device at least once. Then the Sean's solution started to work and the BroadcastReceiver was notified after subsequent reboots.

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

I modified the script by Nicolay77 to output the database to stdout (the usual way of unix scripts) so that I could output the data to text file or pipe it to any program I want. The resulting script is a bit simpler and works well.

Some examples:

./mdb_to_mysql.sh database.mdb > data.sql

./mdb_to_mysql.sh database.mdb | mysql destination-db -u user -p

Here is the modified script (save to mdb_to_mysql.sh)

#!/bin/bash
TABLES=$(mdb-tables -1 $1)

for t in $TABLES
do
    echo "DROP TABLE IF EXISTS $t;"
done

mdb-schema $1 mysql

for t in $TABLES
do
    mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t
done

belongs_to through associations

So you cant have the behavior that you want but you can do something that feels like it. You want to be able to do Choice.first.question

what I have done in the past is something like this

class Choice
  belongs_to :user
  belongs_to :answer
  validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
  ...
  def question
    answer.question
  end
end

this way the you can now call question on Choice

Python, Unicode, and the Windows console

Kind of related on the answer by J. F. Sebastian, but more direct.

If you are having this problem when printing to the console/terminal, then do this:

>set PYTHONIOENCODING=UTF-8

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

Need to add to chosen answer: As of now, npm install in a package directory (containing package.json) will install devDependencies, whereas npm install -g will not install them.

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

Commit empty folder structure (with git)

In Git, you cannot commit empty folders, because Git does not actually save folders, only files. You'll have to create some placeholder file inside those directories if you actually want them to be "empty" (i.e. you have no committable content).

Best way to convert an ArrayList to a string

For this simple use case, you can simply join the strings with comma. If you use Java 8:

String csv = String.join("\t", yourArray);

otherwise commons-lang has a join() method:

String csv = org.apache.commons.lang3.StringUtils.join(yourArray, "\t");

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Use ` backticks for MYSQL reserved words...

table name "table" is reserved word for MYSQL...

so your query should be as follows...

$sql="INSERT INTO `table` (`username`, `password`)
VALUES
('$_POST[username]','$_POST[password]')";

How to set image in imageview in android?

        ImageView iv= (ImageView)findViewById(R.id.img_selected_image);
        public static int getDrawable(Context context, String name)//method to get id
        {
         Assert.assertNotNull(context);
         Assert.assertNotNull(name);
        return context.getResources().getIdentifier(name,    //return id
            "your drawable", context.getPackageName());
        }
        image.setImageResource(int Id);//set id using this method

How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

Things have changed a little in the way Charles provides HTTPS proxying.

First the certificates installation options have been moved to the help menu.

Help -> SSL Proxying -> Install Charles Root Certificate
Help -> SSL Proxying -> Install Charles Root Certificate in iOS Simulators

Charles SSL Proxying

Second, starting in iOS 9 you must provide a NSAppTransportSecurity option in your Info.plist and if you want Charles to work properly as a man in the middle, you must add:

<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>

as part of the your domains see full example:

<key>NSExceptionDomains</key>
    <dict>
        <key>yourdomain.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
        </dict>

The reason being (I guess) that Charles at some point communicates in clear http after acting as the man in the middle https server.

Last step is to activate SSL Proxying for this domain in Charles (right click on domain and select Enable SSL Proxying)

enable HTTP Proxying

Disable spell-checking on HTML textfields

Update: As suggested by a commenter (additional credit to How can I disable the spell checker on text inputs on the iPhone), use this to handle all desktop and mobile browsers.

<tag autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>

Original answer: Javascript cannot override user settings, so unless you use another mechanism other than textfields, this is not (or shouldn't be) possible.

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

In my case, the error was in using angular2-notifications 0.9.8 instead of 0.9.7

Reading output of a command into an array in Bash

Here is an example. Imagine that you are going to put the files and directory names (under the current folder) to an array and count its items. The script would be like;

my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length

Or, you can iterate over this array by adding the following script:

for element in "${my_array[@]}"
do
   echo "${element}"
done

Please note that this is the core concept and the input is considered to be sanitized before, i.e. removing extra characters, handling empty Strings, and etc. (which is out of the topic of this thread).

Python string prints as [u'String']

You probably have a list containing one unicode string. The repr of this is [u'String'].

You can convert this to a list of byte strings using any variation of the following:

# Functional style.
print map(lambda x: x.encode('ascii'), my_list)

# List comprehension.
print [x.encode('ascii') for x in my_list]

# Interesting if my_list may be a tuple or a string.
print type(my_list)(x.encode('ascii') for x in my_list)

# What do I care about the brackets anyway?
print ', '.join(repr(x.encode('ascii')) for x in my_list)

# That's actually not a good way of doing it.
print ' '.join(repr(x).lstrip('u')[1:-1] for x in my_list)

Disable text input history

<input type="text" autocomplete="off" />

VBA - If a cell in column A is not blank the column B equals

A simpler way to do this would be:

Sub populateB()

For Each Cel in Range("A1:A100")
    If Cel.value <> "" Then Cel.Offset(0, 1).value = "Your Text"
Next

End Sub

Changing an element's ID with jQuery

What you mean to do is:

jQuery(this).prev("li").attr("id", "newID");

That will set the ID to the new ID

How to add `style=display:"block"` to an element using jQuery?

If you need to add multiple then you can do it like this:

$('#element').css({
    'margin-left': '5px',
    'margin-bottom': '-4px',
    //... and so on
});

As a good practice I would also put the property name between quotes to allow the dash since most styles have a dash in them. If it was 'display', then quotes are optional but if you have a dash, it will not work without the quotes. Anyways, to make it simple: always enclose them in quotes.

Measuring elapsed time with the Time module

Here is an update to Vadim Shender's clever code with tabular output:

import collections
import time
from functools import wraps

PROF_DATA = collections.defaultdict(list)

def profile(fn):
    @wraps(fn)
    def with_profiling(*args, **kwargs):
        start_time = time.time()
        ret = fn(*args, **kwargs)
        elapsed_time = time.time() - start_time
        PROF_DATA[fn.__name__].append(elapsed_time)
        return ret
    return with_profiling

Metrics = collections.namedtuple("Metrics", "sum_time num_calls min_time max_time avg_time fname")

def print_profile_data():
    results = []
    for fname, elapsed_times in PROF_DATA.items():
        num_calls = len(elapsed_times)
        min_time = min(elapsed_times)
        max_time = max(elapsed_times)
        sum_time = sum(elapsed_times)
        avg_time = sum_time / num_calls
        metrics = Metrics(sum_time, num_calls, min_time, max_time, avg_time, fname)
        results.append(metrics)
    total_time = sum([m.sum_time for m in results])
    print("\t".join(["Percent", "Sum", "Calls", "Min", "Max", "Mean", "Function"]))
    for m in sorted(results, reverse=True):
        print("%.1f\t%.3f\t%d\t%.3f\t%.3f\t%.3f\t%s" % (100 * m.sum_time / total_time, m.sum_time, m.num_calls, m.min_time, m.max_time, m.avg_time, m.fname))
    print("%.3f Total Time" % total_time)

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

In:

for i in range(c/10):

You're creating a float as a result - to fix this use the int division operator:

for i in range(c // 10):

Read Content from Files which are inside Zip file

Because of the condition in while, the loop might never break:

while (entry != null) {
  // If entry never becomes null here, loop will never break.
}

Instead of the null check there, you can try this:

ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
  // Rest of your code
}

How to keep the local file or the remote file during merge using Git and the command line?

This approach seems more straightforward, avoiding the need to individually select each file:

# keep remote files
git merge --strategy-option theirs
# keep local files
git merge --strategy-option ours

or

# keep remote files
git pull -Xtheirs
# keep local files
git pull -Xours

Copied directly from: Resolve Git merge conflicts in favor of their changes during a pull

How to read data when some numbers contain commas as thousand separator?

You can have read.table or read.csv do this conversion for you semi-automatically. First create a new class definition, then create a conversion function and set it as an "as" method using the setAs function like so:

setClass("num.with.commas")
setAs("character", "num.with.commas", 
        function(from) as.numeric(gsub(",", "", from) ) )

Then run read.csv like:

DF <- read.csv('your.file.here', 
   colClasses=c('num.with.commas','factor','character','numeric','num.with.commas'))

What's the best way to break from nested loops in JavaScript?

Here are five ways to break out of nested loops in JavaScript:

1) Set parent(s) loop to the end

for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (j === 2)
        {
            i = 5;
            break;
        }
    }
}

2) Use label

exit_loops:
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (j === 2)
            break exit_loops;
    }
}

3) Use variable

var exit_loops = false;
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (j === 2)
        {
            exit_loops = true;
            break;
        }
    }
    if (exit_loops)
        break;
}

4) Use self executing function

(function()
{
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 5; j++)
        {
             if (j === 2)
                 return;
        }
    }
})();

5) Use regular function

function nested_loops()
{
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 5; j++)
        {
             if (j === 2)
                 return;
        }
    }
}
nested_loops();

Array Length in Java

if you mean by "logical size", the index of array, then simply int arrayLength = arr.length-1; since the the array index starts with "0", so the logical or "array index" will always be less than the actual size by "one".

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

In my case, I had to use different certificates for different git repositories.

Follow steps below (If you have a certificate of your repository, you can read from step 5)

  1. Go to remote repository's site. Ex: github.com, bitbucket.org, tfs.example...

  2. Click Lock icon on the upper left side and click Certificate.

  3. Go to Certification Path tab and double click to .. Root Certificate

  4. Go to Details tab and click Copy to file.

  5. Export/Copy certificate to wherever you want. Ex: C:\certs\example.cer

  6. Open git bash at your local repository folder and type:

    $ git config http.sslCAInfo "C:\certs\example.cer"

Now you can use different certificates for each repository.

Remember, calling with the --global parameter will also change the certificates of git repositories in other folders, so you should not use the --global parameter when executing this command.

Adding an image to a project in Visual Studio

You need to turn on Show All Files option on solution pane toolbar and include this file manually.

How to generate keyboard events?

user648852's idea at least for me works great for OS X, here is the code to do it:

#!/usr/bin/env python

import time
from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost

# Python releases things automatically, using CFRelease will result in a scary error
#from Quartz.CoreGraphics import CFRelease

from Quartz.CoreGraphics import kCGHIDEventTap

# From http://stackoverflow.com/questions/281133/controlling-the-mouse-from-python-in-os-x
# and from https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/index.html#//apple_ref/c/func/CGEventCreateKeyboardEvent


def KeyDown(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)

def KeyUp(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

def KeyPress(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)



# From http://stackoverflow.com/questions/3202629/where-can-i-find-a-list-of-mac-virtual-key-codes

def toKeyCode(c):
    shiftKey = False
    # Letter
    if c.isalpha():
        if not c.islower():
            shiftKey = True
            c = c.lower()

    if c in shiftChars:
        shiftKey = True
        c = shiftChars[c]
    if c in keyCodeMap:
        keyCode = keyCodeMap[c]
    else:
        keyCode = ord(c)
    return keyCode, shiftKey

shiftChars = {
    '~': '`',
    '!': '1',
    '@': '2',
    '#': '3',
    '$': '4',
    '%': '5',
    '^': '6',
    '&': '7',
    '*': '8',
    '(': '9',
    ')': '0',
    '_': '-',
    '+': '=',
    '{': '[',
    '}': ']',
    '|': '\\',
    ':': ';',
    '"': '\'',
    '<': ',',
    '>': '.',
    '?': '/'
}


keyCodeMap = {
    'a'                 : 0x00,
    's'                 : 0x01,
    'd'                 : 0x02,
    'f'                 : 0x03,
    'h'                 : 0x04,
    'g'                 : 0x05,
    'z'                 : 0x06,
    'x'                 : 0x07,
    'c'                 : 0x08,
    'v'                 : 0x09,
    'b'                 : 0x0B,
    'q'                 : 0x0C,
    'w'                 : 0x0D,
    'e'                 : 0x0E,
    'r'                 : 0x0F,
    'y'                 : 0x10,
    't'                 : 0x11,
    '1'                 : 0x12,
    '2'                 : 0x13,
    '3'                 : 0x14,
    '4'                 : 0x15,
    '6'                 : 0x16,
    '5'                 : 0x17,
    '='                 : 0x18,
    '9'                 : 0x19,
    '7'                 : 0x1A,
    '-'                 : 0x1B,
    '8'                 : 0x1C,
    '0'                 : 0x1D,
    ']'                 : 0x1E,
    'o'                 : 0x1F,
    'u'                 : 0x20,
    '['                 : 0x21,
    'i'                 : 0x22,
    'p'                 : 0x23,
    'l'                 : 0x25,
    'j'                 : 0x26,
    '\''                : 0x27,
    'k'                 : 0x28,
    ';'                 : 0x29,
    '\\'                : 0x2A,
    ','                 : 0x2B,
    '/'                 : 0x2C,
    'n'                 : 0x2D,
    'm'                 : 0x2E,
    '.'                 : 0x2F,
    '`'                 : 0x32,
    'k.'                : 0x41,
    'k*'                : 0x43,
    'k+'                : 0x45,
    'kclear'            : 0x47,
    'k/'                : 0x4B,
    'k\n'               : 0x4C,
    'k-'                : 0x4E,
    'k='                : 0x51,
    'k0'                : 0x52,
    'k1'                : 0x53,
    'k2'                : 0x54,
    'k3'                : 0x55,
    'k4'                : 0x56,
    'k5'                : 0x57,
    'k6'                : 0x58,
    'k7'                : 0x59,
    'k8'                : 0x5B,
    'k9'                : 0x5C,

    # keycodes for keys that are independent of keyboard layout
    '\n'                : 0x24,
    '\t'                : 0x30,
    ' '                 : 0x31,
    'del'               : 0x33,
    'delete'            : 0x33,
    'esc'               : 0x35,
    'escape'            : 0x35,
    'cmd'               : 0x37,
    'command'           : 0x37,
    'shift'             : 0x38,
    'caps lock'         : 0x39,
    'option'            : 0x3A,
    'ctrl'              : 0x3B,
    'control'           : 0x3B,
    'right shift'       : 0x3C,
    'rshift'            : 0x3C,
    'right option'      : 0x3D,
    'roption'           : 0x3D,
    'right control'     : 0x3E,
    'rcontrol'          : 0x3E,
    'fun'               : 0x3F,
    'function'          : 0x3F,
    'f17'               : 0x40,
    'volume up'         : 0x48,
    'volume down'       : 0x49,
    'mute'              : 0x4A,
    'f18'               : 0x4F,
    'f19'               : 0x50,
    'f20'               : 0x5A,
    'f5'                : 0x60,
    'f6'                : 0x61,
    'f7'                : 0x62,
    'f3'                : 0x63,
    'f8'                : 0x64,
    'f9'                : 0x65,
    'f11'               : 0x67,
    'f13'               : 0x69,
    'f16'               : 0x6A,
    'f14'               : 0x6B,
    'f10'               : 0x6D,
    'f12'               : 0x6F,
    'f15'               : 0x71,
    'help'              : 0x72,
    'home'              : 0x73,
    'pgup'              : 0x74,
    'page up'           : 0x74,
    'forward delete'    : 0x75,
    'f4'                : 0x76,
    'end'               : 0x77,
    'f2'                : 0x78,
    'page down'         : 0x79,
    'pgdn'              : 0x79,
    'f1'                : 0x7A,
    'left'              : 0x7B,
    'right'             : 0x7C,
    'down'              : 0x7D,
    'up'                : 0x7E
}

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Your selector is a little off, it's missing the trailing ]

var mySelect = $('select[name=' + name + ']')

you may also need to put quotes around the name, like so:

var mySelect = $('select[name="' + name + '"]')

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

When your browser redirects the user to Google's oAuth page, are you passing as a parameter the redirect URI you want Google's server to return to with the token response? Setting a redirect URI in the console is not a way of telling Google where to go when a login attempt comes in, but rather it's a way of telling Google what the allowed redirect URIs are (so if someone else writes a web app with your client ID but a different redirect URI it will be disallowed); your web app should, when someone clicks the "login" button, send the browser to:

https://accounts.google.com/o/oauth2/auth?client_id=XXXXX&redirect_uri=http://localhost:8080/WEBAPP/youtube-callback.html&response_type=code&scope=https://www.googleapis.com/auth/youtube.upload

(the callback URI passed as a parameter must be url-encoded, btw).

When Google's server gets authorization from the user, then, it'll redirect the browser to whatever you sent in as the redirect_uri. It'll include in that request the token as a parameter, so your callback page can then validate the token, get an access token, and move on to the other parts of your app.

If you visit:

http://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow

You can see better samples of the java client there, demonstrating that you have to override the getRedirectUri method to specify your callback path so the default isn't used.

The redirect URIs are in the client_secrets.json file for multiple reasons ... one big one is so that the oAuth flow can verify that the redirect your app specifies matches what your app allows.

If you visit https://developers.google.com/api-client-library/java/apis/youtube/v3 You can generate a sample application for yourself that's based directly off your app in the console, in which (again) the getRedirectUri method is overwritten to use your specific callbacks.

Are the decimal places in a CSS width respected?

Even when the number is rounded when the page is painted, the full value is preserved in memory and used for subsequent child calculation. For example, if your box of 100.4999px paints to 100px, it's child with a width of 50% will be calculated as .5*100.4999 instead of .5*100. And so on to deeper levels.

I've created deeply nested grid layout systems where parents widths are ems, and children are percents, and including up to four decimal points upstream had a noticeable impact.

Edge case, sure, but something to keep in mind.

is it possible to add colors to python output?

being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -

eventually decided to use CLINT as an answer that was given there by great and smart people

Laravel blade check empty foreach

Check the documentation for the best result:

@forelse($status->replies as $reply)
    <p>{{ $reply->body }}</p>
@empty
    <p>No replies</p>
@endforelse

Insert current date/time using now() in a field using MySQL/PHP

now()

worked for me . but my field type is date only and yours is datetime. i am not sure if this is the case

Return Type for jdbcTemplate.queryForList(sql, object, classType)

In order to map a the result set of query to a particular Java class you'll probably be best (assuming you're interested in using the object elsewhere) off with a RowMapper to convert the columns in the result set into an object instance.

See Section 12.2.1.1 of Data access with JDBC on how to use a row mapper.

In short, you'll need something like:

List<Conversation> actors = jdbcTemplate.query(
    SELECT_ALL_CONVERSATIONS_SQL_FULL,
    new Object[] {userId, dateFrom, dateTo},
    new RowMapper<Conversation>() {
        public Conversation mapRow(ResultSet rs, int rowNum) throws SQLException {
            Conversation c = new Conversation();
            c.setId(rs.getLong(1));
            c.setRoom(rs.getString(2));
            [...]
            return c;
        }
    });

How do I set the focus to the first input element in an HTML form independent from the id?

Putting this code at the end of your body tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.

<script>
    (function(){
        var forms = document.forms || [];
        for(var i = 0; i < forms.length; i++){
            for(var j = 0; j < forms[i].length; j++){
                if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
                    forms[i][j].focus();
                    return;
                }
            }
        }
    })();
</script>

REST API Best practices: Where to put parameters?

According to the URI standard the path is for hierarchical parameters and the query is for non-hierarchical parameters. Ofc. it can be very subjective what is hierarchical for you.

In situations where multiple URIs are assigned to the same resource I like to put the parameters - necessary for identification - into the path and the parameters - necessary to build the representation - into the query. (For me this way it is easier to route.)

For example:

  • /users/123 and /users/123?fields="name, age"
  • /users and /users?name="John"&age=30

For map reduce I like to use the following approaches:

  • /users?name="John"&age=30
  • /users/name:John/age:30

So it is really up to you (and your server side router) how you construct your URIs.

note: Just to mention these parameters are query parameters. So what you are really doing is defining a simple query language. By complex queries (which contain operators like and, or, greater than, etc.) I suggest you to use an already existing query language. The capabilities of URI templates are very limited...

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

The mysql deamon should be running.

If not try this:

#/etc/init.d/mysql start

Or this:

#service mysqld start

And if you want to add mysql on boot:

# chkconfig --add mysqld
# chkconfig -- level 235 mysqld on

If yes, and it is still not working try this:

Uncomment the following lines in /etc/php/php.ini

extension=mysqli.so
extension=mysql.so

And please check your post above '/usr/lib64/php/modules/msql.so'. It should be mysql.so (if it's mistyped ignore it...)

How to square all the values in a vector in R?

How about sapply (not really necessary for this simple case):

newData<- sapply(data, function(x) x^2)

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

As m.edmondson mentioned, "The remote host closed the connection." occurs when a user or browser cancels something, or the network connection drops etc. It doesn't necessarily have to be a file download however, just any request for any resource that results in a response to the client. Basically the error means that the response could not be sent because the server can no longer talk to the client(browser).

There are a number of steps that you can take in order to stop it happening. If you are manually sending something in the response with a Response.Write, Response.Flush, returning data from a web servivce/page method or something similar, then you should consider checking Response.IsClientConnected before sending the response. Also, if the response is likely to take a long time or a lot of server-side processing is required, you should check this periodically until the response.end if called. See the following for details on this property:

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx

Alternatively, which I believe is most likely in your case, the error is being caused by something inside the framework. The following link may by of use:

http://blog.whitesites.com/fixing-The-remote-host-closed-the-connection-The-error-code-is-0x80070057__633882307305519259_blog.htm

The following stack-overflow post might also be of interest:

"The remote host closed the connection" in Response.OutputStream.Write

Aesthetics must either be length one, or the same length as the dataProblems

I hit this error because I was specifying a label attribute in my geom (geom_text) but was specifying a color in the top level aes:

df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)

# don't do this!
ggplot(df, aes(x=V6, y=V1, color=V1)) +
  geom_text(angle=45, label=df$V1, size=2)

To fix this, I just moved the label attribute out of the geom and into the top level aes:

df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)

# do this!
ggplot(df, aes(x=V6, y=V1, color=V1, label=V1)) +
  geom_text(angle=45, size=2)

How to set selected value on select using selectpicker plugin from bootstrap

$('select[name=selValue]').val(1);
$('.selectpicker').selectpicker('refresh');

This is all you need to do. No need to change the generated html of selectpicker directly, just change the hidden select field, and then call the selectpicker('refresh').

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

Tab key == 4 spaces and auto-indent after curly braces in Vim

Related, if you open a file that uses both tabs and spaces, assuming you've got

set expandtab ts=4 sw=4 ai

You can replace all the tabs with spaces in the entire file with

:%retab

Pagination using MySQL LIMIT, OFFSET

First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:

http://yoursite.com/itempage.php?page=2

You can access the requested page number via $_GET['page'].

This makes your SQL formulation really easy:

// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    if(false === $page) {
        $page = 1;
    }
}

// set the number of items to display per page
$items_per_page = 4;

// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;

So for example if input here was page=2, with 4 rows per page, your query would be"

SELECT * FROM menuitem LIMIT 4,4

So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).

In order to do this, you must understand the number of rows in the table.

You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).

This is actually quite simple:

$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
if(false === $result) {
   throw new Exception('Query failed with: ' . mysqli_error());
} else {
   $row_count = mysqli_num_rows($result);
   // free the result set as you don't need it anymore
   mysqli_free_result($result);
}

$page_count = 0;
if (0 === $row_count) {  
    // maybe show some error since there is nothing in your table
} else {
   // determine page_count
   $page_count = (int)ceil($row_count / $items_per_page);
   // double check that request page is in range
   if($page > $page_count) {
        // error to user, maybe set page to 1
        $page = 1;
   }
}

// make your LIMIT query here as shown above


// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
   if ($i === $page) { // this is current page
       echo 'Page ' . $i . '<br>';
   } else { // show link to other page   
       echo '<a href="/menuitem.php?page=' . $i . '">Page ' . $i . '</a><br>';
   }
}

Angular: How to update queryParams without changing route

If you want to change query params without change the route. see below example might help you: current route is : /search & Target route is(without reload page) : /search?query=love

    submit(value: string) {
      this.router.navigate( ['.'],  { queryParams: { query: value } })
        .then(_ => this.search(q));
    }
    search(keyword:any) { 
    //do some activity using }

please note : you can use this.router.navigate( ['search'] instead of this.router.navigate( ['.']

Why use pip over easy_install?

Another—as of yet unmentioned—reason for favoring pip is because it is the new hotness and will continue to be used in the future.

The infographic below—from the Current State of Packaging section in the The Hitchhiker's Guide to Packaging v1.0—shows that setuptools/easy_install will go away in the future.

enter image description here

Here's another infographic from distribute's documentation showing that Setuptools and easy_install will be replaced by the new hotness—distribute and pip. While pip is still the new hotness, Distribute merged with Setuptools in 2013 with the release of Setuptools v0.7.

enter image description here

java.lang.IllegalStateException: The specified child already has a parent

You are adding a View into a layout, but the View already is in another layout. A View can't be in more than one place.

Anybody knows any knowledge base open source?

I have used phpMyFAQ and found it to be very good.

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

How to wait for async method to complete?

Actually I found this more helpful for functions that return IAsyncAction.

            var task = asyncFunction();
            while (task.Status == AsyncStatus.Completed) ;

How to modify WooCommerce cart, checkout pages (main theme portion)

Another way to totally override the cart.php is to copy:

woocommerce/templates/cart/cart.php to   
yourtheme/woocommerce/cart/cart.php

Then do whatever you need at the yourtheme/woocommerce/cart/cart.php

use video as background for div

Pure CSS method

It is possible to center a video inside an element just like a cover sized background-image without JS using the object-fit attribute or CSS Transforms.

2021 answer: object-fit

As pointed in the comments, it is possible to achieve the same result without CSS transform, but using object-fit, which I think it's an even better option for the same result:

_x000D_
_x000D_
.video-container {
    height: 300px;
    width: 300px;
    position: relative;
}

.video-container video {
  width: 100%;
  height: 100%;
  position: absolute;
  object-fit: cover;
  z-index: 0;
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
}
_x000D_
<div class="video-container">
    <video autoplay muted loop>
        <source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
    </video>
    <div class="caption">
      <h2>Your caption here</h2>
    </div>
</div>
_x000D_
_x000D_
_x000D_


Previous answer: CSS Transform

You can set a video as a background to any HTML element easily thanks to transform CSS property.

Note that you can use the transform technique to center vertically and horizontally any HTML element.

_x000D_
_x000D_
.video-container {
  height: 300px;
  width: 300px;
  overflow: hidden;
  position: relative;
}

.video-container video {
  min-width: 100%;
  min-height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
}
_x000D_
<div class="video-container">
  <video autoplay muted loop>
    <source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
  </video>
  <div class="caption">
    <h2>Your caption here</h2>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How do I update Node.js?

  1. npm clean cache - you forget to clean ur cache

  2. npm update -g

    This works on mine Windows, I hope it will also work for you :D

jQuery datepicker years shown

what no one else has put is that you can also set hard-coded date ranges:

for example:

yearRange: "1901:2012"

whilst it may be advisable to not do this, it is however, an option that is perfectly valid (and useful if you are legitimately looking for say a specific year in a catalogue - such as "1963:1984" ).

How to write multiple conditions in Makefile.am with "else if"

As you've discovered, you can't do that. You can do:

libtest_LIBS = 

...

if HAVE_CLIENT
libtest_LIBS += libclient.la
endif

if HAVE_SERVER
libtest_LIBS += libserver.la
endif

form_for but to post to a different action

Alternatively the same can be reached using form_tag with the syntax:

form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_form")
# => '<form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">'

As described in http://guides.rubyonrails.org/form_helpers.html#multiple-hashes-in-form-helper-calls

How to validate array in Laravel?

The below code working for me on array coming from ajax call .

  $form = $request->input('form');
  $rules = array(
            'facebook_account' => 'url',
            'youtube_account' => 'url',
            'twitter_account' => 'url',
            'instagram_account' => 'url',
            'snapchat_account' => 'url',
            'website' => 'url',
        );
        $validation = Validator::make($form, $rules);

        if ($validation->fails()) {
            return Response::make(['error' => $validation->errors()], 400);
        }

app.config for a class library

Actually, for some rare case you could store app.config in class libraries (by adding manually) and parse it by OpenExeConfiguration.

 var fileMap =
    new ExeConfigurationFileMap {ExeConfigFilename = 
    @"C:\..somePath..\someName.config"};
 System.Configuration.Configuration config =
    ConfigurationManager.OpenMappedExeConfiguration(fileMap, 
    ConfigurationUserLevel.None);

You should really estimate the real need of this. For abstract data its not the best solution, but "Config Sections" could be very usefull!!

For example, we organised our N-Tier WCF architecture decoupled, without any metadata, simply by using Unity Container and Injection Factory based on Channel Factory T. We added externall ClassLibrary dll with just [Service Contract] Interfaces and common app.config in order to read endpoints from clientsection, and easily add/change them at one place.

How do I revert a Git repository to a previous commit?

There is a command (not a part of core Git, but it is in the git-extras package) specifically for reverting and staging old commits:

git back

Per the man page, it can also be used as such:

# Remove the latest three commits
git back 3

Calling Java from Python

If you're in Python 3, there's a fork of JPype called JPype1-py3

pip install JPype1-py3

This works for me on OSX / Python 3.4.3. (You may need to export JAVA_HOME=/Library/Java/JavaVirtualMachines/your-java-version)

from jpype import *
startJVM(getDefaultJVMPath(), "-ea")
java.lang.System.out.println("hello world")
shutdownJVM()

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

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

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

Access-control-allow-origin with multiple domains

In Web.API this attribute can be added using Microsoft.AspNet.WebApi.Cors as detailed at http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

In MVC you could create a filter attribute to do this work for you:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
                AllowMultiple = true, Inherited = true)]
public class EnableCorsAttribute : FilterAttribute, IActionFilter {
    private const string IncomingOriginHeader = "Origin";
    private const string OutgoingOriginHeader = "Access-Control-Allow-Origin";
    private const string OutgoingMethodsHeader = "Access-Control-Allow-Methods";
    private const string OutgoingAgeHeader = "Access-Control-Max-Age";

    public void OnActionExecuted(ActionExecutedContext filterContext) {
        // Do nothing
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var isLocal = filterContext.HttpContext.Request.IsLocal;
        var originHeader = 
             filterContext.HttpContext.Request.Headers.Get(IncomingOriginHeader);
        var response = filterContext.HttpContext.Response;

        if (!String.IsNullOrWhiteSpace(originHeader) &&
            (isLocal || IsAllowedOrigin(originHeader))) {
            response.AddHeader(OutgoingOriginHeader, originHeader);
            response.AddHeader(OutgoingMethodsHeader, "GET,POST,OPTIONS");
            response.AddHeader(OutgoingAgeHeader, "3600");
        }
    }

    protected bool IsAllowedOrigin(string origin) {
        // ** replace with your own logic to check the origin header
        return true;
    }
}

Then either enable it for specific actions / controllers:

[EnableCors]
public class SecurityController : Controller {
    // *snip*
    [EnableCors]
    public ActionResult SignIn(Guid key, string email, string password) {

Or add it for all controllers in Global.asax.cs

protected void Application_Start() {
    // *Snip* any existing code

    // Register global filter
    GlobalFilters.Filters.Add(new EnableCorsAttribute());
    RegisterGlobalFilters(GlobalFilters.Filters);

    // *snip* existing code
}

What is the javascript filename naming convention?

There is no official, universal, convention for naming JavaScript files.

There are some various options:

  • scriptName.js
  • script-name.js
  • script_name.js

are all valid naming conventions, however I prefer the jQuery suggested naming convention (for jQuery plugins, although it works for any JS)

  • jquery.pluginname.js

The beauty to this naming convention is that it explicitly describes the global namespace pollution being added.

  • foo.js adds window.foo
  • foo.bar.js adds window.foo.bar

Because I left out versioning: it should come after the full name, preferably separated by a hyphen, with periods between major and minor versions:

  • foo-1.2.1.js
  • foo-1.2.2.js
  • ...
  • foo-2.1.24.js

How to download/checkout a project from Google Code in Windows?

If you have a github account and don't want to download software, you can export to github, then download a zip from github.

How to check if the key pressed was an arrow key in Java KeyListener?

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
            //Right arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
            //Left arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_UP ) {
            //Up arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
            //Down arrow key code
    }

    repaint();
}

The KeyEvent codes are all a part of the API: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

SQL Error: ORA-00913: too many values

For me this works perfect

insert into oehr.employees select * from employees where employee_id=99

I am not sure why you get error. The nature of the error code you have produced is the columns didn't match.

One good approach will be to use the answer @Parodo specified

Cannot read property 'getContext' of null, using canvas

You don't have to include JQuery.

In the index.html:
<canvas id="canvas" width="640" height="480"></canvas><script src="javascript/game.js"> This should work without JQuery...

Edit: You should put the script tag IN the body tag...

Ubuntu: Using curl to download an image

If you want to keep the original name — use uppercase -O

curl -O https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

If you want to save remote file with a different name — use lowercase -o

curl -o myPic.png https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

Reading a text file in MATLAB line by line

If you really want to process your file line by line, a solution might be to use fgetl:

  1. Open the data file with fopen
  2. Read the next line into a character array using fgetl
  3. Retreive the data you need using sscanf on the character array you just read
  4. Perform any relevant test
  5. Output what you want to another file
  6. Back to point 2 if you haven't reached the end of your file.

Unlike the previous answer, this is not very much in the style of Matlab but it might be more efficient on very large files.

Hope this will help.

Simple way to encode a string according to a password?

I'll give 4 solutions:

1) Using Fernet encryption with cryptography library

Here is a solution using the package cryptography, that you can install as usual with pip install cryptography:

import base64
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

def cipherFernet(password):
    key = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=b'abcd', iterations=1000, backend=default_backend()).derive(password)
    return Fernet(base64.urlsafe_b64encode(key))

def encrypt1(plaintext, password):
    return cipherFernet(password).encrypt(plaintext)

def decrypt1(ciphertext, password):
    return cipherFernet(password).decrypt(ciphertext)

# Example:

print(encrypt1(b'John Doe', b'mypass'))  
# b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg=='
print(decrypt1(b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg==', b'mypass')) 
# b'John Doe'
try:  # test with a wrong password
    print(decrypt1(b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg==', b'wrongpass')) 
except InvalidToken:
    print('Wrong password')

You can adapt with your own salt, iteration count, etc. This code is not very far from @HCLivess's answer but the goal is here to have ready-to-use encrypt and decrypt functions. Source: https://cryptography.io/en/latest/fernet/#using-passwords-with-fernet.

Note: use .encode() and .decode() everywhere if you want strings 'John Doe' instead of bytes like b'John Doe'.


2) Simple AES encryption with Crypto library

This works with Python 3:

import base64
from Crypto import Random
from Crypto.Hash import SHA256
from Crypto.Cipher import AES

def cipherAES(password, iv):
    key = SHA256.new(password).digest()
    return AES.new(key, AES.MODE_CFB, iv)

def encrypt2(plaintext, password):
    iv = Random.new().read(AES.block_size)
    return base64.b64encode(iv + cipherAES(password, iv).encrypt(plaintext))

def decrypt2(ciphertext, password):
    d = base64.b64decode(ciphertext)
    iv, ciphertext = d[:AES.block_size], d[AES.block_size:]
    return cipherAES(password, iv).decrypt(ciphertext)

# Example:    

print(encrypt2(b'John Doe', b'mypass'))
print(decrypt2(b'B/2dGPZTD8V22cIVKfp2gD2tTJG/UfP/', b'mypass'))
print(decrypt2(b'B/2dGPZTD8V22cIVKfp2gD2tTJG/UfP/', b'wrongpass'))  # wrong password: no error, but garbled output

Note: you can remove base64.b64encode and .b64decode if you don't want text-readable output and/or if you want to save the ciphertext to disk as a binary file anyway.


3) AES using a better password key derivation function and the ability to test if "wrong password entered", with Crypto library

The solution 2) with AES "CFB mode" is ok, but has two drawbacks: the fact that SHA256(password) can be easily bruteforced with a lookup table, and that there is no way to test if a wrong password has been entered. This is solved here by the use of AES in "GCM mode", as discussed in AES: how to detect that a bad password has been entered? and Is this method to say “The password you entered is wrong” secure?:

import Crypto.Random, Crypto.Protocol.KDF, Crypto.Cipher.AES

def cipherAES_GCM(pwd, nonce):
    key = Crypto.Protocol.KDF.PBKDF2(pwd, nonce, count=100000)
    return Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_GCM, nonce=nonce, mac_len=16)

def encrypt3(plaintext, password):
    nonce = Crypto.Random.new().read(16)
    return nonce + b''.join(cipherAES_GCM(password, nonce).encrypt_and_digest(plaintext))  # you case base64.b64encode it if needed

def decrypt3(ciphertext, password):
    nonce, ciphertext, tag = ciphertext[:16], ciphertext[16:len(ciphertext)-16], ciphertext[-16:]
    return cipherAES_GCM(password, nonce).decrypt_and_verify(ciphertext, tag)

# Example:

print(encrypt3(b'John Doe', b'mypass'))
print(decrypt3(b'\xbaN_\x90R\xdf\xa9\xc7\xd6\x16/\xbb!\xf5Q\xa9]\xe5\xa5\xaf\x81\xc3\n2e/("I\xb4\xab5\xa6ezu\x8c%\xa50', b'mypass'))
try:
    print(decrypt3(b'\xbaN_\x90R\xdf\xa9\xc7\xd6\x16/\xbb!\xf5Q\xa9]\xe5\xa5\xaf\x81\xc3\n2e/("I\xb4\xab5\xa6ezu\x8c%\xa50', b'wrongpass'))
except ValueError:
    print("Wrong password")

4) Using RC4 (no library needed)

Adapted from https://github.com/bozhu/RC4-Python/blob/master/rc4.py.

def PRGA(S):
    i = 0
    j = 0
    while True:
        i = (i + 1) % 256
        j = (j + S[i]) % 256
        S[i], S[j] = S[j], S[i]
        yield S[(S[i] + S[j]) % 256]

def encryptRC4(plaintext, key, hexformat=False):
    key, plaintext = bytearray(key), bytearray(plaintext)  # necessary for py2, not for py3
    S = list(range(256))
    j = 0
    for i in range(256):
        j = (j + S[i] + key[i % len(key)]) % 256
        S[i], S[j] = S[j], S[i]
    keystream = PRGA(S)
    return b''.join(b"%02X" % (c ^ next(keystream)) for c in plaintext) if hexformat else bytearray(c ^ next(keystream) for c in plaintext)

print(encryptRC4(b'John Doe', b'mypass'))                           # b'\x88\xaf\xc1\x04\x8b\x98\x18\x9a'
print(encryptRC4(b'\x88\xaf\xc1\x04\x8b\x98\x18\x9a', b'mypass'))   # b'John Doe'

(Outdated since the latest edits, but kept for future reference): I had problems using Windows + Python 3.6 + all the answers involving pycrypto (not able to pip install pycrypto on Windows) or pycryptodome (the answers here with from Crypto.Cipher import XOR failed because XOR is not supported by this pycrypto fork ; and the solutions using ... AES failed too with TypeError: Object type <class 'str'> cannot be passed to C code). Also, the library simple-crypt has pycrypto as dependency, so it's not an option.

How do I upgrade the Python installation in Windows 10?

If you are upgrading any 3.x.y to 3.x.z (patch) Python version, just go to Python downloads page get the latest version and start the installation. Since you already have Python installed on your machine installer will prompt you for "Upgrade Now". Click on that button and it will replace the existing version with a new one. You also will have to restart a computer after installation.

enter image description here

If you are upgrading from 3.x to 3.y (minor) then you will be prompted with "Install Now". In this case, you are not upgrading, but you are installing a new version of Python. You can have more than one version installed on your machine. They will be located in different directories. When you have more than one Python version on your machine you will need to use py lanucher to launch a specific version of Python.

For instance:

py -3.7

or

py -3.8

Make sure you have py launcher installed on your machine. It will be installed automatically if you are using default settings of windows installer. You can always check it if you click on "Customize installation" link on the installation window.

If you have several Python versions installed on your machine and you have a project that is using the previous version of Python using virtual environment e.g. (venv) you can upgrade Python just in that venv using:

python -m venv --upgrade "your virtual environment path"

For instance, I have Python 3.7 in my ./venv virtual environment and I would like upgrade venv to Python 3.8, I would do following

python -m venv --upgrade ./venv

How to add multiple font files for the same font?

The solution seems to be to add multiple @font-face rules, for example:

@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans.ttf");
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Bold.ttf");
    font-weight: bold;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Oblique.ttf");
    font-style: italic, oblique;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-BoldOblique.ttf");
    font-weight: bold;
    font-style: italic, oblique;
}

By the way, it would seem Google Chrome doesn't know about the format("ttf") argument, so you might want to skip that.

(This answer was correct for the CSS 2 specification. CSS3 only allows for one font-style rather than a comma-separated list.)

How to download Visual Studio Community Edition 2015 (not 2017)

You can use these links to download Visual Studio 2015

Community Edition:

And for anyone in the future who might be looking for the other editions here are the links for them as well:

Professional Edition:

Enterprise Edition:

How to Update Multiple Array Elements in mongodb

The thread is very old, but I came looking for answer here hence providing new solution.

With MongoDB version 3.6+, it is now possible to use the positional operator to update all items in an array. See official documentation here.

Following query would work for the question asked here. I have also verified with Java-MongoDB driver and it works successfully.

.update(   // or updateMany directly, removing the flag for 'multi'
   {"events.profile":10},
   {$set:{"events.$[].handled":0}},  // notice the empty brackets after '$' opearor
   false,
   true
)

Hope this helps someone like me.

What does the function then() mean in JavaScript?

Here is a small JS_Fiddle.

then is a method callback stack which is available after a promise is resolved it is part of library like jQuery but now it is available in native JavaScript and below is the detail explanation how it works

You can do a Promise in native JavaScript : just like there are promises in jQuery, Every promise can be stacked and then can be called with Resolve and Reject callbacks, This is how you can chain asynchronous calls.

I forked and Edited from MSDN Docs on Battery charging status..

What this does is try to find out if user laptop or device is charging battery. then is called and you can do your work post success.

navigator
    .getBattery()
    .then(function(battery) {
       var charging = battery.charging;
       alert(charging);
    })
    .then(function(){alert("YeoMan : SINGH is King !!");});

Another es6 Example

function fetchAsync (url, timeout, onData, onError) {
    …
}
let fetchPromised = (url, timeout) => {
    return new Promise((resolve, reject) => {
        fetchAsync(url, timeout, resolve, reject)
    })
}
Promise.all([
    fetchPromised("http://backend/foo.txt", 500),
    fetchPromised("http://backend/bar.txt", 500),
    fetchPromised("http://backend/baz.txt", 500)
]).then((data) => {
    let [ foo, bar, baz ] = data
    console.log(`success: foo=${foo} bar=${bar} baz=${baz}`)
}, (err) => {
    console.log(`error: ${err}`)
})

Definition :: then is a method used to solve Asynchronous callbacks

this is introduced in ES6

Please find the proper documentation here Es6 Promises

Is there a way for non-root processes to bind to "privileged" ports on Linux?

My "standard workaround" uses socat as the user-space redirector:

socat tcp6-listen:80,fork tcp6:8080

Beware that this won't scale, forking is expensive but it's the way socat works.

Format date and time in a Windows batch script

Create a file called "search_files.bat" and place the contents below into the file. Then double click it. The temporary %THH% variable was put in place to handle the AM appropriately. If there is a 0 in the first 2 digits of the time, Windows ignores the rest of the file name of the LOG file.

CD .
SET THH=%time:~0,2%
SET THH=%THH: =0%
dir /s /b *.* > %date:~10,4%-%date:~4,2%-%date:~7,2%@%THH%.%time:~3,2%.%time:~6,2%.LOG

How to convert Blob to File in JavaScript

Typescript

public blobToFile = (theBlob: Blob, fileName:string): File => {       
    return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}

Javascript

function blobToFile(theBlob, fileName){       
    return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}

Output

screenshot

File {name: "fileName", lastModified: 1597081051454, lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time), webkitRelativePath: "", size: 601887, …}
lastModified: 1597081051454
lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time) {}
name: "fileName"
size: 601887
type: "image/png"
webkitRelativePath: ""
__proto__: File

Get source JARs from Maven repository

To download some specific source or javadoc we need to include the GroupIds - Its a comma separated value as shown below

mvn dependency:sources -DincludeGroupIds=com.jcraft,org.testng -Dclassifier=sources

Note that the classifier are not comma separated, to download the javadoc we need to run the above command one more time with the classifier as javadoc

mvn dependency:sources -DincludeGroupIds=com.jcraft,org.testng -Dclassifier=javadoc

How to get an object's property's value by property name?

Here is an alternative way to get an object's property value:

write-host $(get-something).SomeProp

What is Options +FollowSymLinks?

Parameter Options FollowSymLinks enables you to have a symlink in your webroot pointing to some other file/dir. With this disabled, Apache will refuse to follow such symlink. More secure Options SymLinksIfOwnerMatch can be used instead - this will allow you to link only to other files which you do own.

If you use Options directive in .htaccess with parameter which has been forbidden in main Apache config, server will return HTTP 500 error code.

Allowed .htaccess options are defined by directive AllowOverride in the main Apache config file. To allow symlinks, this directive need to be set to All or Options.

Besides allowing use of symlinks, this directive is also needed to enable mod_rewrite in .htaccess context. But for this, also the more secure SymLinksIfOwnerMatch option can be used.

How can I validate a string to only allow alphanumeric characters in it?

Based on cletus's answer you may create new extension.

public static class StringExtensions
{        
    public static bool IsAlphaNumeric(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return false;

        Regex r = new Regex("^[a-zA-Z0-9]*$");
        return r.IsMatch(str);
    }
}

Python object.__repr__(self) should be an expression?

To see how the repr works within a class, run the following code, first with and then without the repr method.

class Coordinate (object):
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def getX(self):
        # Getter method for a Coordinate object's x coordinate.
        # Getter methods are better practice than just accessing an attribute directly
        return self.x
    def getY(self):

        # Getter method for a Coordinate object's y coordinate
        return self.y

    def __repr__(self):  #remove this and the next line and re-run
        return 'Coordinate(' + str(self.getX()) + ',' + str(self.getY()) + ')' 

>>>c = Coordinate(2,-8)
>>>print(c)

Running Bash commands in Python

Also you can use 'os.popen'. Example:

import os

command = os.popen('ls -al')
print(command.read())
print(command.close())

Output:

total 16
drwxr-xr-x 2 root root 4096 ago 13 21:53 .
drwxr-xr-x 4 root root 4096 ago 13 01:50 ..
-rw-r--r-- 1 root root 1278 ago 13 21:12 bot.py
-rw-r--r-- 1 root root   77 ago 13 21:53 test.py

None

Python argparse: default value or specified value

Actually, you only need to use the default argument to add_argument as in this test.py script:

import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--example', default=1)
    args = parser.parse_args()
    print(args.example)

test.py --example
% 1
test.py --example 2
% 2

Details are here.

Repeat table headers in print mode

Some browsers repeat the thead element on each page, as they are supposed to. Others need some help: Add this to your CSS:

thead {display: table-header-group;}
tfoot {display: table-header-group;}

Opera 7.5 and IE 5 won't repeat headers no matter what you try.

(source)

Show percent % instead of counts in charts of categorical variables

Since version 3.3 of ggplot2, we have access to the convenient after_stat() function.

We can do something similar to @Andrew's answer, but without using the .. syntax:

# original example data
mydata <- c("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc")

# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
                     y = after_stat(count/sum(count)))) +
  geom_bar() +
  scale_y_continuous(labels = scales::percent)

You can find all the "computed variables" available to use in the documentation of the geom_ and stat_ functions. For example, for geom_bar(), you can access the count and prop variables. (See the documentation for computed variables.)

One comment about your NULL values: they are ignored when you create the vector (i.e. you end up with a vector of length 9, not 11). If you really want to keep track of missing data, you will have to use NA instead (ggplot2 will put NAs at the right end of the plot):

# use NA instead of NULL
mydata <- c("aa", "bb", NA, "bb", "cc", "aa", "aa", "aa", "ee", NA, "cc")
length(mydata)
#> [1] 11

# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
                     y = after_stat(count/sum(count)))) +
  geom_bar() +
  scale_y_continuous(labels = scales::percent)

Created on 2021-02-09 by the reprex package (v1.0.0)

(Note that using chr or fct data will not make a difference for your example.)

JavaScript: Get image dimensions

Make a new Image

var img = new Image();

Set the src

img.src = your_src

Get the width and the height

//img.width
//img.height

What is SOA "in plain english"?

Reading the responses above, it sounds to me that SOA is what developers (good ones at least) have been doing from day one.

The name does not exist in the namespace error in XAML

I had this problem recently using VS 2015 Update 3 for my WPF project in .NET 4.6.2. The copy of my project was in a network folder, I moved it locally and that solved the problem.

This may solve other sort of problems, as it looks like VS 2015 doesn't like network paths. Another issue that is a big problem for them is syncing git repositories if my project is in a network path, also solved by moving it locally.

What are good examples of genetic algorithms/genetic programming solutions?

I experimented with GA in my youth. I wrote a simulator in Python that worked as follows.

The genes encoded the weights of a neural network.

The neural network's inputs were "antennae" that detected touches. Higher values meant very close and 0 meant not touching.

The outputs were to two "wheels". If both wheels went forward, the guy went forward. If the wheels were in opposite directions, the guy turned. The strength of the output determined the speed of the wheel turning.

A simple maze was generated. It was really simple--stupid even. There was the start at the bottom of the screen and a goal at the top, with four walls in between. Each wall had a space taken out randomly, so there was always a path.

I started random guys (I thought of them as bugs) at the start. As soon as one guy reached the goal, or a time limit was reached, the fitness was calculated. It was inversely proportional to the distance to the goal at that time.

I then paired them off and "bred" them to create the next generation. The probability of being chosen to be bred was proportional to its fitness. Sometimes this meant that one was bred with itself repeatedly if it had a very high relative fitness.

I thought they would develop a "left wall hugging" behavior, but they always seemed to follow something less optimal. In every experiment, the bugs converged to a spiral pattern. They would spiral outward until they touched a wall to the right. They'd follow that, then when they got to the gap, they'd spiral down (away from the gap) and around. They would make a 270 degree turn to the left, then usually enter the gap. This would get them through a majority of the walls, and often to the goal.

One feature I added was to put in a color vector into the genes to track relatedness between individuals. After a few generations, they'd all be the same color, which tell me I should have a better breeding strategy.

I tried to get them to develop a better strategy. I complicated the neural net--adding a memory and everything. It didn't help. I always saw the same strategy.

I tried various things like having separate gene pools that only recombined after 100 generations. But nothing would push them to a better strategy. Maybe it was impossible.

Another interesting thing is graphing the fitness over time. There were definite patterns, like the maximum fitness going down before it would go up. I have never seen an evolution book talk about that possibility.

How do I pause my shell script for a second before continuing?

You can make it wait using $RANDOM, a default random number generator. In the below I am using 240 seconds. Hope that helps @

> WAIT_FOR_SECONDS=`/usr/bin/expr $RANDOM % 240` /bin/sleep
> $WAIT_FOR_SECONDS

How to get image width and height in OpenCV?

You can use rows and cols:

cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;

or size():

cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;

How to know if docker is already logged in to a docker registry server

Just checked, today it looks like this:

$ docker login
Authenticating with existing credentials...
Login Succeeded

NOTE: this is on a macOS with the latest version of Docker CE, docker-credential-helper - both installed with homebrew.

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

Just add remove_button_css as class to your button tag. You can verify the code for Link 1

.remove_button_css { 
  outline: none;
  padding: 5px; 
  border: 0px; 
  box-sizing: none; 
  background-color: transparent; 
}

enter image description here

Extra Styles Edit

Add color: #337ab7; and :hover and :focus to match OOTB (bootstrap3)

.remove_button_css:focus,
.remove_button_css:hover {
    color: #23527c;
    text-decoration: underline;
}

Javascript Cookie with no expiration date

Nope. That can't be done. The best 'way' of doing that is just making the expiration date be like 2100.