Programs & Examples On #Rowcount

count number of rows in a data frame in R based on group

Using the example data set that Ananda dummied up, here's an example using aggregate(), which is part of core R. aggregate() just needs something to count as function of the different values of MONTH-YEAR. In this case, I used VALUE as the thing to count:

aggregate(cbind(count = VALUE) ~ MONTH.YEAR, 
          data = mydf, 
          FUN = function(x){NROW(x)})

which gives you..

  MONTH.YEAR count
1  FEB. 2012     2
2  JAN. 2012     2
3  MAR. 2012     1

How to fetch the row count for all tables in a SQL SERVER database

select all rows from the information_schema.tables view, and issue a count(*) statement for each entry that has been returned from that view.

declare c_tables cursor fast_forward for
select table_name from information_schema.tables

open c_tables
declare @tablename varchar(255)
declare @stmt nvarchar(2000)
declare @rowcount int
fetch next from c_tables into @tablename

while @@fetch_status = 0
begin

    select @stmt = 'select @rowcount = count(*) from ' + @tablename

    exec sp_executesql @stmt, N'@rowcount int output', @rowcount=@rowcount OUTPUT

    print N'table: ' + @tablename + ' has ' + convert(nvarchar(1000),@rowcount) + ' rows'

    fetch next from c_tables into @tablename

end

close c_tables
deallocate c_tables

Get record counts for all tables in MySQL database

This stored procedure lists tables, counts records, and produces a total number of records at the end.

To run it after adding this procedure:

CALL `COUNT_ALL_RECORDS_BY_TABLE` ();

-

The Procedure:

DELIMITER $$

CREATE DEFINER=`root`@`127.0.0.1` PROCEDURE `COUNT_ALL_RECORDS_BY_TABLE`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE TNAME CHAR(255);

DECLARE table_names CURSOR for 
    SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE();

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN table_names;   

DROP TABLE IF EXISTS TCOUNTS;
CREATE TEMPORARY TABLE TCOUNTS 
  (
    TABLE_NAME CHAR(255),
    RECORD_COUNT INT
  ) ENGINE = MEMORY; 


WHILE done = 0 DO

  FETCH NEXT FROM table_names INTO TNAME;

   IF done = 0 THEN
    SET @SQL_TXT = CONCAT("INSERT INTO TCOUNTS(SELECT '" , TNAME  , "' AS TABLE_NAME, COUNT(*) AS RECORD_COUNT FROM ", TNAME, ")");

    PREPARE stmt_name FROM @SQL_TXT;
    EXECUTE stmt_name;
    DEALLOCATE PREPARE stmt_name;  
  END IF;

END WHILE;

CLOSE table_names;

SELECT * FROM TCOUNTS;

SELECT SUM(RECORD_COUNT) AS TOTAL_DATABASE_RECORD_CT FROM TCOUNTS;

END

How to return the output of stored procedure into a variable in sql server

That depends on the nature of the information you want to return.

If it is a single integer value, you can use the return statement

 create proc myproc
 as 
 begin
     return 1
 end
 go
 declare @i int
 exec @i = myproc

If you have a non integer value, or a number of scalar values, you can use output parameters

create proc myproc
  @a int output,
  @b varchar(50) output
as
begin
  select @a = 1, @b='hello'
end
go
declare @i int, @j varchar(50)
exec myproc @i output, @j output

If you want to return a dataset, you can use insert exec

create proc myproc
as 
begin
     select name from sysobjects
end
go

declare @t table (name varchar(100))
insert @t (name)
exec myproc

You can even return a cursor but that's just horrid so I shan't give an example :)

Difference between uint32 and uint32_t

uint32_t is standard, uint32 is not. That is, if you include <inttypes.h> or <stdint.h>, you will get a definition of uint32_t. uint32 is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.

IF statement: how to leave cell blank if condition is false ("" does not work)

Here is what I do

=IF(OR(ISBLANK(AH38),AH38=""),"",IF(AI38=0,0,AH38/AI38))

Use the OR condition OR(ISBLANK(cell), cell="")

Input Type image submit form value?

To submit a form you could use:

<input type="submit">

or

<input type="button"> + Javascript 

I never heard of such a crazy guy to try to send a form using a image or a checkbox as you want :))

Get current folder path

System.AppDomain.CurrentDomain.BaseDirectory

This will give you running directory of your application. This even works for web applications. Afterwards you can reach your file.

Swift GET request with parameters

You can extend your Dictionary to only provide stringFromHttpParameter if both key and value conform to CustomStringConvertable like this

extension Dictionary where Key : CustomStringConvertible, Value : CustomStringConvertible {
  func stringFromHttpParameters() -> String {
    var parametersString = ""
    for (key, value) in self {
      parametersString += key.description + "=" + value.description + "&"
    }
    return parametersString
  }
}

this is much cleaner and prevents accidental calls to stringFromHttpParameters on dictionaries that have no business calling that method

batch file - counting number of files in folder and storing in a variable

FOR /f "delims=" %%i IN ('attrib.exe ./*.* ^| find /v "File not found - " ^| find /c /v ""') DO SET myVar=%%i
ECHO %myVar%

This is based on the (much) earlier post that points out that the count would be wrong for an empty directory if you use DIR rather than attrib.exe.

For anyone else who got stuck on the syntax for putting the command in a FOR loop, enclose the command in single quotes (assuming it doesn't contain them) and escape pipes with ^.

How to make a promise from setTimeout

Update (2017)

Here in 2017, Promises are built into JavaScript, they were added by the ES2015 spec (polyfills are available for outdated environments like IE8-IE11). The syntax they went with uses a callback you pass into the Promise constructor (the Promise executor) which receives the functions for resolving/rejecting the promise as arguments.

First, since async now has a meaning in JavaScript (even though it's only a keyword in certain contexts), I'm going to use later as the name of the function to avoid confusion.

Basic Delay

Using native promises (or a faithful polyfill) it would look like this:

function later(delay) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay);
    });
}

Note that that assumes a version of setTimeout that's compliant with the definition for browsers where setTimeout doesn't pass any arguments to the callback unless you give them after the interval (this may not be true in non-browser environments, and didn't used to be true on Firefox, but is now; it's true on Chrome and even back on IE8).

Basic Delay with Value

If you want your function to optionally pass a resolution value, on any vaguely-modern browser that allows you to give extra arguments to setTimeout after the delay and then passes those to the callback when called, you can do this (current Firefox and Chrome; IE11+, presumably Edge; not IE8 or IE9, no idea about IE10):

function later(delay, value) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay, value); // Note the order, `delay` before `value`
        /* Or for outdated browsers that don't support doing that:
        setTimeout(function() {
            resolve(value);
        }, delay);
        Or alternately:
        setTimeout(resolve.bind(null, value), delay);
        */
    });
}

If you're using ES2015+ arrow functions, that can be more concise:

function later(delay, value) {
    return new Promise(resolve => setTimeout(resolve, delay, value));
}

or even

const later = (delay, value) =>
    new Promise(resolve => setTimeout(resolve, delay, value));

Cancellable Delay with Value

If you want to make it possible to cancel the timeout, you can't just return a promise from later, because promises can't be cancelled.

But we can easily return an object with a cancel method and an accessor for the promise, and reject the promise on cancel:

const later = (delay, value) => {
    let timer = 0;
    let reject = null;
    const promise = new Promise((resolve, _reject) => {
        reject = _reject;
        timer = setTimeout(resolve, delay, value);
    });
    return {
        get promise() { return promise; },
        cancel() {
            if (timer) {
                clearTimeout(timer);
                timer = 0;
                reject();
                reject = null;
            }
        }
    };
};

Live Example:

_x000D_
_x000D_
const later = (delay, value) => {_x000D_
    let timer = 0;_x000D_
    let reject = null;_x000D_
    const promise = new Promise((resolve, _reject) => {_x000D_
        reject = _reject;_x000D_
        timer = setTimeout(resolve, delay, value);_x000D_
    });_x000D_
    return {_x000D_
        get promise() { return promise; },_x000D_
        cancel() {_x000D_
            if (timer) {_x000D_
                clearTimeout(timer);_x000D_
                timer = 0;_x000D_
                reject();_x000D_
                reject = null;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
};_x000D_
_x000D_
const l1 = later(100, "l1");_x000D_
l1.promise_x000D_
  .then(msg => { console.log(msg); })_x000D_
  .catch(() => { console.log("l1 cancelled"); });_x000D_
_x000D_
const l2 = later(200, "l2");_x000D_
l2.promise_x000D_
  .then(msg => { console.log(msg); })_x000D_
  .catch(() => { console.log("l2 cancelled"); });_x000D_
setTimeout(() => {_x000D_
  l2.cancel();_x000D_
}, 150);
_x000D_
_x000D_
_x000D_


Original Answer from 2014

Usually you'll have a promise library (one you write yourself, or one of the several out there). That library will usually have an object that you can create and later "resolve," and that object will have a "promise" you can get from it.

Then later would tend to look something like this:

function later() {
    var p = new PromiseThingy();
    setTimeout(function() {
        p.resolve();
    }, 2000);

    return p.promise(); // Note we're not returning `p` directly
}

In a comment on the question, I asked:

Are you trying to create your own promise library?

and you said

I wasn't but I guess now that's actually what I was trying to understand. That how a library would do it

To aid that understanding, here's a very very basic example, which isn't remotely Promises-A compliant: Live Copy

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Very basic promises</title>
</head>
<body>
  <script>
    (function() {

      // ==== Very basic promise implementation, not remotely Promises-A compliant, just a very basic example
      var PromiseThingy = (function() {

        // Internal - trigger a callback
        function triggerCallback(callback, promise) {
          try {
            callback(promise.resolvedValue);
          }
          catch (e) {
          }
        }

        // The internal promise constructor, we don't share this
        function Promise() {
          this.callbacks = [];
        }

        // Register a 'then' callback
        Promise.prototype.then = function(callback) {
          var thispromise = this;

          if (!this.resolved) {
            // Not resolved yet, remember the callback
            this.callbacks.push(callback);
          }
          else {
            // Resolved; trigger callback right away, but always async
            setTimeout(function() {
              triggerCallback(callback, thispromise);
            }, 0);
          }
          return this;
        };

        // Our public constructor for PromiseThingys
        function PromiseThingy() {
          this.p = new Promise();
        }

        // Resolve our underlying promise
        PromiseThingy.prototype.resolve = function(value) {
          var n;

          if (!this.p.resolved) {
            this.p.resolved = true;
            this.p.resolvedValue = value;
            for (n = 0; n < this.p.callbacks.length; ++n) {
              triggerCallback(this.p.callbacks[n], this.p);
            }
          }
        };

        // Get our underlying promise
        PromiseThingy.prototype.promise = function() {
          return this.p;
        };

        // Export public
        return PromiseThingy;
      })();

      // ==== Using it

      function later() {
        var p = new PromiseThingy();
        setTimeout(function() {
          p.resolve();
        }, 2000);

        return p.promise(); // Note we're not returning `p` directly
      }

      display("Start " + Date.now());
      later().then(function() {
        display("Done1 " + Date.now());
      }).then(function() {
        display("Done2 " + Date.now());
      });

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>

JavaScript hide/show element

Vanilla JS for Classes and IDs

By ID

document.querySelector('#element-id').style.display = 'none';

By Class (Single element)

document.querySelector('.element-class-name').style.display = 'none';

By Class (Multiple elements)

for (const elem of document.querySelectorAll('.element-class-name')) {
    elem.style.display = 'none';
}

NuGet behind a proxy

Try this. Basically, connection could fail if your system doesn't trust nuget certificate.

Android: How to use webcam in emulator?

I would suggest checking the drivers and updating them if required.

Maven: repository element was not specified in the POM inside distributionManagement?

The ID of the two repos are both localSnap; that's probably not what you want and it might confuse Maven.

If that's not it: There might be more repository elements in your POM. Search the output of mvn help:effective-pom for repository to make sure the number and place of them is what you expect.

How to merge specific files from Git branches

The simplest solution is:

git checkout the name of the source branch and the paths to the specific files that we want to add to our current branch

git checkout sourceBranchName pathToFile

"Untrusted App Developer" message when installing enterprise iOS Application

For iOS 13.6

Go to settings -> General -> Device Management -> Click on Trust « Apple Development » -> Click on the red trust button and you’re all set! Enjoy

Android Percentage Layout Height

You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

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

I know this is a little old, but for anyone stumbling across this page should know there is a difference between \n and \r\n.

The \r\n gives a CRLF end of line and the \n gives an LF end of line character. There is very little difference to the eye in general.

Create a .txt from the string and then try and open in notepad (normal not notepad++) and you will notice the difference

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIOD
Q44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901
Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

The above is using 'CRLF' and the below is what 'LF only' would look like (There is a character that cant be seen where the LF shows).

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIODQ44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

If the Line Ends need to be corrected and the file is small enough in size, you can change the line endings in NotePad++ (or paste into word then back into Notepad - although this will make CRLF only).

This may cause some functions that read these files to potenitially no longer function (The example lines given are from GP Prescribing data - England. The file has changed from a CRLF Line end to an LF line end). This stopped an SSIS job from running and failed as couldn't read the LF line endings.

Source of Line Ending Information: https://en.wikipedia.org/wiki/Newline#Representations_in_different_character_encoding_specifications

Hope this helps someone in future :) CRLF = Windows based, LF or CF are from Unix based systems (Linux, MacOS etc.)

Place cursor at the end of text in EditText

If your EditText is not clear:

editText.setText("");
editText.append("New text");

or

editText.setText(null);
editText.append("New text");

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

****You can also use conditions by using this method** **

 int _moneyCounter = 0;
  void _rainMoney(){
    setState(() {
      _moneyCounter +=  100;
    });
  }

new Expanded(
          child: new Center(
            child: new Text('\$$_moneyCounter', 

            style:new TextStyle(
              color: _moneyCounter > 1000 ? Colors.blue : Colors.amberAccent,
              fontSize: 47,
              fontWeight: FontWeight.w800
            )

            ),
          ) 
        ),

Get key from a HashMap using the value

You mixed the keys and the values.

Hashmap <Integer,String> hashmap = new HashMap<Integer, String>();

hashmap.put(100, "one");
hashmap.put(200, "two");

Afterwards a

hashmap.get(100);

will give you "one"

Check if any type of files exist in a directory using BATCH script

For files in a directory, you can use things like:

if exist *.csv echo "csv file found"

or

if not exist *.csv goto nofile

Simplest way to detect a mobile device in PHP

You only need to include user_agent.php file which can be found from Mobile device detection in PHP page and use the following code.

<?php
//include file
include_once 'user_agent.php';

//create an instance of UserAgent class
$ua = new UserAgent();

//if site is accessed from mobile, then redirect to the mobile site.
if($ua->is_mobile()){
   header("Location:http://m.codexworld.com");
   exit;
}
?>

Counting repeated elements in an integer array

package jaa.stu.com.wordgame;

/**
 * Created by AnandG on 3/14/2016.
 */
public final class NumberMath {
    public static boolean isContainDistinct(int[] arr) {

        boolean isDistinct = true;
        for (int i = 0; i < arr.length; i++)

        {

            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == arr[j] && i!=j) {
                    isDistinct = false;
                    break;
                }
            }

        }
        return isDistinct;
    }
    public static boolean isContainDistinct(float[] arr) {

        boolean isDistinct = true;
        for (int i = 0; i < arr.length; i++)

        {

            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == arr[j] && i!=j) {
                    isDistinct = false;
                    break;
                }
            }

        }
        return isDistinct;
    }
    public static boolean isContainDistinct(char[] arr) {

        boolean isDistinct = true;
        for (int i = 0; i < arr.length; i++)

        {

            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == arr[j] && i!=j) {
                    isDistinct = false;
                    break;
                }
            }

        }
        return isDistinct;
    }
    public static boolean isContainDistinct(String[] arr) {

        boolean isDistinct = true;
        for (int i = 0; i < arr.length; i++)

        {

            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == arr[j] && i!=j) {
                    isDistinct = false;
                    break;
                }
            }

        }
        return isDistinct;
    }
    public static int[] NumberofRepeat(int[] arr) {

        int[] repCount= new int[arr.length];
        for (int i = 0; i < arr.length; i++)

        {

            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == arr[j] ) {
                    repCount[i]+=1;
                }
            }

        }
        return repCount;
    }
}


