Programs & Examples On #Rowdatabound

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

int total = 0;
protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotal");
lblamount.Text = total.ToString();
}
}

How to find Control in TemplateField of GridView?

protected void gvTurnos_RowDataBound(object sender, GridViewRowEventArgs e)
{
    try
    {

        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
        {
            LinkButton btn = (LinkButton)e.Row.FindControl("btnAgregarVacio");
            if (btn != null)
            {
                btn.Visible = rbFiltroEstatusCampus.SelectedValue == "1" ? true : false;
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Getting value from a cell from a gridview on RowDataBound event

use RowDataBound function to bind data with a perticular cell, and to get control use (ASP Control Name like DropDownList) GridView.FindControl("Name of Control")

Controlling mouse with Python

very easy 1- install pakage :

pip install mouse

2- add library to project :

import mouse

3- use it for example :

mouse.right_click()

in this url describe all function that you can use it :

https://github.com/boppreh/mouse

Bash Templating: How to build configuration files from templates with Bash?

A longer but more robust version of the accepted answer:

perl -pe 's;(\\*)(\$([a-zA-Z_][a-zA-Z_0-9]*)|\$\{([a-zA-Z_][a-zA-Z_0-9]*)\})?;substr($1,0,int(length($1)/2)).($2&&length($1)%2?$2:$ENV{$3||$4});eg' template.txt

This expands all instances of $VAR or ${VAR} to their environment values (or, if they're undefined, the empty string).

It properly escapes backslashes, and accepts a backslash-escaped $ to inhibit substitution (unlike envsubst, which, it turns out, doesn't do this).

So, if your environment is:

FOO=bar
BAZ=kenny
TARGET=backslashes
NOPE=engi

and your template is:

Two ${TARGET} walk into a \\$FOO. \\\\
\\\$FOO says, "Delete C:\\Windows\\System32, it's a virus."
$BAZ replies, "\${NOPE}s."

the result would be:

Two backslashes walk into a \bar. \\
\$FOO says, "Delete C:\Windows\System32, it's a virus."
kenny replies, "${NOPE}s."

If you only want to escape backslashes before $ (you could write "C:\Windows\System32" in a template unchanged), use this slightly-modified version:

perl -pe 's;(\\*)(\$([a-zA-Z_][a-zA-Z_0-9]*)|\$\{([a-zA-Z_][a-zA-Z_0-9]*)\});substr($1,0,int(length($1)/2)).(length($1)%2?$2:$ENV{$3||$4});eg' template.txt

How to compare two NSDates: Which is more recent?

Use this simple function for date comparison

-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{

BOOL isTokonValid;

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");
    isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
    isTokonValid = NO;
} else {
    isTokonValid = NO;
    NSLog(@"dates are the same");
}

return isTokonValid;}

Global Variable from a different file Python

Importing file2 in file1.py makes the global (i.e., module level) names bound in file2 available to following code in file1 -- the only such name is SomeClass. It does not do the reverse: names defined in file1 are not made available to code in file2 when file1 imports file2. This would be the case even if you imported the right way (import file2, as @nate correctly recommends) rather than in the horrible, horrible way you're doing it (if everybody under the Sun forgot the very existence of the construct from ... import *, life would be so much better for everybody).

Apparently you want to make global names defined in file1 available to code in file2 and vice versa. This is known as a "cyclical dependency" and is a terrible idea (in Python, or anywhere else for that matter).

So, rather than showing you the incredibly fragile, often unmaintainable hacks to achieve (some semblance of) a cyclical dependency in Python, I'd much rather discuss the many excellent way in which you can avoid such terrible structure.

For example, you could put global names that need to be available to both modules in a third module (e.g. file3.py, to continue your naming streak;-) and import that third module into each of the other two (import file3 in both file1 and file2, and then use file3.foo etc, that is, qualified names, for the purpose of accessing or setting those global names from either or both of the other modules, not barenames).

Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly why you think you need a cyclical dependency (just one easy prediction: no matter what makes you think you need a cyclical dependency, you're wrong;-).

Can you run GUI applications in a Docker container?

The solution given at http://fabiorehm.com/blog/2014/09/11/running-gui-apps-with-docker/ does seem to be an easy way of starting GUI applications from inside the containers ( I tried for firefox over ubuntu 14.04) but I found that a small additional change is required to the solution posted by the author.

Specifically, for running the container, the author has mentioned:

    docker run -ti --rm \
    -e DISPLAY=$DISPLAY \
    -v /tmp/.X11-unix:/tmp/.X11-unix \
    firefox

But I found that (based on a particular comment on the same site) that two additional options

    -v $HOME/.Xauthority:$HOME/.Xauthority

and

    -net=host 

need to be specified while running the container for firefox to work properly:

    docker run -ti --rm \
    -e DISPLAY=$DISPLAY \
    -v /tmp/.X11-unix:/tmp/.X11-unix \
    -v $HOME/.Xauthority:$HOME/.Xauthority \
    -net=host \
    firefox

I have created a docker image with the information on that page and these additional findings: https://hub.docker.com/r/amanral/ubuntu-firefox/

Changing variable names with Python for loops

Use a list.

groups = [0]*3
for i in xrange(3):
    groups[i] = self.getGroup(selected, header + i)

or more "Pythonically":

groups = [self.getGroup(selected, header + i) for i in xrange(3)]

For what it's worth, you could try to create variables the "wrong" way, i.e. by modifying the dictionary which holds their values:

l = locals()
for i in xrange(3):
    l['group' + str(i)] = self.getGroup(selected, header + i)

but that's really bad form, and possibly not even guaranteed to work.

Finishing current activity from a fragment

Every time I use finish to close the fragment, the entire activity closes. According to the docs, fragments should remain as long as the parent activity remains.

Instead, I found that I can change views back the the parent activity by using this statement: setContentView(R.layout.activity_main);

This returns me back to the parent activity.

I hope that this helps someone else who may be looking for this.

Is there an exponent operator in C#?

The C# language doesn't have a power operator. However, the .NET Framework offers the Math.Pow method:

Returns a specified number raised to the specified power.

So your example would look like this:

float Result, Number1, Number2;

Number1 = 2;
Number2 = 2;

Result = Math.Pow(Number1, Number2);

tsql returning a table from a function or store procedure

You don't need (shouldn't use) a function as far as I can tell. The stored procedure will return tabular data from any SELECT statements you include that return tabular data.

A stored proc does not use RETURN statements.

 CREATE PROCEDURE name
 AS

 SELECT stuff INTO #temptbl1

 .......


 SELECT columns FROM #temptbln

Ajax passing data to php script

You can also use bellow code for pass data using ajax.

var dataString = "album" + title;
$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: dataString,
    success: function(response) {
        content.html(response);
    }
});

In Node.js, how do I "include" functions from my other files?

Udo G. said:

  • The eval() can't be used inside a function and must be called inside the global scope otherwise no functions or variables will be accessible (i.e. you can't create a include() utility function or something like that).

He's right, but there's a way to affect the global scope from a function. Improving his example:

function include(file_) {
    with (global) {
        eval(fs.readFileSync(file_) + '');
    };
};

include('somefile_with_some_declarations.js');

// the declarations are now accessible here.

Hope, that helps.

ERROR: Cannot open source file " "

  1. Copy the contents of the file,
  2. Create an .h file, give it the name of the original .h file
  3. Copy the contents of the original file to the newly created one
  4. Build it
  5. VOILA!!

Query to get only numbers from a string

This UDF will work for all types of strings:

CREATE FUNCTION udf_getNumbersFromString (@string varchar(max))
RETURNS varchar(max)
AS
BEGIN
    WHILE  @String like '%[^0-9]%'
    SET    @String = REPLACE(@String, SUBSTRING(@String, PATINDEX('%[^0-9]%', @String), 1), '')
    RETURN @String
END

How to add a spinner icon to button when it's in the Loading state?

These are mine, based on pure SVG and CSS animations. Don't pay attention to JS code in the snippet bellow, it's just for demoing purposes. Feel free to make your custom ones basing on mine, it's super easy.

_x000D_
_x000D_
var svg = d3.select("svg"),_x000D_
    columnsCount = 3;_x000D_
_x000D_
['basic', 'basic2', 'basic3', 'basic4', 'loading', 'loading2', 'spin', 'chrome', 'chrome2', 'flower', 'flower2', 'backstreet_boys'].forEach(function(animation, i){_x000D_
  var x = (i%columnsCount+1) * 200-100,_x000D_
      y = 20 + (Math.floor(i/columnsCount) * 200);_x000D_
  _x000D_
  _x000D_
  svg.append("text")_x000D_
    .attr('text-anchor', 'middle')_x000D_
    .attr("x", x)_x000D_
    .attr("y", y)_x000D_
    .text((i+1)+". "+animation);_x000D_
  _x000D_
  svg.append("circle")_x000D_
    .attr("class", animation)_x000D_
    .attr("cx",  x)_x000D_
    .attr("cy",  y+40)_x000D_
    .attr("r",  16)_x000D_
});
_x000D_
circle {_x000D_
  fill: none;_x000D_
  stroke: #bbb;_x000D_
  stroke-width: 4_x000D_
}_x000D_
_x000D_
.basic {_x000D_
  animation: basic 0.5s linear infinite;_x000D_
  stroke-dasharray: 20 80;_x000D_
}_x000D_
_x000D_
@keyframes basic {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic2 {_x000D_
  animation: basic2 0.5s linear infinite;_x000D_
  stroke-dasharray: 80 20;_x000D_
}_x000D_
_x000D_
@keyframes basic2 {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic3 {_x000D_
  animation: basic3 0.5s linear infinite;_x000D_
  stroke-dasharray: 20 30;_x000D_
}_x000D_
_x000D_
@keyframes basic3 {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic4 {_x000D_
  animation: basic4 0.5s linear infinite;_x000D_
  stroke-dasharray: 10 23.3;_x000D_
}_x000D_
_x000D_
@keyframes basic4 {_x000D_
  0%    {stroke-dashoffset: 100;}_x000D_
  100%  {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.loading {_x000D_
  animation: loading 1s linear infinite;_x000D_
  stroke-dashoffset: 25;_x000D_
}_x000D_
_x000D_
@keyframes loading {_x000D_
  0%    {stroke-dashoffset: 0;    stroke-dasharray: 50 0; }_x000D_
  50%   {stroke-dashoffset: -100; stroke-dasharray: 0 50;}_x000D_
  100%  { stroke-dashoffset: -200;stroke-dasharray: 50 0;}_x000D_
}_x000D_
_x000D_
.loading2 {_x000D_
  animation: loading2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes loading2 {_x000D_
  0% {stroke-dasharray: 5 28.3;   stroke-dashoffset: 75;}_x000D_
  50% {stroke-dasharray: 45 5;    stroke-dashoffset: -50;}_x000D_
  100% {stroke-dasharray: 5 28.3; stroke-dashoffset: -125; }_x000D_
}_x000D_
_x000D_
.spin {_x000D_
  animation: spin 1s linear infinite;_x000D_
  stroke-dashoffset: 25;_x000D_
}_x000D_
_x000D_
@keyframes spin {_x000D_
  0%    {stroke-dashoffset: 0;    stroke-dasharray: 33.3 0; }_x000D_
  50%   {stroke-dashoffset: -100; stroke-dasharray: 0 33.3;}_x000D_
  100%  { stroke-dashoffset: -200;stroke-dasharray: 33.3 0;}_x000D_
}_x000D_
_x000D_
.chrome {_x000D_
  animation: chrome 2s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes chrome {_x000D_
  0%    {stroke-dasharray: 0 100; stroke-dashoffset: 25;}_x000D_
  25%   {stroke-dasharray: 75 25; stroke-dashoffset: 0;}_x000D_
  50%   {stroke-dasharray: 0 100;  stroke-dashoffset: -125;}_x000D_
  75%    {stroke-dasharray: 75 25; stroke-dashoffset: -150;}_x000D_
  100%   {stroke-dasharray: 0 100; stroke-dashoffset: -275;}_x000D_
}_x000D_
_x000D_
.chrome2 {_x000D_
  animation: chrome2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes chrome2 {_x000D_
  0%    {stroke-dasharray: 0 100; stroke-dashoffset: 25;}_x000D_
  25%   {stroke-dasharray: 50 50; stroke-dashoffset: 0;}_x000D_
  50%   {stroke-dasharray: 0 100;  stroke-dashoffset: -50;}_x000D_
  75%   {stroke-dasharray: 50 50;  stroke-dashoffset: -125;}_x000D_
  100%  {stroke-dasharray: 0 100;  stroke-dashoffset: -175;}_x000D_
}_x000D_
_x000D_
.flower {_x000D_
  animation: flower 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes flower {_x000D_
  0%    {stroke-dasharray: 0  20; stroke-dashoffset: 25;}_x000D_
  50%   {stroke-dasharray: 20 0;  stroke-dashoffset: -50;}_x000D_
  100%  {stroke-dasharray: 0 20;  stroke-dashoffset: -125;}_x000D_
}_x000D_
_x000D_
.flower2 {_x000D_
  animation: flower2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes flower2 {_x000D_
  0%    {stroke-dasharray: 5 20;  stroke-dashoffset: 25;}_x000D_
  50%   {stroke-dasharray: 20 5;  stroke-dashoffset: -50;}_x000D_
  100%  {stroke-dasharray: 5 20;  stroke-dashoffset: -125;}_x000D_
}_x000D_
_x000D_
.backstreet_boys {_x000D_
  animation: backstreet_boys 3s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes backstreet_boys {_x000D_
  0%    {stroke-dasharray: 5 28.3;  stroke-dashoffset: -225;}_x000D_
  15%    {stroke-dasharray: 5 28.3;  stroke-dashoffset: -300;}_x000D_
  30%   {stroke-dasharray: 5 20;  stroke-dashoffset: -300;}_x000D_
  45%    {stroke-dasharray: 5 20;  stroke-dashoffset: -375;}_x000D_
  60%   {stroke-dasharray: 5 15;  stroke-dashoffset: -375;}_x000D_
  75%    {stroke-dasharray: 5 15;  stroke-dashoffset: -450;}_x000D_
  90%   {stroke-dasharray: 5 15;  stroke-dashoffset: -525;}_x000D_
  100%   {stroke-dasharray: 5 28.3;  stroke-dashoffset: -925;}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>_x000D_
<svg width="600px" height="700px"></svg>
_x000D_
_x000D_
_x000D_

Also available on CodePen: https://codepen.io/anon/pen/PeRazr

Hexadecimal To Decimal in Shell Script

I have this handy script on my $PATH to filter 0x1337-like; 1337; or "0x1337" lines of input into decimal strings (expanded for clarity):

#!/usr/bin/env bash

while read data; do
  withoutQuotes=`echo ${data} | sed s/\"//g`
  without0x=`echo ${withoutQuotes} | sed s/0x//g`
  clean=${without0x}
  echo $((16#${clean}))
done

What is the function __construct used for?

I Hope this Help:

<?php
    // The code below creates the class
    class Person {
        // Creating some properties (variables tied to an object)
        public $isAlive = true;
        public $firstname;
        public $lastname;
        public $age;

        // Assigning the values
        public function __construct($firstname, $lastname, $age) {
          $this->firstname = $firstname;
          $this->lastname = $lastname;
          $this->age = $age;
        }

        // Creating a method (function tied to an object)
        public function greet() {
          return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
        }
      }

    // Creating a new person called "boring 12345", who is 12345 years old ;-)
    $me = new Person('boring', '12345', 12345);

    // Printing out, what the greet method returns
    echo $me->greet(); 
    ?>

For More Information You need to Go to codecademy.com

How do I calculate percentiles with python/numpy?

check for scipy.stats module:

 scipy.stats.scoreatpercentile

Generating a UUID in Postgres for Insert statement?

The answer by Craig Ringer is correct. Here's a little more info for Postgres 9.1 and later…

Is Extension Available?

You can only install an extension if it has already been built for your Postgres installation (your cluster in Postgres lingo). For example, I found the uuid-ossp extension included as part of the installer for Mac OS X kindly provided by EnterpriseDB.com. Any of a few dozen extensions may be available.

To see if the uuid-ossp extension is available in your Postgres cluster, run this SQL to query the pg_available_extensions system catalog:

SELECT * FROM pg_available_extensions;

Install Extension

To install that UUID-related extension, use the CREATE EXTENSION command as seen in this this SQL:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

Beware: I found the QUOTATION MARK characters around extension name to be required, despite documentation to the contrary.

The SQL standards committee or Postgres team chose an odd name for that command. To my mind, they should have chosen something like "INSTALL EXTENSION" or "USE EXTENSION".

Verify Installation

You can verify the extension was successfully installed in the desired database by running this SQL to query the pg_extension system catalog:

SELECT * FROM pg_extension;

UUID as default value

For more info, see the Question: Default value for UUID column in Postgres

The Old Way

The information above uses the new Extensions feature added to Postgres 9.1. In previous versions, we had to find and run a script in a .sql file. The Extensions feature was added to make installation easier, trading a bit more work for the creator of an extension for less work on the part of the user/consumer of the extension. See my blog post for more discussion.

Types of UUIDs

By the way, the code in the Question calls the function uuid_generate_v4(). This generates a type known as Version 4 where nearly all of the 128 bits are randomly generated. While this is fine for limited use on smaller set of rows, if you want to virtually eliminate any possibility of collision, use another "version" of UUID.

For example, the original Version 1 combines the MAC address of the host computer with the current date-time and an arbitrary number, the chance of collisions is practically nil.

For more discussion, see my Answer on related Question.

Controlling number of decimal digits in print output in R

The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options value as a default.

As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.

Mathematica or Maple will allow you to give as many decimal places as your heart desires.

EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.

On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin (usually 2e-308).

Compare these two analyses.

x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1)  #Should throw an error

x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2)  #ok

In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.


As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr package.

mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")

These are slower and more memory intensive to use than regular (double precision) numeric vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'") or die(mysql_error());

while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}

Sometimes suppressing the query as @mysql_query(your query);

Delete all the queues from RabbitMQ?

This commands deletes all your queues

python rabbitmqadmin.py \
  -H YOURHOST -u guest -p guest -f bash list queues | \
xargs -n1 | \
xargs -I{} \
  python rabbitmqadmin.py -H YOURHOST -u guest -p guest delete queue name={}

This script is super simple because it uses -f bash, which outputs the queues as a list.

Then we use xargs -n1 to split that up into multiple variables

Then we use xargs -I{} that will run the command following, and replace {} in the command.

What does "exited with code 9009" mean during this build?

For me it happened after upgrade nuget packages from one PostSharp version to next one in a big solution (~80 project). I've got compiler errors for projects that have commands in PreBuild events.

'cmd' is not recognized as an internal or external command, operable program or batch file. C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1249,5): error MSB3073: The command "cmd /c C:\GitRepos\main\ServiceInterfaces\DEV.Config\PreBuild.cmd ServiceInterfaces" exited with code 9009.

PATH variable was corrupted becoming too long with multiple repeated paths related to PostSharp.Patterns.Diagnostics. When I closed Visual Studio and opened it again, the problem was fixed.

how to check if a file is a directory or regular file in python?

os.path.isfile("bob.txt") # Does bob.txt exist?  Is it a file, or a directory?
os.path.isdir("bob")

How can I convert a Unix timestamp to DateTime and vice versa?

From Wikipedia:

UTC does not change with a change of seasons, but local time or civil time may change if a time zone jurisdiction observes daylight saving time (summer time). For example, local time on the east coast of the United States is five hours behind UTC during winter, but four hours behind while daylight saving is observed there.

So this is my code:

TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc));
double unixTime = span.TotalSeconds;

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

Access camera from a browser

There is a really cool solution from Danny Markov for that. It uses navigator.getUserMedia method and should work in modern browsers. I have tested it successfully with Firefox and Chrome. IE didn't work:

Here is a demo:

https://tutorialzine.github.io/pwa-photobooth/

Link to Danny Markovs description page:

http://tutorialzine.com/2016/09/everything-you-should-know-about-progressive-web-apps/

Link to GitHub:

https://github.com/tutorialzine/pwa-photobooth/

Appending to an object

jQuery $.extend(obj1, obj2) would merge 2 objects for you, but you should really be using an array.

var alertsObj = {
    1: {app:'helloworld','message'},
    2: {app:'helloagain',message:'another message'}
};

var alertArr = [
    {app:'helloworld','message'},
    {app:'helloagain',message:'another message'}
];

var newAlert = {app:'new',message:'message'};

$.extend(alertsObj, newAlert);
alertArr.push(newAlert);

adb uninstall failed

Try disable "Instant run" from settings window

How to use Javascript to read local text file and read line by line?

Using ES6 the javascript becomes a little cleaner

handleFiles(input) {

    const file = input.target.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
        const file = event.target.result;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.forEach((line) => {
            console.log(line);
        });
    };

    reader.onerror = (event) => {
        alert(event.target.error.name);
    };

    reader.readAsText(file);
}

Can we pass model as a parameter in RedirectToAction?

Yes you can pass the model that you have shown using

return RedirectToAction("GetStudent", "Student", student1 );

assuming student1 is an instance of Student

which will generate the following url (assuming your using the default routes and the value of student1 are ID=4 and Name="Amit")

.../Student/GetStudent/4?Name=Amit

Internally the RedirectToAction() method builds a RouteValueDictionary by using the .ToString() value of each property in the model. However, binding will only work if all the properties in the model are simple properties and it fails if any properties are complex objects or collections because the method does not use recursion. If for example, Student contained a property List<string> Subjects, then that property would result in a query string value of

....&Subjects=System.Collections.Generic.List'1[System.String]

and binding would fail and that property would be null

How does @synchronized lock/unlock in Objective-C?

It just associates a semaphore with every object, and uses that.

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

Nothing above made it work for me. The thing for me is that I was testing a subscription and i forgot SkuType.SUBS, changing it to INAPP for the reserved google test product fixed it.

Importing PNG files into Numpy?

According to the doc, scipy.misc.imread is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread instead.

Example:

import imageio

im = imageio.imread('my_image.png')
print(im.shape)

You can also use imageio to load from fancy sources:

im = imageio.imread('http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png')

Edit:

To load all of the *.png files in a specific folder, you could use the glob package:

import imageio
import glob

for im_path in glob.glob("path/to/folder/*.png"):
     im = imageio.imread(im_path)
     print(im.shape)
     # do whatever with the image here

Get AVG ignoring Null or Zero values

In Case of not considering '0' or 'NULL' in average function. Simply use

AVG(NULLIF(your_column_name,0))

What is a monad?

tl;dr

{-# LANGUAGE InstanceSigs #-}

newtype Id t = Id t

instance Monad Id where
   return :: t -> Id t
   return = Id

   (=<<) :: (a -> Id b) -> Id a -> Id b
   f =<< (Id x) = f x

Prologue

The application operator $ of functions

forall a b. a -> b

is canonically defined

($) :: (a -> b) -> a -> b
f $ x = f x

infixr 0 $

in terms of Haskell-primitive function application f x (infixl 10).

Composition . is defined in terms of $ as

(.) :: (b -> c) -> (a -> b) -> (a -> c)
f . g = \ x -> f $ g x

infixr 9 .

and satisfies the equivalences forall f g h.

     f . id  =  f            :: c -> d   Right identity
     id . g  =  g            :: b -> c   Left identity
(f . g) . h  =  f . (g . h)  :: a -> d   Associativity

. is associative, and id is its right and left identity.

The Kleisli triple

In programming, a monad is a functor type constructor with an instance of the monad type class. There are several equivalent variants of definition and implementation, each carrying slightly different intuitions about the monad abstraction.

A functor is a type constructor f of kind * -> * with an instance of the functor type class.

{-# LANGUAGE KindSignatures #-}

class Functor (f :: * -> *) where
   map :: (a -> b) -> (f a -> f b)

In addition to following statically enforced type protocol, instances of the functor type class must obey the algebraic functor laws forall f g.

       map id  =  id           :: f t -> f t   Identity
map f . map g  =  map (f . g)  :: f a -> f c   Composition / short cut fusion

Functor computations have the type

forall f t. Functor f => f t

A computation c r consists in results r within context c.

Unary monadic functions or Kleisli arrows have the type

forall m a b. Functor m => a -> m b

Kleisi arrows are functions that take one argument a and return a monadic computation m b.

Monads are canonically defined in terms of the Kleisli triple forall m. Functor m =>

(m, return, (=<<))

implemented as the type class

class Functor m => Monad m where
   return :: t -> m t
   (=<<)  :: (a -> m b) -> m a -> m b

infixr 1 =<<

The Kleisli identity return is a Kleisli arrow that promotes a value t into monadic context m. Extension or Kleisli application =<< applies a Kleisli arrow a -> m b to results of a computation m a.

Kleisli composition <=< is defined in terms of extension as

(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
f <=< g = \ x -> f =<< g x

infixr 1 <=<

<=< composes two Kleisli arrows, applying the left arrow to results of the right arrow’s application.

Instances of the monad type class must obey the monad laws, most elegantly stated in terms of Kleisli composition: forall f g h.

   f <=< return  =  f                :: c -> m d   Right identity
   return <=< g  =  g                :: b -> m c   Left identity
(f <=< g) <=< h  =  f <=< (g <=< h)  :: a -> m d   Associativity

<=< is associative, and return is its right and left identity.

Identity

The identity type

type Id t = t

is the identity function on types

Id :: * -> *

Interpreted as a functor,

   return :: t -> Id t
=      id :: t ->    t

    (=<<) :: (a -> Id b) -> Id a -> Id b
=     ($) :: (a ->    b) ->    a ->    b

    (<=<) :: (b -> Id c) -> (a -> Id b) -> (a -> Id c)
=     (.) :: (b ->    c) -> (a ->    b) -> (a ->    c)

In canonical Haskell, the identity monad is defined

newtype Id t = Id t

instance Functor Id where
   map :: (a -> b) -> Id a -> Id b
   map f (Id x) = Id (f x)

instance Monad Id where
   return :: t -> Id t
   return = Id

   (=<<) :: (a -> Id b) -> Id a -> Id b
   f =<< (Id x) = f x

Option

An option type

data Maybe t = Nothing | Just t

encodes computation Maybe t that not necessarily yields a result t, computation that may “fail”. The option monad is defined

instance Functor Maybe where
   map :: (a -> b) -> (Maybe a -> Maybe b)
   map f (Just x) = Just (f x)
   map _ Nothing  = Nothing

instance Monad Maybe where
   return :: t -> Maybe t
   return = Just

   (=<<) :: (a -> Maybe b) -> Maybe a -> Maybe b
   f =<< (Just x) = f x
   _ =<< Nothing  = Nothing

a -> Maybe b is applied to a result only if Maybe a yields a result.

newtype Nat = Nat Int

The natural numbers can be encoded as those integers greater than or equal to zero.

toNat :: Int -> Maybe Nat
toNat i | i >= 0    = Just (Nat i)
        | otherwise = Nothing

The natural numbers are not closed under subtraction.

(-?) :: Nat -> Nat -> Maybe Nat
(Nat n) -? (Nat m) = toNat (n - m)

infixl 6 -?

The option monad covers a basic form of exception handling.

(-? 20) <=< toNat :: Int -> Maybe Nat

List

The list monad, over the list type

data [] t = [] | t : [t]

infixr 5 :

and its additive monoid operation “append”

(++) :: [t] -> [t] -> [t]
(x : xs) ++ ys = x : xs ++ ys
[]       ++ ys = ys

infixr 5 ++

encodes nonlinear computation [t] yielding a natural amount 0, 1, ... of results t.

instance Functor [] where
   map :: (a -> b) -> ([a] -> [b])
   map f (x : xs) = f x : map f xs
   map _ []       = []

instance Monad [] where
   return :: t -> [t]
   return = (: [])

   (=<<) :: (a -> [b]) -> [a] -> [b]
   f =<< (x : xs) = f x ++ (f =<< xs)
   _ =<< []       = []

Extension =<< concatenates ++ all lists [b] resulting from applications f x of a Kleisli arrow a -> [b] to elements of [a] into a single result list [b].

Let the proper divisors of a positive integer n be

divisors :: Integral t => t -> [t]
divisors n = filter (`divides` n) [2 .. n - 1]

divides :: Integral t => t -> t -> Bool
(`divides` n) = (== 0) . (n `rem`)

then

forall n.  let { f = f <=< divisors } in f n   =   []

In defining the monad type class, instead of extension =<<, the Haskell standard uses its flip, the bind operator >>=.

class Applicative m => Monad m where
   (>>=) :: forall a b. m a -> (a -> m b) -> m b

   (>>) :: forall a b. m a -> m b -> m b
   m >> k = m >>= \ _ -> k
   {-# INLINE (>>) #-}

   return :: a -> m a
   return = pure

For simplicity's sake, this explanation uses the type class hierarchy

class              Functor f
class Functor m => Monad m

In Haskell, the current standard hierarchy is

class                  Functor f
class Functor p     => Applicative p
class Applicative m => Monad m

because not only is every monad a functor, but every applicative is a functor and every monad is an applicative, too.

Using the list monad, the imperative pseudocode

for a in (1, ..., 10)
   for b in (1, ..., 10)
      p <- a * b
      if even(p)
         yield p

roughly translates to the do block,

do a <- [1 .. 10]
   b <- [1 .. 10]
   let p = a * b
   guard (even p)
   return p

the equivalent monad comprehension,

[ p | a <- [1 .. 10], b <- [1 .. 10], let p = a * b, even p ]

and the expression

[1 .. 10] >>= (\ a ->
   [1 .. 10] >>= (\ b ->
      let p = a * b in
         guard (even p) >>       -- [ () | even p ] >>
            return p
      )
   )

Do notation and monad comprehensions are syntactic sugar for nested bind expressions. The bind operator is used for local name binding of monadic results.

let x = v in e    =   (\ x -> e)  $  v   =   v  &  (\ x -> e)
do { r <- m; c }  =   (\ r -> c) =<< m   =   m >>= (\ r -> c)

where

(&) :: a -> (a -> b) -> b
(&) = flip ($)

infixl 0 &

The guard function is defined

guard :: Additive m => Bool -> m ()
guard True  = return ()
guard False = fail

where the unit type or “empty tuple”

data () = ()

Additive monads that support choice and failure can be abstracted over using a type class

class Monad m => Additive m where
   fail  :: m t
   (<|>) :: m t -> m t -> m t

infixl 3 <|>

instance Additive Maybe where
   fail = Nothing

   Nothing <|> m = m
   m       <|> _ = m

instance Additive [] where
   fail = []
   (<|>) = (++)

where fail and <|> form a monoid forall k l m.

     k <|> fail  =  k
     fail <|> l  =  l
(k <|> l) <|> m  =  k <|> (l <|> m)

and fail is the absorbing/annihilating zero element of additive monads

_ =<< fail  =  fail

If in

guard (even p) >> return p

even p is true, then the guard produces [()], and, by the definition of >>, the local constant function

\ _ -> return p

is applied to the result (). If false, then the guard produces the list monad’s fail ( [] ), which yields no result for a Kleisli arrow to be applied >> to, so this p is skipped over.

State

Infamously, monads are used to encode stateful computation.

A state processor is a function

forall st t. st -> (t, st)

that transitions a state st and yields a result t. The state st can be anything. Nothing, flag, count, array, handle, machine, world.

The type of state processors is usually called

type State st t = st -> (t, st)

The state processor monad is the kinded * -> * functor State st. Kleisli arrows of the state processor monad are functions

forall st a b. a -> (State st) b

In canonical Haskell, the lazy version of the state processor monad is defined

newtype State st t = State { stateProc :: st -> (t, st) }

instance Functor (State st) where
   map :: (a -> b) -> ((State st) a -> (State st) b)
   map f (State p) = State $ \ s0 -> let (x, s1) = p s0
                                     in  (f x, s1)

instance Monad (State st) where
   return :: t -> (State st) t
   return x = State $ \ s -> (x, s)

   (=<<) :: (a -> (State st) b) -> (State st) a -> (State st) b
   f =<< (State p) = State $ \ s0 -> let (x, s1) = p s0
                                     in  stateProc (f x) s1

A state processor is run by supplying an initial state:

run :: State st t -> st -> (t, st)
run = stateProc

eval :: State st t -> st -> t
eval = fst . run

exec :: State st t -> st -> st
exec = snd . run

State access is provided by primitives get and put, methods of abstraction over stateful monads:

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}

class Monad m => Stateful m st | m -> st where
   get :: m st
   put :: st -> m ()

m -> st declares a functional dependency of the state type st on the monad m; that a State t, for example, will determine the state type to be t uniquely.

instance Stateful (State st) st where
   get :: State st st
   get = State $ \ s -> (s, s)

   put :: st -> State st ()
   put s = State $ \ _ -> ((), s)

with the unit type used analogously to void in C.

modify :: Stateful m st => (st -> st) -> m ()
modify f = do
   s <- get
   put (f s)

gets :: Stateful m st => (st -> t) -> m t
gets f = do
   s <- get
   return (f s)

gets is often used with record field accessors.

The state monad equivalent of the variable threading

let s0 = 34
    s1 = (+ 1) s0
    n = (* 12) s1
    s2 = (+ 7) s1
in  (show n, s2)

where s0 :: Int, is the equally referentially transparent, but infinitely more elegant and practical

(flip run) 34
   (do
      modify (+ 1)
      n <- gets (* 12)
      modify (+ 7)
      return (show n)
   )

modify (+ 1) is a computation of type State Int (), except for its effect equivalent to return ().

(flip run) 34
   (modify (+ 1) >>
      gets (* 12) >>= (\ n ->
         modify (+ 7) >>
            return (show n)
      )
   )

The monad law of associativity can be written in terms of >>= forall m f g.

(m >>= f) >>= g  =  m >>= (\ x -> f x >>= g)

or

do {                 do {                   do {
   r1 <- do {           x <- m;                r0 <- m;
      r0 <- m;   =      do {            =      r1 <- f r0;
      f r0                 r1 <- f x;          g r1
   };                      g r1             }
   g r1                 }
}                    }

Like in expression-oriented programming (e.g. Rust), the last statement of a block represents its yield. The bind operator is sometimes called a “programmable semicolon”.

Iteration control structure primitives from structured imperative programming are emulated monadically

for :: Monad m => (a -> m b) -> [a] -> m ()
for f = foldr ((>>) . f) (return ())

while :: Monad m => m Bool -> m t -> m ()
while c m = do
   b <- c
   if b then m >> while c m
        else return ()

forever :: Monad m => m t
forever m = m >> forever m

Input/Output

data World

The I/O world state processor monad is a reconciliation of pure Haskell and the real world, of functional denotative and imperative operational semantics. A close analogue of the actual strict implementation:

type IO t = World -> (t, World)

Interaction is facilitated by impure primitives

getChar         :: IO Char
putChar         :: Char -> IO ()
readFile        :: FilePath -> IO String
writeFile       :: FilePath -> String -> IO ()
hSetBuffering   :: Handle -> BufferMode -> IO ()
hTell           :: Handle -> IO Integer
. . .              . . .

The impurity of code that uses IO primitives is permanently protocolized by the type system. Because purity is awesome, what happens in IO, stays in IO.

unsafePerformIO :: IO t -> t

Or, at least, should.

The type signature of a Haskell program

main :: IO ()
main = putStrLn "Hello, World!"

expands to

World -> ((), World)

A function that transforms a world.

Epilogue

The category whiches objects are Haskell types and whiches morphisms are functions between Haskell types is, “fast and loose”, the category Hask.

A functor T is a mapping from a category C to a category D; for each object in C an object in D

Tobj :  Obj(C) -> Obj(D)
   f :: *      -> *

and for each morphism in C a morphism in D

Tmor :  HomC(X, Y) -> HomD(Tobj(X), Tobj(Y))
 map :: (a -> b)   -> (f a -> f b)

where X, Y are objects in C. HomC(X, Y) is the homomorphism class of all morphisms X -> Y in C. The functor must preserve morphism identity and composition, the “structure” of C, in D.

                    Tmor    Tobj

      T(id)  =  id        : T(X) -> T(X)   Identity
T(f) . T(g)  =  T(f . g)  : T(X) -> T(Z)   Composition

The Kleisli category of a category C is given by a Kleisli triple

<T, eta, _*>

of an endofunctor

T : C -> C

(f), an identity morphism eta (return), and an extension operator * (=<<).

Each Kleisli morphism in Hask

      f :  X -> T(Y)
      f :: a -> m b

by the extension operator

   (_)* :  Hom(X, T(Y)) -> Hom(T(X), T(Y))
  (=<<) :: (a -> m b)   -> (m a -> m b)

is given a morphism in Hask’s Kleisli category

     f* :  T(X) -> T(Y)
(f =<<) :: m a  -> m b

Composition in the Kleisli category .T is given in terms of extension

 f .T g  =  f* . g       :  X -> T(Z)
f <=< g  =  (f =<<) . g  :: a -> m c

and satisfies the category axioms

       eta .T g  =  g                :  Y -> T(Z)   Left identity
   return <=< g  =  g                :: b -> m c

       f .T eta  =  f                :  Z -> T(U)   Right identity
   f <=< return  =  f                :: c -> m d

  (f .T g) .T h  =  f .T (g .T h)    :  X -> T(U)   Associativity
(f <=< g) <=< h  =  f <=< (g <=< h)  :: a -> m d

which, applying the equivalence transformations

     eta .T g  =  g
     eta* . g  =  g               By definition of .T
     eta* . g  =  id . g          forall f.  id . f  =  f
         eta*  =  id              forall f g h.  f . h  =  g . h  ==>  f  =  g

(f .T g) .T h  =  f .T (g .T h)
(f* . g)* . h  =  f* . (g* . h)   By definition of .T
(f* . g)* . h  =  f* . g* . h     . is associative
    (f* . g)*  =  f* . g*         forall f g h.  f . h  =  g . h  ==>  f  =  g

in terms of extension are canonically given

               eta*  =  id                 :  T(X) -> T(X)   Left identity
       (return =<<)  =  id                 :: m t -> m t

           f* . eta  =  f                  :  Z -> T(U)      Right identity
   (f =<<) . return  =  f                  :: c -> m d

          (f* . g)*  =  f* . g*            :  T(X) -> T(Z)   Associativity
(((f =<<) . g) =<<)  =  (f =<<) . (g =<<)  :: m a -> m c

Monads can also be defined in terms not of Kleislian extension, but a natural transformation mu, in programming called join. A monad is defined in terms of mu as a triple over a category C, of an endofunctor

     T :  C -> C
     f :: * -> *

and two natural tranformations

   eta :  Id -> T
return :: t  -> f t

    mu :  T . T   -> T
  join :: f (f t) -> f t

satisfying the equivalences

       mu . T(mu)  =  mu . mu               :  T . T . T -> T . T   Associativity
  join . map join  =  join . join           :: f (f (f t)) -> f t

      mu . T(eta)  =  mu . eta       =  id  :  T -> T               Identity
join . map return  =  join . return  =  id  :: f t -> f t

The monad type class is then defined

class Functor m => Monad m where
   return :: t -> m t
   join   :: m (m t) -> m t

The canonical mu implementation of the option monad:

instance Monad Maybe where
   return = Just

   join (Just m) = m
   join Nothing  = Nothing

The concat function

concat :: [[a]] -> [a]
concat (x : xs) = x ++ concat xs
concat []       = []

is the join of the list monad.

instance Monad [] where
   return :: t -> [t]
   return = (: [])

   (=<<) :: (a -> [b]) -> ([a] -> [b])
   (f =<<) = concat . map f

Implementations of join can be translated from extension form using the equivalence

     mu  =  id*           :  T . T -> T
   join  =  (id =<<)      :: m (m t) -> m t

The reverse translation from mu to extension form is given by

     f*  =  mu . T(f)     :  T(X) -> T(Y)
(f =<<)  =  join . map f  :: m a -> m b

But why should a theory so abstract be of any use for programming?

The answer is simple: as computer scientists, we value abstraction! When we design the interface to a software component, we want it to reveal as little as possible about the implementation. We want to be able to replace the implementation with many alternatives, many other ‘instances’ of the same ‘concept’. When we design a generic interface to many program libraries, it is even more important that the interface we choose have a variety of implementations. It is the generality of the monad concept which we value so highly, it is because category theory is so abstract that its concepts are so useful for programming.

It is hardly suprising, then, that the generalisation of monads that we present below also has a close connection to category theory. But we stress that our purpose is very practical: it is not to ‘implement category theory’, it is to find a more general way to structure combinator libraries. It is simply our good fortune that mathematicians have already done much of the work for us!

from Generalising Monads to Arrows by John Hughes

unix - count of columns in file

you may try:

head -1 stores.dat | grep -o \|  | wc -l

How to change Angular CLI favicon

as simple and easy as :

  1. add your icon or png in the same directory as favicon
  2. edit .angular-cli.json, in assets remove favicon.ico put yours in place
  3. edit index.html, search favicon and put yours in place
  4. run ng serve again

that's done

Django DB Settings 'Improperly Configured' Error

For people using IntelliJ, with these settings I was able to query from the shell (on windows).

enter image description here

Mean of a column in a data frame, given the column's name

Suppose you have a data frame(say df) with columns "x" and "y", you can find mean of column (x or y) using:

1.Using mean() function

z<-mean(df$x)

2.Using the column name(say x) as a variable using attach() function

 attach(df)
 mean(x)

When done you can call detach() to remove "x"

detach()

3.Using with() function, it lets you use columns of data frame as distinct variables.

 z<-with(df,mean(x))

Relative imports - ModuleNotFoundError: No module named x

Declare correct sys.path list before you call module:

import os, sys

#'/home/user/example/parent/child'
current_path = os.path.abspath('.')

#'/home/user/example/parent'
parent_path = os.path.dirname(current_path)

sys.path.append(parent_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'child.settings')

Detect browser or tab closing

//Detect Browser or Tab Close Events
$(window).on('beforeunload',function(e) {
  e = e || window.event;
  var localStorageTime = localStorage.getItem('storagetime')
  if(localStorageTime!=null && localStorageTime!=undefined){
    var currentTime = new Date().getTime(),
        timeDifference = currentTime - localStorageTime;

    if(timeDifference<25){//Browser Closed
       localStorage.removeItem('storagetime');
    }else{//Browser Tab Closed
       localStorage.setItem('storagetime',new Date().getTime());
    }

  }else{
    localStorage.setItem('storagetime',new Date().getTime());
  }
});

JSFiddle Link

Hi all, I was able to achieve 'Detect Browser and Tab Close Event' clicks by using browser local storage and timestamp. Hope all of you will get solved your problems by using this solution.

After my initial research i found that when we close a browser, the browser will close all the tabs one by one to completely close the browser. Hence, i observed that there will be very little time delay between closing the tabs. So I taken this time delay as my main validation point and able to achieve the browser and tab close event detection.

I tested it on Chrome Browser Version 76.0.3809.132 and found working

:) Vote Up if you found my answer helpful....

How to compute the sum and average of elements in an array?

I think we can do like

var k=elmt.reduce(function(a,b){return parseFloat(a+parseFloat(b));})
var avg=k/elmt.length; 
console.log(avg);

I am using parseFloat twice because when 1) you add (a)9+b("1") number then result will be "91" but we want addition. so i used parseFloat

2)When addition of (a)9+parseFloat("1") happen though result will be "10" but it will be in string which we don't want so again i used parseFloat.

I hope i am clear. Suggestions are welcome

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

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

Run a single test method with maven

To run a single test method in Maven, you need to provide the command as:

mvn test -Dtest=TestCircle#xyz test

where TestCircle is the test class name and xyz is the test method.

Wild card characters also work; both in the method name and class name.

If you're testing in a multi-module project, specify the module that the test is in with -pl <module-name>.

For integration tests use it.test=... option instead of test=...:

mvn -pl <module-name> -Dit.test=TestCircle#xyz integration-test

implements Closeable or implements AutoCloseable

Here is the small example

public class TryWithResource {

    public static void main(String[] args) {
        try (TestMe r = new TestMe()) {
            r.generalTest();
        } catch(Exception e) {
            System.out.println("From Exception Block");
        } finally {
            System.out.println("From Final Block");
        }
    }
}



public class TestMe implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println(" From Close -  AutoCloseable  ");
    }

    public void generalTest() {
        System.out.println(" GeneralTest ");
    }
}

Here is the output:

GeneralTest 
From Close -  AutoCloseable  
From Final Block

Replace multiple characters in one replace call

Use the OR operator (|):

var str = '#this #is__ __#a test###__';
str.replace(/#|_/g,''); // result: "this is a test"

You could also use a character class:

str.replace(/[#_]/g,'');

Fiddle

If you want to replace the hash with one thing and the underscore with another, then you will just have to chain. However, you could add a prototype:

String.prototype.allReplace = function(obj) {
    var retStr = this;
    for (var x in obj) {
        retStr = retStr.replace(new RegExp(x, 'g'), obj[x]);
    }
    return retStr;
};

console.log('aabbaabbcc'.allReplace({'a': 'h', 'b': 'o'}));
// console.log 'hhoohhoocc';

Why not chain, though? I see nothing wrong with that.

SQL Server 2008 - Case / If statements in SELECT Clause

Simple CASE expression:

CASE input_expression 
     WHEN when_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

Searched CASE expression:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

Reference: http://msdn.microsoft.com/en-us/library/ms181765.aspx

Cannot read configuration file due to insufficient permissions

I was running a website at localhost/MyApp built and run through Visual Studio - via a Virtual Directory created by Visual Studio itself.

The "solution" for me was to delete the Virtual Directory and let Visual Studio recreate it.

An error occurred while signing: SignTool.exe not found

  1. Solution Explorer
  2. Your app Right Clik
  3. Propatis
  4. Security
  5. Unchek (Enable ClickOnce Security Settings) Thats Solve..... __:)
  6. https://i.stack.imgur.com/62nKZ.png See

[enter image description here]

How to get the size of a JavaScript object?

I know this is absolutely not the right way to do it, yet it've helped me a few times in the past to get the approx object file size:

Write your object/response to the console or a new tab, copy the results to a new notepad file, save it, and check the file size. The notepad file itself is just a few bytes, so you'll get a fairly accurate object file size.

Finding whether a point lies inside a rectangle or not

I've borrowed from Eric Bainville's answer:

0 <= dot(AB,AM) <= dot(AB,AB) && 0 <= dot(BC,BM) <= dot(BC,BC)

Which in javascript looks like this:

function pointInRectangle(m, r) {
    var AB = vector(r.A, r.B);
    var AM = vector(r.A, m);
    var BC = vector(r.B, r.C);
    var BM = vector(r.B, m);
    var dotABAM = dot(AB, AM);
    var dotABAB = dot(AB, AB);
    var dotBCBM = dot(BC, BM);
    var dotBCBC = dot(BC, BC);
    return 0 <= dotABAM && dotABAM <= dotABAB && 0 <= dotBCBM && dotBCBM <= dotBCBC;
}

function vector(p1, p2) {
    return {
            x: (p2.x - p1.x),
            y: (p2.y - p1.y)
    };
}

function dot(u, v) {
    return u.x * v.x + u.y * v.y; 
}

eg:

var r = {
    A: {x: 50, y: 0},
    B: {x: 0, y: 20},
    C: {x: 10, y: 50},
    D: {x: 60, y: 30}
};

var m = {x: 40, y: 20};

then:

pointInRectangle(m, r); // returns true.

Here's a codepen to draw the output as a visual test :) http://codepen.io/mattburns/pen/jrrprN

enter image description here

How do I install cURL on Windows?

You may find XAMPP at http://www.apachefriends.org/en/xampp.html

http://www.apachefriends.org/en/xampp-windows.html explains XMAPP for Windows.

Yes, there are 3 php.ini files after installation, one is for php4, one is for php5, and one is for apache. Please modify them accordingly.

Show or hide element in React

You set a boolean value in the state (e.g. 'show)', and then do:

var style = {};
if (!this.state.show) {
  style.display = 'none'
}

return <div style={style}>...</div>

Global Events in Angular

DO Not Use EventEmitter for your service communication.

You should use one of the Observable types. I personally like BehaviorSubject.

Simple example:

You can pass initial state, here I passing null

let subject = new BehaviorSubject(null);

When you want to update the subject

subject.next(myObject)

Observe from any service or component and act when it gets new updates.

subject.subscribe(this.YOURMETHOD);

Here is more information..

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

i am going with @Hiren Patel answer but slightly change in android studio 2.2 and later

enter image description here

Alternative to the HTML Bold tag

<p style="font-weight:bold;"></p>

Synchronization vs Lock

Brian Goetz's "Java Concurrency In Practice" book, section 13.3: "...Like the default ReentrantLock, intrinsic locking offers no deterministic fairness guarantees, but the statistical fairness guarantees of most locking implementations are good enough for almost all situations..."

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

You can skip the var declaration and the stringify. Otherwise, that will work just fine.

$.ajax({
    url: '/home/check',
    type: 'POST',
    data: {
        Address1: "423 Judy Road",
        Address2: "1001",
        City: "New York",
        State: "NY",
        ZipCode: "10301",
        Country: "USA"
    },
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert(data.success);
    },
    error: function () {
        alert("error");
    }
});

How to know if .keyup() is a character key (jQuery)

You can't do this reliably with the keyup event. If you want to know something about the character that was typed, you have to use the keypress event instead.

The following example will work all the time in most browsers but there are some edge cases that you should be aware of. For what is in my view the definitive guide on this, see http://unixpapa.com/js/key.html.

$("input").keypress(function(e) {
    if (e.which !== 0) {
        alert("Charcter was typed. It was: " + String.fromCharCode(e.which));
    }
});

keyup and keydown give you information about the physical key that was pressed. On standard US/UK keyboards in their standard layouts, it looks like there is a correlation between the keyCode property of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.

JavaScript get element by name

Note the plural in this method:

document.getElementsByName()

That returns an array of elements, so use [0] to get the first occurence, e.g.

document.getElementsByName()[0]

Python 3 ImportError: No module named 'ConfigParser'

For me the following command worked:

sudo python3 -m pip install mysql-connector

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

I was missing System.Data.Entity dll reference and problem was solved

convert string to date in sql server

if you datatype is datetime of the table.col , then database store data contain two partial : 1 (date) 2 (time)

Just in display data use convert or cast.

Example:

create table #test(part varchar(10),lastTime datetime)
go

insert into #test (part ,lastTime )
values('A','2012-11-05 ')

insert into #test (part ,lastTime )
values('B','2012-11-05 10:30')


go

select * from #test 

A   2012-11-05 00:00:00.000
B   2012-11-05 10:30:00.000

select part,CONVERT (varchar,lastTime,111) from #test

A   2012/11/05
B   2012/11/05

select part,CONVERT (varchar(10),lastTime,20) from #test 

A   2012-11-05
B   2012-11-05

Remove rows with all or some NAs (missing values) in data.frame

Also check complete.cases :

> final[complete.cases(final), ]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
6 ENSG00000221312    0    1    2    3    2

na.omit is nicer for just removing all NA's. complete.cases allows partial selection by including only certain columns of the dataframe:

> final[complete.cases(final[ , 5:6]),]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
4 ENSG00000207604    0   NA   NA    1    2
6 ENSG00000221312    0    1    2    3    2

Your solution can't work. If you insist on using is.na, then you have to do something like:

> final[rowSums(is.na(final[ , 5:6])) == 0, ]
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
4 ENSG00000207604    0   NA   NA    1    2
6 ENSG00000221312    0    1    2    3    2

but using complete.cases is quite a lot more clear, and faster.

How can I get browser to prompt to save password?

I spent a lot of time reading the various answers on this thread, and for me, it was actually something slightly different (related, but different). On Mobile Safari (iOS devices), if the login form is HIDDEN when the page loads, the prompt will not appear (after you show the form then submit it). You can test with the following code, which displays the form 5 seconds after the page load. Remove the JS and the display: none and it works. I am yet to find a solution to this, just posted in case anyone else has the same issue and can not figure out the cause.

JS:

$(function() {
  setTimeout(function() {
    $('form').fadeIn();
  }, 5000);
});

HTML:

<form method="POST" style="display: none;">
  <input name='email' id='email' type='email' placeholder='email' />
  <input name='password' id='password' type='password' placeholder='password' />
  <button type="submit">LOGIN</button>
</form>

What's the most useful and complete Java cheat sheet?

  1. I have personally found the dzone cheatsheet on core java to be really handy in the beginning. However the needs change as we grow and get used to things.

  2. There are a few listed (at the end of the post) in on this java learning resources article too

  3. For the most practical use, in recent past I have found Java API doc to be the best place to cheat code and learn new api. This helps specially when you want to focus on latest version of java.

  4. mkyong - is one my fav places to cheat a lot of code for quick start - http://www.mkyong.com/

  5. And last but not the least, Stackoverflow is king of all small handy code snippets. Just google a stuff you are trying and there is a chance that a page will be top of search results, most of my google search results end at stackoverflow. Many of the common questions are available here - https://stackoverflow.com/questions/tagged/java?sort=frequent

What does <T> denote in C#

It is a Generic Type Parameter.

A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.

For example:

public T[] Reverse<T>(T[] array)
{
    var result = new T[array.Length];
    int j=0;
    for(int i=array.Length - 1; i>= 0; i--)
    {
        result[j] = array[i];
        j++;
    }
    return result;
}

reverses the elements in an array. The key point here is that the array elements can be of any type, and the function will still work. You specify the type in the method call; type safety is still guaranteed.

So, to reverse an array of strings:

string[] array = new string[] { "1", "2", "3", "4", "5" };
var result = reverse(array);

Will produce a string array in result of { "5", "4", "3", "2", "1" }

This has the same effect as if you had called an ordinary (non-generic) method that looks like this:

public string[] Reverse(string[] array)
{
    var result = new string[array.Length];
    int j=0;
    for(int i=array.Length - 1; i >= 0; i--)
    {
        result[j] = array[i];
        j++;
    }
    return result;
}

The compiler sees that array contains strings, so it returns an array of strings. Type string is substituted for the T type parameter.


Generic type parameters can also be used to create generic classes. In the example you gave of a SampleCollection<T>, the T is a placeholder for an arbitrary type; it means that SampleCollection can represent a collection of objects, the type of which you specify when you create the collection.

So:

var collection = new SampleCollection<string>();

creates a collection that can hold strings. The Reverse method illustrated above, in a somewhat different form, can be used to reverse the collection's members.

Press enter in textbox to and execute button command

There are some cases, when textbox will not handle enter key. I think it may be when you have accept button set on form. In that case, instead of KeyDown event you should use textbox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)

Can not get a simple bootstrap modal to work

Try skipping the p tag or replace it with a h3 tag or similar. Replace:

<p>One fine body…</p>

with

<h3>One fine body…</h3>

It worked for me, I don't know why, but it seems the p tag is somehow not fully compatible with some versions of Bootstrap.

How do I compile jrxml to get jasper?

Using Version 5.1.0:

Just click preview and it will create a YourReportName.jasper for you in the same working directory.

How to add an UIViewController's view as subview

As of iOS 5, Apple now allows you to make custom containers for the purpose of adding a UIViewController to another UIViewController particularly via methods such as addChildViewController so it is indeed possible to nest UIViewControllers

EDIT: Including in-place summary so as to avoid link breakage

I quote:

iOS provides many standard containers to help you organize your apps. However, sometimes you need to create a custom workflow that doesn’t match that provided by any of the system containers. Perhaps in your vision, your app needs a specific organization of child view controllers with specialized navigation gestures or animation transitions between them. To do that, you implement a custom container - Tell me more...

...and:

When you design a container, you create explicit parent-child relationships between your container, the parent, and other view controllers, its children - Tell me more

Sample (courtesy of Apple docs) Adding another view controller’s view to the container’s view hierarchy

- (void) displayContentController: (UIViewController*) content
{
   [self addChildViewController:content];                 
   content.view.frame = [self frameForContentController]; 
   [self.view addSubview:self.currentClientView];
   [content didMoveToParentViewController:self];          
}

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

How do I convert an existing callback API to promises?

The Q library by kriskowal includes callback-to-promise functions. A method like this:

obj.prototype.dosomething(params, cb) {
  ...blah blah...
  cb(error, results);
}

can be converted with Q.ninvoke

Q.ninvoke(obj,"dosomething",params).
then(function(results) {
});

Converting a char to ASCII?

You can use chars as is as single byte integers.

Is there a Subversion command to reset the working copy?

Delete unversioned files and revert any changes:

svn revert D:\tmp\sql -R
svn cleanup D:\tmp\sql --remove-unversioned

Out:

D         D:\tmp\sql\update\abc.txt

how to log in to mysql and query the database from linux terminal

I assume you are looking to use mysql client, which is a good thing and much more efficient to use than any phpMyAdmin alternatives.

The proper way to log in with the commandline client is by typing:

mysql -u username -p

Notice I did not type the password. Doing so would of made the password visible on screen, that is not good in multi-user environnment!

After typing this hit enter key, mysql will ask you for your password.

Once logged in, of course you will need:

use databaseName;

to do anything.

Good-luck.

How to read a config file using python

In order to use my example,Your file "abc.txt" needs to look like:

[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"

Then in your software you can use the config parser:

import ConfigParser

and then in you code:

 configParser = ConfigParser.RawConfigParser()   
 configFilePath = r'c:\abc.txt'
 configParser.read(configFilePath)

Use case:

self.path = configParser.get('your-config', 'path1')

*Edit (@human.js)

in python 3, ConfigParser is renamed to configparser (as described here)

html5 input for money/currency

More easy and beautiful if you has vue.js v-money-spinner :)

enter image description here

JavaScript: set dropdown selected item based on option text

A modern alternative:

const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

"/openStudentPage" is the page that i want to open first, i did :

 @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
     return "redirect:/openStudentPage";
    }

@RequestMapping(value = "/openStudentPage", method = RequestMethod.GET)
public String listStudents(Model model) {
    model.addAttribute("student", new Student());
    model.addAttribute("listStudents", this.StudentService.listStudents());
    return "index";
}

How do I find the location of Python module sources?

The sys.path list contains the list of directories which will be searched for modules at runtime:

python -v
>>> import sys
>>> sys.path
['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ]

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

Loop in Jade (currently known as "Pug") template engine

An unusual but pretty way of doing it

Without index:

each _ in Array(5)
  = 'a'

Will print: aaaaa

With index:

each _, i in Array(5)
  = i

Will print: 01234

Notes: In the examples above, I have assigned the val parameter of jade's each iteration syntax to _ because it is required, but will always return undefined.

What does "Git push non-fast-forward updates were rejected" mean?

A fast-forward update is where the only changes one one side are after the most recent commit on the other side, so there doesn't need to be any merging. This is saying that you need to merge your changes before you can push.

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

How to get the response of XMLHttpRequest?

In XMLHttpRequest, using XMLHttpRequest.responseText may raise the exception like below

 Failed to read the \'responseText\' property from \'XMLHttpRequest\': 
 The value is only accessible if the object\'s \'responseType\' is \'\' 
 or \'text\' (was \'arraybuffer\')

Best way to access the response from XHR as follows

function readBody(xhr) {
    var data;
    if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
    } else if (xhr.responseType === "document") {
        data = xhr.responseXML;
    } else {
        data = xhr.response;
    }
    return data;
}

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(readBody(xhr));
    }
}
xhr.open('GET', 'http://www.google.com', true);
xhr.send(null);

Copy a variable's value into another

I do not understand why the answers are so complex. In Javascript, primitives (strings, numbers, etc) are passed by value, and copied. Objects, including arrays, are passed by reference. In any case, assignment of a new value or object reference to 'a' will not change 'b'. But changing the contents of 'a' will change the contents of 'b'.

var a = 'a'; var b = a; a = 'c'; // b === 'a'

var a = {a:'a'}; var b = a; a = {c:'c'}; // b === {a:'a'} and a = {c:'c'}

var a = {a:'a'}; var b = a; a.a = 'c'; // b.a === 'c' and a.a === 'c'

Paste any of the above lines (one at a time) into node or any browser javascript console. Then type any variable and the console will show it's value.

No such keg: /usr/local/Cellar/git

Had a similar issue while installing "Lua" in OS X using homebrew. I guess it could be useful for other users facing similar issue in homebrew.

On running the command:

$ brew install lua

The command returned an error:

Error: /usr/local/opt/lua is not a valid keg
(in general the error can be of /usr/local/opt/ is not a valid keg

FIXED it by deleting the file/directory it is referring to, i.e., deleting the "/usr/local/opt/lua" file.

root-user # rm -rf /usr/local/opt/lua

And then running the brew install command returned success.

Is arr.__len__() the preferred way to get the length of an array in Python?

Python uses duck typing: it doesn't care about what an object is, as long as it has the appropriate interface for the situation at hand. When you call the built-in function len() on an object, you are actually calling its internal __len__ method. A custom object can implement this interface and len() will return the answer, even if the object is not conceptually a sequence.

For a complete list of interfaces, have a look here: http://docs.python.org/reference/datamodel.html#basic-customization

How do I simulate a hover with a touch in touch enabled browsers?

My personal taste is to attribute the :hover styles to the :focus state as well, like:

p {
    color: red;
}

p:hover, p:focus {
    color: blue;
}

Then with the following HTML:

<p id="some-p-tag" tabindex="-1">WOOOO</p>

And the following JavaScript:

$("#some-p-tag").on("touchstart", function(e){
    e.preventDefault();
    var $elem = $(this);

    if($elem.is(":focus")) {
        //this can be registered as a "click" on a mobile device, as it's a double tap
        $elem.blur()
    }
    else {
        $elem.focus();
    }
});

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

ExecuteNonQuery: Connection property has not been initialized.

You are not initializing connection.That's why this kind of error is coming to you.

Your code:

cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ");

Corrected code:

cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ",connection1);

TypeScript error TS1005: ';' expected (II)

I was injecting service like this:

private messageShowService MessageShowService

instead of:

private messageShowService: MessageShowService

and that was the reason of error, despite nothing related with ',' was there.

Byte Array to Image object

If you know the type of image and only want to generate a file, there's no need to get a BufferedImage instance. Just write the bytes to a file with the correct extension.

try (OutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
    out.write(bytes);
}

Creating a "logical exclusive or" operator in Java

Java has a logical AND operator.
Java has a logical OR operator.

Wrong.

Java has

  • two logical AND operators: normal AND is & and short-circuit AND is &&, and
  • two logical OR operators: normal OR is | and short-circuit OR is ||.

XOR exists only as ^, because short-circuit evaluation is not possible.

PHP function to generate v4 UUID

From tom, on http://www.php.net/manual/en/function.uniqid.php

$r = unpack('v*', fread(fopen('/dev/random', 'r'),16));
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
    $r[1], $r[2], $r[3], $r[4] & 0x0fff | 0x4000,
    $r[5] & 0x3fff | 0x8000, $r[6], $r[7], $r[8])

How to create a GUID / UUID

For my use-case, I required id generation that was guaranteed to be unique globally; without exception. I struggled with the problem for a while, and came up with a solution called tuid (Truly Unique ID). It generates an id with the first 32 characters being system-generated and the remaining digits representing milliseconds since epoch. In situations where I need to generate id's on client-side javascript, it works well. Have a look:

https://github.com/mongoh/tuid

Check if element found in array c++

There are many ways...one is to use the std::find() algorithm, e.g.

#include <algorithm>

int myArray[] = { 3, 2, 1, 0, 1, 2, 3 };
size_t myArraySize = sizeof(myArray) / sizeof(int);
int *end = myArray + myArraySize;
// find the value 0:
int *result = std::find(myArray, end, 0);
if (result != end) {
  // found value at "result" pointer location...
}

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

How to calculate mean, median, mode and range from a set of numbers

If you only care about unimodal distributions, consider sth. like this.

public static Optional<Integer> mode(Stream<Integer> stream) {
    Map<Integer, Long> frequencies = stream
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    return frequencies.entrySet().stream()
        .max(Comparator.comparingLong(Map.Entry::getValue))
        .map(Map.Entry::getKey);
}

How to get the date and time values in a C program?

The answers given above are good CRT answers, but if you want you can also use the Win32 solution to this. It's almost identical but IMO if you're programming for Windows you might as well just use its API (although I don't know if you are programming in Windows).

char* arrDayNames[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; 
SYSTEMTIME st;
GetLocalTime(&st); // Alternatively use GetSystemTime for the UTC version of the time
printf("The current date and time are: %d/%d/%d %d:%d:%d:%d", st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
printf("The day is: %s", arrDayNames[st.wDayOfWeek]);

Anyway, this is a Windows solution. I hope it will be helpful for you sometime!

Spring JUnit: How to Mock autowired component in autowired component

I created blog post on the topic. It contains also link to Github repository with working example.

The trick is using test configuration, where you override original spring bean with fake one. You can use @Primary and @Profile annotations for this trick.

Use a cell value in VBA function with a variable

VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.

Dim val1 As Integer, val2 As Integer, i As Integer

For i = 1 To 333

  Sheets("Feuil2").Activate
  ActiveSheet.Cells(i, 1).Select

    val1 = Cells(i, 1).Value
    val2 = Cells(i, 2).Value

Sheets("Classeur2.csv").Select
Cells(val1, val2).Select

ActiveCell.FormulaR1C1 = "1"

Next i

How to open html file?

import codecs
f=codecs.open("test.html", 'r')
print f.read()

Try something like this.

LaTeX beamer: way to change the bullet indentation?

Setting \itemindent for a new itemize environment solves the problem:

\newenvironment{beameritemize}
{ \begin{itemize}
  \setlength{\itemsep}{1.5ex}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}   
  \addtolength{\itemindent}{-2em}  }
{ \end{itemize} } 

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

How to get input text length and validate user in javascript

JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.

var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
    //red
    textBox.style.backgroundColor = "#FF0000";
}
else
{
    //green
    textBox.style.backgroundColor = "#00FF00";
}

Browser Timeouts

You can see the default value in Chrome in this link

int64_t g_used_idle_socket_timeout_s = 300 // 5 minutes

In Chrome, as far as I know, there isn't an easy way (as Firefox do) to change the timeout value.

What represents a double in sql server?

It sounds like you can pick and choose. If you pick float, you may lose 11 digits of precision. If that's acceptable, go for it -- apparently the Linq designers thought this to be a good tradeoff.

However, if your application needs those extra digits, use decimal. Decimal (implemented correctly) is way more accurate than a float anyway -- no messy translation from base 10 to base 2 and back.

How do I check if a variable is of a certain type (compare two types) in C?

C is statically typed language. You can't declare a function which operate on type A or type B, and you can't declare variable which hold type A or type B. Every variable has an explicitly declared and unchangeable type, and you supposed to use this knowledge.

And when you want to know if void * points to memory representation of float or integer - you have to store this information somewhere else. The language is specifically designed not to care if char * points to something stored as int or char.

Angular 2 Sibling Component Communication

There is a discussion about it here.

https://github.com/angular/angular.io/issues/2663

Alex J's answer is good but it no longer works with current Angular 4 as of July, 2017.

And this plunker link would demonstrate how to communicate between siblings using shared service and observable.

https://embed.plnkr.co/P8xCEwSKgcOg07pwDrlO/

How to insert a data table into SQL Server database table?

    //best way to deal with this is sqlbulkcopy 
    //but if you dont like it you can do it like this
    //read current sql table in an adapter
    //add rows of datatable , I have mentioned a simple way of it
    //and finally updating changes

    Dim cnn As New SqlConnection("connection string")        
    cnn.Open()
    Dim cmd As New SqlCommand("select * from  sql_server_table", cnn)
    Dim da As New SqlDataAdapter(cmd)       
    Dim ds As New DataSet()
    da.Fill(ds, "sql_server_table")
    Dim cb As New SqlCommandBuilder(da)        

    //for each datatable row
    ds.Tables("sql_server_table").Rows.Add(COl1, COl2)

    da.Update(ds, "sql_server_table")

Insert json file into mongodb

the following two ways work well:

C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs --file example2.json
C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs < example2.json

if the collections are under a specific user, you can use -u -p --authenticationDatabase

SQL LEFT JOIN Subquery Alias

You didn't select post_id in the subquery. You have to select it in the subquery like this:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 

How do I read from parameters.yml in a controller in symfony2?

In Symfony 2.6 and older versions, to get a parameter in a controller - you should get the container first, and then - the needed parameter.

$this->container->getParameter('api_user');

This documentation chapter explains it.

While $this->get() method in a controller will load a service (doc)

In Symfony 2.7 and newer versions, to get a parameter in a controller you can use the following:

$this->getParameter('api_user');

How to initialize struct?

You use an implicit operator that converts the string value to a struct value:

public struct MyStruct {
  public string s;
  public int length;

  public static implicit operator MyStruct(string value) {
    return new MyStruct() { s = value, length = value.Length };
  }

}

Example:

MyStruct myStruct = "Lol";
Console.WriteLine(myStruct.s);
Console.WriteLine(myStruct.length);

Output:

Lol
3

Deleting all files in a directory with Python

Via os.listdir and os.remove:

import os

filelist = [ f for f in os.listdir(mydir) if f.endswith(".bak") ]
for f in filelist:
    os.remove(os.path.join(mydir, f))

Using only a single loop:

for f in os.listdir(mydir):
    if not f.endswith(".bak"):
        continue
    os.remove(os.path.join(mydir, f))

Or via glob.glob:

import glob, os, os.path

filelist = glob.glob(os.path.join(mydir, "*.bak"))
for f in filelist:
    os.remove(f)

Be sure to be in the correct directory, eventually using os.chdir.

XAMPP - Apache could not start - Attempting to start Apache service

For me it wasn't a port or service issue; I had to re-run the XAMPP setup script. Although this didn't directly fix the issue for me, the script was much more verbose than the XAMPP log, pointing me in the right direction to actually solve the problem.

From the XAMPP GUI, click on Shell, type set, press Tab to autocomplete to the setup_xampp.bat file, and then press Enter to run it.

In my case I got the following output:

[ERROR]: Test php.exe failed !!!
[ERROR]: Perhaps the Microsoft C++ 2008 runtime package is not installed.
[ERROR]: Please try to install the MS VC++ 2008 Redistributable Package from the Mircrosoft page first
[ERROR]: http://www.microsoft.com/en-us/download/details.aspx?id=5582

This particular error is misleading. Although it specifies the Visual C++ 2008 Redistributable Package, PHP 7.4.x requires the Visual C++ 2019 Redistributable Package.

After installing that and following the prompt to restart, sure enough I'm now able to start Apache as normal.

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

hide/show a image in jquery

If you're trying to hide upload img and show bandwidth img on bandwidth click and viceversa this would work

<script>

    function show_img(id)
    {
        if(id=='bandwidth')
        {
           $("#upload").hide();
           $("#bandwith").show();
        }
        else if(id=='upload')
        {
            $("#upload").show();
            $("#bandwith").hide();
        }
    return false;
     } 
    </script>
    <a href="#" onclick="javascript:show_img('bandwidth');">Bandwidth</a>
    <a href="#" onclick="javascript:show_img('upload');">Upload</a>
    <p align="center"> 
      <img src="/media/img/close.png" style="visibility: hidden;" id="bandwidth"/>
      <img src="/media/img/close.png" style="visibility: hidden;" id="upload"/>
    </p>

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

<context:component-scan base-package="" /> 

tells Spring to scan those packages for Annotations.

<mvc:annotation-driven> 

registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.

This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.

You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.

Check out the 3.1 documentation to learn more.

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config

How to print out a variable in makefile

All versions of make require that command lines be indented with a TAB (not space) as the first character in the line. If you showed us the entire rule instead of just the two lines in question we could give a clearer answer, but it should be something like:

myTarget: myDependencies
        @echo hi

where the first character in the second line must be TAB.

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

You are checking Parent properties for null in your delegate. The same should work with lambda expressions too.

List<AnalysisObject> analysisObjects = analysisObjectRepository
        .FindAll()
        .Where(x => 
            (x.ID == packageId) || 
            (x.Parent != null &&
                (x.Parent.ID == packageId || 
                (x.Parent.Parent != null && x.Parent.Parent.ID == packageId)))
        .ToList();

How to use an existing database with an Android application

If you already have a database, keep it in your asset folder and copy it in your application. For more detail, see Android database basics.

error opening trace file: No such file or directory (2)

I think this is the problem

A little background

Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance. Enabling it creates a .trace file in the sdcard root folder which can then be extracted by ADB and processed by traceview bat file for processing. It also can get added by the DDMS.

It is a system used internally by the logger. In general unless you are using traceview to extract the trace file this error shouldnt bother you. You should look at error/logs directly related to your application

How do I enable it:

There are two ways to generate trace logs:

  1. Include the Debug class in your code and call its methods such as startMethodTracing() and stopMethodTracing(), to start and stop logging of trace information to disk. This option is very precise because you can specify exactly where to start and stop logging trace data in your code.

  2. Use the method profiling feature of DDMS to generate trace logs. This option is less precise because you do not modify code, but rather specify when to start and stop logging with DDMS. Although you have less control on exactly where logging starts and stops, this option is useful if you don't have access to the application's code, or if you do not need precise log timing.

But the following restrictions exist for the above

If you are using the Debug class, your application must have permission to write to external storage (WRITE_EXTERNAL_STORAGE).

If you are using DDMS: Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card. Android 2.2 and later devices do not need an SD card. The trace log files are streamed directly to your development machine.

So in essence the traceFile access requires two things

1.) Permission to write a trace log file i.e. WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for good measure

2.) An emulator with an SDCard attached with sufficient space. The doc doesnt say if this is only for DDMS but also for debug, so I am assuming this is also true for debugging via the application.

What do I do with this error:

Now the error is essentially a fall out of either not having the sdcard path to create a tracefile or not having permission to access it. This is an old thread, but the dev behind the bounty, check if are meeting the two prerequisites. You can then go search for the .trace file in the sdcard folder in your emulator. If it exists it shouldn't be giving you this problem, if it doesnt try creating it by adding the startMethodTracing to your app.
I'm not sure why it automatically looks for this file when the logger kicks in. I think when an error/log event occurs , the logger internally tries to write to trace file and does not find it, in which case it throws the error.Having scoured through the docs, I don't find too many references to why this is automatically on. But in general this doesn't affect you directly, you should check direct application logs/errors. Also as an aside Android 2.2 and later devices do not need an SD card for DDMS trace logging. The trace log files are streamed directly to your development machine.

Additional information on Traceview:

Copying Trace Files to a Host Machine

After your application has run and the system has created your trace files .trace on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy the files. Here's an example that shows how to copy an example file, calc.trace, from the default location on the emulator to the /tmp directory on the emulator host machine:

adb pull /sdcard/calc.trace /tmp Viewing Trace Files in Traceview To run Traceview and view the trace files, enter traceview . For example, to run Traceview on the example files copied in the previous section, use:

traceview /tmp/calc Note: If you are trying to view the trace logs of an application that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information on this file, see the Proguard documentation.

I think any other answer regarding positioning of oncreate statements or removing uses-sdk are not related, but this is Android and I could be wrong. Would be useful to redirect this question to an android engineer or post it as a bug

More in the docs

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

You could also do what I do and by a commercial control like this one: http://www.syncfusion.com/products/reporting-edition/xlsio

I have been struging for years before ending with a commercial solution. I first tried the OLEDB approach that is very easy to use in my development environment but can be a knightmare to deploy. Then I tried the open source solutions but most of the are outdated and have bad support.

The xlsio controls from syncfusion are just the ones I use and are happy with but others exists. If you can affort it, do not hesitate, it's the best solution. Why? Because it has no dependencies with the system and supports all version of office right away. Among other advantages like, it's really fast.

And no, I do not work for synfusion ;)

Purpose of returning by const value?

It could be used as a wrapper function for returning a reference to a private constant data type. For example in a linked list you have the constants tail and head, and if you want to determine if a node is a tail or head node, then you can compare it with the value returned by that function.

Though any optimizer would most likely optimize it out anyway...

An invalid XML character (Unicode: 0xc) was found

The character 0x0C is be invalid in XML 1.0 but would be a valid character in XML 1.1. So unless the xml file specifies the version as 1.1 in the prolog it is simply invalid and you should complain to the producer of this file.

Closing a file after File.Create

File.Create returns a FileStream object that you can call Close() on.

What is MVC and what are the advantages of it?

MVC is the separation of model, view and controller — nothing more, nothing less. It's simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class.

For example, while a table grid view should obviously present data once shown, it should not have code on where to retrieve the data from, or what its native structure (the model) is like. Likewise, while it may have a function to sum up a column, the actual summing is supposed to happen in the controller.

A 'save file' dialog (view) ultimately passes the path, once picked by the user, on to the controller, which then asks the model for the data, and does the actual saving.

This separation of responsibilities allows flexibility down the road. For example, because the view doesn't care about the underlying model, supporting multiple file formats is easier: just add a model subclass for each.

Validate phone number using angular js

You can also use ng-pattern and I feel that will be a best practice. Similarly try to use ng-message. Please look the ng-pattern attribute on the following html. The code snippet is partial but hope you understand it.

angular.module('myApp', ['ngMessages']);
angular.module("myApp.controllers",[]).controller("registerCtrl", function($scope, Client) {
  $scope.ph_numbr = /^(\+?(\d{1}|\d{2}|\d{3})[- ]?)?\d{3}[- ]?\d{3}[- ]?\d{4}$/;
});
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
  <div class="form-group" ng-class="{ 'has-error' : (registration.phone.$invalid || registration.phone.$pristine)}">
    <label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
    <div class="col-sm-9">
      <input type="number" class="form-control" ng-pattern="ph_numbr"  id="inputPhone" name="phone" placeholder="Phone" ng-model="user.phone" ng-required="true">
      <div class="help-block" ng-messages="registration.phone.$error">
        <p ng-message="required">Phone number is required.</p>
        <p ng-message="pattern">Phone number is invalid.</p>
      </div>
    </div>
  </div>
</form>

Scrollbar without fixed height/Dynamic height with scrollbar

Flexbox is a modern alternative that lets you do this without fixed heights or JavaScript.

Setting display: flex; flex-direction: column; on the container and flex-shrink: 0; on the header and footer divs does the trick:

HTML:

<div id="body">
    <div id="head">
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>
        <p>Dynamic size without scrollbar</p>  
    </div>
    <div id="content">
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
        <p>Dynamic size with scrollbar</p>
    </div>
    <div id="foot">
        <p>Fixed size without scrollbar</p>
        <p>Fixed size without scrollbar</p>
    </div>  
</div>

CSS:

#body {
    position: absolute;
    top: 150px;
    left: 150px;
    height: 300px;
    width: 500px;
    border: black dashed 2px;
    display: flex;
    flex-direction: column;
}

#head {
    border: green solid 1px;
    flex-shrink: 0;
}

#content{
    border: red solid 1px;
    overflow-y: auto;
    /*height: 100%;*/
}

#foot {
    border: blue solid 1px;
    height: 50px;
    flex-shrink: 0;
}

