Programs & Examples On #Winqual

0

Finding blocking/locking queries in MS SQL (mssql)

Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.

How to squash commits in git after they have been pushed?

1) git rebase -i HEAD~4

To elaborate: It works on the current branch; the HEAD~4 means squashing the latest four commits; interactive mode (-i)

2) At this point, the editor opened, with the list of commits, to change the second and following commits, replacing pick with squash then save it.

output: Successfully rebased and updated refs/heads/branch-name.

3) git push origin refs/heads/branch-name --force

output:

remote:
remote: To create a merge request for branch-name, visit:
remote: http://xxx/sc/server/merge_requests/new?merge_request%5Bsource_branch%5D=sss
remote:To ip:sc/server.git
 + 84b4b60...5045693 branch-name -> branch-name (forced update)

How to test valid UUID/GUID?

If you want to check or validate a specific UUID version, here are the corresponding regexes.

Note that the only difference is the version number, which is explained in 4.1.3. Version chapter of UUID 4122 RFC.

The version number is the first character of the third group : [VERSION_NUMBER][0-9A-F]{3} :

  • UUID v1 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v2 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v3 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v4 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v5 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    

How can I check if two segments intersect?

Suppose the two segments have endpoints A,B and C,D. The numerically robust way to determine intersection is to check the sign of the four determinants:

| Ax-Cx  Bx-Cx |    | Ax-Dx  Bx-Dx |
| Ay-Cy  By-Cy |    | Ay-Dy  By-Dy |

| Cx-Ax  Dx-Ax |    | Cx-Bx  Dx-Bx |
| Cy-Ay  Dy-Ay |    | Cy-By  Dy-By |

For intersection, each determinant on the left must have the opposite sign of the one to the right, but there need not be any relationship between the two lines. You are basically checking each point of a segment against the other segment to make sure they lie on opposite sides of the line defined by the other segment.

See here: http://www.cs.cmu.edu/~quake/robust.html

How to find rows in one table that have no corresponding row in another table

I can't tell you which of these methods will be best on H2 (or even if all of them will work), but I did write an article detailing all of the (good) methods available in TSQL. You can give them a shot and see if any of them works for you:

http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=QueryBasedUponAbsenceOfData&referringTitle=Home

What is the difference between a .cpp file and a .h file?

By convention, .h files are included by other files, and never compiled directly by themselves. .cpp files are - again, by convention - the roots of the compilation process; they include .h files directly or indirectly, but generally not .cpp files.

How do I use CSS with a ruby on rails application?

Use the rails style sheet tag to link your main.css like this

<%= stylesheet_link_tag "main" %>

Go to

config/initializers/assets.rb

Once inside the assets.rb add the following code snippet just below the Rails.application.config.assets.version = '1.0'

Rails.application.config.assets.version = '1.0'
Rails.application.config.assets.precompile += %w( main.css )

Restart your server.

Pandas get topmost n records within each group

Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:

g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)

Get current location of user in Android without using GPS or internet

Have you take a look Google Maps Geolocation Api? Google Map Geolocation

This is simple RestApi, you just need POST a request, the the service will return a location with accuracy in meters.

How can I present a file for download from an MVC controller?

Although standard action results FileContentResult or FileStreamResult may be used for downloading files, for reusability, creating a custom action result might be the best solution.

As an example let's create a custom action result for exporting data to Excel files on the fly for download.

ExcelResult class inherits abstract ActionResult class and overrides the ExecuteResult method.

We are using FastMember package for creating DataTable from IEnumerable object and ClosedXML package for creating Excel file from the DataTable.

public class ExcelResult<T> : ActionResult
{
    private DataTable dataTable;
    private string fileName;

    public ExcelResult(IEnumerable<T> data, string filename, string[] columns)
    {
        this.dataTable = new DataTable();
        using (var reader = ObjectReader.Create(data, columns))
        {
            dataTable.Load(reader);
        }
        this.fileName = filename;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context != null)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            response.AddHeader("content-disposition", string.Format(@"attachment;filename=""{0}""", fileName));
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dataTable, "Sheet1");
                using (MemoryStream stream = new MemoryStream())
                {
                    wb.SaveAs(stream);
                    response.BinaryWrite(stream.ToArray());
                }
            }
        }
    }
}

In the Controller use the custom ExcelResult action result as follows

[HttpGet]
public async Task<ExcelResult<MyViewModel>> ExportToExcel()
{
    var model = new Models.MyDataModel();
    var items = await model.GetItems();
    string[] columns = new string[] { "Column1", "Column2", "Column3" };
    string filename = "mydata.xlsx";
    return new ExcelResult<MyViewModel>(items, filename, columns);
}

Since we are downloading the file using HttpGet, create an empty View without model and empty layout.

Blog post about custom action result for downloading files that are created on the fly:

https://acanozturk.blogspot.com/2019/03/custom-actionresult-for-files-in-aspnet.html

DropDownList's SelectedIndexChanged event not firing

For me answer was aspx page attribute, i added Async="true" to page attributes and this solved my problem.

<%@ Page Language="C#" MasterPageFile="~/MasterPage/Reports.Master"..... 
    AutoEventWireup="true" Async="true" %>

This is the structure of my update panel

<div>
  <asp:UpdatePanel ID="updt" runat="server">
    <ContentTemplate>

      <asp:DropDownList ID="id" runat="server" AutoPostBack="true"        onselectedindexchanged="your server side function" />

   </ContentTemplate>
  </asp:UpdatePanel>
</div>

Best place to insert the Google Analytics code

If you want your scripts to load after page has been rendered, you can use:

function getScript(a, b) {
    var c = document.createElement("script");
    c.src = a;
    var d = document.getElementsByTagName("head")[0],
        done = false;
    c.onload = c.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
            done = true;
            b();
            c.onload = c.onreadystatechange = null;
            d.removeChild(c)
        }
    };
    d.appendChild(c)
}

//call the function
getScript("http://www.google-analytics.com/ga.js", function() {
    // do stuff after the script has loaded
});

Set value of textarea in jQuery

The accepted answer works for me, but only after I realized I had to execute my code after the page was finished loading. In this situation inline script didn't work, I guess because #my_form wasn't done loading yet.

$(document).ready(function() {
  $("#my_form textarea").val('');
});

grep for special characters in Unix

The one that worked for me is:

grep -e '->'

The -e means that the next argument is the pattern, and won't be interpreted as an argument.

From: http://www.linuxquestions.org/questions/programming-9/how-to-grep-for-string-769460/

What's the best way to dedupe a table?

Adding the actual code here for future reference

So, there are 3 steps, and therefore 3 SQL statements:

Step 1: Move the non duplicates (unique tuples) into a temporary table

CREATE TABLE new_table as
SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by];

Step 2: delete the old table (or rename it) We no longer need the table with all the duplicate entries, so drop it!

DROP TABLE old_table;

Step 3: rename the new_table to the name of the old_table

RENAME TABLE new_table TO old_table;

And of course, don't forget to fix your buggy code to stop inserting duplicates!

How do you do natural logs (e.g. "ln()") with numpy in Python?

from numpy.lib.scimath import logn
from math import e

#using: x - var
logn(e, x)

How can I replace a regex substring match in Javascript?

I think the simplest way to achieve your goal is this:

var str   = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

You are passing floats to a classifier which expects categorical values as the target vector. If you convert it to int it will be accepted as input (although it will be questionable if that's the right way to do it).

It would be better to convert your training scores by using scikit's labelEncoder function.

The same is true for your DecisionTree and KNeighbors qualifier.

from sklearn import preprocessing
from sklearn import utils

lab_enc = preprocessing.LabelEncoder()
encoded = lab_enc.fit_transform(trainingScores)
>>> array([1, 3, 2, 0], dtype=int64)

print(utils.multiclass.type_of_target(trainingScores))
>>> continuous

print(utils.multiclass.type_of_target(trainingScores.astype('int')))
>>> multiclass

print(utils.multiclass.type_of_target(encoded))
>>> multiclass

Why is the <center> tag deprecated in HTML?

You can still use this with XHTML 1.0 Transitional and HTML 4.01 Transitional if you like. The only other way (best way, in my opinion) is with margins:

<div style="width:200px;margin:auto;">
  <p>Hello World</p>
</div>

Your HTML should define the element, not govern its presentation.

SQL Server - How to lock a table until a stored procedure finishes

Needed this answer myself and from the link provided by David Moye, decided on this and thought it might be of use to others with the same question:

CREATE PROCEDURE ...
AS
BEGIN
  BEGIN TRANSACTION

  -- lock table "a" till end of transaction
  SELECT ...
  FROM a
  WITH (TABLOCK, HOLDLOCK)
  WHERE ...

  -- do some other stuff (including inserting/updating table "a")



  -- release lock
  COMMIT TRANSACTION
END

Creating new database from a backup of another Database on the same server?

It's even possible to restore without creating a blank database at all.

In Sql Server Management Studio, right click on Databases and select Restore Database... enter image description here

In the Restore Database dialog, select the Source Database or Device as normal. Once the source database is selected, SSMS will populate the destination database name based on the original name of the database.

It's then possible to change the name of the database and enter a new destination database name.

enter image description here

With this approach, you don't even need to go to the Options tab and click the "Overwrite the existing database" option.

Also, the database files will be named consistently with your new database name and you still have the option to change file names if you want.

libclntsh.so.11.1: cannot open shared object file.

For the benefit of anyone else coming here by far the best thing to do is to update cx_Oracle to the latest version (6+). This version does not need LD_LIBRARY_PATH set at all.

How do I remove a single breakpoint with GDB?

Try these (reference):

clear linenum
clear filename:linenum

selecting unique values from a column

Depends on what you need.

In this case I suggest:

SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;

because there are few fields and the execution time of DISTINCT is lower than the execution of GROUP BY.

In other cases, for example where there are many fields, I prefer:

SELECT * FROM buy GROUP BY date ORDER BY date DESC;

Cannot simply use PostgreSQL table name ("relation does not exist")

This is realy helpfull

SET search_path TO schema,public;

I digged this issues more, and found out about how to set this "search_path" by defoult for a new user in current database.

Open DataBase Properties then open Sheet "Variables" and simply add this variable for your user with actual value.

So now your user will get this schema_name by defoult and you could use tableName without schemaName.

Should you commit .gitignore into the Git repos?

Normally yes, .gitignore is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG or something. In those cases you probably don't want to force that on anyone else.

Problems installing the devtools package

Centos 6.8

this work like charm for me

  1. install libcurl $yum -y install libcurl libcurl-devel
  2. restart R Software $rstudio-server verify-installation

Two constructors

To call one constructor from another you need to use this() and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.

How do I iterate over a range of numbers defined by variables in Bash?

These are all nice but seq is supposedly deprecated and most only work with numeric ranges.

If you enclose your for loop in double quotes, the start and end variables will be dereferenced when you echo the string, and you can ship the string right back to BASH for execution. $i needs to be escaped with \'s so it is NOT evaluated before being sent to the subshell.

RANGE_START=a
RANGE_END=z
echo -e "for i in {$RANGE_START..$RANGE_END}; do echo \\${i}; done" | bash

This output can also be assigned to a variable:

VAR=`echo -e "for i in {$RANGE_START..$RANGE_END}; do echo \\${i}; done" | bash`

The only "overhead" this should generate should be the second instance of bash so it should be suitable for intensive operations.

How is a CSS "display: table-column" supposed to work?

The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html

A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.

"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).

Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.

The table itself is always structured the same way it is in HTML.

In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):

<table ..>
  <col .. />
  <col .. />
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
</table>

Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):