call  by NumberMath.isContainDistinct(array) for find is it contains repeat or not

call by int[] repeat=NumberMath.NumberofRepeat(array) for find repeat count. Each location contains how many repeat corresponding value of array...

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

JVM option -Xss - What does it do exactly?

Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.

How to change visibility of layout programmatically

You can change layout visibility just in the same way as for regular view. Use setVisibility(View.GONE) etc. All layouts are just Views, they have View as their parent.

Creating a "logical exclusive or" operator in Java

you'll need to switch to Scala to implement your own operators

pipe example

What is the best (idiomatic) way to check the type of a Python variable?

I've been using a different approach:

from inspect import getmro
if (type([]) in getmro(obj.__class__)):
    # This is a list, or a subclass of...
elif (type{}) in getmro(obj.__class__)):
    # This one is a dict, or ...

I can't remember why I used this instead of isinstance, though...

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

Usually this kind of error comes when you do DateTime conversion or parsing. Check the calendar setting in the server where the application is hosted, mainly the time zone and short date format, and ensure it's set to the right time zone for the location. Hope this would resolve the issue.

youtube: link to display HD video by default

Nick Vogt at H3XED posted this syntax: https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Take this link and replace the expression "VIDEOID" with the (shortened/shared) ID of the video.

Exapmple for ID: i3jNECZ3ybk looks like this: ... /v/i3jNECZ3ybk?version=3&vq=hd1080

What you get as a result is the standalone 1080p video but not in the Tube environment.

How to make a query with group_concat in sql server

Query:

SELECT
      m.maskid
    , m.maskname
    , m.schoolid
    , s.schoolname
    , maskdetail = STUFF((
          SELECT ',' + md.maskdetail
          FROM dbo.maskdetails md
          WHERE m.maskid = md.maskid
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM dbo.tblmask m
JOIN dbo.school s ON s.ID = m.schoolid
ORDER BY m.maskname

Additional information:

String Aggregation in the World of SQL Server

Xcode variables

Here's a list of the environment variables. I think you might want CURRENT_VARIANT. See also BUILD_VARIANTS.

Javascript - Replace html using innerHTML

You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

No need for array. Just use something like this:

Sub ARRAYER()

    Dim Rng As Range
    Dim Number_of_Sims As Long
    Dim i As Long
    Number_of_Sims = 10

    Set Rng = Range("C4:G4")
    For i = 1 To Number_of_Sims
       Rng.Offset(i, 0).Value = Rng.Value
       Worksheets("Sheetname").Calculate   'replacing Sheetname with name of your sheet
    Next

End Sub

Pan & Zoom Image

The answer was posted above but wasn't complete. here is the completed version:

XAML

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MapTest.Window1"
x:Name="Window"
Title="Window1"
Width="1950" Height="1546" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:Controls="clr-namespace:WPFExtensions.Controls;assembly=WPFExtensions" mc:Ignorable="d" Background="#FF000000">

<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="52.92"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Border Grid.Row="1" Name="border">
        <Image Name="image" Source="map3-2.png" Opacity="1" RenderTransformOrigin="0.5,0.5"  />
    </Border>

</Grid>

Code Behind

using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace MapTest
{
    public partial class Window1 : Window
    {
        private Point origin;
        private Point start;

        public Window1()
        {
            InitializeComponent();

            TransformGroup group = new TransformGroup();

            ScaleTransform xform = new ScaleTransform();
            group.Children.Add(xform);

            TranslateTransform tt = new TranslateTransform();
            group.Children.Add(tt);

            image.RenderTransform = group;

            image.MouseWheel += image_MouseWheel;
            image.MouseLeftButtonDown += image_MouseLeftButtonDown;
            image.MouseLeftButtonUp += image_MouseLeftButtonUp;
            image.MouseMove += image_MouseMove;
        }

        private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            image.ReleaseMouseCapture();
        }

        private void image_MouseMove(object sender, MouseEventArgs e)
        {
            if (!image.IsMouseCaptured) return;

            var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
            Vector v = start - e.GetPosition(border);
            tt.X = origin.X - v.X;
            tt.Y = origin.Y - v.Y;
        }

        private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            image.CaptureMouse();
            var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
            start = e.GetPosition(border);
            origin = new Point(tt.X, tt.Y);
        }

        private void image_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            TransformGroup transformGroup = (TransformGroup) image.RenderTransform;
            ScaleTransform transform = (ScaleTransform) transformGroup.Children[0];

            double zoom = e.Delta > 0 ? .2 : -.2;
            transform.ScaleX += zoom;
            transform.ScaleY += zoom;
        }
    }
}

I have an example of a full wpf project using this code on my website: Jot the sticky note app.

Comparing double values in C#

Taking a tip from the Java code base, try using .CompareTo and test for the zero comparison. This assumes the .CompareTo function takes in to account floating point equality in an accurate manner. For instance,

System.Math.PI.CompareTo(System.Math.PI) == 0

This predicate should return true.

How to use readline() method in Java?

In summary: I would be careful as to what code you copy. It is possible you are copying code which happens to work, rather than well chosen code.

In intnumber, parseInt is used and in floatnumber valueOf is used why so?

There is no good reason I can see. It's an inconsistent use of the APIs as you suspect.


Java is case sensitive, and there isn't any Readline() method. Perhaps you mean readLine().

DataInputStream.readLine() is deprecated in favour of using BufferedReader.readLine();

However, for your case, I would use the Scanner class.

Scanner sc = new Scanner(System.in);
int intNum = sc.nextInt();
float floatNum = sc.nextFloat();

If you want to know what a class does I suggest you have a quick look at the Javadoc.

How can I view an old version of a file with Git?

To quickly see the differences with older revisions of a file:

git show -1 filename.txt > to compare against the last revision of file

git show -2 filename.txt > to compare against the 2nd last revision

git show -3 fielname.txt > to compare against the last 3rd last revision

Efficiently replace all accented characters in a string?

I can't speak to what you are trying to do specifically with the function itself, but if you don't like the regex being built every time, here are two solutions and some caveats about each.

Here is one way to do this:

function makeSortString(s) {
  if(!makeSortString.translate_re) makeSortString.translate_re = /[öäüÖÄÜ]/g;
  var translate = {
    "ä": "a", "ö": "o", "ü": "u",
    "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
  };
  return ( s.replace(makeSortString.translate_re, function(match) { 
    return translate[match]; 
  }) );
}

This will obviously make the regex a property of the function itself. The only thing you may not like about this (or you may, I guess it depends) is that the regex can now be modified outside of the function's body. So, someone could do this to modify the interally-used regex:

makeSortString.translate_re = /[a-z]/g;

So, there is that option.

One way to get a closure, and thus prevent someone from modifying the regex, would be to define this as an anonymous function assignment like this:

var makeSortString = (function() {
  var translate_re = /[öäüÖÄÜ]/g;
  return function(s) {
    var translate = {
      "ä": "a", "ö": "o", "ü": "u",
      "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
    };
    return ( s.replace(translate_re, function(match) { 
      return translate[match]; 
    }) );
  }
})();

Hopefully this is useful to you.


UPDATE: It's early and I don't know why I didn't see the obvious before, but it might also be useful to put you translate object in a closure as well:

var makeSortString = (function() {
  var translate_re = /[öäüÖÄÜ]/g;
  var translate = {
    "ä": "a", "ö": "o", "ü": "u",
    "Ä": "A", "Ö": "O", "Ü": "U"   // probably more to come
  };
  return function(s) {
    return ( s.replace(translate_re, function(match) { 
      return translate[match]; 
    }) );
  }
})();

Write values in app.config file

string filePath = System.IO.Path.GetFullPath("settings.app.config");

var map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
try
{
    // Open App.Config of executable
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

    // Add an Application Setting if not exist

        config.AppSettings.Settings.Add("key1", "value1");
        config.AppSettings.Settings.Add("key2", "value2");

    // Save the changes in App.config file.
    config.Save(ConfigurationSaveMode.Modified);

    // Force a reload of a changed section.
    ConfigurationManager.RefreshSection("appSettings");
}
catch (ConfigurationErrorsException ex)
{
    if (ex.BareMessage == "Root element is missing.")
    {
        File.Delete(filePath);
        return;
    }
    MessageBox.Show(ex.Message);
}

Setting up MySQL and importing dump within Dockerfile

The latest version of the official mysql docker image allows you to import data on startup. Here is my docker-compose.yml

data:
  build: docker/data/.
mysql:
  image: mysql
  ports:
    - "3307:3306"
  environment:
    MYSQL_ROOT_PASSWORD: 1234
  volumes:
    - ./docker/data:/docker-entrypoint-initdb.d
  volumes_from:
    - data

Here, I have my data-dump.sql under docker/data which is relative to the folder the docker-compose is running from. I am mounting that sql file into this directory /docker-entrypoint-initdb.d on the container.