SQL Server 2012 can't start because of a login failure

This happened to me. A policy on the domain was taking away the SQL Server user account's "Log on as a service" rights. You can work around this using JLo's solution, but does not address the group policy problem specifically and it will return next time the group policies are refreshed on the machine.

The specific policy causing the issue for me was: Under, Computer Configuration -> Windows Settings -> Security Settings -> Local Policies -> User Rights Assignments: Log on as a service

You can see which policies are being applied to your machine by running the command "rsop" from the command line. Follow the path to the policy listed above and you will see its current value as well as which GPO set the value.

C99 stdint.h header and MS Visual Studio

Visual Studio 2003 - 2008 (Visual C++ 7.1 - 9) don't claim to be C99 compatible. (Thanks to rdentato for his comment.)

What does on_delete do on Django models?

Here is answer for your question that says: why we use on_delete?

When an object referenced by a ForeignKey is deleted, Django by default emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey. This behavior can be overridden by specifying the on_delete argument. For example, if you have a nullable ForeignKey and you want it to be set null when the referenced object is deleted:

user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)

The possible values for on_delete are found in django.db.models:

CASCADE: Cascade deletes; the default.

PROTECT: Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

SET_NULL: Set the ForeignKey null; this is only possible if null is True.

SET_DEFAULT: Set the ForeignKey to its default value; a default for the ForeignKey must be set.