_x000D_
_x000D_
.mytable {_x000D_
  display: table;_x000D_
}_x000D_
.myrow {_x000D_
  display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
  display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
  display: table-column;_x000D_
  background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
  display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 1</div>_x000D_
    <div class="mycell">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 2</div>_x000D_
    <div class="mycell">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_



OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:

_x000D_
_x000D_
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow row1">_x000D_
    <div class="mycell cell1">contents of first cell in row 1</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow row2">_x000D_
    <div class="mycell cell1">contents of first cell in row 2</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In today's flexible designs, which use <div> for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr> in HTML became class myrow, and <td> became class mycell. This convention is what makes the above CSS selectors useful.

PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *, such as .row1 * or even .row1 > *. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 * first does *, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1. This might be slow in a complex document on a slow device. .row1 > * is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1. (.row1 > .cell1 is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >.)

The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *.

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

How to use multiprocessing pool.map with multiple arguments?

This is an example of the routine I use to pass multiple arguments to a one-argument function used in a pool.imap fork:

from multiprocessing import Pool

# Wrapper of the function to map:
class makefun:
    def __init__(self, var2):
        self.var2 = var2
    def fun(self, i):
        var2 = self.var2
        return var1[i] + var2

# Couple of variables for the example:
var1 = [1, 2, 3, 5, 6, 7, 8]
var2 = [9, 10, 11, 12]

# Open the pool:
pool = Pool(processes=2)

# Wrapper loop
for j in range(len(var2)):
    # Obtain the function to map
    pool_fun = makefun(var2[j]).fun

    # Fork loop
    for i, value in enumerate(pool.imap(pool_fun, range(len(var1))), 0):
        print(var1[i], '+' ,var2[j], '=', value)

# Close the pool
pool.close()

MIME types missing in IIS 7 for ASP.NET - 404.17

Fix:

I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".

After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.

C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
 Volume in drive C is Windows
 Volume Serial Number is 8EE6-5DD0

 Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319

03/18/2010  08:23 PM            19,296 aspnet_regbrowsers.exe
03/18/2010  08:23 PM            36,696 aspnet_regiis.exe
03/18/2010  08:23 PM           102,232 aspnet_regsql.exe
               3 File(s)        158,224 bytes
               0 Dir(s)  34,836,508,672 bytes free

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.

HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

Using an authorization header with Fetch in React Native

Example fetch with authorization header:

fetch('URL_GOES_HERE', { 
   method: 'post', 
   headers: new Headers({
     'Authorization': 'Basic '+btoa('username:password'), 
     'Content-Type': 'application/x-www-form-urlencoded'
   }), 
   body: 'A=1&B=2'
 });

String Pattern Matching In Java

You can use the Pattern class for this. If you want to match only word characters inside the {} then you can use the following regex. \w is a shorthand for [a-zA-Z0-9_]. If you are ok with _ then use \w or else use [a-zA-Z0-9].

String URL = "https://localhost:8080/sbs/01.00/sip/dreamworks/v/01.00/cui/print/$fwVer/{$fwVer}/$lang/en/$model/{$model}/$region/us/$imageBg/{$imageBg}/$imageH/{$imageH}/$imageSz/{$imageSz}/$imageW/{$imageW}/movie/Kung_Fu_Panda_two/categories/3D_Pix/item/{item}/_back/2?$uniqueID={$uniqueID}";
Pattern pattern = Pattern.compile("/\\{\\w+\\}/");
Matcher matcher = pattern.matcher(URL);
if (matcher.find()) {
    System.out.println(matcher.group(0)); //prints /{item}/
} else {
    System.out.println("Match not found");
}

How to replace all special character into a string using C#

Assume you want to replace symbols which are not digits or letters (and _ character as @Guffa correctly pointed):

string input = "Hello@Hello&Hello(Hello)";
string result = Regex.Replace(input, @"[^\w\d]", ",");
// Hello,Hello,Hello,Hello,

You can add another symbols which should not be replaced. E.g. if you want white space symbols to stay, then just add \s to pattern: \[^\w\d\s]

How to make multiple divs display in one line but still retain width?

Flex is the better way. Just try..

display: flex;

getResourceAsStream() is always returning null

I had the same problem when I changed from Websphere 8.5 to WebSphere Liberty.

I utilized FileInputStream instead of getResourceAsStream(), because for some reason WebSphere Liberty can't locate the file in the WEB-INF folder.

The script was :

FileInputStream fis = new FileInputStream(getServletContext().getRealPath("/") 
                        + "\WEBINF\properties\myProperties.properties")

Note: I used this script only for development.

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

Laravel - Session store not set on request

Laravel 5.3+ web middleware group is automatically applied to your routes/web.php file by the RouteServiceProvider.

Unless you modify kernel $middlewareGroups array in an unsupported order, probably you are trying to inject requests as a regular dependency from the constructor.

Use request as

public function show(Request $request){

}

instead of

public function __construct(Request $request){

}

Count indexes using "for" in Python

use enumerate:

>>> l = ['a', 'b', 'c', 'd']
>>> for index, val in enumerate(l):
...    print "%d: %s" % (index, val)
... 
0: a
1: b
2: c
3: d

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Depending how intrinsic this kind of functionality is to your project, you might want to consider something like MEF which will take care of the loading and tying together of components for you.

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:

  1. Suggest using c.sendall() instead of c.send() to prevent possible issues where you may not have sent the entire msg with one call (see docs).
  2. For literals, add a 'b' for bytes string: c.sendall(b'Thank you for connecting')
  3. For variables, you need to encode Unicode strings to byte strings (see below)

Best solution (should work w/both 2.x & 3.x):

output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))

Epilogue/background: this isn't an issue in Python 2 because strings are bytes strings already -- your OP code would work perfectly in that environment. Unicode strings were added to Python in releases 1.6 & 2.0 but took a back seat until 3.0 when they became the default string type. Also see this similar question as well as this one.

Angular 4/5/6 Global Variables

You can access Globals entity from any point of your App via Angular dependency injection. If you want to output Globals.role value in some component's template, you should inject Globals through the component's constructor like any service:

// hello.component.ts
import { Component } from '@angular/core';
import { Globals } from './globals';

@Component({
  selector: 'hello',
  template: 'The global role is {{globals.role}}',
  providers: [ Globals ] // this depends on situation, see below
})

export class HelloComponent {
  constructor(public globals: Globals) {}
}

I provided Globals in the HelloComponent, but instead it could be provided in some HelloComponent's parent component or even in AppModule. It will not matter until your Globals has only static data that could not be changed (say, constants only). But if it's not true and for example different components/services might want to change that data, then the Globals must be a singleton. In that case it should be provided in the topmost level of the hierarchy where it is going to be used. Let's say this is AppModule:

import { Globals } from './globals'

@NgModule({
  // ... imports, declarations etc
  providers: [
    // ... other global providers
    Globals // so do not provide it into another components/services if you want it to be a singleton
  ]
})

Also, it's impossible to use var the way you did, it should be

// globals.ts
import { Injectable } from '@angular/core';

@Injectable()
export class Globals {
  role: string = 'test';
}

Update

At last, I created a simple demo on stackblitz, where single Globals is being shared between 3 components and one of them can change the value of Globals.role.

Primitive type 'short' - casting in Java

EDIT: Okay, now we know it's Java...

Section 4.2.2 of the Java Language Specification states:

The Java programming language provides a number of operators that act on integral values:

[...]

  • The numerical operators, which result in a value of type int or long:
  • [...]
  • The additive operators + and - (§15.18)

  • In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int or long, which is why you need to cast to assign to a short variable.

    Original answer (C#)

    In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:

    int operator +(int x, int y);
    uint operator +(uint x, uint y);
    long operator +(long x, long y);
    ulong operator +(ulong x, ulong y);
    float operator +(float x, float y);
    double operator +(double x, double y);
    

    These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:

    decimal operator +(decimal x, decimal y);
    

    (Enumeration addition, string concatenation and delegate combination are also defined there.)

    As you can see, there's no short operator +(short x, short y) operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.

    Does it make sense to use Require.js with Angular.js?

    It makes sense to use requirejs with angularjs if you plan on lazy loading controllers and directives etc, while also combining multiple lazy dependencies into single script files for much faster lazy loading. RequireJS has an optimisation tool that makes the combining easy. See http://ify.io/using-requirejs-with-optimisation-for-lazy-loading-angularjs-artefacts/

    Masking password input from the console : Java

    The given code given will work absolutely fine if we run from console. and there is no package name in the class

    You have to make sure where you have your ".class" file. because, if package name is given for the class, you have to make sure to keep the ".class" file inside the specified folder. For example, my package name is "src.main.code" , I have to create a code folder,inside main folder, inside src folder and put Test.class in code folder. then it will work perfectly.

    Undo a merge by pull request?

    There is a better answer to this problem, though I could just break this down step-by-step.

    You will need to fetch and checkout the latest upstream changes like so, e.g.:

    git fetch upstream
    git checkout upstream/master -b revert/john/foo_and_bar
    

    Taking a look at the commit log, you should find something similar to this:

    commit b76a5f1f5d3b323679e466a1a1d5f93c8828b269
    Merge: 9271e6e a507888
    Author: Tim Tom <[email protected]>
    Date:   Mon Apr 29 06:12:38 2013 -0700
    
        Merge pull request #123 from john/foo_and_bar
    
        Add foo and bar
    
    commit a507888e9fcc9e08b658c0b25414d1aeb1eef45e
    Author: John Doe <[email protected]>
    Date:   Mon Apr 29 12:13:29 2013 +0000
    
        Add bar
    
    commit 470ee0f407198057d5cb1d6427bb8371eab6157e
    Author: John Doe <[email protected]>
    Date:   Mon Apr 29 10:29:10 2013 +0000
    
        Add foo
    

    Now you want to revert the entire pull request with the ability to unrevert later. To do so, you will need to take the ID of the merge commit.

    In the above example the merge commit is the top one where it says "Merged pull request #123...".

    Do this to revert the both changes ("Add bar" and "Add foo") and you will end up with in one commit reverting the entire pull request which you can unrevert later on and keep the history of changes clean:

    git revert -m 1 b76a5f1f5d3b323679e466a1a1d5f93c8828b269
    

    R: "Unary operator error" from multiline ggplot2 command

    It looks like you might have inserted an extra + at the beginning of each line, which R is interpreting as a unary operator (like - interpreted as negation, rather than subtraction). I think what will work is

    ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
        geom_boxplot() +
        scale_fill_manual(values = c("yellow", "orange")) + 
        ggtitle("Expression comparisons for ACTB") + 
        theme(axis.text.x = element_text(angle=90, face="bold", colour="black"))
    

    Perhaps you copy and pasted from the output of an R console? The console uses + at the start of the line when the input is incomplete.

    How can I get the last day of the month in C#?

    Something like:

    DateTime today = DateTime.Today;
    DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);
    

    Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.

    What do I do when my program crashes with exception 0xc0000005 at address 0?

    Exception code 0xc0000005 is an Access Violation. An AV at fault offset 0x00000000 means that something in your service's code is accessing a nil pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.

    Copying Code from Inspect Element in Google Chrome

    you dont have to do that in the Google chrome. Use the Internet explorer it offers the option to copy the css associated and after you copy and paste select the style and put that into another file .css to call into that html which you have created. Hope this will solve you problem than anything else:)

    Setting PayPal return URL and making it auto return?

    I think that the idea of setting the Auto Return values as described above by Kevin is a bit strange!

    Say, for example, that you have a number of websites that use the same PayPal account to handle your payments, or say that you have a number of sections in one website that perform different purchasing tasks, and require different return-addresses when the payment is completed. If I put a button on my page as described above in the 'Sample form using PHP for direct payments' section, you can see that there is a line there:

    input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php"
    

    where you set the individual return value. Why does it have to be set generally, in the profile section as well?!?!

    Also, because you can only set one value in the Profile Section, it means (AFAIK) that you cannot use the Auto Return on a site with multiple actions.

    Comments please??

    Add views in UIStackView programmatically

    Swift 5 version of Oleg Popov's answer, which is based on user1046037's answer

    //Image View
    let imageView = UIImageView()
    imageView.backgroundColor = UIColor.blue
    imageView.heightAnchor.constraint(equalToConstant: 120.0).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 120.0).isActive = true
    imageView.image = UIImage(named: "buttonFollowCheckGreen")
    
    //Text Label
    let textLabel = UILabel()
    textLabel.backgroundColor = UIColor.yellow
    textLabel.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true
    textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
    textLabel.text  = "Hi World"
    textLabel.textAlignment = .center
    
    //Stack View
    let stackView   = UIStackView()
    stackView.axis  = NSLayoutConstraint.Axis.vertical
    stackView.distribution  = UIStackView.Distribution.equalSpacing
    stackView.alignment = UIStackView.Alignment.center
    stackView.spacing   = 16.0
    
    stackView.addArrangedSubview(imageView)
    stackView.addArrangedSubview(textLabel)
    stackView.translatesAutoresizingMaskIntoConstraints = false
    
    self.view.addSubview(stackView)
    
    //Constraints
    stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
    

    Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

    It's quite easy for a fix.

    For me, we had more than one inputs in the form. We need to isolate the input / line causing error and simply add the name attribute. That fixed the issue for me:

    Before:

    <form class="example-form">
    
        <mat-form-field appearance="outline">
    

          <mat-select placeholder="Select your option" [(ngModel)]="sample.stat"> <!--HERE -->
    

              <mat-option *ngFor="let option of actions" [value]="option">{{option}</mat-option>
          </mat-select>
        </mat-form-field>
    
        <mat-form-field appearance="outline">
          <mat-label>Enter number</mat-label>
    

          <input id="myInput" type="text" placeholder="Enter number" aria-label="Number"
            matInput [formControl]="myFormControl" required [(ngModel)]="number">  <!--HERE -->
    

        </mat-form-field>
    

        <mat-checkbox [(ngModel)]="isRight">Check!</mat-checkbox> <!--HERE -->
    

      </form>
    

    After: i just added the name attribute for select and checkbox and that fixed the issue. As follows:

    <mat-select placeholder="Select your option" name="mySelect" 
      [(ngModel)]="sample.stat"> <!--HERE: Observe the "name" attribute -->
    
    <input id="myInput" type="text" placeholder="Enter number" aria-label="Number"
            matInput [formControl]="myFormControl" required [(ngModel)]="number">  <!--HERE -->
    
    <mat-checkbox name="myCheck" [(ngModel)]="isRight">Check!</mat-checkbox> <!--HERE: Observe the "name" attribute -->
    

    As you see added the name attribute. It is not necessary to be given same as your ngModel name. Just providing the name attribute will fix the issue.

    List of Stored Procedures/Functions Mysql Command Line

    My preference is for something that:

    1. Lists both functions and procedures,
    2. Lets me know which are which,
    3. Gives the procedures' names and types and nothing else,
    4. Filters results by the current database, not the current definer
    5. Sorts the result

    Stitching together from other answers in this thread, I end up with

    select 
      name, type 
    from 
      mysql.proc 
    where 
      db = database() 
    order by 
      type, name;
    

    ... which ends you up with results that look like this:

    mysql> select name, type from mysql.proc where db = database() order by type, name;
    +------------------------------+-----------+
    | name                         | type      |
    +------------------------------+-----------+
    | get_oldest_to_scan           | FUNCTION  |
    | get_language_prevalence      | PROCEDURE |
    | get_top_repos_by_user        | PROCEDURE |
    | get_user_language_prevalence | PROCEDURE |
    +------------------------------+-----------+
    4 rows in set (0.30 sec)
    

    What is the difference between a token and a lexeme?

    LEXEME - Sequence of characters matched by PATTERN forming the TOKEN

    PATTERN - The set of rule that define a TOKEN

    TOKEN - The meaningful collection of characters over the character set of the programming language ex:ID, Constant, Keywords, Operators, Punctuation, Literal String

    SELECT from nothing?

    Here is the most complete list of database support of dual from https://blog.jooq.org/tag/dual-table/:

    In many other RDBMS, there is no need for dummy tables, as you can issue statements like these:

    SELECT 1;
    SELECT 1 + 1;
    SELECT SQRT(2);
    

    These are the RDBMS, where the above is generally possible:

    • H2
    • MySQL
    • Ingres
    • Postgres
    • SQLite
    • SQL Server
    • Sybase ASE

    In other RDBMS, dummy tables are required, like in Oracle. Hence, you’ll need to write things like these:

    SELECT 1       FROM DUAL;
    SELECT 1 + 1   FROM DUAL;
    SELECT SQRT(2) FROM DUAL;
    

    These are the RDBMS and their respective dummy tables:

    • DB2: SYSIBM.DUAL
    • Derby: SYSIBM.SYSDUMMY1
    • H2: Optionally supports DUAL
    • HSQLDB: INFORMATION_SCHEMA.SYSTEM_USERS
    • MySQL: Optionally supports DUAL
    • Oracle: DUAL
    • Sybase SQL Anywhere: SYS.DUMMY

    Ingres has no DUAL, but would actually need it as in Ingres you cannot have a WHERE, GROUP BY or HAVING clause without a FROM clause.

    C# - What does the Assert() method do? Is it still useful?

    Assert allows you to assert a condition (post or pre) applies in your code. It's a way of documenting your intentions and having the debugger inform you with a dialog if your intention is not met.

    Unlike a breakpoint, the Assert goes with your code and can be used to add additional detail about your intention.

    Remove all classes that begin with a certain string

    http://www.mail-archive.com/[email protected]/msg03998.html says:

    ...and .removeClass() would remove all classes...

    It works for me ;)

    cheers

    How do I recognize "#VALUE!" in Excel spreadsheets?

    Use IFERROR(value, value_if_error)

    Query to select data between two dates with the format m/d/yyyy

    DateTime dt1 = this.dateTimePicker1.Value.Date;
    DateTime dt2 = this.dateTimePicker2.Value.Date.AddMinutes(1440);
    String query = "SELECT * FROM student WHERE sdate BETWEEN '" + dt1 + "' AND '" + dt2 + "'";
    

    Store multiple values in single key in json

    {
        "success": true,
        "data": {
            "BLR": {
                "origin": "JAI",
                "destination": "BLR",
                "price": 127,
                "transfers": 0,
                "airline": "LB",
                "flight_number": 655,
                "departure_at": "2017-06-03T18:20:00Z",
                "return_at": "2017-06-07T08:30:00Z",
                "expires_at": "2017-03-05T08:40:31Z"
            }
        }
    };
    

    How to get jQuery to wait until an effect is finished?

    With jQuery 1.6 version you can use the .promise() method.

    $(selector).fadeOut('slow');
    $(selector).promise().done(function(){
        // will be called when all the animations on the queue finish
    });
    

    How to coerce a list object to type 'double'

    If you want to convert all elements of a to a single numeric vector and length(a) is greater than 1 (OK, even if it is of length 1), you could unlist the object first and then convert.

    as.numeric(unlist(a))
    # [1]  10  38  66 101 129 185 283 374
    

    Bear in mind that there aren't any quality controls here. Also, X$Days a mighty odd name.

    What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

    In a project, my client would like a floating box in another div, so I use margin-top CSS property rather than top in order to my floating box stay in its parent.

    Programmatically change UITextField Keyboard type

    This is the UIKeyboardTypes for Swift 3:

    public enum UIKeyboardType : Int {
    
        case `default` // Default type for the current input method.
        case asciiCapable // Displays a keyboard which can enter ASCII characters
        case numbersAndPunctuation // Numbers and assorted punctuation.
        case URL // A type optimized for URL entry (shows . / .com prominently).
        case numberPad // A number pad with locale-appropriate digits (0-9, ?-?, ?-?, etc.). Suitable for PIN entry.
        case phonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).
        case namePhonePad // A type optimized for entering a person's name or phone number.
        case emailAddress // A type optimized for multiple email address entry (shows space @ . prominently).
    
        @available(iOS 4.1, *)
        case decimalPad // A number pad with a decimal point.
    
        @available(iOS 5.0, *)
        case twitter // A type optimized for twitter text entry (easy access to @ #)
    
        @available(iOS 7.0, *)
        case webSearch // A default keyboard type with URL-oriented addition (shows space . prominently).
    
        @available(iOS 10.0, *)
        case asciiCapableNumberPad // A number pad (0-9) that will always be ASCII digits.
    
    
        public static var alphabet: UIKeyboardType { get } // Deprecated
    }
    

    This is an example to use a keyboard type from the list:

    textField.keyboardType = .numberPad
    

    jquery live hover

    WARNING: There is a significant performance penalty with the live version of hover. It's especially noticeable in a large page on IE8.

    I am working on a project where we load multi-level menus with AJAX (we have our reasons :). Anyway, I used the live method for the hover which worked great on Chrome (IE9 did OK, but not great). However, in IE8 It not only slowed down the menus (you had to hover for a couple seconds before it would drop), but everything on the page was painfully slow, including scrolling and even checking simple checkboxes.

    Binding the events directly after they loaded resulted in adequate performance.

    jQuery: serialize() form and other parameters

    Alternatively you could use form.serialize() with $.param(object) if you store your params in some object variable. The usage would be:

    var data = form.serialize() + '&' + $.param(object)
    

    See http://api.jquery.com/jQuery.param for further reference.

    Displaying the Error Messages in Laravel after being Redirected from controller

    Laravel 4

    When the validation fails return back with the validation errors.

    if($validator->fails()) {
        return Redirect::back()->withErrors($validator);
    }
    

    You can catch the error on your view using

    @if($errors->any())
        {{ implode('', $errors->all('<div>:message</div>')) }}
    @endif
    

    UPDATE

    To display error under each field you can do like this.

    <input type="text" name="firstname">
    @if($errors->has('firstname'))
        <div class="error">{{ $errors->first('firstname') }}</div>
    @endif
    

    For better display style with css.

    You can refer to the docs here.

    UPDATE 2

    To display all errors at once

    @if($errors->any())
        {!! implode('', $errors->all('<div>:message</div>')) !!}
    @endif
    

    To display error under each field.

    @error('firstname')
        <div class="error">{{ $message }}</div>
    @enderror
    

    Check line for unprintable characters while reading text file

    If you want to check a string has unprintable characters you can use a regular expression

    [^\p{Print}]
    

    How can I make the browser wait to display the page until it's fully loaded?

    obligatory: "use jQuery"

    I've seen pages that put a black or white div that covers everything on top of the page, then remove it on the document.load event. Or you could use .ready in jQuery That being said, it was one of the most anoying web pages I've ever seen, I would advise against it.

    angular js unknown provider

    I had same problem. I fixed that using $('body').attr("ng-app", 'MyApp') instead of <body ng-app="MyApp"> to boostrap.

    Because I did

    angular.element(document).ready(function () {        
        angular.bootstrap(document, [App.Config.Settings.AppName]);
    })
    

    for architecture requirements.

    What are "res" and "req" parameters in Express functions?

    req is an object containing information about the HTTP request that raised the event. In response to req, you use res to send back the desired HTTP response.

    Those parameters can be named anything. You could change that code to this if it's more clear:

    app.get('/user/:id', function(request, response){
      response.send('user ' + request.params.id);
    });
    

    Edit:

    Say you have this method:

    app.get('/people.json', function(request, response) { });
    

    The request will be an object with properties like these (just to name a few):

    • request.url, which will be "/people.json" when this particular action is triggered
    • request.method, which will be "GET" in this case, hence the app.get() call.
    • An array of HTTP headers in request.headers, containing items like request.headers.accept, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.
    • An array of query string parameters if there were any, in request.query (e.g. /people.json?foo=bar would result in request.query.foo containing the string "bar").

    To respond to that request, you use the response object to build your response. To expand on the people.json example:

    app.get('/people.json', function(request, response) {
      // We want to set the content-type header so that the browser understands
      //  the content of the response.
      response.contentType('application/json');
    
      // Normally, the data is fetched from a database, but we can cheat:
      var people = [
        { name: 'Dave', location: 'Atlanta' },
        { name: 'Santa Claus', location: 'North Pole' },
        { name: 'Man in the Moon', location: 'The Moon' }
      ];
    
      // Since the request is for a JSON representation of the people, we
      //  should JSON serialize them. The built-in JSON.stringify() function
      //  does that.
      var peopleJSON = JSON.stringify(people);
    
      // Now, we can use the response object's send method to push that string
      //  of people JSON back to the browser in response to this request:
      response.send(peopleJSON);
    });
    

    The SQL OVER() clause - when and why is it useful?

    The OVER clause when combined with PARTITION BY state that the preceding function call must be done analytically by evaluating the returned rows of the query. Think of it as an inline GROUP BY statement.

    OVER (PARTITION BY SalesOrderID) is stating that for SUM, AVG, etc... function, return the value OVER a subset of the returned records from the query, and PARTITION that subset BY the foreign key SalesOrderID.

    So we will SUM every OrderQty record for EACH UNIQUE SalesOrderID, and that column name will be called 'Total'.

    It is a MUCH more efficient means than using multiple inline views to find out the same information. You can put this query within an inline view and filter on Total then.

    SELECT ...,
    FROM (your query) inlineview
    WHERE Total < 200
    

    Cannot find vcvarsall.bat when running a Python script

    Installing Visual C++ is a good first step, though I couldn't say for sure whether the 2010 version will work. Anyway give it a try.

    Look for vcvarsall.bat in the Visual C++ installation directory (for Visual Studio 2010 it's in ProgramFiles\Microsoft Visual Studio 10.0\VC). Then add that directory to the system path. If you're doing this on the command line, you can try:

    path %path%;c:\path\to\vs2010\bin
    

    then try again to run whatever you were trying to run.

    For more permanent effect, add it in the computer system path settings.

    How do I name the "row names" column in r

    The tibble package now has a dedicated function that converts row names to an explicit variable.

    library(tibble)
    rownames_to_column(mtcars, var="das_Auto") %>% head
    

    Gives:

               das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb
    1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
    2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
    3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
    4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
    5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
    6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
    

    Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

    I asked a similar question, but where possible I try to copy the names already in the .NET framework, and I look for ideas in the Java and Android frameworks.

    It seems Helper, Manager, and Util are the unavoidable nouns you attach for coordinating classes that contain no state and are generally procedural and static. An alternative is Coordinator.

    You could get particularly purple prosey with the names and go for things like Minder, Overseer, Supervisor, Administrator, and Master, but as I said I prefer keeping it like the framework names you're used to.


    Some other common suffixes (if that is the correct term) you also find in the .NET framework are:

    • Builder
    • Writer
    • Reader
    • Handler
    • Container

    What are "named tuples" in Python?

    What are named tuples?

    A named tuple is a tuple.

    It does everything a tuple can.

    But it's more than just a tuple.

    It's a specific subclass of a tuple that is programmatically created to your specification, with named fields and a fixed length.

    This, for example, creates a subclass of tuple, and aside from being of fixed length (in this case, three), it can be used everywhere a tuple is used without breaking. This is known as Liskov substitutability.

    New in Python 3.6, we can use a class definition with typing.NamedTuple to create a namedtuple:

    from typing import NamedTuple
    
    class ANamedTuple(NamedTuple):
        """a docstring"""
        foo: int
        bar: str
        baz: list
    

    The above is the same as the below, except the above additionally has type annotations and a docstring. The below is available in Python 2+:

    >>> from collections import namedtuple
    >>> class_name = 'ANamedTuple'
    >>> fields = 'foo bar baz'
    >>> ANamedTuple = namedtuple(class_name, fields)
    

    This instantiates it:

    >>> ant = ANamedTuple(1, 'bar', [])
    

    We can inspect it and use its attributes:

    >>> ant
    ANamedTuple(foo=1, bar='bar', baz=[])
    >>> ant.foo
    1
    >>> ant.bar
    'bar'
    >>> ant.baz.append('anything')
    >>> ant.baz
    ['anything']
    

    Deeper explanation

    To understand named tuples, you first need to know what a tuple is. A tuple is essentially an immutable (can't be changed in-place in memory) list.

    Here's how you might use a regular tuple:

    >>> student_tuple = 'Lisa', 'Simpson', 'A'
    >>> student_tuple
    ('Lisa', 'Simpson', 'A')
    >>> student_tuple[0]
    'Lisa'
    >>> student_tuple[1]
    'Simpson'
    >>> student_tuple[2]
    'A'
    

    You can expand a tuple with iterable unpacking:

    >>> first, last, grade = student_tuple
    >>> first
    'Lisa'
    >>> last
    'Simpson'
    >>> grade
    'A'
    

    Named tuples are tuples that allow their elements to be accessed by name instead of just index!

    You make a namedtuple like this:

    >>> from collections import namedtuple
    >>> Student = namedtuple('Student', ['first', 'last', 'grade'])
    

    You can also use a single string with the names separated by spaces, a slightly more readable use of the API:

    >>> Student = namedtuple('Student', 'first last grade')
    

    How to use them?

    You can do everything tuples can do (see above) as well as do the following:

    >>> named_student_tuple = Student('Lisa', 'Simpson', 'A')
    >>> named_student_tuple.first
    'Lisa'
    >>> named_student_tuple.last
    'Simpson'
    >>> named_student_tuple.grade
    'A'
    >>> named_student_tuple._asdict()
    OrderedDict([('first', 'Lisa'), ('last', 'Simpson'), ('grade', 'A')])
    >>> vars(named_student_tuple)
    OrderedDict([('first', 'Lisa'), ('last', 'Simpson'), ('grade', 'A')])
    >>> new_named_student_tuple = named_student_tuple._replace(first='Bart', grade='C')
    >>> new_named_student_tuple
    Student(first='Bart', last='Simpson', grade='C')
    

    A commenter asked:

    In a large script or programme, where does one usually define a named tuple?

    The types you create with namedtuple are basically classes you can create with easy shorthand. Treat them like classes. Define them on the module level, so that pickle and other users can find them.

    The working example, on the global module level:

    >>> from collections import namedtuple
    >>> NT = namedtuple('NT', 'foo bar')
    >>> nt = NT('foo', 'bar')
    >>> import pickle
    >>> pickle.loads(pickle.dumps(nt))
    NT(foo='foo', bar='bar')
    

    And this demonstrates the failure to lookup the definition:

    >>> def foo():
    ...     LocalNT = namedtuple('LocalNT', 'foo bar')
    ...     return LocalNT('foo', 'bar')
    ... 
    >>> pickle.loads(pickle.dumps(foo()))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    _pickle.PicklingError: Can't pickle <class '__main__.LocalNT'>: attribute lookup LocalNT on __main__ failed
    

    Why/when should I use named tuples instead of normal tuples?

    Use them when it improves your code to have the semantics of tuple elements expressed in your code.

    You can use them instead of an object if you would otherwise use an object with unchanging data attributes and no functionality.

    You can also subclass them to add functionality, for example:

    class Point(namedtuple('Point', 'x y')):
        """adding functionality to a named tuple"""
            __slots__ = ()
            @property
            def hypot(self):
                return (self.x ** 2 + self.y ** 2) ** 0.5
            def __str__(self):
                return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)
    

    Why/when should I use normal tuples instead of named tuples?

    It would probably be a regression to switch from using named tuples to tuples. The upfront design decision centers around whether the cost from the extra code involved is worth the improved readability when the tuple is used.

    There is no extra memory used by named tuples versus tuples.

    Is there any kind of "named list" (a mutable version of the named tuple)?

    You're looking for either a slotted object that implements all of the functionality of a statically sized list or a subclassed list that works like a named tuple (and that somehow blocks the list from changing in size.)

    A now expanded, and perhaps even Liskov substitutable, example of the first:

    from collections import Sequence
    
    class MutableTuple(Sequence): 
        """Abstract Base Class for objects that work like mutable
        namedtuples. Subclass and define your named fields with 
        __slots__ and away you go.
        """
        __slots__ = ()
        def __init__(self, *args):
            for slot, arg in zip(self.__slots__, args):
                setattr(self, slot, arg)
        def __repr__(self):
            return type(self).__name__ + repr(tuple(self))
        # more direct __iter__ than Sequence's
        def __iter__(self): 
            for name in self.__slots__:
                yield getattr(self, name)
        # Sequence requires __getitem__ & __len__:
        def __getitem__(self, index):
            return getattr(self, self.__slots__[index])
        def __len__(self):
            return len(self.__slots__)
    

    And to use, just subclass and define __slots__:

    class Student(MutableTuple):
        __slots__ = 'first', 'last', 'grade' # customize 
    
    
    >>> student = Student('Lisa', 'Simpson', 'A')
    >>> student
    Student('Lisa', 'Simpson', 'A')
    >>> first, last, grade = student
    >>> first
    'Lisa'
    >>> last
    'Simpson'
    >>> grade
    'A'
    >>> student[0]
    'Lisa'
    >>> student[2]
    'A'
    >>> len(student)
    3
    >>> 'Lisa' in student
    True
    >>> 'Bart' in student
    False
    >>> student.first = 'Bart'
    >>> for i in student: print(i)
    ... 
    Bart
    Simpson
    A
    

    Updating a dataframe column in spark

    DataFrames are based on RDDs. RDDs are immutable structures and do not allow updating elements on-site. To change values, you will need to create a new DataFrame by transforming the original one either using the SQL-like DSL or RDD operations like map.

    A highly recommended slide deck: Introducing DataFrames in Spark for Large Scale Data Science.

    DateTime group by date and hour

    Using MySQL I usually do it that way:

    SELECT count( id ), ...
    FROM quote_data
    GROUP BY date_format( your_date_column, '%Y%m%d%H' )
    order by your_date_column desc;
    

    Or in the same idea, if you need to output the date/hour:

    SELECT count( id ) , date_format( your_date_column, '%Y-%m-%d %H' ) as my_date
    FROM  your_table 
    GROUP BY my_date
    order by your_date_column desc;
    

    If you specify an index on your date column, MySQL should be able to use it to speed up things a little.

    How to save a PNG image server-side, from a base64 data string

    Try this:

    file_put_contents('img.png', base64_decode($base64string));
    

    file_put_contents docs

    How to center absolute div horizontally using CSS?

    You need to set left: 0 and right: 0.

    This specifies how far to offset the margin edges from the sides of the window.

    Like 'top', but specifies how far a box's right margin edge is offset to the [left/right] of the [right/left] edge of the box's containing block.

    Source: http://www.w3.org/TR/CSS2/visuren.html#position-props

    Note: The element must have a width smaller than the window or else it will take up the entire width of the window.

    If you could use media queries to specify a minimum margin, and then transition to auto for larger screen sizes.


    _x000D_
    _x000D_
    .container {_x000D_
      left:0;_x000D_
      right:0;_x000D_
    _x000D_
      margin-left: auto;_x000D_
      margin-right: auto;_x000D_
    _x000D_
      position: absolute;_x000D_
      width: 40%;_x000D_
    _x000D_
      outline: 1px solid black;_x000D_
      background: white;_x000D_
    }
    _x000D_
    <div class="container">_x000D_
      Donec ullamcorper nulla non metus auctor fringilla._x000D_
      Maecenas faucibus mollis interdum._x000D_
      Sed posuere consectetur est at lobortis._x000D_
      Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor._x000D_
      Sed posuere consectetur est at lobortis._x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    In Oracle, is it possible to INSERT or UPDATE a record through a view?

    There are two times when you can update a record through a view:

    1. If the view has no joins or procedure calls and selects data from a single underlying table.
    2. If the view has an INSTEAD OF INSERT trigger associated with the view.

    Generally, you should not rely on being able to perform an insert to a view unless you have specifically written an INSTEAD OF trigger for it. Be aware, there are also INSTEAD OF UPDATE triggers that can be written as well to help perform updates.

    Uninstall / remove a Homebrew package including all its dependencies

    A More-Complete Bourne Shell Function

    There are a number of good answers already, but some are out of date and none of them are entirely complete. In particular, most of them will remove dependencies but still leave it up to you to remove the originally-targeted formula afterwards. The posted one-liners can also be tedious to work with if you want to uninstall more than one formula at a time.

    Here is a Bourne-compatible shell function (without any known Bashisms) that takes a list of formulae, removes each one's dependencies, removes all copies of the formula itself, and then reinstalls any missing dependencies.

    unbrew () {
        local formula
        for formula in "$@"; do
            brew deps "$formula" |
            xargs brew uninstall --ignore-dependencies --force
            brew uninstall --force "$formula"
        done
        brew missing | cut -f2 -d: | sort -u | xargs brew install
    }
    

    It was tested on Homebrew 1.7.4.

    Caveats

    This works on all standard formulae that I tested. It does not presently handle casks, but neither will it complain loudly if you attempt to unbrew a cask with the same name as a standard formula (e.g. MacVim).

    Alter a MySQL column to be AUTO_INCREMENT

    Try the following:

    ALTER TABLE table_name MODIFY COLUMN id datatype auto_increment;
    

    Append an int to a std::string

    You cannot cast an int to a char* to get a string. Try this:

    std::ostringstream sstream;
    sstream << "select logged from login where id = " << ClientID;
    std::string query = sstream.str();
    

    stringstream reference

    Simplest way to serve static data from outside the application server in a Java web application

    Add to server.xml :

     <Context docBase="c:/dirtoshare" path="/dir" />
    

    Enable dir file listing parameter in web.xml :

        <init-param>
            <param-name>listings</param-name>
            <param-value>true</param-value>
        </init-param>
    

    Custom date format with jQuery validation plugin

    You can create your own custom validation method using the addMethod function. Say you wanted to validate "dd/mm/yyyy":

    $.validator.addMethod(
        "australianDate",
        function(value, element) {
            // put your own logic here, this is just a (crappy) example
            return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
        },
        "Please enter a date in the format dd/mm/yyyy."
    );
    

    And then on your form add:

    $('#myForm')
        .validate({
            rules : {
                myDate : {
                    australianDate : true
                }
            }
        })
    ;
    

    What precisely does 'Run as administrator' do?

    When you log on Windows creates an access token. This identifies you, the groups you are a member of and your privileges. And note that whether a user is an administrator or not is determined by whether the user is a member of the Administrators group.

    Without UAC, when you run a program it gets a copy of the access token, and this controls what the program can access.

    With UAC, when you run a program it gets a restricted access token. This is the original access token with "Administrators" removed from the list of groups (and some other changes). Even though your user is a member of the Administrators group, the program can't use Administrator privileges.

    When you select "Run as Administrator" and your user is an administrator the program is launched with the original unrestricted access token. If your user is not an administrator you are prompted for an administrator account, and the program is run under that account.

    What is the syntax of the enhanced for loop in Java?

    Enhanced for loop:

    for (String element : array) {
    
        // rest of code handling current element
    }
    

    Traditional for loop equivalent:

    for (int i=0; i < array.length; i++) {
        String element = array[i]; 
    
        // rest of code handling current element
    }
    

    Take a look at these forums: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

    http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html

    Selecting an element in iFrame jQuery

    If the case is accessing the IFrame via console, e. g. Chrome Dev Tools then you can just select the context of DOM requests via dropdown (see the picture).

    Chrome Dev Tools - Selecting the iFrame

    Difference between h:button and h:commandButton

    This is taken from the book - The Complete Reference by Ed Burns & Chris Schalk

    h:commandButton vs h:button

    What’s the difference between h:commandButton|h:commandLink and h:button|h:link ?

    The latter two components were introduced in 2.0 to enable bookmarkable JSF pages, when used in concert with the View Parameters feature.

    There are 3 main differences between h:button|h:link and h:commandButton|h:commandLink.

    First, h:button|h:link causes the browser to issue an HTTP GET request, while h:commandButton|h:commandLink does a form POST. This means that any components in the page that have values entered by the user, such as text fields, checkboxes, etc., will not automatically be submitted to the server when using h:button|h:link. To cause values to be submitted with h:button|h:link, extra action has to be taken, using the “View Parameters” feature.

    The second main difference between the two kinds of components is that h:button|h:link has an outcome attribute to describe where to go next while h:commandButton|h:commandLink uses an action attribute for this purpose. This is because the former does not result in an ActionEvent in the event system, while the latter does.

    Finally, and most important to the complete understanding of this feature, the h:button|h:link components cause the navigation system to be asked to derive the outcome during the rendering of the page, and the answer to this question is encoded in the markup of the page. In contrast, the h:commandButton|h:commandLink components cause the navigation system to be asked to derive the outcome on the POSTBACK from the page. This is a difference in timing. Rendering always happens before POSTBACK.

    Setting background color for a JFrame

    Resurrecting a thread from stasis.

    In 2018 this solution works for Swing/JFrame in NetBeans (should work in any IDE :):

    this.getContentPane().setBackground(Color.GREEN);

    Array inside a JavaScript Object?

    // define
    var foo = {
      bar: ['foo', 'bar', 'baz']
    };
    
    // access
    foo.bar[2]; // will give you 'baz'
    

    matplotlib: colorbars and its text labels

    To add to tacaswell's answer, the colorbar() function has an optional cax input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.

    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    fig, ax = plt.subplots()
    heatmap = ax.imshow(data)
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('bottom', size='10%', pad=0.6)
    cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
    
    cax.set_xlabel('data label')  # cax == cb.ax
    

    Move column by name to front of table in pandas

    The most simplist thing you can try is:

    df=df[[ 'Mid',   'Upper',   'Lower', 'Net'  , 'Zsore']]
    

    Adding a dictionary to another

    The most obvious way is:

    foreach(var kvp in NewAnimals)
       Animals.Add(kvp.Key, kvp.Value); 
      //use Animals[kvp.Key] = kvp.Value instead if duplicate keys are an issue
    

    Since Dictionary<TKey, TValue>explicitly implements theICollection<KeyValuePair<TKey, TValue>>.Addmethod, you can also do this:

    var animalsAsCollection = (ICollection<KeyValuePair<string, string>>) Animals;
    
    foreach(var kvp in NewAnimals)
       animalsAsCollection.Add(kvp);
    

    It's a pity the class doesn't have anAddRangemethod likeList<T> does.

    JPA entity without id

    See the Java Persistence book: Identity and Sequencing

    The relevant part for your question is the No Primary Key section:

    Sometimes your object or table has no primary key. The best solution in this case is normally to add a generated id to the object and table. If you do not have this option, sometimes there is a column or set of columns in the table that make up a unique value. You can use this unique set of columns as your id in JPA. The JPA Id does not always have to match the database table primary key constraint, nor is a primary key or a unique constraint required.

    If your table truly has no unique columns, then use all of the columns as the id. Typically when this occurs the data is read-only, so even if the table allows duplicate rows with the same values, the objects will be the same anyway, so it does not matter that JPA thinks they are the same object. The issue with allowing updates and deletes is that there is no way to uniquely identify the object's row, so all of the matching rows will be updated or deleted.

    If your object does not have an id, but its' table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.

    use localStorage across subdomains

    Set to cookie in the main domain -

    document.cookie = "key=value;domain=.mydomain.com"
    

    and then take the data from any main domain or sub domain and set it on the localStorage

    Convert a string representation of a hex dump to a byte array using Java?

    The BigInteger() Method from java.math is very Slow and not recommandable.

    Integer.parseInt(HEXString, 16)

    can cause problems with some characters without converting to Digit / Integer

    a Well Working method:

    Integer.decode("0xXX") .byteValue()
    

    Function:

    public static byte[] HexStringToByteArray(String s) {
        byte data[] = new byte[s.length()/2];
        for(int i=0;i < s.length();i+=2) {
            data[i/2] = (Integer.decode("0x"+s.charAt(i)+s.charAt(i+1))).byteValue();
        }
        return data;
    }
    

    Have Fun, Good Luck

    Add carriage return to a string

    Environment.NewLine should be used as Dan Rigby said but there is one problem with the String.Empty. It will remain always empty no matter if it is read before or after it reads. I had a problem in my project yesterday with that. I removed it and it worked the way it was supposed to. It's better to declare the variable and then call it when it's needed. String.Empty will always keep it empty unless the variable needs to be initialized which only then should you use String.Empty. Thought I would throw this tid-bit out for everyone as I've experienced it.

    How to use unicode characters in Windows command line?

    On a Windows 10 x64 machine, I made the command prompt display non-English characters by:

    Open an elevated command prompt (run CMD.EXE as administrator). Query your registry for available TrueType fonts to the console by:

        REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"
    

    You'll see an output like:

        0    REG_SZ    Lucida Console
        00    REG_SZ    Consolas
        936    REG_SZ    *???
        932    REG_SZ    *MS ????
    

    Now we need to add a TrueType font that supports the characters you need like Courier New. We do this by adding zeros to the string name, so in this case the next one would be "000":

        REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"
    

    Now we implement UTF-8 support:

        REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f
    

    Set default font to "Courier New":

        REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f
    

    Set font size to 20:

        REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f
    

    Enable quick edit if you like:

        REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f
    

    Check if character is number?

    square = function(a) {
        if ((a * 0) == 0) {
            return a*a;
        } else {
            return "Enter a valid number.";
        }
    }
    

    Source

    Merge trunk to branch in Subversion

    Last revision merged from trunk to branch can be found by running this command inside the working copy directory:

    svn log -v --stop-on-copy
    

    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 edit .csproj file

    There is an easier way so you don't have to unload the project. Just install this tool called EditProj in Visual Studio:
    https://marketplace.visualstudio.com/items?itemName=EdMunoz.EditProj

    Then right click edit you will have a new menu item Edit Project File :)
    enter image description here

    Fastest way to ping a network range and return responsive hosts?

    You should use NMAP:

    nmap -T5 -sP 192.168.0.0-255
    

    How to clamp an integer to some range?

    many interesting answers here, all about the same, except... which one's faster?

    import numpy
    np_clip = numpy.clip
    mm_clip = lambda x, l, u: max(l, min(u, x))
    s_clip = lambda x, l, u: sorted((x, l, u))[1]
    py_clip = lambda x, l, u: l if x < l else u if x > u else x
    
    >>> import random
    >>> rrange = random.randrange
    >>> %timeit mm_clip(rrange(100), 10, 90)
    1000000 loops, best of 3: 1.02 µs per loop
    
    >>> %timeit s_clip(rrange(100), 10, 90)
    1000000 loops, best of 3: 1.21 µs per loop
    
    >>> %timeit np_clip(rrange(100), 10, 90)
    100000 loops, best of 3: 6.12 µs per loop
    
    >>> %timeit py_clip(rrange(100), 10, 90)
    1000000 loops, best of 3: 783 ns per loop
    

    paxdiablo has it!, use plain ol' python. The numpy version is, perhaps not surprisingly, the slowest of the lot. Probably because it's looking for arrays, where the other versions just order their arguments.

    T-SQL query to show table definition?

    Since SQL 2012 you can run the following statement:

    Exec sp_describe_first_result_set @tsql= N'Select * from <yourtable>'
    

    If you enter a complex select statement (joins, subselects, etc), it will give you the definition of the result set. This is very handy, if you need to create a new table (or temp table) and you don't want to check every single field definition manually.

    https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-describe-first-result-set-transact-sql

    How to fix libeay32.dll was not found error

    I encountered the same problem when I tried to install curl in my 32 bit win 7 machine. As answered by Buravchik it is indeed dependency of SSL and installing openssl fixed it. Just a point to take care is that while installing openssl you will get a prompt to ask where do you wish to put the dependent DLLS. Make sure to put it in windows system directory as other programs like curl and wget will also be needing it.

    enter image description here

    Detect Safari using jQuery

    The only way I found is check if navigator.userAgent contains iPhone or iPad word

    if (navigator.userAgent.toLowerCase().match(/(ipad|iphone)/)) {
        //is safari
    }
    

    How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

    "N/A" is not an integer. It must throw NumberFormatException if you try to parse it to an integer.

    Check before parsing or handle Exception properly.

    1. Exception Handling

      try{
          int i = Integer.parseInt(input);
      } catch(NumberFormatException ex){ // handle your exception
          ...
      }
      

    or - Integer pattern matching -

    String input=...;
    String pattern ="-?\\d+";
    if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
     ...
    }
    

    Passing base64 encoded strings in URL

    Yes and no.

    The basic charset of base64 may in some cases collide with traditional conventions used in URLs. But many of base64 implementations allow you to change the charset to match URLs better or even come with one (like Python's urlsafe_b64encode()).

    Another issue you may be facing is the limit of URL length or rather — lack of such limit. Because standards do not specify any maximum length, browsers, servers, libraries and other software working with HTTP protocol may define its' own limits.

    How do I determine the current operating system with Node.js

    when you are using 32bits node on 64bits windows(like node-webkit or atom-shell developers), process.platform will echo win32

    use

        function isOSWin64() {
          return process.arch === 'x64' || process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
        }
    

    (check here for details)

    How do I calculate someone's age based on a DateTime type birthday?

    Here's yet another answer:

    public static int AgeInYears(DateTime birthday, DateTime today)
    {
        return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
    }
    

    This has been extensively unit-tested. It does look a bit "magic". The number 372 is the number of days there would be in a year if every month had 31 days.

    The explanation of why it works (lifted from here) is:

    Let's set Yn = DateTime.Now.Year, Yb = birthday.Year, Mn = DateTime.Now.Month, Mb = birthday.Month, Dn = DateTime.Now.Day, Db = birthday.Day

    age = Yn - Yb + (31*(Mn - Mb) + (Dn - Db)) / 372

    We know that what we need is either Yn-Yb if the date has already been reached, Yn-Yb-1 if it has not.

    a) If Mn<Mb, we have -341 <= 31*(Mn-Mb) <= -31 and -30 <= Dn-Db <= 30

    -371 <= 31*(Mn - Mb) + (Dn - Db) <= -1

    With integer division

    (31*(Mn - Mb) + (Dn - Db)) / 372 = -1

    b) If Mn=Mb and Dn<Db, we have 31*(Mn - Mb) = 0 and -30 <= Dn-Db <= -1

    With integer division, again

    (31*(Mn - Mb) + (Dn - Db)) / 372 = -1

    c) If Mn>Mb, we have 31 <= 31*(Mn-Mb) <= 341 and -30 <= Dn-Db <= 30

    1 <= 31*(Mn - Mb) + (Dn - Db) <= 371

    With integer division

    (31*(Mn - Mb) + (Dn - Db)) / 372 = 0

    d) If Mn=Mb and Dn>Db, we have 31*(Mn - Mb) = 0 and 1 <= Dn-Db <= 30

    With integer division, again

    (31*(Mn - Mb) + (Dn - Db)) / 372 = 0

    e) If Mn=Mb and Dn=Db, we have 31*(Mn - Mb) + Dn-Db = 0

    and therefore (31*(Mn - Mb) + (Dn - Db)) / 372 = 0

    Selecting text in an element (akin to highlighting with your mouse)

    Added jQuery.browser.webkit to the "else if" for Chrome. Could not get this working in Chrome 23.

    Made this script below for selecting the content in a <pre> tag that has the class="code".

    jQuery( document ).ready(function() {
        jQuery('pre.code').attr('title', 'Click to select all');
        jQuery( '#divFoo' ).click( function() {
            var refNode = jQuery( this )[0];
            if ( jQuery.browser.msie ) {
                var range = document.body.createTextRange();
                range.moveToElementText( refNode );
                range.select();
            } else if ( jQuery.browser.mozilla || jQuery.browser.opera  || jQuery.browser.webkit ) {
                var selection = refNode.ownerDocument.defaultView.getSelection();
                console.log(selection);
                var range = refNode.ownerDocument.createRange();
                range.selectNodeContents( refNode );
                selection.removeAllRanges();
                selection.addRange( range );
            } else if ( jQuery.browser.safari ) {
                var selection = refNode.ownerDocument.defaultView.getSelection();
                selection.setBaseAndExtent( refNode, 0, refNode, 1 );
            }
        } );
    } );
    

    How to delete all files from a specific folder?

    Try this:

    foreach (string file in Directory.GetFiles(@"c:\directory\"))
      File.Delete(file);
    

    How to read an http input stream

    Try with this code:

    InputStream in = address.openStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder result = new StringBuilder();
    String line;
    while((line = reader.readLine()) != null) {
        result.append(line);
    }
    System.out.println(result.toString());
    

    .NET NewtonSoft JSON deserialize map to a different property name

    Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".

        /// <summary>
        /// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not 
        /// let the JsonProperty control everything.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
        {
            private Dictionary<string, string> PropertyMappings { get; set; }
    
            public IgnoreJsonPropertyResolver()
            {
                this.PropertyMappings = new Dictionary<string, string>();
                var properties = ReflectionHelper<T>.GetGetProperties(false)();
                foreach (var propertyInfo in properties)
                {
                    var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
                    if (jsonProperty != null)
                    {
                        PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
                    }
                }
            }
    
            protected override string ResolvePropertyName(string propertyName)
            {
                string resolvedName = null;
                var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
                return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
            }
        }
    

    Usage:

            var settings = new JsonSerializerSettings();
            settings.DateFormatString = "YYYY-MM-DD";
            settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
            var model = new PlanViewModel() {Amount = 100};
            var strModel = JsonConvert.SerializeObject(model,settings);
    

    Model:

    public class PlanViewModel
    {
    
        /// <summary>
        ///     The customer is charged an amount over an interval for the subscription.
        /// </summary>
        [JsonProperty(PropertyName = "RecurringPrice")]
        public double Amount { get; set; }
    
        /// <summary>
        ///     Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
        ///     months or years depending on the value for interval_unit.
        /// </summary>
        public int Interval { get; set; } = 1;
    
        /// <summary>
        ///     Number of free trial days that can be granted when a customer is subscribed to this plan.
        /// </summary>
        public int TrialPeriod { get; set; } = 30;
    
        /// <summary>
        /// This indicates a one-time fee charged upfront while creating a subscription for this plan.
        /// </summary>
        [JsonProperty(PropertyName = "SetupFee")]
        public double SetupAmount { get; set; } = 0;
    
    
        /// <summary>
        /// String representing the type id, usually a lookup value, for the record.
        /// </summary>
        [JsonProperty(PropertyName = "TypeId")]
        public string Type { get; set; }
    
        /// <summary>
        /// Billing Frequency
        /// </summary>
        [JsonProperty(PropertyName = "BillingFrequency")]
        public string Period { get; set; }
    
    
        /// <summary>
        /// String representing the type id, usually a lookup value, for the record.
        /// </summary>
        [JsonProperty(PropertyName = "PlanUseType")]
        public string Purpose { get; set; }
    }
    

    How to use the addr2line command in Linux?

    You can also use gdb instead of addr2line to examine memory address. Load executable file in gdb and print the name of a symbol which is stored at the address. 16 Examining the Symbol Table.

    (gdb) info symbol 0x4005BDC 
    

    How can I set a custom baud rate on Linux?

    dougg3 has this pretty much (I can't comment there). The main additional thing you need to know is the headers which don't conflict with each other but do provide the correct prototypes. The answer is

    #include <stropts.h>
    #include <asm/termios.h>
    

    After that you can use dougg3's code, preferably with error checking round the ioctl() calls. You will probably need to put this in a separate .c file to the rest of your serial port code which uses the normal termios to set other parameters. Doing POSIX manipulations first, then this to set the custom speed, works fine on the built-in UART of the Raspberry Pi to get a 250k baud rate.

    What is the purpose of willSet and didSet in Swift?

    One thing where didSet is really handy is when you use outlets to add additional configuration.

    @IBOutlet weak var loginOrSignupButton: UIButton! {
      didSet {
            let title = NSLocalizedString("signup_required_button")
            loginOrSignupButton.setTitle(title, for: .normal)
            loginOrSignupButton.setTitle(title, for: .highlighted)
      }
    

    What operator is <> in VBA

    It is the "not equal" operator, i.e. the equivalent of != in pretty much every other language.

    Is there a way to get colored text in GitHubflavored Markdown?

    You cannot get green/red text, but you can get green/red highlighted text using the diff language template. Example:

    ```diff
    + this text is highlighted in green
    - this text is highlighted in red
    ```
    

    How to generate class diagram from project in Visual Studio 2013?

    Right click on the project in solution explorer or class view window --> "View" --> "View Class Diagram"

    HSL to RGB color conversion

    For when you need RGB to HSV and vice versa instead:

    function rgbToHsv(r, g, b)
    {
        r /= 255, g /= 255, b /= 255;
    
        var min = Math.min(r, g, b),
        max = Math.max(r, g, b),
        delta = max - min,
        h = 0, s = 0, v = max;
    
        if (min != max)
        {
            s = (delta / max);
    
            switch (max)
            {
                case r: h = (g - b) / delta + (g < b ? 6 : 0); break;
                case g: h = (b - r) / delta + 2; break;
                case b: h = (r - g) / delta + 4; break;
            }
    
            h /= 6;
        }
    
        return [h, s, v];
    }
    
    function hsvToRgb(h, s, v)
    {
        var step = h / (1 / 6),
        pos = step - Math.floor(step), // the hue position within the current step
        m = (Math.floor(step) % 2) ? (1 - pos) * v : pos * v, // mix color value adjusted to the brightness(v)
        max = 1 * v,
        min = (1 - s) * v,
        med = m + ((1 - s) * (v - m)),
        r, g, b;
    
        switch (Math.floor(step))
        {
            case 0:
                r = max;
                g = med;
                b = min;
                break;
            case 1:
                r = med;
                g = max;
                b = min;
                break;
            case 2:
                r = min;
                g = max;
                b = med;
                break;
            case 3:
                r = min;
                g = med;
                b = max;
                break;
            case 4:
                r = med;
                g = min;
                b = max;
                break;
            case 5:
                r = max;
                g = min;
                b = med;
                break;
        }
    
        return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
    }
    

    In c++ what does a tilde "~" before a function name signify?

    It's a destructor. The function is guaranteed to be called when the object goes out of scope.

    Passing Multiple route params in Angular2

    Two Methods for Passing Multiple route params in Angular

    Method-1

    In app.module.ts

    Set path as component2.

    imports: [
     RouterModule.forRoot(
     [ {path: 'component2/:id1/:id2', component: MyComp2}])
    ]
    

    Call router to naviagte to MyComp2 with multiple params id1 and id2.

    export class MyComp1 {
    onClick(){
        this._router.navigate( ['component2', "id1","id2"]);
     }
    }
    

    Method-2

    In app.module.ts

    Set path as component2.

    imports: [
     RouterModule.forRoot(
     [ {path: 'component2', component: MyComp2}])
    ]
    

    Call router to naviagte to MyComp2 with multiple params id1 and id2.

    export class MyComp1 {
    onClick(){
        this._router.navigate( ['component2', {id1: "id1 Value", id2: 
        "id2  Value"}]);
     }
    }
    

    error: command 'gcc' failed with exit status 1 on CentOS

    " error: command 'gcc' failed with exit status 1 ". the installation failed because of missing python-devel and some dependencies.

    the best way to correct gcc problem:

    You need to reinstall gcc , gcc-c++ and dependencies.

    For python 2.7

    $ sudo yum -y install gcc gcc-c++ kernel-devel
    $ sudo yum -y install python-devel libxslt-devel libffi-devel openssl-devel
    $ pip install "your python packet"
    

    For python 3.4

    $ sudo apt-get install python3-dev
    $ pip install "your python packet"
    

    Hope this will help.

    Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

    In your MoviesService you should import FirebaseListObservable in order to define return type FirebaseListObservable<any[]>

    import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
    

    then get() method should like this-

    get (): FirebaseListObservable<any[]>{
            return this.db.list('/movies');
        }
    

    this get() method will return FirebaseListObervable of movies list

    In your MoviesComponent should look like this

    export class MoviesComponent implements OnInit {
      movies: any[];
    
      constructor(private moviesDb: MoviesService) { }
    
      ngOnInit() {
        this.moviesDb.get().subscribe((snaps) => {
           this.movies = snaps;
       });
     }
    }
    

    Then you can easily iterate through movies without async pipe as movies[] data is not observable type, your html should be this

    ul
      li(*ngFor='let movie of movies')
        {{ movie.title }}
    

    if you declear movies as a

    movies: FirebaseListObservable<any[]>;
    

    then you should simply call

    movies: FirebaseListObservable<any[]>;
    ngOnInit() {
        this.movies = this.moviesDb.get();
    }
    

    and your html should be this

    ul
      li(*ngFor='let movie of movies | async')
        {{ movie.title }}
    

    How to limit file upload type file size in PHP?

    Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:

    if(isset($_FILES['uploaded_file'])) {
        $errors     = array();
        $maxsize    = 2097152;
        $acceptable = array(
            'application/pdf',
            'image/jpeg',
            'image/jpg',
            'image/gif',
            'image/png'
        );
    
        if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
            $errors[] = 'File too large. File must be less than 2 megabytes.';
        }
    
        if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
            $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
        }
    
        if(count($errors) === 0) {
            move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
        } else {
            foreach($errors as $error) {
                echo '<script>alert("'.$error.'");</script>';
            }
    
            die(); //Ensure no more processing is done
        }
    }
    

    Look into the docs for move_uploaded_file() (it's called move not store) for more.

    Number of elements in a javascript object

    The concept of number/length/dimensionality doesn't really make sense for an Object, and needing it suggests you really want an Array to me.

    Edit: Pointed out to me that you want an O(1) for this. To the best of my knowledge no such way exists I'm afraid.

    Delete element in a slice

    ... is syntax for variadic arguments.

    I think it is implemented by the complier using slice ([]Type), just like the function append :

    func append(slice []Type, elems ...Type) []Type
    

    when you use "elems" in "append", actually it is a slice([]type). So "a = append(a[:0], a[1:]...)" means "a = append(a[0:0], a[1:])"

    a[0:0] is a slice which has nothing

    a[1:] is "Hello2 Hello3"

    This is how it works

    Why does this code using random strings print "hello world"?

    When an instance of java.util.Random is constructed with a specific seed parameter (in this case -229985452 or -147909649), it follows the random number generation algorithm beginning with that seed value.

    Every Random constructed with the same seed will generate the same pattern of numbers every time.

    How to get the class of the clicked element?

    $("div").click(function() {
      var txtClass = $(this).attr("class");
      console.log("Class Name : "+txtClass);
    });
    

    Get value of c# dynamic property via string

    Dynamitey is an open source .net std library, that let's you call it like the dynamic keyword, but using the a string for the property name rather than the compiler doing it for you, and it ends up being equal to reflection speedwise (which is not nearly as fast as using the dynamic keyword, but this is due to the extra overhead of caching dynamically, where the compiler caches statically).

    Dynamic.InvokeGet(d,"value2");
    

    Best way to compare dates in Android

    You can directly create a Calendar from a Date:

    Calendar validDate = new GregorianCalendar();
    validDate.setTime(strDate);
    if (Calendar.getInstance().after(validDate)) {
        catalog_outdated = 1;
    }
    

    How to show changed file name only with git log?

    Thanks for your answers, @mvp, @xero, I get what I want base on both of your answers.

    git log --name-only 
    

    or

    git log --name-only --oneline
    

    for short.

    How can I change image source on click with jQuery?

    You need to use preventDefault() to make it so the link does not go through when u click on it:

    fiddle: http://jsfiddle.net/maniator/Sevdm/

    $(function() {
     $('.menulink').click(function(e){
         e.preventDefault();
       $("#bg").attr('src',"img/picture1.jpg");
     });
    });
    

    How to run VBScript from command line without Cscript/Wscript

    I am wondering why you cannot put this in a batch file. Example:

    cd D:\VBS\
    WSCript Converter.vbs
    

    Put the above code in a text file and save the text file with .bat extension. Now you have to simply run this .bat file.

    "Exception has been thrown by the target of an invocation" error (mscorlib)

    This is may have 2 reasons

    1.I found the connection string error in my web.config file i had changed the connection string and its working.

    1. Connection string is proper then check with the control panel>services> SQL Server Browser > start or not

    CSS: Control space between bullet and <li>

    For list-style-type: inline:

    It's almost the same like DSMann8's answer but less css code.

    You just need to

    <style>
        li:before {
            content: "";
            padding-left: 10px;
        }
    </style>
    
    <ul>
        <li>Some content</li>
    </ul>
    

    Cheers

    libaio.so.1: cannot open shared object file

    In case one does not have sudo privilege, but still needs to install the library.

    Download source for the software/library using:

    apt-get source libaio
    

    or

    wget https://src.fedoraproject.org/lookaside/pkgs/libaio/libaio-0.3.110.tar.gz/2a35602e43778383e2f4907a4ca39ab8/libaio-0.3.110.tar.gz
    

    unzip the library

    Install with the following command to user-specific library:

    make prefix=`pwd`/usr install #(Copy from INSTALL file of libaio-0.3.110)
    

    or

    make prefix=/path/to/your/lib/libaio install
    

    Include libaio library into LD_LIBRARY_PATH for your app:

    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/your/lib/libaio/lib
    

    Now, your app should be able to find libaio.so.1

    How to get client IP address using jQuery

    
    <html lang="en">
    <head>
        <title>Jquery - get ip address</title>
        <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
    </head>
    <body>
    
    
    <h1>Your Ip Address : <span class="ip"></span></h1>
    
    
    <script type="text/javascript">
        $.getJSON("http://jsonip.com?callback=?", function (data) {
            $(".ip").text(data.ip);
        });
    </script>
    
    
    </body>
    </html>
    

    Chrome extension: accessing localStorage in content script

    Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.

    One downside is that it is asynchronous.

    https://developer.chrome.com/extensions/storage.html

    How do I do a not equal in Django queryset filtering?

    You can use Q objects for this. They can be negated with the ~ operator and combined much like normal Python expressions:

    from myapp.models import Entry
    from django.db.models import Q
    
    Entry.objects.filter(~Q(id=3))
    

    will return all entries except the one(s) with 3 as their ID:

    [<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]
    

    What are the main differences between JWT and OAuth authentication?

    JWT is an open standard that defines a compact and self-contained way for securely transmitting information between parties. It is an authentication protocol where we allow encoded claims (tokens) to be transferred between two parties (client and server) and the token is issued upon the identification of a client. With each subsequent request we send the token.

    Whereas OAuth2 is an authorization framework, where it has a general procedures and setups defined by the framework. JWT can be used as a mechanism inside OAuth2.

    You can read more on this here

    OAuth or JWT? Which one to use and why?

    JavaScript: function returning an object

    The latest way to do this with ES2016 JavaScript

    let makeGamePlayer = (name, totalScore, gamesPlayed) => ({
        name,
        totalScore,
        gamesPlayed
    })
    

    XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

    Try finding the Service running on the PID that is blocking the service from Task manager->Services

    In case this isn't of help go to Task Manager->Services Go to the Services button on bottom right of window and stop the Web Deployment Agent Service. Retry starting Apache . That might solve the problem.

    What is the significance of url-pattern in web.xml and how to configure servlet?

    Servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

    First specification of url-pattern a web.xml file for the server context on the servlet container at server .com matches the pattern in <url-pattern>/status/*</url-pattern> as follows:

    http://server.com/server/status/synopsis               = Matches
    http://server.com/server/status/complete?date=today    = Matches
    http://server.com/server/status                        = Matches
    http://server.com/server/server1/status                = Does not match
    

    Second specification of url-pattern A context located at the path /examples on the Agent at example.com matches the pattern in <url-pattern>*.map</url-pattern> as follows:

     http://server.com/server/US/Oregon/Portland.map    = Matches
     http://server.com/server/US/server/Seattle.map     = Matches
     http://server.com/server/Paris.France.map          = Matches
     http://server.com/server/US/Oregon/Portland.MAP    = Does not match, the extension is uppercase
     http://example.com/examples/interface/description/mail.mapi  =Does not match, the extension is mapi rather than map`
    

    Third specification of url-mapping,A mapping that contains the pattern <url-pattern>/</url-pattern> matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.

    The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.

    The servlet-mapping element below maps the server servlet instance to the default mapping.

    <servlet-mapping>
      <servlet-name>server</servlet-name>
      <url-pattern>/</url-pattern>
    </servlet-mapping>
    

    For the context that contains this element, any request that is not handled by another mapping is forwarded to the server servlet.

    And Most importantly we should Know about Rule for URL path mapping

    1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
    2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
    3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
    4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

    Reference URL Pattern

    How to output in CLI during execution of PHP Unit tests?

    I output my Testresults HTML based, in this case it was helpfull to flush the content:

    var_dump($array);
    ob_flush();
    

    There is a second PHP Method

    flush() 
    

    which i not has tried.

    Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

    Problem solved, I've not added the index.html. Which is point out in the web.xml

    enter image description here

    Note: a project may have more than one web.xml file.

    if there are another web.xml in

    src/main/webapp/WEB-INF

    Then you might need to add another index (this time index.jsp) to

    src/main/webapp/WEB-INF/pages/

    OSError: [WinError 193] %1 is not a valid Win32 application

    The file hello.py is not an executable file. You need to specify a file like python.exe

    try following:

    import sys
    subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])
    

    phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

    Follow these steps- 1.go to config.inc.php file and find - $cfg['Servers'][$i]['auth_type']

    2.change the value of $cfg['Servers'][$i]['auth_type'] to 'cookie' or 'http'.

    3.find $cfg['Servers'][$i]['AllowNoPassword'] and change it's value to true.

    Now whenever you want to login, enter root as your username,skip the password and go ahead pressing the submit button..

    Note- if you choose authentication type as cookie then whenever you will close the browser and reopen it ,again you have to login.

    WPF User Control Parent

    Try using the following:

    Window parentWindow = Window.GetWindow(userControlReference);
    

    The GetWindow method will walk the VisualTree for you and locate the window that is hosting your control.

    You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow method from returning null. E.g. wire up an event:

    this.Loaded += new RoutedEventHandler(UserControl_Loaded); 
    

    git: 'credential-cache' is not a git command

    I faced this problem while using AptanaStudio3 on windows7. This helped me:

    git config --global credential.helper wincred
    

    Code taken from here

    maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

    open the file named "jquery.fileupload-ui.js", you will see the code like this:

     $.widget('blueimp.fileupload', $.blueimp.fileupload, {
    
        options: {
            // By default, files added to the widget are uploaded as soon
            // as the user clicks on the start buttons. To enable automatic
            // uploads, set the following option to true:
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            autoUpload: false,
            // The ID of the upload template:
            uploadTemplateId: 'template-upload',
            // The ID of the download template:
            downloadTemplateId: 'template-download',
            ????
    

    just add one line code --- the new attribute "acceptFileTypes",like this:

     options: {
            // By default, files added to the widget are uploaded as soon
            // as the user clicks on the start buttons. To enable automatic
            // uploads, set the following option to true:
            **acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,**
            autoUpload: false,
            // The ID of the upload template:
            uploadTemplateId: 'template-upload',
            // The ID of the download template:
            downloadTemplateId: 'template-d
    

    now you'll see everything is allright!~ you just take the attribute with a wrong place.

    Making a DateTime field in a database automatic?

    Just right click on that column and select properties and write getdate()in Default value or binding.like image:

    enter image description here

    If you want do it in CodeFirst in EF you should add this attributes befor of your column definition:

    [Databasegenerated(Databaseoption.computed)]

    this attributes can found in System.ComponentModel.Dataannotion.Schema.

    In my opinion first one is better:))

    git with IntelliJ IDEA: Could not read from remote repository

    1. Go to Settings->Git->Select Native in SSH executable dropdown. (If it is not selected)
    2. Copy HTTPS link from your Github repository.
    3. Go to VCS->Git->Remotes..
    4. Edit the origin and Paste HTTPS link in the URL field.
    5. Press Ctrl+Shift+k and push the project to repository. It works.

    jQuery - What are differences between $(document).ready and $(window).load?

    $(document).ready(function(e) { 
        // executes when HTML-Document is loaded and DOM is ready  
        console.log("page is loading now"); 
    });
    
    $(document).load(function(e) { 
        //when html page complete loaded
        console.log("completely loaded"); 
    });
    

    Find the PID of a process that uses a port on Windows

    Just open a command shell and type (saying your port is 123456):

    netstat -a -n -o | find "123456"
    

    You will see everything you need.

    The headers are:

     Proto  Local Address          Foreign Address        State           PID
     TCP    0.0.0.0:37             0.0.0.0:0              LISTENING       1111
    

    How to make a owl carousel with arrows instead of next previous

    If you using latest Owl Carousel 2 version. You can replace the Navigation text by fontawesome icon. Code is below.

    $('.your-class').owlCarousel({
            loop: true,
            items: 1, // Select Item Number
            autoplay:true,
            dots: false,
            nav: true,
            navText: ["<i class='fa fa-long-arrow-left'></i>","<i class='fa fa-long-arrow-right'></i>"],
    
        });
    

    Declare global variables in Visual Studio 2010 and VB.NET

    You could just add a new Variable under the properties of your project Each time you want to get that variable you just have to use

    My.Settings.(Name of variable)
    

    That'll work for the entire Project in all forms

    jQuery Combobox/select autocomplete?

    This works great for me and I'm doing more, writing less with jQuery's example modified.

    I defined the select object on my page, just like the jQuery ex. I took the text and pushed it to an array. Then I use the array as my source to my input autocomplete. tadaa.

    $(function() {
       var mySource = [];
       $("#mySelect").children("option").map(function() {
          mySource.push($(this).text());
       });
    
       $("#myInput").autocomplete({
          source: mySource,
          minLength: 3
       });
    }
    

    How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

    I followed the below steps and it worked for me.

    Step1: Edit eclipse.ini by adding javaw.exe path and remove --launcher.appendVmargs line. Below shows the original and edited file

    Orginal eclipse.ini openFile --launcher.appendVmargs -vmargs -Dosgi.requiredJavaVersion=1.8

    After editing eclipse.ini: openFile -vm C:/ProgramFiles/Java/javapath/javaw.exe -vmargs -Dosgi.requiredJavaVersion=1.8

    Step2: Copied the org.eclipse.equinox.launcher_1.5.700.v20200207-2156.jar to eclipse installation folder . You can find the .jar location in eclipse.ini eg : C:\Users\Username.p2\pool\plugins

    Ajax call Into MVC Controller- Url Issue

    A good way to do it without getting the view involved may be:

    $.ajax({
        type: "POST",
        url: '/Controller/Search',
        data: { queryString: searchVal },
        success: function (data) {
          alert("here" + data.d.toString());
        }
    });
    

    This will try to POST to the URL:

    "http://domain/Controller/Search (which is the correct URL for the action you want to use)"

    how to check if item is selected from a comboBox in C#

    I've found that using this null comparison works well:

    if (Combobox.SelectedItem != null){
       //Do something
    }
    else{
      MessageBox.show("Please select a item");
    }
    

    This will only accept the selected item and no other value which may have been entered manually by the user which could cause validation issues.

    How to access a mobile's camera from a web app?

    well, there's a new HTML5 features for accessing the native device camera - "getUserMedia API"

    NOTE: HTML5 can handle photo capture from a web page on Android devices (at least on the latest versions, run by the Honeycomb OS; but it can’t handle it on iPhones but iOS 6 ).

    Sorting multiple keys with Unix sort

    Take care though:

    If you want to sort the file primarily by field 3, and secondarily by field 2 you want this:

    sort -k 3,3 -k 2,2 < inputfile
    

    Not this: sort -k 3 -k 2 < inputfile which sorts the file by the string from the beginning of field 3 to the end of line (which is potentially unique).

    -k, --key=POS1[,POS2]     start a key at POS1 (origin 1), end it at POS2
                              (default end of line)
    

    How to use timer in C?

    May be this examples help to you

    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    
    
    /*
        Implementation simple timeout
    
        Input: count milliseconds as number
    
        Usage:
            setTimeout(1000) - timeout on 1 second
            setTimeout(10100) - timeout on 10 seconds and 100 milliseconds
     */
    void setTimeout(int milliseconds)
    {
        // If milliseconds is less or equal to 0
        // will be simple return from function without throw error
        if (milliseconds <= 0) {
            fprintf(stderr, "Count milliseconds for timeout is less or equal to 0\n");
            return;
        }
    
        // a current time of milliseconds
        int milliseconds_since = clock() * 1000 / CLOCKS_PER_SEC;
    
        // needed count milliseconds of return from this timeout
        int end = milliseconds_since + milliseconds;
    
        // wait while until needed time comes
        do {
            milliseconds_since = clock() * 1000 / CLOCKS_PER_SEC;
        } while (milliseconds_since <= end);
    }
    
    
    int main()
    {
    
        // input from user for time of delay in seconds
        int delay;
        printf("Enter delay: ");
        scanf("%d", &delay);
    
        // counter downtime for run a rocket while the delay with more 0
        do {
            // erase the previous line and display remain of the delay
            printf("\033[ATime left for run rocket: %d\n", delay);
    
            // a timeout for display
            setTimeout(1000);
    
            // decrease the delay to 1
            delay--;
    
        } while (delay >= 0);
    
        // a string for display rocket
        char rocket[3] = "-->";
    
        // a string for display all trace of the rocket and the rocket itself
        char *rocket_trace = (char *) malloc(100 * sizeof(char));
    
        // display trace of the rocket from a start to the end
        int i;
        char passed_way[100] = "";
        for (i = 0; i <= 50; i++) {
            setTimeout(25);
            sprintf(rocket_trace, "%s%s", passed_way, rocket);
            passed_way[i] = ' ';
            printf("\033[A");
            printf("| %s\n", rocket_trace);
        }
    
        // erase a line and write a new line
        printf("\033[A");
        printf("\033[2K");
        puts("Good luck!");
    
        return 0;
    }
    

    Compile file, run and delete after (my preference)

    $ gcc timeout.c -o timeout && ./timeout && rm timeout
    

    Try run it for yourself to see result.

    Notes:

    Testing environment

    $ uname -a
    Linux wlysenko-Aspire 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
    $ gcc --version
    gcc (Ubuntu 4.8.5-2ubuntu1~14.04.1) 4.8.5
    Copyright (C) 2015 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    

    PostgreSQL column 'foo' does not exist

    If for some reason you have created a mixed-case or upper-case column name, you need to quote it, or get this error:

    test=> create table moo("FOO" int);
    CREATE TABLE
    test=> select * from moo;
     FOO 
    -----
    (0 rows)
    test=> select "foo" from moo;
    ERROR:  column "foo" does not exist
    LINE 1: select "foo" from moo;
                   ^
    test=> _
    

    Note how the error message gives the case in quotes.

    How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

    I would use this in HTML 5... Just sayin

    #footer {
      position: absolute;
      bottom: 0;
      width: 100%;
      height: 60px;
      background-color: #f5f5f5;
    }
    

    Java, How to get number of messages in a topic in apache kafka

    The simplest way I've found is to use the Kafdrop REST API /topic/topicName and specify the key: "Accept" / value: "application/json" header in order to get back a JSON response.

    This is documented here.

    How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

    The straight up answer to your question is: No. The signature for the PostAsync method is as follows:

    public Task PostAsync(Uri requestUri, HttpContent content)

    So, while you can pass an object to PostAsync it must be of type HttpContent and your anonymous type does not meet that criteria.

    However, there are ways to accomplish what you want to accomplish. First, you will need to serialize your anonymous type to JSON, the most common tool for this is Json.NET. And the code for this is pretty trivial:

    var myContent = JsonConvert.SerializeObject(data);
    

    Next, you will need to construct a content object to send this data, I will use a ByteArrayContent object, but you could use or create a different type if you wanted.

    var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
    var byteContent = new ByteArrayContent(buffer);
    

    Next, you want to set the content type to let the API know this is JSON.

    byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    

    Then you can send your request very similar to your previous example with the form content:

    var result = client.PostAsync("", byteContent).Result
    

    On a side note, calling the .Result property like you're doing here can have some bad side effects such as dead locking, so you want to be careful with this.

    How to easily get network path to the file you are working on?

    Just paste the below formula in any of the cells, it will render the path of the file:

    =LEFT(CELL("filename"),FIND("]",CELL("filename"),1))
    

    The above formula works in any version of Excel.

    Shorten string without cutting words in JavaScript

    I'm late to the party, but here's a small and easy solution I came up with to return an amount of words.

    It's not directly related to your requirement of characters, but it serves the same outcome that I believe you were after.

    function truncateWords(sentence, amount, tail) {
      const words = sentence.split(' ');
    
      if (amount >= words.length) {
        return sentence;
      }
    
      const truncated = words.slice(0, amount);
      return `${truncated.join(' ')}${tail}`;
    }
    
    const sentence = 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.';
    
    console.log(truncateWords(sentence, 10, '...'));
    

    See the working example here: https://jsfiddle.net/bx7rojgL/

    Hiding and Showing TabPages in tabControl

    There are at least two ways to code a solution in software... Thanks for posting answers. Just wanted to update this with another version. A TabPage array is used to shadow the Tab Control. During the Load event, the TabPages in the TabControl are copied to the shadow array. Later, this shadow array is used as the source to copy the TabPages into the TabControl...and in the desired presentation order.

        Private tabControl1tabPageShadow() As TabPage = Nothing
    
        Private Sub Form2_DailyReportPackageViewer_Load(sender As Object, e As EventArgs) Handles Me.Load
            LoadTabPageShadow()
        End Sub
    
    
        Private Sub LoadTabPageShadow()
            ReDim tabControl1tabPageShadow(TabControl1.TabPages.Count - 1)
            For Each tabPage In TabControl1.TabPages
                tabControl1tabPageShadow(tabPage.TabIndex) = tabPage
            Next
        End Sub
    
        Private Sub ViewAllReports(sender As Object, e As EventArgs) Handles Button8.Click
            TabControl1.TabPages.Clear()
            For Each tabPage In tabControl1tabPageShadow
                TabControl1.TabPages.Add(tabPage)
            Next
        End Sub
    
    
        Private Sub ViewOperationsReports(sender As Object, e As EventArgs) Handles Button10.Click
            TabControl1.TabPages.Clear()
    
            For tabCount As Integer = 0 To 9
                For Each tabPage In tabControl1tabPageShadow
                    Select Case tabPage.Text
                        Case "Overview"
                            If tabCount = 0 Then TabControl1.TabPages.Add(tabPage)
                        Case "Production Days Under 110%"
                            If tabCount = 1 Then TabControl1.TabPages.Add(tabPage)
                        Case "Screening Status"
                            If tabCount = 2 Then TabControl1.TabPages.Add(tabPage)
                        Case "Rework Status"
                            If tabCount = 3 Then TabControl1.TabPages.Add(tabPage)
                        Case "Secondary by Machine"
                            If tabCount = 4 Then TabControl1.TabPages.Add(tabPage)
                        Case "Secondary Set Ups"
                            If tabCount = 5 Then TabControl1.TabPages.Add(tabPage)
                        Case "Secondary Run Times"
                            If tabCount = 6 Then TabControl1.TabPages.Add(tabPage)
                        Case "Primary Set Ups"
                            If tabCount = 7 Then TabControl1.TabPages.Add(tabPage)
                        Case "Variance"
                            If tabCount = 8 Then TabControl1.TabPages.Add(tabPage)
                        Case "Schedule Changes"
                            If tabCount = 9 Then TabControl1.TabPages.Add(tabPage)
                    End Select
                Next
            Next
    
    
    

    data.map is not a function

    data needs to be Json object, to do so please make sure the follow:

    data = $.parseJSON(data);
    

    Now you can do something like:

    data.map(function (...) {
                ...
            });
    

    I hope this help some one

    GoogleMaps API KEY for testing

    Updated Answer

    As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.

    This answer is no longer valid

    As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.

    Why use pip over easy_install?

    REQUIREMENTS files.

    Seriously, I use this in conjunction with virtualenv every day.


    QUICK DEPENDENCY MANAGEMENT TUTORIAL, FOLKS

    Requirements files allow you to create a snapshot of all packages that have been installed through pip. By encapsulating those packages in a virtualenvironment, you can have your codebase work off a very specific set of packages and share that codebase with others.

    From Heroku's documentation https://devcenter.heroku.com/articles/python

    You create a virtual environment, and set your shell to use it. (bash/*nix instructions)

    virtualenv env
    source env/bin/activate
    

    Now all python scripts run with this shell will use this environment's packages and configuration. Now you can install a package locally to this environment without needing to install it globally on your machine.

    pip install flask
    

    Now you can dump the info about which packages are installed with

    pip freeze > requirements.txt
    

    If you checked that file into version control, when someone else gets your code, they can setup their own virtual environment and install all the dependencies with:

    pip install -r requirements.txt
    

    Any time you can automate tedium like this is awesome.

    can't multiply sequence by non-int of type 'float'

    You're multipling your "1 + 0.01" times the growthRate list, not the item in the list you're iterating through. I've renamed i to rate and using that instead. See the updated code below:

    def nestEgVariable(salary, save, growthRates):
        SavingsRecord = []
        fund = 0
        depositPerYear = salary * save * 0.01
        #    V-- rate is a clearer name than i here, since you're iterating through the rates contained in the growthRates list
        for rate in growthRates:  
            #                           V-- Use the `rate` item in the growthRate list you're iterating through rather than multiplying by the `growthRate` list itself.
            fund = fund * (1 + 0.01 * rate) + depositPerYear
            SavingsRecord += [fund,]
        return SavingsRecord 
    
    
    print nestEgVariable(10000,10,[3,4,5,0,3])
    

    TypeError: $.ajax(...) is not a function?

    Not sure, but it looks like you have a syntax error in your code. Try:

    $.ajax({
      type: 'POST',
      url: url,
      data: postedData,
      dataType: 'json',
      success: callback
    });
    

    You had extra brackets next to $.ajax which were not needed. If you still get the error, then the jQuery script file is not loaded.

    How to declare a constant map in Golang?

    And as suggested above by Siu Ching Pong -Asuka Kenji with the function which in my opinion makes more sense and leaves you with the convenience of the map type without the function wrapper around:

       // romanNumeralDict returns map[int]string dictionary, since the return
           // value is always the same it gives the pseudo-constant output, which
           // can be referred to in the same map-alike fashion.
           var romanNumeralDict = func() map[int]string { return map[int]string {
                1000: "M",
                900:  "CM",
                500:  "D",
                400:  "CD",
                100:  "C",
                90:   "XC",
                50:   "L",
                40:   "XL",
                10:   "X",
                9:    "IX",
                5:    "V",
                4:    "IV",
                1:    "I",
              }
            }
    
            func printRoman(key int) {
              fmt.Println(romanNumeralDict()[key])
            }
    
            func printKeyN(key, n int) {
              fmt.Println(strings.Repeat(romanNumeralDict()[key], n))
            }
    
            func main() {
              printRoman(1000)
              printRoman(50)
              printKeyN(10, 3)
            }
    

    Try this at play.golang.org.

    Getting parts of a URL (Regex)

    I tried this regex for parsing url partitions:

    ^((http[s]?|ftp):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*))(\?([^#]*))?(#(.*))?$
    

    URL: https://www.google.com/my/path/sample/asd-dsa/this?key1=value1&key2=value2

    Matches:

    Group 1.    0-7 https:/
    Group 2.    0-5 https
    Group 3.    8-22    www.google.com
    Group 6.    22-50   /my/path/sample/asd-dsa/this
    Group 7.    22-46   /my/path/sample/asd-dsa/
    Group 8.    46-50   this
    Group 9.    50-74   ?key1=value1&key2=value2
    Group 10.   51-74   key1=value1&key2=value2
    

    Xcode Simulator: how to remove older unneeded devices?

    I wrote up one-line bash script that would delete ALL your simulators:

    xcrun simctl list devices | grep -E -o -i "([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})" | xargs -L1 xcrun simctl delete
    
    • xcrun simctl list devices will list all the simulators installed on your machine
    • grep -E -o -i "([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})" will grab the device UUID
    • xargs -L1 xcrun simctl delete will attempt to delete the device for each UUID it found

    If you want to see everything it'll execute, you can add echo before xcrun, i.e.

    xcrun simctl list devices | grep -E -o -i "([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})" | xargs -L1 echo xcrun simctl delete
    

    How can I get a list of repositories 'apt-get' is checking?

    It seems the closest is:

    apt-cache policy
    

    Comparing Java enum members: == or equals()?

    Both are technically correct. If you look at the source code for .equals(), it simply defers to ==.

    I use ==, however, as that will be null safe.

    Styling twitter bootstrap buttons

    I found the simplest way is to put this in your overrides. Sorry for my unimaginative color choice

    Bootstrap 4-Alpha SASS

    .my-btn {
      //@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
      @include button-variant(red, white, blue);
    }
    

    Bootstrap 4 Alpha SASS Example

    Bootstrap 3 LESS

    .my-btn {
      //.button-variant(@btn-primary-color; @btn-primary-bg; @btn-primary-border);
      .button-variant(red; white; blue);
    }
    

    Bootstrap 3 LESS Example

    Bootstrap 3 SASS

    .my-btn {
      //@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
      @include button-variant(red, white, blue);
    }
    

    Bootstrap 3 SASS Example

    Bootstrap 2.3 LESS

    .btn-primary {
      //.buttonBackground(@btnBackground, @btnBackgroundHighlight, @grayDark, 0 1px 1px rgba(255,255,255,.75));
      .buttonBackground(red, white);
    }
    

    Bootstrap 2.3 LESS Example

    Bootstrap 2.3 SASS

    .btn-primary {
      //@include buttonBackground($btnPrimaryBackground, $btnPrimaryBackgroundHighlight); 
      @include buttonBackground(red, white); 
    }
    

    It will take care of the hover/actives for you

    From the comments, if you want to lighten the button instead of darken when using black (or just want to inverse) you need to extend the class a bit further like so:

    Bootstrap 3 SASS Ligthen

    .my-btn {
      // @include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
      $color: #fff;
      $background: #000;
      $border: #333;
      @include button-variant($color, $background, $border);
      // override the default darkening with lightening
      &:hover,
      &:focus,
      &.focus,
      &:active,
      &.active,
      .open > &.dropdown-toggle {
        color: $color;
        background-color: lighten($background, 20%); //10% default
        border-color: lighten($border, 22%); // 12% default
      }
    }
    

    Bootstrap 3 SASS Lighten Example

    How to detect when facebook's FB.init is complete

    You can subscribe to the event:

    ie)

    FB.Event.subscribe('auth.login', function(response) {
      FB.api('/me', function(response) {
        alert(response.name);
      });
    });
    

    Change a Nullable column to NOT NULL with Default Value

    I think you will need to do this as three separate statements. I've been looking around and everything i've seen seems to suggest you can do it if you are adding a column, but not if you are altering one.

    ALTER TABLE dbo.MyTable
    ADD CONSTRAINT my_Con DEFAULT GETDATE() for created
    
    UPDATE MyTable SET Created = GetDate() where Created IS NULL
    
    ALTER TABLE dbo.MyTable 
    ALTER COLUMN Created DATETIME NOT NULL 
    

    Change the mouse cursor on mouse over to anchor-like style

    If you want to do this in jQuery instead of CSS, you basically follow the same process.

    Assuming you have some <div id="target"></div>, you can use the following code:

    $("#target").hover(function() {
        $(this).css('cursor','pointer');
    }, function() {
        $(this).css('cursor','auto');
    });
    

    and that should do it.

    Change hover color on a button with Bootstrap customization

    The color for your buttons comes from the btn-x classes (e.g., btn-primary, btn-success), so if you want to manually change the colors by writing your own custom css rules, you'll need to change:

    /*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/
    .btn-primary {
        color: #fff;
        background-color: #0495c9;
        border-color: #357ebd; /*set the color you want here*/
    }
    .btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
        color: #fff;
        background-color: #00b3db;
        border-color: #285e8e; /*set the color you want here*/
    }
    

    How do I specify unique constraint for multiple columns in MySQL?

    If you want to avoid duplicates in future. Create another column say id2.

    UPDATE tablename SET id2 = id;
    

    Now add the unique on two columns:

    alter table tablename add unique index(columnname, id2);
    

    Error: Module not specified (IntelliJ IDEA)

    Faced the same issue. To solve it,

    How to start color picker on Mac OS?

    You can call up the color picker from any Cocoa application (TextEdit, Mail, Keynote, Pages, etc.) by hitting Shift-Command-C

    The following article explains more about using Mac OS's Color Picker.

    http://www.macworld.com/article/46746/2005/09/colorpickersecrets.html