If you are interested to see how this works, have a look at their docker-entrypoint.sh in GitHub. They have added this block to allow importing data

    echo
    for f in /docker-entrypoint-initdb.d/*; do
        case "$f" in
            *.sh)  echo "$0: running $f"; . "$f" ;;
            *.sql) echo "$0: running $f"; "${mysql[@]}" < "$f" && echo ;;
            *)     echo "$0: ignoring $f" ;;
        esac
        echo
    done

An additional note, if you want the data to be persisted even after the mysql container is stopped and removed, you need to have a separate data container as you see in the docker-compose.yml. The contents of the data container Dockerfile are very simple.

FROM n3ziniuka5/ubuntu-oracle-jdk:14.04-JDK8

VOLUME /var/lib/mysql

CMD ["true"]

The data container doesn't even have to be in start state for persistence.

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

In the relevant page which makes a mixed content https to http call which is not accessible we can add the following entry in the relevant and get rid of the mixed content error.

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

Convert Mercurial project to Git

Some notes of my experience converting Mercurial to Git.

1. hg-fast-export

Using hg-fast-export failed and I needed --force as noted above. Next I got this error:

error: cannot lock ref 'refs/heads/stable': 'refs/heads/stable/sub-branch-name' exists; cannot create 'refs/heads/stable'

Upon completion of the hg-fast-export I ended up with an amputated repo. I think that this repo had a good few orphaned branches and that hg-fast-export needs a somewhat idealised repo. This all seemed a bit rough around the edges, so I moved on to Kiln Harmony (http://blog.fogcreek.com/announcing-kiln-harmony-the-future-of-dvcs/)

2. Kiln

Kiln Harmony does not appear to exist on a free tier account as suggested above. I could choose between Git-only and Mercurial-only repos and there is no option to switch. I raised a support ticket and will share the result if they reply.

3. hg-git

The Hg-Git mercurial plugin (http://hg-git.github.io/) did work for me. FYI on Mac OSX I installed hg-git via macports as follows:

  • sudo port install python27
  • sudo port select --set python python27
  • sudo port install py27-hggit
  • vi ~/.hgrc

.hgrc needs these lines:

[ui]
username = Name Surname <[email protected]>

[extensions]
hgext.bookmarks =
hggit = 

I then had success with:

hg push git+ssh://[email protected]:myaccount/myrepo.git

4. Caveat: Know your repo

All the above are blunt instruments and I only pushed ahead because it took enough time to get the team to use git properly.

Upon first pushing the project per (3) I ended up with all new changes missing. This is because this line of code must be viewed as a guide only:

$ hg bookmark -r default master # make a bookmark of master for default, so a ref gets created

The theory is that the default branch can be deemed to be master when pushing to git, and in my case I inherited a repo where they used 'stable' as the equivalent of master. Moreover, I also discovered that the tip of the repo was a hotfix not yet merged with the 'stable' branch.

Without properly understanding both Mercurial and the repo to be converted, you are probably better off not doing the conversion.

I did the following in order to get the repo ready for a second conversion attempt:

hg update -C stable
hg merge stable/hotfix-feature
hg ci -m "Merge with stable branch"
hg push git+ssh://[email protected]:myaccount/myrepo.git

After this I had a verifiably equivalent project in git, however all the orphaned branches I mentioned earlier are gone. I don't think that is too serious, but I may well live to regret this as an oversight. Therefore my final thought is to keep the original anyway.

Edit: If you just want the latest commit in git, this is simpler than the above merge:

hg book -r tip master
hg push git+ssh://[email protected]:myaccount/myrepo.git

Java TreeMap Comparator

you can swipe the key and the value. For example

        String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
        int[] v = {341, 273, 278, 329, 445};
        TreeMap<Integer,String>a=new TreeMap();
        for (int i = 0; i < k.length; i++) 
           a.put(v[i],k[i]);            
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
        a.remove(a.firstEntry().getKey());
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());

How can I check whether Google Maps is fully loaded?

Where the variable map is an object of type GMap2:

    GEvent.addListener(map, "tilesloaded", function() {
      console.log("Map is fully loaded");
    });

How to upload a file to directory in S3 bucket using boto

import boto3

s3 = boto3.resource('s3')
BUCKET = "test"

s3.Bucket(BUCKET).upload_file("your/local/file", "dump/file")

Intersect Two Lists in C#

From performance point of view if two lists contain number of elements that differ significantly, you can try such approach (using conditional operator ?:):

1.First you need to declare a converter:

Converter<string, int> del = delegate(string s) { return Int32.Parse(s); };

2.Then you use a conditional operator:

var r = data1.Count > data2.Count ?
 data2.ConvertAll<int>(del).Intersect(data1) :
 data1.Select(v => v.ToString()).Intersect(data2).ToList<string>().ConvertAll<int>(del);

You convert elements of shorter list to match the type of longer list. Imagine an execution speed if your first set contains 1000 elements and second only 10 (or opposite as it doesn't matter) ;-)

As you want to have a result as List, in a last line you convert the result (only result) back to int.

Possible to change where Android Virtual Devices are saved?

Go to the Android tools directory. Edit the android.bat command file. At about the end of the command file, find a line similar to

call %java_exe% -Djava.ext.dirs=%java_ext_dirs% -Dcom.android.sdkmanager.toolsdir="%tools_dir%" -Dcom.android.sdkmanager.workdir="%work_dir%" -jar %jar_path% %*

and replace

call %java_exe%

with

call %java_exe% -Duser.home={your_prefer_dir}

where {your_prefer_dire} is your preferred directory without braces but add doublequotes,

e.g.

call %java_exe% -Duser.home="E:\Program Files (x86)\android-sdk-windows"

Disable browser cache for entire ASP.NET website

Instead of rolling your own, simply use what's provided for you.

As mentioned previously, do not disable caching for everything. For instance, jQuery scripts used heavily in ASP.NET MVC should be cached. Actually ideally you should be using a CDN for those anyway, but my point is some content should be cached.

What I find works best here rather than sprinkling the [OutputCache] everywhere is to use a class:

[System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class NoCacheController  : Controller
{
}

All of your controllers you want to disable caching for then inherit from this controller.

If you need to override the defaults in the NoCacheController class, simply specify the cache settings on your action method and the settings on your Action method will take precedence.

[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ViewResult Index()
{
  ...
}

Getting msbuild.exe without installing Visual Studio

Download MSBuild with the link from @Nicodemeus answer was OK, yet the installation was broken until I've added these keys into a register:

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\12.0]
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))" 

How do I download code using SVN/Tortoise from Google Code?

After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout. Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".

Should you always favor xrange() over range()?

A good example given in book: Practical Python By Magnus Lie Hetland

>>> zip(range(5), xrange(100000000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

I wouldn’t recommend using range instead of xrange in the preceding example—although only the first five numbers are needed, range calculates all the numbers, and that may take a lot of time. With xrange, this isn’t a problem because it calculates only those numbers needed.

Yes I read @Brian's answer: In python 3, range() is a generator anyway and xrange() does not exist.

How do I explicitly specify a Model's table-name mapping in Rails?

Rails >= 3.2 (including Rails 4+ and 5+):

class Countries < ActiveRecord::Base
  self.table_name = "cc"
end

Rails <= 3.1:

class Countries < ActiveRecord::Base
  self.set_table_name "cc"
  ...
end

Rename package in Android Studio

for example if you want change package from com.example.a to com.example.b

1)change project style folder from android to package (in project side)

2)right click top of folder and click replace in path

3)select in project button

4)in first input write com.example.a

5)in second input write com.example.b

6)when you see warning select replace all to replace value

after finish replace you can see your package name is com.example.b

Parsing XML in Python using ElementTree example

If I understand your question correctly:

for elem in doc.findall('timeSeries/values/value'):
    print elem.get('dateTime'), elem.text

or if you prefer (and if there is only one occurrence of timeSeries/values:

values = doc.find('timeSeries/values')
for value in values:
    print value.get('dateTime'), elem.text

The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

JavaScript object: access variable property by name as string

Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script type="text/javascript">_x000D_
    function displayFile(whatOption, whatColor) {_x000D_
      var Test01 = {_x000D_
        rectangle: {_x000D_
          red: "RectangleRedFile",_x000D_
          blue: "RectangleBlueFile"_x000D_
        },_x000D_
        square: {_x000D_
          red: "SquareRedFile",_x000D_
          blue: "SquareBlueFile"_x000D_
        }_x000D_
      };_x000D_
      var filename = Test01[whatOption][whatColor];_x000D_
      alert(filename);_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
<body>_x000D_
  <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'red')">[ Sq Red ]</p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

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

I don't know of any way to access a mobile phone's camera from the web browser without some additional mechanism (i.e. Flash or some type of container that allows access to the hardware API)

For the latter have a look at PhoneGap: http://docs.phonegap.com/phonegap_camera_camera.md.html

With this you should be able to access the camera at least on iOS and Android-based devices.

Git will not init/sync/update new submodules

Deleting submodule dir and its contents ("external/pyfacebook" folder) if it exists before git submodule add ... might fix problems.

Opening Chrome From Command Line

Let's take a look at the start command.

Open Windows command prompt

To open a new Chrome window (blank), type the following:

start chrome --new-window 

or

start chrome

To open a URL in Chrome, type the following:

start chrome --new-window "http://www.iot.qa/2018/02/narrowband-iot.html"

To open a URL in Chrome in incognito mode, type the following:

start chrome --new-window --incognito "http://www.iot.qa/2018/02/narrowband-iot.html"

or

start chrome --incognito "http://www.iot.qa/2018/02/narrowband-iot.html"

Script to get the HTTP status code of a list of urls?

Use curl to fetch the HTTP-header only (not the whole file) and parse it:

$ curl -I  --stderr /dev/null http://www.google.co.uk/index.html | head -1 | cut -d' ' -f2
200

How can I make a TextBox be a "password box" and display stars when using MVVM?

Send the passwordbox control as a parameter to your login command.

<Button Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=PasswordBox}"...>

Then you can call CType(parameter, PasswordBox).Password in your viewmodel.

How can I use getSystemService in a non-activity class (LocationManager)?

For some non-activity classes, like Worker, you're already given a Context object in the public constructor.

Worker(Context context, WorkerParameters workerParams)

You can just use that, e.g., save it to a private Context variable in the class (say, mContext), and then, for example

mContext.getSystenService(Context.ACTIVITY_SERVICE)

How to set a value for a span using jQuery

You can do:

$("#submittername").text("testing");

or

$("#submittername").html("testing <b>1 2 3</b>");

How to make a dropdown readonly using jquery?

This is what you are looking for:

$('#cf_1268591').attr("style", "pointer-events: none;");

Works like a charm.

Remove Primary Key in MySQL

"if you restore the primary key, you sure may revert it back to AUTO_INCREMENT"

There should be no question of whether or not it is desirable to "restore the PK property" and "restore the autoincrement property" of the ID column.

Given that it WAS an autoincrement in the prior definition of the table, it is quite likely that there exists some program that inserts into this table without providing an ID value (because the ID column is autoincrement anyway).

Any such program's operation will break by not restoring the autoincrement property.

HTML form readonly SELECT tag/input

I know that it is far too late, but it can be done with simple CSS:

select[readonly] option, select[readonly] optgroup {
    display: none;
}

The style hides all the options and the groups when the select is in readonly state, so the user can not change his selection.

No JavaScript hacks needed.

Can I force a page break in HTML printing?

Try this link

<style>
@media print
{
h1 {page-break-before:always}
}
</style>

HTML5 placeholder css padding

I had similar issue, my problem was with the side padding, and the solution was with, text-indent, I wasn't realize that text indent effect the placeholder side position.

input{
  text-indent: 10px;
}

How can I change the text inside my <span> with jQuery?

Try this

$("#abc").html('<span class = "xyz"> SAMPLE TEXT</span>');

Handle all the css relevant to that span within xyz

HTML: how to force links to open in a new tab, not new window

It is possible!

This appears to override browser settings. Hope it works for you.

<script type="text/javascript">
// Popup window code
function newPopup(url) {
    popupWindow = window.open(url,'popUpWindow1','height=600,width=600,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
</script>

<body>
  <a href="JavaScript:newPopup('http://stimsonstopmotion.wordpress.com');">Try me</a>
</body>

#include errors detected in vscode

For Windows:

  1. Please add this directory to your environment variable(Path):

C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin\

  1. For Include errors detected, mention the path of your include folder into

"includePath": [ "C:/mingw-w64/x86_64-8.1.0-win32-seh-rt_v6-rev0/mingw64/include/" ]

, as this is the path from where the compiler fetches the library to be included in your program.

Find out a Git branch creator

As far as I know, you may see if you are the creator of a branch only. This is indicated by the first row in .git/ref/heads/<branch>. If it ends with "Created from HEAD" you are the creator.

What is the difference between UTF-8 and Unicode?

This article explains all the details http://kunststube.net/encoding/

WRITING TO BUFFER

if you write to a 4 byte buffer, symbol ? with UTF8 encoding, your binary will look like this:

00000000 11100011 10000001 10000010

if you write to a 4 byte buffer, symbol ? with UTF16 encoding, your binary will look like this:

00000000 00000000 00110000 01000010

As you can see, depending on what language you would use in your content this will effect your memory accordingly.

e.g. For this particular symbol: ? UTF16 encoding is more efficient since we have 2 spare bytes to use for the next symbol. But it doesn't mean that you must use UTF16 for Japan alphabet.

READING FROM BUFFER

Now if you want to read the above bytes, you have to know in what encoding it was written to and decode it back correctly.

e.g. If you decode this : 00000000 11100011 10000001 10000010 into UTF16 encoding, you will end up with ? not ?

Note: Encoding and Unicode are two different things. Unicode is the big (table) with each symbol mapped to a unique code point. e.g. ? symbol (letter) has a (code point): 30 42 (hex). Encoding on the other hand, is an algorithm that converts symbols to more appropriate way, when storing to hardware.

30 42 (hex) - > UTF8 encoding - > E3 81 82 (hex), which is above result in binary.

30 42 (hex) - > UTF16 encoding - > 30 42 (hex), which is above result in binary.

enter image description here

How to cherry-pick from a remote branch?

The commit should be present in your local, check by using git log.

If the commit is not present then try git fetch to update the local with the latest remote.

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

This worked for me! You can convert to datatype you want be it a date or string

to_char(TO_DATE(TO_CHAR(end_date),'MM-DD-YYYY'),'YYYY-MM-DD') AS end_date

Changes in import statement python3

For relative imports see the documentation. A relative import is when you import from a module relative to that module's location, instead of absolutely from sys.path.

As for import *, Python 2 allowed star imports within functions, for instance:

>>> def f():
...     from math import *
...     print sqrt

A warning is issued for this in Python 2 (at least recent versions). In Python 3 it is no longer allowed and you can only do star imports at the top level of a module (not inside functions or classes).

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

Tools to generate database tables diagram with Postgresql?

Just found http://www.sqlpower.ca/page/architect through the Postgres Community Guide mentioned by Frank Heikens. It can easily generate a diagram, and then lets you adjust the connectors!

Ubuntu says "bash: ./program Permission denied"

chmod u+x program_name. Then execute it.

If that does not work, copy the program from the USB device to a native volume on the system. Then chmod u+x program_name on the local copy and execute that.

Unix and Unix-like systems generally will not execute a program unless it is marked with permission to execute. The way you copied the file from one system to another (or mounted an external volume) may have turned off execute permission (as a safety feature). The command chmod u+x name adds permission for the user that owns the file to execute it.

That command only changes the permissions associated with the file; it does not change the security controls associated with the entire volume. If it is security controls on the volume that are interfering with execution (for example, a noexec option may be specified for a volume in the Unix fstab file, which says not to allow execute permission for files on the volume), then you can remount the volume with options to allow execution. However, copying the file to a local volume may be a quicker and easier solution.

How to fix docker: Got permission denied issue

I ran into a similar problem as well, but where the container I wanted to create needed to mount /var/run/docker.sock as a volume (Portainer Agent), while running it all under a different namespace. Normally a container does not care about which namespace it is started in -- that is sort of the point -- but since access was made from a different namespace, this had to be circumvented.

Adding --userns=host to the run command for the container enabled it to use the attain the correct permissions.

Quite a specific use case, but after more research hours than I want to admit I just thought I should share it with the world if someone else ends up in this situation :)

psql - save results of command to a file

Use the below query to store the result in a CSV file

\copy (your query) to 'file path' csv header;

Example

\copy (select name,date_order from purchase_order) to '/home/ankit/Desktop/result.csv' cvs header;

Hope this helps you.

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

How to select a value in dropdown javascript?

easiest way is to just use this

document.getElementById("mySelect").value = "banana";

myselect is name of your dropdown banana is just one of items in your dropdown list

The difference between sys.stdout.write and print?

A difference between print and sys.stdout.write to point out in Python 3, is also the value which is returned when executed in the terminal. In Python 3, sys.stdout.write returns the length of the string whereas print returns just None.

So for example running following code interactively in the terminal would print out the string followed by its length, since the length is returned and output when run interactively:

>>> sys.stdout.write(" hi ")
 hi 4

How can I define an array of objects?

You are better off using a native array instead of an object literal with number-like properties, so that numbering (as well as numerous other array functions) are taken care of off-the-shelf.

What you are looking for here is an inline interface definition for your array that defines every element in that array, whether initially present or introduced later:

let userTestStatus: { id: number, name: string }[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
];

userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]

If you are initializing your array with values right away, the explicit type definition is not a necessity; TypeScript can automatically infer most element types from the initial assignment:

let userTestStatus = [
    { "id": 0, "name": "Available" },
    ...
];

userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]

java : convert float to String and String to float

String str = "1234.56";
float num = 0.0f;

int digits = str.length()- str.indexOf('.') - 1;

float factor = 1f;

for(int i=0;i<digits;i++) factor /= 10;

for(int i=str.length()-1;i>=0;i--){

    if(str.charAt(i) == '.'){
        factor = 1;
        System.out.println("Reset, value="+num);
        continue;
    }

    num += (str.charAt(i) - '0') * factor;
    factor *= 10;
}

System.out.println(num);

How do I load a PHP file into a variable?

I suppose you want to get the content generated by PHP, if so use:

$Vdata = file_get_contents('http://YOUR_HOST/YOUR/FILE.php');

Otherwise if you want to get the source code of the PHP file, it's the same as a .txt file:

$Vdata = file_get_contents('path/to/YOUR/FILE.php');

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

Take a look at the equation you can find that binary cross entropy not only punish those label = 1, predicted =0, but also label = 0, predicted = 1.

However categorical cross entropy only punish those label = 1 but predicted = 1.That's why we make assumption that there is only ONE label positive.

Which version of MVC am I using?

In Solution Explorer open packages.config and find Microsoft.AspNet.MVC:

package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net461"

From the above we can see it's an Asp.Net MVC 5.2.3 Version.

Moreover packages.config file also helps us to track all the installed packages with their respective versions.

Java variable number or arguments for a method

That's correct. You can find more about it in the Oracle guide on varargs.

Here's an example:

void foo(String... args) {
    for (String arg : args) {
        System.out.println(arg);
    }
}

which can be called as

foo("foo"); // Single arg.
foo("foo", "bar"); // Multiple args.
foo("foo", "bar", "lol"); // Don't matter how many!
foo(new String[] { "foo", "bar" }); // Arrays are also accepted.
foo(); // And even no args.

Java equivalent to C# extension methods

Project Lombok provides an annotation @ExtensionMethod that can be used to achieve the functionality you are asking for.

Trim leading and trailing spaces from a string in awk

Simplest solution is probably to use tr

$ cat -A input
^I    Name, ^IOrder  $
  Trim, working  $
cat,cat1^I  

$ tr -d '[:blank:]' < input | cat -A
Name,Order$
Trim,working$
cat,cat1

How can I remove non-ASCII characters but leave periods and spaces using Python?

You may use the following code to remove non-English letters:

import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)

This will return

123456790 ABC#%? .()

Emulate a 403 error page

I have read all the answers here and none of them was complete answer for my situation (which is exactly the same in this question) so here is how I gathered some parts of the suggested answers and come up with the exact solution:

  1. Land on your server's real 403 page. (Go to a forbidden URL on your server, or go to any 403 page you like)
  2. Right-click and select 'view source'. Select all the source and save it to file on your domain like: http://domain.com/403.html
  3. now go to your real forbidden page (or a forbidden situation in some part of your php) example: http://domain.com/members/this_is_forbidden.php
  4. echo this code below before any HTML output or header! (even a whitespace will cause PHP to send HTML/TEXT HTTP Header and it won't work) The code below should be your first line!

        <?php header('HTTP/1.0 403 Forbidden');
        $contents = file_get_contents('/home/your_account/public_html/domain.com/403.html', TRUE);
        exit($contents);
    

Now you have the exact solution. I checked and verified with CPANEL Latest Visitors and it is registered as exact 403 event.

Rename all files in a folder with a prefix in a single command

If your filenames contain no whitepace and you don't have any subdirectories, you can use a simple for loop:

$ for FILENAME in *; do mv $FILENAME Unix_$FILENAME; done 

Otherwise use the convenient rename command (which is a perl script) - although it might not be available out of the box on every Unix (e.g. OS X doesn't come with rename).

A short overview at debian-administration.org:

If your filenames contain whitespace it's easier to use find, on Linux the following should work:

$ find . -type f -name '*' -printf "echo mv '%h/%f' '%h/Unix_%f\n'" | sh

On BSD systems, there is no -printf option, unfortunately. But GNU findutils should be installable (on e.g. Mac OS X with brew install findutils).

$ gfind . -type f -name '*' -printf "mv \"%h/%f\" \"%h/Unix_%f\"\n" | sh

When to favor ng-if vs. ng-show/ng-hide?

One important note:

ngIf (unlike ngShow) usually creates child scopes that may produce unexpected results.

I had an issue related to this and I've spent MUCH time to figure out what was going on.

(My directive was writing its model values to the wrong scope.)

So, to save your hair just use ngShow unless you run too slow.

The performance difference is barely noticable anyway and I am not sure yet on who's favour is it without a test...

Detect if an element is visible with jQuery

if($('#testElement').is(':visible')){
    //what you want to do when is visible
}

Sending HTTP Post request with SOAP action using org.apache.http

The soapAction must passed as a http-header parameter - when used, it's not part of the http-body/payload.

Look here for an example with apache httpclient: http://svn.apache.org/repos/asf/httpcomponents/oac.hc3x/trunk/src/examples/PostSOAP.java

Easiest way to read/write a file's content in Python

Use pathlib.

Python 3.5 and above:

from pathlib import Path
contents = Path(file_path).read_text()

For lower versions of Python use pathlib2:

$ pip install pathlib2

Then

from pathlib2 import Path
contents = Path(file_path).read_text()

Writing is just as easy:

Path(file_path).write_text('my text')

Postgresql 9.2 pg_dump version mismatch

You can just locate pg_dump and use the full path in command

locate pg_dump

/usr/bin/pg_dump
/usr/bin/pg_dumpall
/usr/lib/postgresql/9.3/bin/pg_dump
/usr/lib/postgresql/9.3/bin/pg_dumpall
/usr/lib/postgresql/9.6/bin/pg_dump
/usr/lib/postgresql/9.6/bin/pg_dumpall

Now just use the path of the desired version in the command

/usr/lib/postgresql/9.6/bin/pg_dump books > books.out

How to disable right-click context-menu in JavaScript

I have used this:

document.onkeydown = keyboardDown;
document.onkeyup = keyboardUp;
document.oncontextmenu = function(e){
 var evt = new Object({keyCode:93});
 stopEvent(e);
 keyboardUp(evt);
}
function stopEvent(event){
 if(event.preventDefault != undefined)
  event.preventDefault();
 if(event.stopPropagation != undefined)
  event.stopPropagation();
}
function keyboardDown(e){
 ...
}
function keyboardUp(e){
 ...
}

Then I catch e.keyCode property in those two last functions - if e.keyCode == 93, I know that the user either released the right mouse button or pressed/released the Context Menu key.

Hope it helps.

What's the best CRLF (carriage return, line feed) handling strategy with Git?

Don't convert line endings. It's not the VCS's job to interpret data -- just store and version it. Every modern text editor can read both kinds of line endings anyway.

Checking if a variable exists in javascript

I found this shorter and much better:

    if(varName !== (undefined || null)) { //do something }

How do I set cell value to Date and apply default Excel date format?

To set to default Excel type Date (defaulted to OS level locale /-> i.e. xlsx will look different when opened by a German or British person/ and flagged with an asterisk if you choose it in Excel's cell format chooser) you should:

    CellStyle cellStyle = xssfWorkbook.createCellStyle();
    cellStyle.setDataFormat((short)14);
    cell.setCellStyle(cellStyle);

I did it with xlsx and it worked fine.

Shortest way to print current year in a website

<script type="text/javascript">document.write(new Date().getFullYear());</script>

Can you issue pull requests from the command line on GitHub?

Git now ships with a subcommand 'git request-pull' [-p] <start> <url> [<end>]

You can see the docs here

You may find this useful but it is not exactly the same as GitHub's feature.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

If you want to use valueChangeListener, you need to submit the form every time a new option is chosen. Something like this:

<p:selectOneMenu value="#{mymb.employee}" onchange="submit()"
                 valueChangeListener="#{mymb.handleChange}" >
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

public void handleChange(ValueChangeEvent event){  
    System.out.println("New value: " + event.getNewValue());
}

Or else, if you want to use <p:ajax>, it should look like this:

<p:selectOneMenu value="#{mymb.employee}" >
    <p:ajax listener="#{mymb.handleChange}" />
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

private String employeeID;

public void handleChange(){  
    System.out.println("New value: " + employee);
}

One thing to note is that in your example code, I saw that the value attribute of your <p:selectOneMenu> is #{mymb.employeesList} which is the same as the value of <f:selectItems>. The value of your <p:selectOneMenu> should be similar to my examples above which point to a single employee, not a list of employees.

How do you dynamically add elements to a ListView on Android?

If you want to have the ListView in an AppCompatActivity instead of ListActivity, you can do the following (Modifying @Shardul's answer):

public class ListViewDemoActivity extends AppCompatActivity {
    //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    ArrayList<String> listItems=new ArrayList<String>();

    //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
    ArrayAdapter<String> adapter;

    //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
    int clickCounter=0;
    private ListView mListView;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_list_view_demo);

        if (mListView == null) {
            mListView = (ListView) findViewById(R.id.listDemo);
        }

        adapter=new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                listItems);
        setListAdapter(adapter);
    }

    //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
    public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
    }

    protected ListView getListView() {
        if (mListView == null) {
            mListView = (ListView) findViewById(R.id.listDemo);
        }
        return mListView;
    }

    protected void setListAdapter(ListAdapter adapter) {
        getListView().setAdapter(adapter);
    }

    protected ListAdapter getListAdapter() {
        ListAdapter adapter = getListView().getAdapter();
        if (adapter instanceof HeaderViewListAdapter) {
            return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
        } else {
            return adapter;
        }
    }
}

And in you layout instead of using android:id="@android:id/list" you can use android:id="@+id/listDemo"

So now you can have a ListView inside a normal AppCompatActivity.

Converting NSData to NSString in Objective c

-[NSString initWithData:encoding] is your friend but only when you use a proper encoding.

Passing arguments to JavaScript function from code-behind

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

That's not possible as far as I know

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

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

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

You can also apply the default 'text' classes available from bootstrap itself

 <h1 class='text-info'>Hey... I'm blue</h1>

http://twitter.github.io/bootstrap/base-css.html

How do you upload a file to a document library in sharepoint?

I used this article to allow to c# to access to a sharepoint site.

http://www.thesharepointguide.com/access-office-365-using-a-console-application/

Basically you create a ClientId and ClientSecret keys to access to the site with c#

Hope this can help you!

#pragma once vs include guards?

Until the day #pragma once becomes standard (that's not currently a priority for the future standards), I suggest you use it AND use guards, this way:

#ifndef BLAH_H
#define BLAH_H
#pragma once

// ...

#endif

The reasons are :

  • #pragma once is not standard, so it is possible that some compiler don't provide the functionality. That said, all major compiler supports it. If a compiler don't know it, at least it will be ignored.
  • As there is no standard behavior for #pragma once, you shouldn't assume that the behavior will be the same on all compiler. The guards will ensure at least that the basic assumption is the same for all compilers that at least implement the needed preprocessor instructions for guards.
  • On most compilers, #pragma once will speed up compilation (of one cpp) because the compiler will not reopen the file containing this instruction. So having it in a file might help, or not, depending on the compiler. I heard g++ can do the same optimization when guards are detected but it have to be confirmed.

Using the two together you get the best of each compiler for this.

Now, if you don't have some automatic script to generate the guards, it might be more convenient to just use #pragma once. Just know what that means for portable code. (I'm using VAssistX to generate the guards and pragma once quickly)

You should almost always think your code in a portable way (because you don't know what the future is made of) but if you really think that it's not meant to be compiled with another compiler (code for very specific embedded hardware for example) then you should just check your compiler documentation about #pragma once to know what you're really doing.

Import Python Script Into Another?

I highly recommend the reading of a lecture in SciPy-lectures organization:

https://scipy-lectures.org/intro/language/reusing_code.html

It explains all the commented doubts.

But, new paths can be easily added and avoiding duplication with the following code:

import sys
new_path = 'insert here the new path'

if new_path not in sys.path:
    sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script

Matplotlib discrete colorbar

You could follow this example:

#!/usr/bin/env python
"""
Use a pcolor or imshow with a custom colormap to make a contour plot.

Since this example was initially written, a proper contour routine was
added to matplotlib - see contour_demo.py and
http://matplotlib.sf.net/matplotlib.pylab.html#-contour.
"""

from pylab import *


delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians

cmap = cm.get_cmap('PiYG', 11)    # 11 discrete colors

im = imshow(Z, cmap=cmap, interpolation='bilinear',
            vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()

show()

which produces the following image:

poormans_contour

error: use of deleted function

I encountered this error when inheriting from an abstract class and not implementing all of the pure virtual methods in my subclass.

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

Copy the installation files into your hard drive. Rename the installer file name to vs_professional.exe for professional edition. Enjoy.

Does Java read integers in little endian or big endian?

I would read the bytes one by one, and combine them into a long value. That way you control the endianness, and the communication process is transparent.

How to add SHA-1 to android application

Just In case: while using the command line to generate the SHA1 fingerprint, be careful while specifying the folder path. If your User Name or android folder path has a space, you should add two double quotes as below:

keytool -list -v -keystore "C:\Users\User Name\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

Load and execute external js file in node.js with access to local variables?

If you are planning to load an external javascript file's functions or objects, load on this context using the following code – note the runInThisContext method:

var vm = require("vm");
var fs = require("fs");

var data = fs.readFileSync('./externalfile.js');
const script = new vm.Script(data);
script.runInThisContext();

// here you can use externalfile's functions or objects as if they were instantiated here. They have been added to this context. 

How to download videos from youtube on java?

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

public class JavaYoutubeDownloader {

 public static String newline = System.getProperty("line.separator");
 private static final Logger log = Logger.getLogger(JavaYoutubeDownloader.class.getCanonicalName());
 private static final Level defaultLogLevelSelf = Level.FINER;
 private static final Level defaultLogLevel = Level.WARNING;
 private static final Logger rootlog = Logger.getLogger("");
 private static final String scheme = "http";
 private static final String host = "www.youtube.com";
 private static final Pattern commaPattern = Pattern.compile(",");
 private static final Pattern pipePattern = Pattern.compile("\\|");
 private static final char[] ILLEGAL_FILENAME_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' };

 private static void usage(String error) {
  if (error != null) {
   System.err.println("Error: " + error);
  }
  System.err.println("usage: JavaYoutubeDownload VIDEO_ID DESTINATION_DIRECTORY");
  System.exit(-1);
 }

 public static void main(String[] args) {
  if (args == null || args.length == 0) {
   usage("Missing video id. Extract from http://www.youtube.com/watch?v=VIDEO_ID");
  }
  try {
   setupLogging();

   log.fine("Starting");
   String videoId = null;
   String outdir = ".";
   // TODO Ghetto command line parsing
   if (args.length == 1) {
    videoId = args[0];
   } else if (args.length == 2) {
    videoId = args[0];
    outdir = args[1];
   }

   int format = 18; // http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs
   String encoding = "UTF-8";
   String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
   File outputDir = new File(outdir);
   String extension = getExtension(format);

   play(videoId, format, encoding, userAgent, outputDir, extension);

  } catch (Throwable t) {
   t.printStackTrace();
  }
  log.fine("Finished");
 }

 private static String getExtension(int format) {
  // TODO
  return "mp4";
 }

 private static void play(String videoId, int format, String encoding, String userAgent, File outputdir, String extension) throws Throwable {
  log.fine("Retrieving " + videoId);
  List<NameValuePair> qparams = new ArrayList<NameValuePair>();
  qparams.add(new BasicNameValuePair("video_id", videoId));
  qparams.add(new BasicNameValuePair("fmt", "" + format));
  URI uri = getUri("get_video_info", qparams);

  CookieStore cookieStore = new BasicCookieStore();
  HttpContext localContext = new BasicHttpContext();
  localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

  HttpClient httpclient = new DefaultHttpClient();
  HttpGet httpget = new HttpGet(uri);
  httpget.setHeader("User-Agent", userAgent);

  log.finer("Executing " + uri);
  HttpResponse response = httpclient.execute(httpget, localContext);
  HttpEntity entity = response.getEntity();
  if (entity != null && response.getStatusLine().getStatusCode() == 200) {
   InputStream instream = entity.getContent();
   String videoInfo = getStringFromInputStream(encoding, instream);
   if (videoInfo != null && videoInfo.length() > 0) {
    List<NameValuePair> infoMap = new ArrayList<NameValuePair>();
    URLEncodedUtils.parse(infoMap, new Scanner(videoInfo), encoding);
    String token = null;
    String downloadUrl = null;
    String filename = videoId;

    for (NameValuePair pair : infoMap) {
     String key = pair.getName();
     String val = pair.getValue();
     log.finest(key + "=" + val);
     if (key.equals("token")) {
      token = val;
     } else if (key.equals("title")) {
      filename = val;
     } else if (key.equals("fmt_url_map")) {
      String[] formats = commaPattern.split(val);
      for (String fmt : formats) {
       String[] fmtPieces = pipePattern.split(fmt);
       if (fmtPieces.length == 2) {
        // in the end, download somethin!
        downloadUrl = fmtPieces[1];
        int pieceFormat = Integer.parseInt(fmtPieces[0]);
        if (pieceFormat == format) {
         // found what we want
         downloadUrl = fmtPieces[1];
         break;
        }
       }
      }
     }
    }

    filename = cleanFilename(filename);
    if (filename.length() == 0) {
     filename = videoId;
    } else {
     filename += "_" + videoId;
    }
    filename += "." + extension;
    File outputfile = new File(outputdir, filename);

    if (downloadUrl != null) {
     downloadWithHttpClient(userAgent, downloadUrl, outputfile);
    }
   }
  }
 }

 private static void downloadWithHttpClient(String userAgent, String downloadUrl, File outputfile) throws Throwable {
  HttpGet httpget2 = new HttpGet(downloadUrl);
  httpget2.setHeader("User-Agent", userAgent);

  log.finer("Executing " + httpget2.getURI());
  HttpClient httpclient2 = new DefaultHttpClient();
  HttpResponse response2 = httpclient2.execute(httpget2);
  HttpEntity entity2 = response2.getEntity();
  if (entity2 != null && response2.getStatusLine().getStatusCode() == 200) {
   long length = entity2.getContentLength();
   InputStream instream2 = entity2.getContent();
   log.finer("Writing " + length + " bytes to " + outputfile);
   if (outputfile.exists()) {
    outputfile.delete();
   }
   FileOutputStream outstream = new FileOutputStream(outputfile);
   try {
    byte[] buffer = new byte[2048];
    int count = -1;
    while ((count = instream2.read(buffer)) != -1) {
     outstream.write(buffer, 0, count);
    }
    outstream.flush();
   } finally {
    outstream.close();
   }
  }
 }

 private static String cleanFilename(String filename) {
  for (char c : ILLEGAL_FILENAME_CHARACTERS) {
   filename = filename.replace(c, '_');
  }
  return filename;
 }

 private static URI getUri(String path, List<NameValuePair> qparams) throws URISyntaxException {
  URI uri = URIUtils.createURI(scheme, host, -1, "/" + path, URLEncodedUtils.format(qparams, "UTF-8"), null);
  return uri;
 }

 private static void setupLogging() {
  changeFormatter(new Formatter() {
   @Override
   public String format(LogRecord arg0) {
    return arg0.getMessage() + newline;
   }
  });
  explicitlySetAllLogging(Level.FINER);
 }

 private static void changeFormatter(Formatter formatter) {
  Handler[] handlers = rootlog.getHandlers();
  for (Handler handler : handlers) {
   handler.setFormatter(formatter);
  }
 }

 private static void explicitlySetAllLogging(Level level) {
  rootlog.setLevel(Level.ALL);
  for (Handler handler : rootlog.getHandlers()) {
   handler.setLevel(defaultLogLevelSelf);
  }
  log.setLevel(level);
  rootlog.setLevel(defaultLogLevel);
 }

 private static String getStringFromInputStream(String encoding, InputStream instream) throws UnsupportedEncodingException, IOException {
  Writer writer = new StringWriter();

  char[] buffer = new char[1024];
  try {
   Reader reader = new BufferedReader(new InputStreamReader(instream, encoding));
   int n;
   while ((n = reader.read(buffer)) != -1) {
    writer.write(buffer, 0, n);
   }
  } finally {
   instream.close();
  }
  String result = writer.toString();
  return result;
 }
}

/**
 * <pre>
 * Exploded results from get_video_info:
 * 
 * fexp=90...
 * allow_embed=1
 * fmt_stream_map=35|http://v9.lscache8...
 * fmt_url_map=35|http://v9.lscache8...
 * allow_ratings=1
 * keywords=Stefan Molyneux,Luke Bessey,anarchy,stateless society,giant stone cow,the story of our unenslavement,market anarchy,voluntaryism,anarcho capitalism
 * track_embed=0
 * fmt_list=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
 * author=lukebessey
 * muted=0
 * length_seconds=390
 * plid=AA...
 * ftoken=null
 * status=ok
 * watermark=http://s.ytimg.com/yt/swf/logo-vfl_bP6ud.swf,http://s.ytimg.com/yt/swf/hdlogo-vfloR6wva.swf
 * timestamp=12...
 * has_cc=False
 * fmt_map=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
 * leanback_module=http://s.ytimg.com/yt/swfbin/leanback_module-vflJYyeZN.swf
 * hl=en_US
 * endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vflk19iTq.swf
 * vq=auto
 * avg_rating=5.0
 * video_id=S6IZP3yRJ9I
 * token=vPpcFNh...
 * thumbnail_url=http://i4.ytimg.com/vi/S6IZP3yRJ9I/default.jpg
 * title=The Story of Our Unenslavement - Animated
 * </pre>
 */