Passing data between view controllers

This is a really great tutorial for anyone that wants one. Here is the example code:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"myIdentifer]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        myViewController *destViewController = segue.destinationViewController;
        destViewController.name = [object objectAtIndex:indexPath.row];
    }
}

Accessing the web page's HTTP Headers in JavaScript

Like many people I've been digging the net with no real answer :(

I've nevertheless find out a bypass that could help others. In my case I fully control my web server. In fact it is part of my application (see end reference). It is easy for me to add a script to my http response. I modified my httpd server to inject a small script within every html pages. I only push a extra 'js script' line right after my header construction, that set an existing variable from my document within my browser [I choose location], but any other option is possible. While my server is written in nodejs, I've no doubt that the same technique can be use from PHP or others.

  case ".html":
    response.setHeader("Content-Type", "text/html");
    response.write ("<script>location['GPSD_HTTP_AJAX']=true</script>")
    // process the real contend of my page

Now every html pages loaded from my server, have this script executed by the browser at reception. I can then easily check from JavaScript if the variable exist or not. In my usecase I need to know if I should use JSON or JSON-P profile to avoid CORS issue, but the same technique can be used for other purposes [ie: choose in between development/production server, get from server a REST/API key, etc ....]

On the browser you just need to check variable directly from JavaScript as in my example, where I use it to select my Json/JQuery profile

 // Select direct Ajax/Json profile if using GpsdTracking/HttpAjax server otherwise use JsonP
  var corsbypass = true;  
  if (location['GPSD_HTTP_AJAX']) corsbypass = false;

  if (corsbypass) { // Json & html served from two different web servers
    var gpsdApi = "http://localhost:4080/geojson.rest?jsoncallback=?";
  } else { // Json & html served from same web server [no ?jsoncallback=]
    var gpsdApi = "geojson.rest?";
  }
  var gpsdRqt = 
      {key   :123456789 // user authentication key
      ,cmd   :'list'    // rest command
      ,group :'all'     // group to retreive
      ,round : true     // ask server to round numbers
   };
   $.getJSON(gpsdApi,gpsdRqt, DevListCB);