How to calculate a logistic sigmoid function in Python?

I feel many might be interested in free parameters to alter the shape of the sigmoid function. Second for many applications you want to use a mirrored sigmoid function. Third you might want to do a simple normalization for example the output values are between 0 and 1.

Try:

def normalized_sigmoid_fkt(a, b, x):
   '''
   Returns array of a horizontal mirrored normalized sigmoid function
   output between 0 and 1
   Function parameters a = center; b = width
   '''
   s= 1/(1+np.exp(b*(x-a)))
   return 1*(s-min(s))/(max(s)-min(s)) # normalize function to 0-1

And to draw and compare:

def draw_function_on_2x2_grid(x): 
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
    plt.subplots_adjust(wspace=.5)
    plt.subplots_adjust(hspace=.5)

    ax1.plot(x, normalized_sigmoid_fkt( .5, 18, x))
    ax1.set_title('1')

    ax2.plot(x, normalized_sigmoid_fkt(0.518, 10.549, x))
    ax2.set_title('2')

    ax3.plot(x, normalized_sigmoid_fkt( .7, 11, x))
    ax3.set_title('3')

    ax4.plot(x, normalized_sigmoid_fkt( .2, 14, x))
    ax4.set_title('4')
    plt.suptitle('Different normalized (sigmoid) function',size=10 )

    return fig