For who ever would like to check my code: https://www.npmjs.org/package/gpsdtracking

Calculating time difference in Milliseconds

Since Java 1.5, you can get a more precise time value with System.nanoTime(), which obviously returns nanoseconds instead.

There is probably some caching going on in the instances when you get an immediate result.

How to delete items from a dictionary while iterating over it?

With python3, iterate on dic.keys() will raise the dictionary size error. You can use this alternative way:

Tested with python3, it works fine and the Error "dictionary changed size during iteration" is not raised:

my_dic = { 1:10, 2:20, 3:30 }
# Is important here to cast because ".keys()" method returns a dict_keys object.
key_list = list( my_dic.keys() )

# Iterate on the list:
for k in key_list:
    print(key_list)
    print(my_dic)
    del( my_dic[k] )


print( my_dic )
# {}

background-size in shorthand background property (CSS3)

You can do as

 body{
        background:url('equote.png'),url('equote.png');
        background-size:400px 100px,50px 50px;
    }

How do I get an empty array of any size in python?

also you can extend that with extend method of list.

a= []
a.extend([None]*10)
a.extend([None]*20)

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

Your pizza can have exactly three topping types:

  • one type of cheese
  • one type of meat
  • one type of vegetable

So we order two pizzas and choose the following toppings:

Pizza    Topping     Topping Type
-------- ----------  -------------
1        mozzarella  cheese
1        pepperoni   meat
1        olives      vegetable
2        mozzarella  meat
2        sausage     cheese
2        peppers     vegetable