Finally:

x = np.linspace(0,1,100)
Travel_function = draw_function_on_2x2_grid(x)

Sigmoid functions graph

Compare every item to every other item in ArrayList

What's the problem with using for loop inside, just like outside?

for (int j = i + 1; j < list.size(); ++j) {
    ...
}

In general, since Java 5, I used iterators only once or twice.

Remove the last chars of the Java String variable

Another way:

if (s.size > 5) s.reverse.substring(5).reverse

BTW, this is Scala code. May need brackets to work in Java.

Does Java support default parameter values?

No. In general Java doesn't have much (any) syntactic sugar, since they tried to make a simple language.

Best way to convert pdf files to tiff files

https://pypi.org/project/pdf2tiff/

You could also use pdf2ps, ps2image and then convert from the resulting image to tiff with other utilities (I remember 'paul' [paul - Yet another image viewer (displays PNG, TIFF, GIF, JPG, etc.])

Cookies vs. sessions

Basic ideas to distinguish between those two.

Session:

  1. IDU is stored on server (i.e. server-side)
  2. Safer (because of 1)
  3. Expiration can not be set, session variables will be expired when users close the browser. (nowadays it is stored for 24 minutes as default in php)

Cookies:

  1. IDU is stored on web-browser (i.e. client-side)
  2. Not very safe, since hackers can reach and get your information (because of 1)
  3. Expiration can be set (see setcookies() for more information)

Session is preferred when you need to store short-term information/values, such as variables for calculating, measuring, querying etc.

Cookies is preferred when you need to store long-term information/values, such as user's account (so that even when they shutdown the computer for 2 days, their account will still be logged in). I can't think of many examples for cookies since it isn't adopted in most of the situations.

jQuery select by attribute using AND and OR operators

The and operator in a selector is just an empty string, and the or operator is the comma.

There is however no grouping or priority, so you have to repeat one of the conditions:

a=$('[myc=blue][myid="1"],[myc=blue][myid="3"]');

Access cell value of datatable

foreach(DataRow row in dt.Rows)
{
    string value = row[3].ToString();
}

"Fatal error: Unable to find local grunt." when running "grunt" command

I think you have to add grunt to your package.json file. See this link.

sequelize findAll sort order in nodejs

In sequelize you can easily add order by clauses.

exports.getStaticCompanies = function () {
    return Company.findAll({
        where: {
            id: [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680]
        }, 
        // Add order conditions here....
        order: [
            ['id', 'DESC'],
            ['name', 'ASC'],
        ],
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']
    });
};

See how I've added the order array of objects?

order: [
      ['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order
],

Edit:

You might have to order the objects once they've been recieved inside the .then() promise. Checkout this question about ordering an array of objects based on a custom order:

How do I sort an array of objects based on the ordering of another array?

How to convert an ArrayList containing Integers to primitive int array?

Java 8:

int[] intArr = Arrays.stream(integerList).mapToInt(i->i).toArray();

kill -3 to get java thread dump

There is a way to redirect JVM thread dump output on break signal to separate file with LogVMOutput diagnostic option:

-XX:+UnlockDiagnosticVMOptions -XX:+LogVMOutput -XX:LogFile=jvm.log

Get Value of a Edit Text field

step 1 : create layout with name activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#c6cabd"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="17dp"
        android:textColor="#ff0e13"
        />
    <EditText
        android:id="@+id/et"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:hint="Input your country"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get EditText Text"
        android:layout_below="@id/et"
        />
</RelativeLayout>

Step 2 : Create class Main.class

public class Main extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = (Button) findViewById(R.id.btn);
        final TextView tv = (TextView) findViewById(R.id.tv);
        final EditText et = (EditText) findViewById(R.id.et);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String country = et.getText().toString();
                tv.setText("Your inputted country is : " + country);
            }
        });
 }
}

Matching a Forward Slash with a regex

For me, I was trying to match on the / in a date in C#. I did it just by using (\/):

string pattern = "([0-9])([0-9])?(\/)([0-9])([0-9])?(\/)(\d{4})";
string text = "Start Date: 4/1/2018";

Match m = Regex.Match(text, pattern);

if (m.Success) 
{ 
    Console.WriteLine(match.Groups[0].Value);  // 4/1/2018
}
else
{
    Console.WriteLine("Not Found!");
}

JavaScript should also be able to similarly use (\/).

How to mention C:\Program Files in batchfile

use this as somethink

"C:/Program Files (x86)/Nox/bin/nox_adb" install -r app.apk

where

"path_to_executable" commands_argument

How do you create different variable names while in a loop?

One way you can do this is with exec(). For example:

for k in range(5):
    exec(f'cat_{k} = k*2')
>>> print(cat_0)
0
>>> print(cat_1)
2
>>> print(cat_2)
4
>>> print(cat_3)
6
>>> print(cat_4)
8

Here I am taking advantage of the handy f string formatting in Python 3.6+

How to scroll to bottom in a ScrollView on activity startup

After initializing your UI component and fill it with data. add those line to your on create method

Runnable runnable=new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    };
    scrollView.post(runnable);

C# ASP.NET Single Sign-On Implementation

There are multiple options to implement SSO for a .NET application.

Check out the following tutorials online:

Basics of Single Sign on, July 2012

http://www.codeproject.com/Articles/429166/Basics-of-Single-Sign-on-SSO

GaryMcAllisterOnline: ASP.NET MVC 4, ADFS 2.0 and 3rd party STS integration (IdentityServer2), Jan 2013

http://garymcallisteronline.blogspot.com/2013/01/aspnet-mvc-4-adfs-20-and-3rd-party-sts.html

The first one uses ASP.NET Web Forms, while the second one uses ASP.NET MVC4.

If your requirements allow you to use a third-party solution, also consider OpenID. There's an open source library called DotNetOpenAuth.

For further information, read MSDN blog post Integrate OpenAuth/OpenID with your existing ASP.NET application using Universal Providers.

Hope this helps!

Watching variables contents in Eclipse IDE

You can do so by these ways.

Add watchpoint and while debugging you can see variable in debugger window perspective under variable tab. OR Add System.out.println("variable = " + variable); and see in console.

implements Closeable or implements AutoCloseable

AutoCloseable (introduced in Java 7) makes it possible to use the try-with-resources idiom:

public class MyResource implements AutoCloseable {

    public void close() throws Exception {
        System.out.println("Closing!");
    }

}

Now you can say:

try (MyResource res = new MyResource()) {
    // use resource here
}

and JVM will call close() automatically for you.

Closeable is an older interface. For some reason To preserve backward compatibility, language designers decided to create a separate one. This allows not only all Closeable classes (like streams throwing IOException) to be used in try-with-resources, but also allows throwing more general checked exceptions from close().

When in doubt, use AutoCloseable, users of your class will be grateful.

How do I get a list of all subdomains of a domain?

You can use:

$ host -l domain.com

Under the hood, this uses the AXFR query mentioned above. You might not be allowed to do this though. In that case, you'll get a transfer failed message.

shorthand If Statements: C#

Yes. Use the ternary operator.

condition ? true_expression : false_expression;

How to end C++ code

There are several ways, but first you need to understand why object cleanup is important, and hence the reason std::exit is marginalized among C++ programmers.

RAII and Stack Unwinding

C++ makes use of a idiom called RAII, which in simple terms means objects should perform initialization in the constructor and cleanup in the destructor. For instance the std::ofstream class [may] open the file during the constructor, then the user performs output operations on it, and finally at the end of its life cycle, usually determined by its scope, the destructor is called that essentially closes the file and flushes any written content into the disk.

What happens if you don't get to the destructor to flush and close the file? Who knows! But possibly it won't write all the data it was supposed to write into the file.

For instance consider this code

#include <fstream>
#include <exception>
#include <memory>

void inner_mad()
{
    throw std::exception();
}

void mad()
{
    auto ptr = std::make_unique<int>();
    inner_mad();
}

int main()
{
    std::ofstream os("file.txt");
    os << "Content!!!";

    int possibility = /* either 1, 2, 3 or 4 */;

    if(possibility == 1)
        return 0;
    else if(possibility == 2)
        throw std::exception();
    else if(possibility == 3)
        mad();
    else if(possibility == 4)
        exit(0);
}

What happens in each possibility is:

  • Possibility 1: Return essentially leaves the current function scope, so it knows about the end of the life cycle of os thus calling its destructor and doing proper cleanup by closing and flushing the file to disk.
  • Possibility 2: Throwing a exception also takes care of the life cycle of the objects in the current scope, thus doing proper cleanup...
  • Possibility 3: Here stack unwinding enters in action! Even though the exception is thrown at inner_mad, the unwinder will go though the stack of mad and main to perform proper cleanup, all the objects are going to be destructed properly, including ptr and os.
  • Possibility 4: Well, here? exit is a C function and it's not aware nor compatible with the C++ idioms. It does not perform cleanup on your objects, including os in the very same scope. So your file won't be closed properly and for this reason the content might never get written into it!
  • Other Possibilities: It'll just leave main scope, by performing a implicit return 0 and thus having the same effect as possibility 1, i.e. proper cleanup.

But don't be so certain about what I just told you (mainly possibilities 2 and 3); continue reading and we'll find out how to perform a proper exception based cleanup.

Possible Ways To End

Return from main!

You should do this whenever possible; always prefer to return from your program by returning a proper exit status from main.

The caller of your program, and possibly the operating system, might want to know whether what your program was supposed to do was done successfully or not. For this same reason you should return either zero or EXIT_SUCCESS to signal that the program successfully terminated and EXIT_FAILURE to signal the program terminated unsuccessfully, any other form of return value is implementation-defined (§18.5/8).

However you may be very deep in the call stack, and returning all of it may be painful...

[Do not] throw a exception

Throwing a exception will perform proper object cleanup using stack unwinding, by calling the destructor of every object in any previous scope.

But here's the catch! It's implementation-defined whether stack unwinding is performed when a thrown exception is not handled (by the catch(...) clause) or even if you have a noexcept function in the middle of the call stack. This is stated in §15.5.1 [except.terminate]:

  1. In some situations exception handling must be abandoned for less subtle error handling techniques. [Note: These situations are:

    [...]

    when the exception handling mechanism cannot find a handler for a thrown exception (15.3), or when the search for a handler (15.3) encounters the outermost block of a function with a noexcept-specification that does not allow the exception (15.4), or [...]

    [...]

  2. In such cases, std::terminate() is called (18.8.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before std::terminate() is called [...]

So we have to catch it!

Do throw a exception and catch it at main!

Since uncaught exceptions may not perform stack unwinding (and consequently won't perform proper cleanup), we should catch the exception in main and then return a exit status (EXIT_SUCCESS or EXIT_FAILURE).

So a possibly good setup would be:

int main()
{
    /* ... */
    try
    {
        // Insert code that will return by throwing a exception.
    }
    catch(const std::exception&)  // Consider using a custom exception type for intentional
    {                             // throws. A good idea might be a `return_exception`.
        return EXIT_FAILURE;
    }
    /* ... */
}

[Do not] std::exit

This does not perform any sort of stack unwinding, and no alive object on the stack will call its respective destructor to perform cleanup.

This is enforced in §3.6.1/4 [basic.start.init]:

Terminating the program without leaving the current block (e.g., by calling the function std::exit(int) (18.5)) does not destroy any objects with automatic storage duration (12.4). If std::exit is called to end a program during the destruction of an object with static or thread storage duration, the program has undefined behavior.

Think about it now, why would you do such a thing? How many objects have you painfully damaged?

Other [as bad] alternatives

There are other ways to terminate a program (other than crashing), but they aren't recommended. Just for the sake of clarification they are going to be presented here. Notice how normal program termination does not mean stack unwinding but an okay state for the operating system.

  • std::_Exit causes a normal program termination, and that's it.
  • std::quick_exit causes a normal program termination and calls std::at_quick_exit handlers, no other cleanup is performed.
  • std::exit causes a normal program termination and then calls std::atexit handlers. Other sorts of cleanups are performed such as calling static objects destructors.
  • std::abort causes an abnormal program termination, no cleanup is performed. This should be called if the program terminated in a really, really unexpected way. It'll do nothing but signal the OS about the abnormal termination. Some systems perform a core dump in this case.
  • std::terminate calls the std::terminate_handler which calls std::abort by default.

Decode Base64 data in Java

This is a late answer, but Joshua Bloch committed his Base64 class (when he was working for Sun, ahem, Oracle) under the java.util.prefs package. This class existed since JDK 1.4.

E.g.

String currentString = "Hello World";
String base64String = java.util.prefs.Base64.byteArrayToBase64(currentString.getBytes("UTF-8"));

month name to month number and vice versa in python

Just for fun:

from time import strptime

strptime('Feb','%b').tm_mon

when exactly are we supposed to use "public static final String"?

It is kind of standard/best practice. There are already answers listing scenarios, but for your second question:

Why do they have to do that? Why do they have to initialize the value as final prior to using it?

Public constants and fields initialized at declaration should be "static final" rather than merely "final"

These are some of the reasons why it should be like this:

  1. Making a public constant just final as opposed to static final leads to duplicating its value for every instance of the class, uselessly increasing the amount of memory required to execute the application.

  2. Further, when a non-public, final field isn't also static, it implies that different instances can have different values. However, initializing a non-static final field in its declaration forces every instance to have the same value owing to the behavior of the final field.

Get string after character

Use parameter expansion, if the value is already stored in a variable.

$ str="GenFiltEff=7.092200e-01"
$ value=${str#*=}

Or use read

$ IFS="=" read name value <<< "GenFiltEff=7.092200e-01"

Either way,

$ echo $value
7.092200e-01

Check a radio button with javascript

Easiest way would probably be with jQuery, as follows:

$(document).ready(function(){
  $("#_1234").attr("checked","checked");
})

This adds a new attribute "checked" (which in HTML does not need a value). Just remember to include the jQuery library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

PHP: Limit foreach() statement?

You can either use

break;

or

foreach() if ($tmp++ < 2) {
}

(the second solution is even worse)

How to add a “readonly” attribute to an <input>?

Readonly is an attribute as defined in html, so treat it like one.

You need to have something like readonly="readonly" in the object you are working with if you want it not to be editable. And if you want it to be editable again you won't have something like readonly='' (this is not standard if I understood correctly). You really need to remove the attribute as a whole.

As such, while using jquery adding it and removing it is what makes sense.

Set something readonly:

$("#someId").attr('readonly', 'readonly');

Remove readonly:

$("#someId").removeAttr('readonly');

This was the only alternative that really worked for me. Hope it helps!

How to automatically generate getters and setters in Android Studio

You can use AndroidAccessors Plugin of Android Studio to generate getter and setter without m as prefix to methods

Ex: mId; Will generate getId() and setId() instead of getmId() and setmId()

plugin screenshot

Xcode source automatic formatting

You could try that XCode plugin https://github.com/benoitsan/BBUncrustifyPlugin-Xcode

Just clone github repository, open plugin project in XCode and run it. It will be installed automatically. Restart Xode before using formatter plugin.

Don't forget to install uncrustify util before. Homebrew, for exmaple

brew install uncrustify

P.S. You can turn on "after save formatting" feature at Edit > Format Code > BBUncrustifyPlugin Preferences > Format On Save

Hope this will be useful for u ;-)

What is a "callable"?

Callable is a type or class of "Build-in function or Method" with a method call

>>> type(callable)
<class 'builtin_function_or_method'>
>>>

Example: print is a callable object. With a build-in function __call__ When you invoke the print function, Python creates an object of type print and invokes its method __call__ passing the parameters if any.

>>> type(print)
<class 'builtin_function_or_method'>
>>> print.__call__(10)
10
>>> print(10)
10
>>>

Thank you. Regards, Maris

How to serialize an object into a string

Java8 approach, converting Object from/to String, inspired by answer from OscarRyz. For de-/encoding, java.util.Base64 is required and used.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Base64;
import java.util.Optional;

final class ObjectHelper {

  private ObjectHelper() {}

  static Optional<String> convertToString(final Serializable object) {
    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(baos)) {
      oos.writeObject(object);
      return Optional.of(Base64.getEncoder().encodeToString(baos.toByteArray()));
    } catch (final IOException e) {
      e.printStackTrace();
      return Optional.empty();
    }
  }

  static <T extends Serializable> Optional<T> convertFrom(final String objectAsString) {
    final byte[] data = Base64.getDecoder().decode(objectAsString);
    try (final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data))) {
      return Optional.of((T) ois.readObject());
    } catch (final IOException | ClassNotFoundException e) {
      e.printStackTrace();
      return Optional.empty();
    }
  }
}