Wait a second, mozzarella can't be both a cheese and a meat! And sausage isn't a cheese!

We need to prevent these sorts of mistakes, to make mozzarella always be cheese. We should use a separate table for this, so we write down that fact in only one place.

Pizza    Topping
-------- ----------
1        mozzarella
1        pepperoni
1        olives
2        mozzarella 
2        sausage
2        peppers

Topping     Topping Type
----------  -------------
mozzarella  cheese
pepperoni   meat
olives      vegetable
sausage     meat
peppers     vegetable

That was the explanation that an 8 year-old might understand. Here is the more technical version.

BCNF acts differently from 3NF only when there are multiple overlapping candidate keys.

The reason is that the functional dependency X -> Y is of course true if Y is a subset of X. So in any table that has only one candidate key and is in 3NF, it is already in BCNF because there is no column (either key or non-key) that is functionally dependent on anything besides that key.

Because each pizza must have exactly one of each topping type, we know that (Pizza, Topping Type) is a candidate key. We also know intuitively that a given topping cannot belong to different types simultaneously. So (Pizza, Topping) must be unique and therefore is also a candidate key. So we have two overlapping candidate keys.

I showed an anomaly where we marked mozarella as the wrong topping type. We know this is wrong, but the rule that makes it wrong is a dependency Topping -> Topping Type which is not a valid dependency for BCNF for this table. It's a dependency on something other than a whole candidate key.