Extract Google Drive zip from Google colab notebook

Colab research team has a notebook for helping you out.

Still, in short, if you are dealing with a zip file, like for me it is mostly thousands of images and I want to store them in a folder within drive then do this --

!unzip -u "/content/drive/My Drive/folder/example.zip" -d "/content/drive/My Drive/folder/NewFolder"

-u part controls extraction only if new/necessary. It is important if suddenly you lose connection or hardware switches off.

-d creates the directory and extracted files are stored there.

Of course before doing this you need to mount your drive

from google.colab import drive 
drive.mount('/content/drive')

I hope this helps! Cheers!!

Convert Existing Eclipse Project to Maven Project

Right click on the Project name > Configure > Convert to Maven Project > click finish. Here you will add some dependencies to download and add your expected jar file.

This will create an auto-generated pom.xml file. Open that file in xml format in your eclipse editor. After build tag (</build>) add your dependencies which you can copy from maven website and add them there. Now you are good to go. These dependencies will automatically add your required jar files.

How to fade changing background image

Opacity serves your purpose?

If so, try this:

$('#elem').css('opacity','0.3')

Format a JavaScript string using placeholders and an object of substitutions?

The requirements of the original question clearly couldn't benefit from string interpolation, as it seems like it's a runtime processing of arbitrary replacement keys.

However, if you just had to do string interpolation, you can use:

const str = `My name is ${replacements.name} and my age is ${replacements.age}.`

Note the backticks delimiting the string, they are required.


For an answer suiting the particular OP's requirement, you could use String.prototype.replace() for the replacements.

The following code will handle all matches and not touch ones without a replacement (so long as your replacement values are all strings, if not, see below).

var replacements = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"},
    str = 'My Name is %NAME% and my age is %AGE%.';

str = str.replace(/%\w+%/g, function(all) {
   return replacements[all] || all;
});

jsFiddle.

If some of your replacements are not strings, be sure they exists in the object first. If you have a format like the example, i.e. wrapped in percentage signs, you can use the in operator to achieve this.

jsFiddle.

However, if your format doesn't have a special format, i.e. any string, and your replacements object doesn't have a null prototype, use Object.prototype.hasOwnProperty(), unless you can guarantee that none of your potential replaced substrings will clash with property names on the prototype.

jsFiddle.

Otherwise, if your replacement string was 'hasOwnProperty', you would get a resultant messed up string.

jsFiddle.


As a side note, you should be called replacements an Object, not an Array.

Use YAML with variables

if your requirement is like parsing an replacing multiple variable and then use it as a hash/or anything then you can do something like this

require 'yaml'
require 'json'
yaml = YAML.load_file("xxxx.yaml")
blueprint = yaml.to_json % { var_a: "xxxx", var_b: "xxxx"}
hash = JSON.parse(blueprint)

inside the yaml just put variables like this

"%{var_a}"

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

If you don't have double value field or data, maybe you should try to disable sql strict mode.

To do that you have to edit "my.ini" file located in MySQL installation folder, find "Set the SQL mode to strict" line and change the below line:

# Set the SQL mode to strict
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

to this, deleting "STRICT_TRANS_TABLES"

# Set the SQL mode to strict
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

After that, you have to restart MySQL service to enable this change.

To check the change, open the editor an execute this sql sentence:

SHOW VARIABLES LIKE 'sql_mode';

Very Important: Be careful of the file format after saving. Save it as "UTF8" and don't as "TFT8 with BOM" because the service will not restart.

How to correctly display .csv files within Excel 2013?

I know that an answer has already been accepted, but one item to check is the encoding of the CSV file. I have a Powershell script that generates CSV files. By default, it was encoding them as UCS-2 Little Endian (per Notepad++). It would open the file in a single column in Excel and I'd have to do the Text to Columns conversion to split the columns. Changing the script to encode the same output as "ASCII" (UTF-8 w/o BOM per Notepad++) allowed me to open the CSV directly with the columns split out. You can change the encoding of the CSV in Notepad++ too.

  • Menu Encoding > Convert to UTF-8 without BOM
  • Save the CSV file
  • Open in Excel, columns should be split

How to get VM arguments from inside of Java application?

If you want the entire command line of your java process, you can use: JvmArguments.java (uses a combination of JNA + /proc to cover most unix implementations)

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

In the console is telling you that is a conflict with login. I think that you should declare also in the index.html thymeleaf. Something like:

    <html xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:th="http://www.thymeleaf.org" 
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>k</title> 
</head>

Converting Stream to String and back...what are we missing?

In usecase where you want to serialize/deserialize POCOs, Newtonsoft's JSON library is really good. I use it to persist POCOs within SQL Server as JSON strings in an nvarchar field. Caveat is that since its not true de/serialization, it will not preserve private/protected members and class hierarchy.

Installed Java 7 on Mac OS X but Terminal is still using version 6

Check JDK versions installed:

$ ls  /Library/Java/JavaVirtualMachines/
jdk-11.0.2.jdk  jdk1.8.0_91.jdk

Now in your ~/.bashrc export JAVA_HOME specifying the version:

if [ -e /usr/libexec/java_home ]; then
  export JAVA_HOME=$(/usr/libexec/java_home -v 11)
fi

Source the bashrc file and the Java version will be updated:

$ java -version
java version "11.0.2" 2019-01-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)

Float to String format specifier

You can pass a format string to the ToString method, like so:

ToString("N4"); // 4 decimal points Number

If you want to see more modifiers, take a look at MSDN - Standard Numeric Format Strings

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException: Connection reset by peer

The other side has abruptly aborted the connection in midst of a transaction. That can have many causes which are not controllable from the server side on. E.g. the enduser decided to shutdown the client or change the server abruptly while still interacting with your server, or the client program has crashed, or the enduser's internet connection went down, or the enduser's machine crashed, etc, etc.

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

Delete topic in Kafka 0.8.1.1

You can delete a specific kafka topic (example: test) from zookeeper shell command (zookeeper-shell.sh). Use the below command to delete the topic

rmr {path of the topic}

example:

rmr /brokers/topics/test

Using member variable in lambda capture list inside a member function

I believe VS2010 to be right this time, and I'd check if I had the standard handy, but currently I don't.

Now, it's exactly like the error message says: You can't capture stuff outside of the enclosing scope of the lambda. grid is not in the enclosing scope, but this is (every access to grid actually happens as this->grid in member functions). For your usecase, capturing this works, since you'll use it right away and you don't want to copy the grid

auto lambda = [this](){ std::cout << grid[0][0] << "\n"; }

If however, you want to store the grid and copy it for later access, where your puzzle object might already be destroyed, you'll need to make an intermediate, local copy:

vector<vector<int> > tmp(grid);
auto lambda = [tmp](){}; // capture the local copy per copy

† I'm simplifying - Google for "reaching scope" or see §5.1.2 for all the gory details.

How to Get XML Node from XDocument

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>
  <Node>
    <ID>123</ID>
    <Name>ABC</Name>
  </Node>
  <Node>
    <ID>124</ID>
    <Name>DEF</Name>
  </Node>
</Contacts>

Select a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected

XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();

Console.WriteLine(Contact.ToString());

Delete a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";

var Contact = (from xml2 in XMLDoc.Descendants("Node")
               where xml2.Element("ID").Value == id
               select xml2).FirstOrDefault();

Contact.Remove();
XMLDoc.Save("test.xml");

Add new node:

XDocument XMLDoc = XDocument.Load("test.xml");

XElement newNode = new XElement("Node",
    new XElement("ID", "500"),
    new XElement("Name", "Whatever")
);

XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");

How to import/include a CSS file using PHP code and not HTML code?

To use "include" to include CSS, you have to tell PHP you're using CSS code. Add this to your header of your CSS file and make it main.php (or styles.css, or whatever):

header("Content-type: text/css; charset: UTF-8");

This might help with some user's connections, but it theoretically (read: I haven't tested it) adds processor overhead to your server and according to Steve Souder, because your computer can download multiple files at once, using include could be slower. If you have your CSS split into a dozen files, maybe it would be faster?

Steve's blog post: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/ Source: http://css-tricks.com/css-variables-with-php/

Can I have multiple Xcode versions installed?

All the updates for new version of xcode will be available in appstore if you have installed the version from appstore. If you just paste the downloaded version appstore will show install not update. Hence keep the stable version downloaded from appstore in your applications folder.

To try new beta releases i usually put it in separate drive and unzip and install it there. This will avoid confusion while working on stable version.

To avoid confusion you can keep only the stable version in your dock and open the beta version from spotlight(Command + Space). This will place beta temporarily on dock. But it will make sure you don't accidentally edit your client project in beta version.

Most Important:- Working on same project on two different xcode might create some unwanted results. Like there was a bug in interface builder that got introduced in certain version of xcode. Which broke the constraints. It got fixed again in the next one.

Keep track of release notes to know exactly what are additional features and what are known issues.

Abstract variables in Java?

Just add this method to the base class

public abstract class clsAbstractTable {

    public abstract String getTAG();
    public abstract void init();

}

Now every class that extends the base class (and does not want to be abstract) should provide a TAG

You could also go with BalusC's answer

Permanently Set Postgresql Schema Path

You can set the default search_path at the database level:

ALTER DATABASE <database_name> SET search_path TO schema1,schema2;

Or at the user or role level:

ALTER ROLE <role_name> SET search_path TO schema1,schema2;

Or if you have a common default schema in all your databases you could set the system-wide default in the config file with the search_path option.

When a database is created it is created by default from a hidden "template" database named template1, you could alter that database to specify a new default search path for all databases created in the future. You could also create another template database and use CREATE DATABASE <database_name> TEMPLATE <template_name> to create your databases.

How to write a PHP ternary operator

You could also do:

echo "yes" ?: "no" // Assuming that yes is a variable that can be false.

Instead of:

echo (true)  ? "yes" : "no";

Bootstrap 3 unable to display glyphicon properly

For me placing my fonts folder as per location specified in bootstrap.css solved the problem

Mostly its fonts folder should be in parent directory of bootstrap.css file .

I faced this problem , and researching many answers , if anyone still in 2015 faces this problem then its either a CSS problem , or location mismatch for files .

The bug has already been solved by bootstrap

Can I define a class name on paragraph using Markdown?

It should also be mentioned that <span> tags allow inside them -- block-level items negate MD natively inside them unless you configure them not to do so, but in-line styles natively allow MD within them. As such, I often do something akin to...

This is a superfluous paragraph thing.

<span class="class-red">And thus I delve into my topic, Lorem ipsum lollipop bubblegum.</span>

And thus with that I conclude.

I am not 100% sure if this is universal but seems to be the case in all MD editors I've used.

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

Have you thought about creating a view with 'Folder = Show all items without folders', that would get all your documents out of their folders and then perhaps you could create your filter(s) over that view.

Angularjs - ng-cloak/ng-show elements blink

I actually found the suggestion from Rick Strahl's Web Log fixed my issue perfectly (as I still had the odd issue with ng-cloak blinking raw {{code}} at times, especially while running Firebug):

The nuclear option: Hiding the Content manually

Using the explicit CSS is the best choice, so the following shouldn’t ever be necessary. But I’ll mention it here as it gives some insight how you can hide/show content manually on load for other frameworks or in your own markup based templates.

Before I figured out that I could explicitly embed the CSS style into the page, I had tried to figure out why ng-cloak wasn’t doing its job. After wasting an hour getting nowhere I finally decided to just manually hide and show the container. The idea is simple – initially hide the container, then show it once Angular has done its initial processing and removal of the template markup from the page.

You can manually hide the content and make it visible after Angular has gotten control. To do this I used:

<div id="mainContainer" class="mainContainer boxshadow"
    ng-app="app" style="display:none">

Notice the display: none style that explicitly hides the element initially on the page.

Then once Angular has run its initialization and effectively processed the template markup on the page you can show the content. For Angular this ‘ready’ event is the app.run() function:

app.run( function ($rootScope, $location, cellService) {        
    $("#mainContainer").show();
    …
});

This effectively removes the display:none style and the content displays. By the time app.run() fires the DOM is ready to displayed with filled data or at least empty data – Angular has gotten control.

Simulating ENTER keypress in bash script

You might find the yes command useful.

See man yes

Remove last character from string. Swift language

With the new Substring type usage:

Swift 4:

var before: String = "Hello world!"
var lastCharIndex: Int = before.endIndex
var after:String = String(before[..<lastCharIndex])
print(after) // Hello world

Shorter way:

var before: String = "Hello world!"
after = String(before[..<before.endIndex])
print(after) // Hello world

What is the difference between max-device-width and max-width for mobile web?

max-device-width is the device rendering width

@media all and (max-device-width: 400px) {
    /* styles for devices with a maximum width of 400px and less
       Changes only on device orientation */
}

@media all and (max-width: 400px) {
    /* styles for target area with a maximum width of 400px and less
       Changes on device orientation , browser resize */
}

The max-width is the width of the target display area means the current size of browser.

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Css height in percent not working

You need to set 100% height on the parent element.

jQuery object equality

First order your object based on key using this function

function sortObject(o) {
    return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}

Then, compare the stringified version of your object, using this funtion

function isEqualObject(a,b){
    return JSON.stringify(sortObject(a)) == JSON.stringify(sortObject(b));
}

Here is an example

Assuming objects keys are ordered differently and are of the same values

var obj1 = {"hello":"hi","world":"earth"}
var obj2 = {"world":"earth","hello":"hi"}