So to solve this, we take Topping Type out of the Pizzas table and make it a non-key attribute in a Toppings table.

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

Tracking changes in Windows registry

PhiLho has mentioned AutoRuns in passing, but I think it deserves elaboration.

It doesn't scan the whole registry, just the parts containing references to things which get loaded automatically (EXEs, DLLs, drivers etc.) which is probably what you are interested in. It doesn't track changes but can export to a text file, so you can run it before and after installation and do a diff.

Auto increment in phpmyadmin

Just run a simple MySQL query and set the auto increment number to whatever you want.

ALTER TABLE `table_name` AUTO_INCREMENT=10000

In terms of a maximum, as far as I am aware there is not one, nor is there any way to limit such number.

It is perfectly safe, and common practice to set an id number as a primiary key, auto incrementing int. There are alternatives such as using PHP to generate membership numbers for you in a specific format and then checking the number does not exist prior to inserting, however for me personally I'd go with the primary id auto_inc value.

problem with php mail 'From' header

I realize this is an old thread, but i had the same problem since i moved to bluehost yesterday. It may not have been the selected answer but i support the bluehost article 206 reply.

I created a valid email in control panel and used it as my From address and it worked.

Transpose a matrix in Python

If we wanted to return the same matrix we would write:

return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]

What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:

[[1,2,3],
[4,5,6],
[7,8,9]]

Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:

[[1,4,7],
[2,5,8],
[3,6,9]]

Therefore just switch the order in which we iterate:

return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]

Difference between h:button and h:commandButton

h:commandButton must be enclosed in a h:form and has the two ways of navigation i.e. static by setting the action attribute and dynamic by setting the actionListener attribute hence it is more advanced as follows:

<h:form>
    <h:commandButton action="page.xhtml" value="cmdButton"/>
</h:form>

this code generates the follwing html:

<form id="j_idt7" name="j_idt7" method="post" action="/jsf/faces/index.xhtml" enctype="application/x-www-form-urlencoded">

whereas the h:button is simpler and just used for static or rule based navigation as follows

<h:button outcome="page.xhtml" value="button"/>

the generated html is

 <title>Facelet Title</title></head><body><input type="button" onclick="window.location.href='/jsf/faces/page.xhtml'; return false;" value="button" />

symfony2 : failed to write cache directory

if symfony version less than 2.8

_x000D_
_x000D_
sudo chmod -R 777 app/cache/*
_x000D_
_x000D_
_x000D_

if symfony version great than or equal 3.0

_x000D_
_x000D_
sudo chmod -R 777 var/cache/*
_x000D_
_x000D_
_x000D_

Calling a Sub in VBA

For anyone still coming to this post, the other option is to simply omit the parentheses:

Sub SomeOtherSub(Stattyp As String)
    'Daty and the other variables are defined here

    CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2

End Sub

The Call keywords is only really in VBA for backwards compatibilty and isn't actually required.

If however, you decide to use the Call keyword, then you have to change your syntax to suit.

'// With Call
Call Foo(Bar)

'// Without Call
Foo Bar

Both will do exactly the same thing.


That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call keyword and the parentheses

Amazon S3 upload file and get URL

Similarly if you want link through s3Client you can use below.

System.out.println("filelink: " + s3Client.getUrl("your_bucket_name", "your_file_key"));

How to set java_home on Windows 7?

if you have not restarted your computer after installing jdk just restart your computer.

if you want to make a portable java and set path before using java, just make a batch file i explained below.

if you want to run this batch file when your computer start just put your batch file shortcut in startup folder. In windows 7 startup folder is "C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

make a batch file like this:

set Java_Home=C:\Program Files\Java\jdk1.8.0_11
set PATH=%PATH%;C:\Program Files\Java\jdk1.8.0_11\bin

note: java_home and path are variables. you can make any variable as you wish. for example set amir=good_boy and you can see amir by %amir% or you can see java_home by %java_home%

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

If you add the android:theme="@style/Theme.AppCompat.Light" to <application> in AndroidManifest.xml file, problem is solving.

Java8: sum values from specific field of the objects in a list

You can do

int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();

or (using Method reference)

int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();

How to use View.OnTouchListener instead of onClick

for use sample touch listener just you need this code

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {

    ClipData data = ClipData.newPlainText("", "");
    View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
    view.startDrag(data, shadowBuilder, null, 0);

    return true;
}

How to write new line character to a file in Java

The BufferedWriter class offers a newLine() method. Using this will ensure platform independence.

Implement Validation for WPF TextBoxes

To get it done only with XAML you need to add Validation Rules for individual properties. But i would recommend you to go with code behind approach. In your code, define your specifications in properties setters and throw exceptions when ever it doesn't compliance to your specifications. And use error template to display your errors to user in UI. Your XAML will look like this

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <Style x:Key="CustomTextBoxTextStyle" TargetType="TextBox">
        <Setter Property="Foreground" Value="Green" />
        <Setter Property="MaxLength" Value="40" />
        <Setter Property="Width" Value="392" />
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="True">
                <Trigger.Setters>
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>
                    <Setter Property="Background" Value="Red"/>
                </Trigger.Setters>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>
<Grid>
    <TextBox Name="tb2" Height="30" Width="400"
             Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}" 
             Style="{StaticResource CustomTextBoxTextStyle}"/>
</Grid>

Code Behind:

public partial class MainWindow : Window
{
    private ExampleViewModel m_ViewModel;
    public MainWindow()
    {
        InitializeComponent();
        m_ViewModel = new ExampleViewModel();
        DataContext = m_ViewModel;
    }
}


public class ExampleViewModel : INotifyPropertyChanged
{
    private string m_Name = "Type Here";
    public ExampleViewModel()
    {

    }

    public string Name
    {
        get
        {
            return m_Name;
        }
        set
        {
            if (String.IsNullOrEmpty(value))
            {
                throw new Exception("Name can not be empty.");
            }
            if (value.Length > 12)
            {
                throw new Exception("name can not be longer than 12 charectors");
            }
            if (m_Name != value)
            {
                m_Name = value;
                OnPropertyChanged("Name");
            }
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}

How to get browser width using JavaScript code?

Update for 2017

My original answer was written in 2009. While it still works, I'd like to update it for 2017. Browsers can still behave differently. I trust the jQuery team to do a great job at maintaining cross-browser consistency. However, it's not necessary to include the entire library. In the jQuery source, the relevant portion is found on line 37 of dimensions.js. Here it is extracted and modified to work standalone:

_x000D_
_x000D_
function getWidth() {_x000D_
  return Math.max(_x000D_
    document.body.scrollWidth,_x000D_
    document.documentElement.scrollWidth,_x000D_
    document.body.offsetWidth,_x000D_
    document.documentElement.offsetWidth,_x000D_
    document.documentElement.clientWidth_x000D_
  );_x000D_
}_x000D_
_x000D_
function getHeight() {_x000D_
  return Math.max(_x000D_
    document.body.scrollHeight,_x000D_
    document.documentElement.scrollHeight,_x000D_
    document.body.offsetHeight,_x000D_
    document.documentElement.offsetHeight,_x000D_
    document.documentElement.clientHeight_x000D_
  );_x000D_
}_x000D_
_x000D_
console.log('Width:  ' +  getWidth() );_x000D_
console.log('Height: ' + getHeight() );
_x000D_
_x000D_
_x000D_


Original Answer

Since all browsers behave differently, you'll need to test for values first, and then use the correct one. Here's a function that does this for you:

function getWidth() {
  if (self.innerWidth) {
    return self.innerWidth;
  }

  if (document.documentElement && document.documentElement.clientWidth) {
    return document.documentElement.clientWidth;
  }

  if (document.body) {
    return document.body.clientWidth;
  }
}

and similarly for height:

function getHeight() {
  if (self.innerHeight) {
    return self.innerHeight;
  }

  if (document.documentElement && document.documentElement.clientHeight) {
    return document.documentElement.clientHeight;
  }

  if (document.body) {
    return document.body.clientHeight;
  }
}

Call both of these in your scripts using getWidth() or getHeight(). If none of the browser's native properties are defined, it will return undefined.

UNIX export command

When you execute a program the child program inherits its environment variables from the parent. For instance if $HOME is set to /root in the parent then the child's $HOME variable is also set to /root.

This only applies to environment variable that are marked for export. If you set a variable at the command-line like

$ FOO="bar"

That variable will not be visible in child processes. Not unless you export it:

$ export FOO

You can combine these two statements into a single one in bash (but not in old-school sh):

$ export FOO="bar"

Here's a quick example showing the difference between exported and non-exported variables. To understand what's happening know that sh -c creates a child shell process which inherits the parent shell's environment.

$ FOO=bar
$ sh -c 'echo $FOO'

$ export FOO
$ sh -c 'echo $FOO'
bar

Note: To get help on shell built-in commands use help export. Shell built-ins are commands that are part of your shell rather than independent executables like /bin/ls.

dotnet ef not found in .NET Core 3

For me, The problem was solved after I close Visual Studio and Open it again

Spring Boot, Spring Data JPA with multiple DataSources

I checked the source code you provided on GitHub. There were several mistakes / typos in the configuration.

In CustomerDbConfig / OrderDbConfig you should refer to customerEntityManager and packages should point at existing packages:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "customerEntityManager",
    transactionManagerRef = "customerTransactionManager",
    basePackages = {"com.mm.boot.multidb.repository.customer"})
public class CustomerDbConfig {

The packages to scan in customerEntityManager and orderEntityManager were both not pointing at proper package:

em.setPackagesToScan("com.mm.boot.multidb.model.customer");

Also the injection of proper EntityManagerFactory did not work. It should be:

@Bean(name = "customerTransactionManager")
public PlatformTransactionManager transactionManager(EntityManagerFactory customerEntityManager){

}

The above was causing the issue and the exception. While providing the name in a @Bean method you are sure you get proper EMF injected.

The last thing I have done was to disable to automatic configuration of JpaRepositories:

@EnableAutoConfiguration(exclude = JpaRepositoriesAutoConfiguration.class)

And with all fixes the application starts as you probably expect!

CakePHP find method with JOIN

        $services = $this->Service->find('all', array(
            'limit' =>4,
            'fields' => array('Service.*','ServiceImage.*'),
            'joins' => array(
                array(
                        'table' => 'services_images',
                        'alias' => 'ServiceImage',
                        'type' => 'INNER',
                        'conditions' => array(
                        'ServiceImage.service_id' =>'Service.id'
                        )
                    ),
                ),
            )
        );

It goges to array is null.

Laravel form html with PUT method for PUT routes

You CAN add css clases, and any type of attributes you need to blade template, try this:

{{ Form::open(array('url' => '/', 'method' => 'PUT', 'class'=>'col-md-12')) }}
.... wathever code here
{{ Form::close() }}

If you dont want to go the blade way you can add a hidden input. This is the form Laravel does, any way:

Note: Since HTML forms only support POST and GET, PUT and DELETE methods will be spoofed by automatically adding a _method hidden field to your form. (Laravel docs)

<form class="col-md-12" action="<?php echo URL::to('/');?>/post/<?=$post->postID?>" method="POST">

    <!-- Rendered blade HTML form use this hidden. Dont forget to put the form method to POST -->

    <input name="_method" type="hidden" value="PUT">

    <div class="form-group">
        <textarea type="text" class="form-control input-lg" placeholder="Text Here" name="post"><?=$post->post?></textarea>
    </div>

    <div class="form-group">
        <button class="btn btn-primary btn-lg btn-block" type="submit" value="Edit">Edit</button>
    </div>
</form>

Java: Insert multiple rows into MySQL with PreparedStatement

When MySQL driver is used you have to set connection param rewriteBatchedStatements to true ( jdbc:mysql://localhost:3306/TestDB?**rewriteBatchedStatements=true**).

With this param the statement is rewritten to bulk insert when table is locked only once and indexes are updated only once. So it is much faster.

Without this param only advantage is cleaner source code.

How to embed a SWF file in an HTML page?

How about simple HTML5 tag embed?

<!DOCTYPE html>
<html>
<body>

<embed src="anim.swf">

</body>
</html>

How to change owner of PostgreSql database?

ALTER DATABASE name OWNER TO new_owner;

See the Postgresql manual's entry on this for more details.

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Does VBA have Dictionary Structure?

Yes. For VB6, VBA (Excel), and VB.NET

How to automatically select all text on focus in WPF TextBox?

The simplist and perfect solution, is to use a timer to select all text 20ms after textbox got focus:

Dim WithEvents Timer As New DispatcherTimer()

Set the interval: Timer.Interval = TimeSpan.FromMilliseconds(20)

respond to events (I am inheriting the TextBox control here, so I am overriding its events:

Protected Overrides Sub OnGotFocus(e As RoutedEventArgs)
        Timer.Start()
        MyBase.OnGotFocus(e)
    End Sub


    Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
        Timer.Stop()
        Me.SelectAll()
    End Sub

And that is all!

Pass a datetime from javascript to c# (Controller)

The following format should work:

$.ajax({
    type: "POST",
    url: "@Url.Action("refresh", "group")",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ 
        myDate: '2011-04-02 17:15:45'
    }),
    success: function (result) {
        //do something
    },
    error: function (req, status, error) {
        //error                        
    }
});

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Requires PHP5.3:

$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');

$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("l Y-m-d H:i:s\n");
}

This will output all days in the defined period between $start and $end. If you want to include the 10th, set $end to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod.

Python Pandas Counting the Occurrences of a Specific value

easy but not efficient:

list(df.education).count('9th')

Android camera intent

I found a pretty simple way to do this. Use a button to open it using an on click listener to start the function openc(), like this:

String fileloc;
private void openc()
{
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File f = null;
    try 
    {
        f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {               
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
            fileloc = Uri.fromFile(f)+"";
            Log.d("texts", "openc: "+fileloc);
            startActivityForResult(takePictureIntent, 3);
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 3 && resultCode == RESULT_OK) {
        Log.d("texts", "onActivityResult: "+fileloc);
        // fileloc is the uri of the file so do whatever with it
    }
}

You can do whatever you want with the uri location string. For instance, I send it to an image cropper to crop the image.

Is there a way to reset IIS 7.5 to factory settings?

There are automatic backup under %systemdrive%\inetpub\history but it may not help much if you already made lots of changes.

http://blogs.iis.net/bills/archive/2008/03/24/how-to-backup-restore-iis7-configuration.aspx

You will have to regularly back up manually using appcmd.

If you try to reinstall IIS, please first uninstall IIS and WAS via Add/Remove Programs, and then delete all existing files under C:\inetpub and C:\Windows\system32\inetsrv directories. Then you can install again cleanly.

WARN: beginners on IIS are not recommended to execute the steps above without a full backup of the system. The steps should be executed with caution and good understanding of IIS. If you are not capable of or you have doubt, make sure you open a support case with Microsoft via http://support.microsoft.com and consult.

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

The answer actually depends on your specific requirements.

For instance, do you need to protect your web messages or confidentiality is not required and all you need is to authenticate end parties and ensure message integrity? If this is the case - and it often is with web services - HTTPS is probably the wrong hammer.

However - from my experience - do not overlook the complexity of the system you're building. Not only HTTPS is easier to deploy correctly, but an application that relies on the transport layer security is easier to debug (over plain HTTP).

Good luck.

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

On macOS High Sierra, this solved my issue:

sudo gem update --system -n /usr/local/bin/gem

Practical uses for AtomicInteger

If you look at the methods AtomicInteger has, you'll notice that they tend to correspond to common operations on ints. For instance:

static AtomicInteger i;

// Later, in a thread
int current = i.incrementAndGet();

is the thread-safe version of this:

static int i;

// Later, in a thread
int current = ++i;

The methods map like this:
++i is i.incrementAndGet()
i++ is i.getAndIncrement()
--i is i.decrementAndGet()
i-- is i.getAndDecrement()
i = x is i.set(x)
x = i is x = i.get()

There are other convenience methods as well, like compareAndSet or addAndGet

Android offline documentation and sample codes

here is direct link for api 17 documentation. Just extract at under docs folder. Hope it helps.

https://dl-ssl.google.com/android/repository/docs-17_r02.zip   (129 MB)

How to measure elapsed time in Python?

Here are my findings after going through many good answers here as well as a few other articles.

First, if you are debating between timeit and time.time, the timeit has two advantages:

  1. timeit selects the best timer available on your OS and Python version.
  2. timeit disables garbage collection, however, this is not something you may or may not want.

Now the problem is that timeit is not that simple to use because it needs setup and things get ugly when you have a bunch of imports. Ideally, you just want a decorator or use with block and measure time. Unfortunately, there is nothing built-in available for this so you have two options:

Option 1: Use timebudget library

The timebudget is a versatile and very simple library that you can use just in one line of code after pip install.

@timebudget  # Record how long this function takes
def my_method():
    # my code

Option 2: Use my small module

I created below little timing utility module called timing.py. Just drop this file in your project and start using it. The only external dependency is runstats which is again small.

Now you can time any function just by putting a decorator in front of it:

import timing

@timing.MeasureTime
def MyBigFunc():
    #do something time consuming
    for i in range(10000):
        print(i)

timing.print_all_timings()

If you want to time portion of code then just put it inside with block:

import timing

#somewhere in my code

with timing.MeasureBlockTime("MyBlock"):
    #do something time consuming
    for i in range(10000):
        print(i)

# rest of my code

timing.print_all_timings()

Advantages:

There are several half-backed versions floating around so I want to point out few highlights:

  1. Use timer from timeit instead of time.time for reasons described earlier.
  2. You can disable GC during timing if you want.
  3. Decorator accepts functions with named or unnamed params.
  4. Ability to disable printing in block timing (use with timing.MeasureBlockTime() as t and then t.elapsed).
  5. Ability to keep gc enabled for block timing.

Removing Data From ElasticSearch

You can delete an index in python as follows

from elasticsearch import Elasticsearch

es = Elasticsearch([{'host':'localhost', 'port':'9200'}])

es.index(index='grades',doc_type='ist_samester',id=1,body={
    "Name":"Programming Fundamentals",
    "Grade":"A"
})

es.indices.delete(index='grades')

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

The simplest way is

<li class="{{ Request::is('contacts/*') ? 'active' : '' }}">Dashboard</li>

This colud capture the contacts/, contacts/create, contacts/edit...

ConcurrentHashMap vs Synchronized HashMap

As per java doc's

Hashtable and Collections.synchronizedMap(new HashMap()) are synchronized. But ConcurrentHashMap is "concurrent".

A concurrent collection is thread-safe, but not governed by a single exclusion lock.

In the particular case of ConcurrentHashMap, it safely permits any number of concurrent reads as well as a tunable number of concurrent writes. "Synchronized" classes can be useful when you need to prevent all access to a collection via a single lock, at the expense of poorer scalability.

In other cases in which multiple threads are expected to access a common collection, "concurrent" versions are normally preferable. And unsynchronized collections are preferable when either collections are unshared, or are accessible only when holding other locks.

How to redirect Valgrind's output to a file?

You can also set the options --log-fd if you just want to read your logs with a less. For example :

valgrind --log-fd=1 ls | less

Get the system date and split day, month and year

Here is what you are looking for:

String sDate = DateTime.Now.ToString();
DateTime datevalue = (Convert.ToDateTime(sDate.ToString()));

String dy = datevalue.Day.ToString();
String mn = datevalue.Month.ToString();
String yy = datevalue.Year.ToString();

OR

Alternatively, you can use split function to split string date into day, month and year here.

Hope, it will helps you... Cheers. !!

Unable to execute dex: method ID not in [0, 0xffff]: 65536

The below code helps, if you use Gradle. Allows you to easily remove unneeded Google services (presuming you're using them) to get back below the 65k threshold. All credit to this post: https://gist.github.com/dmarcato/d7c91b94214acd936e42

Edit 2014-10-22: There's been a lot of interesting discussion on the gist referenced above. TLDR? look at this one: https://gist.github.com/Takhion/10a37046b9e6d259bb31

Paste this code at the bottom of your build.gradle file and adjust the list of google services you do not need:

def toCamelCase(String string) {
    String result = ""
    string.findAll("[^\\W]+") { String word ->
        result += word.capitalize()
    }
    return result
}

afterEvaluate { project ->
    Configuration runtimeConfiguration = project.configurations.getByName('compile')
    ResolutionResult resolution = runtimeConfiguration.incoming.resolutionResult
    // Forces resolve of configuration
    ModuleVersionIdentifier module = resolution.getAllComponents().find { it.moduleVersion.name.equals("play-services") }.moduleVersion

    String prepareTaskName = "prepare${toCamelCase("${module.group} ${module.name} ${module.version}")}Library"
    File playServiceRootFolder = project.tasks.find { it.name.equals(prepareTaskName) }.explodedDir

    Task stripPlayServices = project.tasks.create(name: 'stripPlayServices', group: "Strip") {
        inputs.files new File(playServiceRootFolder, "classes.jar")
        outputs.dir playServiceRootFolder
        description 'Strip useless packages from Google Play Services library to avoid reaching dex limit'

        doLast {
            copy {
                from(file(new File(playServiceRootFolder, "classes.jar")))
                into(file(playServiceRootFolder))
                rename { fileName ->
                    fileName = "classes_orig.jar"
                }
            }
            tasks.create(name: "stripPlayServices" + module.version, type: Jar) {
                destinationDir = playServiceRootFolder
                archiveName = "classes.jar"
                from(zipTree(new File(playServiceRootFolder, "classes_orig.jar"))) {
                    exclude "com/google/ads/**"
                    exclude "com/google/android/gms/analytics/**"
                    exclude "com/google/android/gms/games/**"
                    exclude "com/google/android/gms/plus/**"
                    exclude "com/google/android/gms/drive/**"
                    exclude "com/google/android/gms/ads/**"
                }
            }.execute()
            delete file(new File(playServiceRootFolder, "classes_orig.jar"))
        }
    }

    project.tasks.findAll { it.name.startsWith('prepare') && it.name.endsWith('Dependencies') }.each { Task task ->
        task.dependsOn stripPlayServices
    }
}

How to check if AlarmManager already has an alarm set?

    Intent intent = new Intent("com.my.package.MY_UNIQUE_ACTION");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    sqlitewraper.context, 0, intent,
                    PendingIntent.FLAG_NO_CREATE);

FLAG_NO_CREATE is not create pending intent so that it gives boolean value false.

            boolean alarmUp = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
                    new Intent("com.my.package.MY_UNIQUE_ACTION"),
                    PendingIntent.FLAG_NO_CREATE) != null);

            if (alarmUp) {
                System.out.print("k");

            }

            AlarmManager alarmManager = (AlarmManager) sqlitewraper.context
                    .getSystemService(Context.ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis(), 1000 * 60, pendingIntent);

After the AlarmManager check the value of Pending Intent it gives true because AlarmManager Update The Flag of Pending Intent.

            boolean alarmUp1 = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
                    new Intent("com.my.package.MY_UNIQUE_ACTION"),
                    PendingIntent.FLAG_UPDATE_CURRENT) != null);
            if (alarmUp1) {
                System.out.print("k");

            }

C++ string to double conversion

You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.

With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)

#include <stdlib.h>

int main()
{
    string word;  
    openfile >> word;
    double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
                                     previously (the function requires it)*/
    return 0;
}