isEqualObject(obj1,obj2);//returns true

Checking if sys.argv[x] is defined

Another way I haven't seen listed yet is to set your sentinel value ahead of time. This method takes advantage of Python's lazy evaluation, in which you don't always have to provide an else statement. Example:

startingpoint = 'blah'
if len(sys.argv) >= 2:
  startingpoint = sys.argv[1]

Or if you're going syntax CRAZY you could use Python's ternary operator:

startingpoint = sys.argv[1] if len(sys.argv) >= 2 else 'blah'

How do I store and retrieve a blob from sqlite?

This worked fine for me (C#):

byte[] iconBytes = null;
using (var dbConnection = new SQLiteConnection(DataSource))
{
    dbConnection.Open();
    using (var transaction = dbConnection.BeginTransaction())
    {
        using (var command = new SQLiteCommand(dbConnection))
        {
            command.CommandText = "SELECT icon FROM my_table";

            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    if (reader["icon"] != null && !Convert.IsDBNull(reader["icon"]))
                    {
                        iconBytes = (byte[]) reader["icon"];
                    }
                }
            }
        }
        transaction.Commit();
    }
}

No need for chunking. Just cast to a byte array.

Best XML parser for Java

I have found dom4j to be the tool for working with XML. Especially compared to Xerces.

What is the difference between SAX and DOM?

I will provide general Q&A-oriented answer for this question:

Answer to Questions

Why do we need XML parser?

We need XML parser because we do not want to do everything in our application from scratch, and we need some "helper" programs or libraries to do something very low-level but very necessary to us. These low-level but necessary things include checking the well-formedness, validating the document against its DTD or schema (just for validating parsers), resolving character reference, understanding CDATA sections, and so on. XML parsers are just such "helper" programs and they will do all these jobs. With XML parser, we are shielded from a lot of these complexities and we could concentrate ourselves on just programming at high-level through the API's implemented by the parsers, and thus gain programming efficiency.

Which one is better, SAX or DOM ?

Both SAX and DOM parser have their advantages and disadvantages. Which one is better should depend on the characteristics of your application (please refer to some questions below).

Which parser can get better speed, DOM or SAX parsers?

SAX parser can get better speed.

What's the difference between tree-based API and event-based API?

A tree-based API is centered around a tree structure and therefore provides interfaces on components of a tree (which is a DOM document) such as Document interface,Node interface, NodeList interface, Element interface, Attr interface and so on. By contrast, however, an event-based API provides interfaces on handlers. There are four handler interfaces, ContentHandler interface, DTDHandler interface, EntityResolver interface and ErrorHandler interface.

What is the difference between a DOM Parser and a SAX Parser?

DOM parsers and SAX parsers work in different ways:

  • A DOM parser creates a tree structure in memory from the input document and then waits for requests from client. But a SAX parser does not create any internal structure. Instead, it takes the occurrences of components of a input document as events, and tells the client what it reads as it reads through the input document. A

  • DOM parser always serves the client application with the entire document no matter how much is actually needed by the client. But a SAX parser serves the client application always only with pieces of the document at any given time.

  • With DOM parser, method calls in client application have to be explicit and forms a kind of chain. But with SAX, some certain methods (usually overriden by the cient) will be invoked automatically (implicitly) in a way which is called "callback" when some certain events occur. These methods do not have to be called explicitly by the client, though we could call them explicitly.

How do we decide on which parser is good?

Ideally a good parser should be fast (time efficient),space efficient, rich in functionality and easy to use. But in reality, none of the main parsers have all these features at the same time. For example, a DOM Parser is rich in functionality (because it creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree), but it is space inefficient when the document is huge, and it takes a little bit long to learn how to work with it. A SAX Parser, however, is much more space efficient in case of big input document (because it creates no internal structure). What's more, it runs faster and is easier to learn than DOM Parser because its API is really simple. But from the functionality point of view, it provides less functions which mean that the users themselves have to take care of more, such as creating their own data structures. By the way, what is a good parser? I think the answer really depends on the characteristics of your application.

What are some real world applications where using SAX parser is advantageous than using DOM parser and vice versa? What are the usual application for a DOM parser and for a SAX parser?

In the following cases, using SAX parser is advantageous than using DOM parser.

  • The input document is too big for available memory (actually in this case SAX is your only choice)
  • You can process the document in small contiguous chunks of input. You do not need the entire document before you can do useful work
  • You just want to use the parser to extract the information of interest, and all your computation will be completely based on the data structures created by yourself. Actually in most of our applications, we create data structures of our own which are usually not as complicated as the DOM tree. From this sense, I think, the chance of using a DOM parser is less than that of using a SAX parser.

In the following cases, using DOM parser is advantageous than using SAX parser.

  • Your application needs to access widely separately parts of the document at the same time.
  • Your application may probably use a internal data structure which is almost as complicated as the document itself.
  • Your application has to modify the document repeatedly.
  • Your application has to store the document for a significant amount of time through many method calls.

Example (Use a DOM parser or a SAX parser?):

Assume that an instructor has an XML document containing all the personal information of the students as well as the points his students made in his class, and he is now assigning final grades for the students using an application. What he wants to produce, is a list with the SSN and the grades. Also we assume that in his application, the instructor use no data structure such as arrays to store the student personal information and the points. If the instructor decides to give A's to those who earned the class average or above, and give B's to the others, then he'd better to use a DOM parser in his application. The reason is that he has no way to know how much is the class average before the entire document gets processed. What he probably need to do in his application, is first to look through all the students' points and compute the average, and then look through the document again and assign the final grade to each student by comparing the points he earned to the class average. If, however, the instructor adopts such a grading policy that the students who got 90 points or more, are assigned A's and the others are assigned B's, then probably he'd better use a SAX parser. The reason is, to assign each student a final grade, he do not need to wait for the entire document to be processed. He could immediately assign a grade to a student once the SAX parser reads the grade of this student. In the above analysis, we assumed that the instructor created no data structure of his own. What if he creates his own data structure, such as an array of strings to store the SSN and an array of integers to sto re the points ? In this case, I think SAX is a better choice, before this could save both memory and time as well, yet get the job done. Well, one more consideration on this example. What if what the instructor wants to do is not to print a list, but to save the original document back with the grade of each student updated ? In this case, a DOM parser should be a better choice no matter what grading policy he is adopting. He does not need to create any data structure of his own. What he needs to do is to first modify the DOM tree (i.e., set value to the 'grade' node) and then save the whole modified tree. If he choose to use a SAX parser instead of a DOM parser, then in this case he has to create a data structure which is almost as complicated as a DOM tree before he could get the job done.

An Example

Problem statement: Write a Java program to extract all the information about circles which are elements in a given XML document. We assume that each circle element has three child elements(i.e., x, y and radius) as well as a color attribute. A sample document is given below:

<?xml version="1.0"?> 
<!DOCTYPE shapes [
<!ELEMENT shapes (circle)*>
<!ELEMENT circle (x,y,radius)>
<!ELEMENT x (#PCDATA)>
<!ELEMENT y (#PCDATA)>
<!ELEMENT radius (#PCDATA)>
<!ATTLIST circle color CDATA #IMPLIED>
]>

<shapes> 
          <circle color="BLUE"> 
                <x>20</x>
                <y>20</y>
                <radius>20</radius> 
          </circle>
          <circle color="RED" >
                <x>40</x>
                <y>40</y>
                <radius>20</radius> 
          </circle>
</shapes> 

Program with DOMparser

import java.io.*;
import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;


public class shapes_DOM {
   static int numberOfCircles = 0;   // total number of circles seen
   static int x[] = new int[1000];   // X-coordinates of the centers
   static int y[] = new int[1000];   // Y-coordinates of the centers  
   static int r[] = new int[1000];   // radius of the circle
   static String color[] = new String[1000];  // colors of the circles 

   public static void main(String[] args) {   

      try{
         // create a DOMParser
         DOMParser parser=new DOMParser();
         parser.parse(args[0]);

         // get the DOM Document object
         Document doc=parser.getDocument();

         // get all the circle nodes
         NodeList nodelist = doc.getElementsByTagName("circle");
         numberOfCircles =  nodelist.getLength();

         // retrieve all info about the circles
         for(int i=0; i<nodelist.getLength(); i++) {

            // get one circle node
            Node node = nodelist.item(i);

            // get the color attribute 
            NamedNodeMap attrs = node.getAttributes();
            if(attrs.getLength() > 0)
               color[i]=(String)attrs.getNamedItem("color").getNodeValue();

            // get the child nodes of a circle node 
            NodeList childnodelist = node.getChildNodes();

            // get the x and y value 
            for(int j=0; j<childnodelist.getLength(); j++) {
               Node childnode = childnodelist.item(j);
               Node textnode = childnode.getFirstChild();//the only text node
               String childnodename=childnode.getNodeName(); 
               if(childnodename.equals("x")) 
                  x[i]= Integer.parseInt(textnode.getNodeValue().trim());
               else if(childnodename.equals("y")) 
                  y[i]= Integer.parseInt(textnode.getNodeValue().trim());
               else if(childnodename.equals("radius")) 
                  r[i]= Integer.parseInt(textnode.getNodeValue().trim());
            }

         }

         // print the result
         System.out.println("circles="+numberOfCircles);
         for(int i=0;i<numberOfCircles;i++) {
             String line="";
             line=line+"(x="+x[i]+",y="+y[i]+",r="+r[i]+",color="+color[i]+")";
             System.out.println(line);
         }

      }  catch (Exception e) {e.printStackTrace(System.err);}

    }

}

Program with SAXparser

import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.parsers.SAXParser;


public class shapes_SAX extends DefaultHandler {

   static int numberOfCircles = 0;   // total number of circles seen
   static int x[] = new int[1000];   // X-coordinates of the centers
   static int y[] = new int[1000];   // Y-coordinates of the centers
   static int r[] = new int[1000];   // radius of the circle
   static String color[] = new String[1000];  // colors of the circles

   static int flagX=0;    //to remember what element has occurred
   static int flagY=0;    //to remember what element has occurred
   static int flagR=0;    //to remember what element has occurred

   // main method 
   public static void main(String[] args) {   
      try{
         shapes_SAX SAXHandler = new shapes_SAX (); // an instance of this class
         SAXParser parser=new SAXParser();          // create a SAXParser object 
         parser.setContentHandler(SAXHandler);      // register with the ContentHandler 
         parser.parse(args[0]);
      }  catch (Exception e) {e.printStackTrace(System.err);}  // catch exeptions
   }

   // override the startElement() method
   public void startElement(String uri, String localName, 
                       String rawName, Attributes attributes) {
         if(rawName.equals("circle"))                      // if a circle element is seen
            color[numberOfCircles]=attributes.getValue("color");  // get the color attribute 

         else if(rawName.equals("x"))      // if a x element is seen set the flag as 1 
            flagX=1;
         else if(rawName.equals("y"))      // if a y element is seen set the flag as 2
            flagY=1;
         else if(rawName.equals("radius")) // if a radius element is seen set the flag as 3 
            flagR=1;
   }

   // override the endElement() method
   public void endElement(String uri, String localName, String rawName) {
         // in this example we do not need to do anything else here
         if(rawName.equals("circle"))                       // if a circle element is ended 
            numberOfCircles +=  1;                          // increment the counter 
   }

   // override the characters() method
   public void characters(char characters[], int start, int length) {
         String characterData = 
             (new String(characters,start,length)).trim(); // get the text

         if(flagX==1) {        // indicate this text is for <x> element 
             x[numberOfCircles] = Integer.parseInt(characterData);
             flagX=0;
         }
         else if(flagY==1) {  // indicate this text is for <y> element 
             y[numberOfCircles] = Integer.parseInt(characterData);
             flagY=0;
         }
         else if(flagR==1) {  // indicate this text is for <radius> element 
             r[numberOfCircles] = Integer.parseInt(characterData);
             flagR=0;
         }
   }

   // override the endDocument() method
   public void endDocument() {
         // when the end of document is seen, just print the circle info 
         System.out.println("circles="+numberOfCircles);
         for(int i=0;i<numberOfCircles;i++) {
             String line="";
             line=line+"(x="+x[i]+",y="+y[i]+",r="+r[i]+",color="+color[i]+")";
             System.out.println(line);
         }
   }


}

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The JAX-WS dependency library “jaxws-rt.jar” is missing.

Go here http://jax-ws.java.net/. Download JAX-WS RI distribution. Unzip it and copy “jaxws-rt.jar” to Tomcat library folder “{$TOMCAT}/lib“. Restart Tomcat.

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

When I used the code mysqld_safe --skip-grant-tables & but I get the error:

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.

$ systemctl stop  mysql.service
$ ps -eaf|grep mysql
$ mysqld_safe --skip-grant-tables &

I solved:

$ mkdir -p /var/run/mysqld
$ chown mysql:mysql /var/run/mysqld

Now I use the same code mysqld_safe --skip-grant-tables & and get

mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

If I use $ mysql -u root I'll get :

Server version: 5.7.18-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Now time to change password:

mysql> use mysql
mysql> describe user;

Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

Database changed

mysql> FLUSH PRIVILEGES;
mysql> SET PASSWORD FOR root@'localhost' = PASSWORD('newpwd');

or If you have a mysql root account that can connect from everywhere, you should also do:

UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';

Alternate Method:

   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')
   WHERE Host = 'localhost' AND User = 'root';

And if you have a root account that can access from everywhere:

 USE mysql
 UPDATE user SET Password = PASSWORD('newpwd')
 WHERE Host = '%' AND User = 'root';`enter code here

now need to quit from mysql and stop/start

FLUSH PRIVILEGES;
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

now again ` mysql -u root -p' and use the new password to get

mysql>