Calling the base class constructor from the derived class constructor

The constructor of PetStore will call a constructor of Farm; there's no way you can prevent it. If you do nothing (as you've done), it will call the default constructor (Farm()); if you need to pass arguments, you'll have to specify the base class in the initializer list:

PetStore::PetStore()
    : Farm( neededArgument )
    , idF( 0 )
{
}

(Similarly, the constructor of PetStore will call the constructor of nameF. The constructor of a class always calls the constructors of all of its base classes and all of its members.)

JPA EntityManager: Why use persist() over merge()?

Going through the answers there are some details missing regarding `Cascade' and id generation. See question

Also, it is worth mentioning that you can have separate Cascade annotations for merging and persisting: Cascade.MERGE and Cascade.PERSIST which will be treated according to the used method.

The spec is your friend ;)

How do I set the time zone of MySQL?

To set the standard time zone at MariaDB you have to go to the 50-server.cnf file.

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

Then you can enter the following entry in the mysqld section.

default-time-zone='+01:00'

Example:

#
# These groups are read by MariaDB server.
# Use it for options that only the server (but not clients) should see
#
# See the examples of server my.cnf files in /usr/share/mysql/
#

# this is read by the standalone daemon and embedded servers
[server]

# this is only for the mysqld standalone daemon
[mysqld]

#
# * Basic Settings
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking

### Default timezone ###
default-time-zone='+01:00'

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.

The change must be made via the configuration file, otherwise the MariaDB server will reset the mysql tables after a restart!

jQuery hasAttr checking to see if there is an attribute on an element

You can also use it with attributes such as disabled="disabled" on the form fields etc. like so:

$("#change_password").click(function() {
    var target = $(this).attr("rel");
    if($("#" + target).attr("disabled")) {
        $("#" + target).attr("disabled", false);
    } else {
        $("#" + target).attr("disabled", true);
    }
});

The "rel" attribute stores the id of the target input field.

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

A similar case solved:

In our case, we wanted to set up linked servers using cnames and with the logins current security context.

All in order we checked that the service account running SQL Server had its' proper spns set and that the AD-object was trusted for delegation. But, while we were able to connect to the cname directly, we still had issues calling a linked server on its' cname: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.

It took us far too long to realize that the cnames we used was for A-record, [A], that was set on a higher dns level, and not in its' own domain AD-level. Originally, we had the cname directing to [A].example.com and not (where it should) to: [A].domain.ad.example.com

Ofcourse we had these errors about anonymous logon.

Closing Excel Application using VBA

Sub button2_click()
'
' Button2_Click Macro
'
' Keyboard Shortcut: Ctrl+Shift+Q
'
    ActiveSheet.Shapes("Button 2").Select
    Selection.Characters.Text = "Logout"
    ActiveSheet.Shapes("Button 2").Select
    Selection.OnAction = "Button2_Click"
    ActiveWorkbook.Saved = True
    ActiveWorkbook.Save
    Application.Quit
End Sub

css width: calc(100% -100px); alternative using jquery

If you want to use calc in your CSS file use a polyfill like PolyCalc. Should be light enough to work on mobile browsers (e.g. below iOS 6 and below Android 4.4 phones).

PostgreSQL database default location on Linux

I think best method is to query pg_setting view:

 select s.name, s.setting, s.short_desc from pg_settings s where s.name='data_directory';

Output:

      name      |        setting         |            short_desc
----------------+------------------------+-----------------------------------
 data_directory | /var/lib/pgsql/10/data | Sets the server's data directory.
(1 row)

regex match any single character (one character only)

Simple answer

If you want to match single character, put it inside those brackets [ ]

Examples

  • match + ...... [+] or +
  • match a ...... a
  • match & ...... &

...and so on. You can check your regular expresion online on this site: https://regex101.com/

(updated based on comment)