Programs & Examples On #Named scopes

How can I tell which button was clicked in a PHP form submit?

With an HTML form like:

<input type="submit" name="btnSubmit" value="Save Changes" />
<input type="submit" name="btnDelete" value="Delete" />

The PHP code to use would look like:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Something posted

    if (isset($_POST['btnDelete'])) {
        // btnDelete
    } else {
        // Assume btnSubmit
    }
}

You should always assume or default to the first submit button to appear in the form HTML source code. In practice, the various browsers reliably send the name/value of a submit button with the post data when:

  1. The user literally clicks the submit button with the mouse or pointing device
  2. Or there is focus on the submit button (they tabbed to it), and then the Enter key is pressed.

Other ways to submit a form exist, and some browsers/versions decide not to send the name/value of any submit buttons in some of these situations. For example, many users submit forms by pressing the Enter key when the cursor/focus is on a text field. Forms can also be submitted via JavaScript, as well as some more obscure methods.

It's important to pay attention to this detail, otherwise you can really frustrate your users when they submit a form, yet "nothing happens" and their data is lost, because your code failed to detect a form submission, because you did not anticipate the fact that the name/value of a submit button may not be sent with the post data.

Also, the above advice should be used for forms with a single submit button too because you should always assume a default submit button.

I'm aware that the Internet is filled with tons of form-handler tutorials, and almost of all them do nothing more than check for the name and value of a submit button. But, they're just plain wrong!

matplotlib get ylim values

Leveraging from the good answers above and assuming you were only using plt as in

import matplotlib.pyplot as plt

then you can get all four plot limits using plt.axis() as in the following example.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8]  # fake data
y = [1, 2, 3, 4, 3, 2, 5, 6]

plt.plot(x, y, 'k')

xmin, xmax, ymin, ymax = plt.axis()

s = 'xmin = ' + str(round(xmin, 2)) + ', ' + \
    'xmax = ' + str(xmax) + '\n' + \
    'ymin = ' + str(ymin) + ', ' + \
    'ymax = ' + str(ymax) + ' '

plt.annotate(s, (1, 5))

plt.show()

The above code should produce the following output plot. enter image description here

Hour from DateTime? in 24 hours format

Using ToString("HH:mm") certainly gives you what you want as a string.

If you want the current hour/minute as numbers, string manipulation isn't necessary; you can use the TimeOfDay property:

TimeSpan timeOfDay = fechaHora.TimeOfDay;
int hour = timeOfDay.Hours;
int minute = timeOfDay.Minutes;

How can I generate random alphanumeric strings?

var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[8];
var random = new Random();

for (int i = 0; i < stringChars.Length; i++)
{
    stringChars[i] = chars[random.Next(chars.Length)];
}

var finalString = new String(stringChars);

Not as elegant as the Linq solution.

(Note: The use of the Random class makes this unsuitable for anything security related, such as creating passwords or tokens. Use the RNGCryptoServiceProvider class if you need a strong random number generator.)

Advantages of std::for_each over for loop

With C++11 and two simple templates, you can write

        for ( auto x: range(v1+4,v1+6) ) {
                x*=2;
                cout<< x <<' ';
        }

as a replacement for for_each or a loop. Why choose it boils down to brevity and safety, there's no chance of error in an expression that's not there.

For me, for_each was always better on the same grounds when the loop body is already a functor, and I'll take any advantage I can get.

You still use the three-expression for, but now when you see one you know there's something to understand there, it's not boilerplate. I hate boilerplate. I resent its existence. It's not real code, there's nothing to learn by reading it, it's just one more thing that needs checking. The mental effort can be measured by how easy it is to get rusty at checking it.

The templates are

template<typename iter>
struct range_ { 
                iter begin() {return __beg;}    iter end(){return __end;}
            range_(iter const&beg,iter const&end) : __beg(beg),__end(end) {}
            iter __beg, __end;
};

template<typename iter>
range_<iter> range(iter const &begin, iter const &end)
    { return range_<iter>(begin,end); }

Location of hibernate.cfg.xml in project?

Somehow placing under "src" folder didn't work for me.

Instead placing cfg.xml as below:

[Project Folder]\src\main\resources\hibernate.cfg.xml

worked. Using this code

new Configuration().configure().buildSessionFactory().openSession();

in a file under

    [Project Folder]/src/main/java/com/abc/xyz/filename.java

In addition have this piece of code in hibernate.cfg.xml

<mapping resource="hibernate/Address.hbm.xml" />
<mapping resource="hibernate/Person.hbm.xml" />

Placed the above hbm.xml files under:

EDIT:

[Project Folder]/src/main/resources/hibernate/Address.hbm.xml
[Project Folder]/src/main/resources/hibernate/Person.hbm.xml

Above structure worked.

Set CFLAGS and CXXFLAGS options using CMake

You must change the cmake C/CXX default FLAGS .

According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE} put in the main CMakeLists.txt one of :

For C

set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")

For C++

set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")

This will override the values defined in CMakeCache.txt

Is it possible to decrypt SHA1

SHA1 is a one way hash. So you can not really revert it.

That's why applications use it to store the hash of the password and not the password itself.

Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.

Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.

Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.

In his blog he shows a table that tells us the probability of collisions for a given input set.

Hash Collision Probabilities Table

As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.

A simple java program will show us what his table shows:

public class Main {

    public static void main(String[] args) {
        char[] inputValue = new char[10];

        Map<Integer, String> hashValues = new HashMap<Integer, String>();

        int collisionCount = 0;

        for (int i = 0; i < 77163; i++) {
            String asString = nextValue(inputValue);
            int hashCode = asString.hashCode();
            String collisionString = hashValues.put(hashCode, asString);
            if (collisionString != null) {
                collisionCount++;
                System.out.println("Collision: " + asString + " <-> " + collisionString);
            }
        }

        System.out.println("Collision count: " + collisionCount);
    }

    private static String nextValue(char[] inputValue) {
        nextValue(inputValue, 0);

        int endIndex = 0;
        for (int i = 0; i < inputValue.length; i++) {
            if (inputValue[i] == 0) {
                endIndex = i;
                break;
            }
        }

        return new String(inputValue, 0, endIndex);
    }

    private static void nextValue(char[] inputValue, int index) {
        boolean increaseNextIndex = inputValue[index] == 'z';

        if (inputValue[index] == 0 || increaseNextIndex) {
            inputValue[index] = 'A';
        } else {
            inputValue[index] += 1;
        }

        if (increaseNextIndex) {
            nextValue(inputValue, index + 1);
        }

    }

}

My output end with:

Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135

It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A and z.

Let's take the last reported collision and check

System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());

My output is

86390
86390

Conclusion:

If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.

And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.

Get the new record primary key ID from MySQL insert query?

simply use "$last_id = mysqli_insert_id($conn);"

Can you create nested WITH clauses for Common Table Expressions?

These answers are pretty good, but as far as getting the items to order properly, you'd be better off looking at this article http://dataeducation.com/dr-output-or-how-i-learned-to-stop-worrying-and-love-the-merge

Here's an example of his query.

WITH paths AS ( 
    SELECT 
        EmployeeID, 
        CONVERT(VARCHAR(900), CONCAT('.', EmployeeID, '.')) AS FullPath 
    FROM EmployeeHierarchyWide 
    WHERE ManagerID IS NULL

    UNION ALL

    SELECT 
        ehw.EmployeeID, 
        CONVERT(VARCHAR(900), CONCAT(p.FullPath, ehw.EmployeeID, '.')) AS FullPath 
    FROM paths AS p 
        JOIN EmployeeHierarchyWide AS ehw ON ehw.ManagerID = p.EmployeeID 
) 
SELECT * FROM paths order by FullPath

iPhone X / 8 / 8 Plus CSS media queries

Here are some of the following media queries for iPhones. Here is the ref link https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions

        /* iphone 3 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 1) { }
        
        /* iphone 4 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 2) { }
        
        /* iphone 5 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (-webkit-device-pixel-ratio: 2) { }
        
        /* iphone 6, 6s, 7, 8 */
        @media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (-webkit-device-pixel-ratio: 2) { }
            
        /* iphone 6+, 6s+, 7+, 8+ */
        @media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (-webkit-device-pixel-ratio: 3) { }
        
        /* iphone X , XS, 11 Pro, 12 Mini */
        @media only screen and (min-device-width: 375px) and (max-device-height: 812px) and (-webkit-device-pixel-ratio: 3) { }

        /* iphone 12, 12 Pro */
        @media only screen and (min-device-width: 390px) and (max-device-height: 844px) and (-webkit-device-pixel-ratio: 3) { }
       
        /* iphone XR, 11 */
        @media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 2) { }
            
        /* iphone XS Max, 11 Pro Max */
        @media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 3) { }

        /* iphone 12 Pro Max */
        @media only screen and (min-device-width : 428px) and (max-device-height : 926px) and (-webkit-device-pixel-ratio : 3) { }

HTML5 Video autoplay on iPhone

Does playsinline attribute help?

Here's what I have:

<video autoplay loop muted playsinline class="video-background ">
  <source src="videos/intro-video3.mp4" type="video/mp4">
</video>

See the comment on playsinline here: https://webkit.org/blog/6784/new-video-policies-for-ios/

How to securely save username/password (local)?

I wanted to encrypt and decrypt the string as a readable string.

Here is a very simple quick example in C# Visual Studio 2019 WinForms based on the answer from @Pradip.

Right click project > properties > settings > Create a username and password setting.

enter image description here

Now you can leverage those settings you just created. Here I save the username and password but only encrypt the password in it's respectable value field in the user.config file.

Example of the encrypted string in the user.config file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <secure_password_store.Properties.Settings>
            <setting name="username" serializeAs="String">
                <value>admin</value>
            </setting>
            <setting name="password" serializeAs="String">
                <value>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAQpgaPYIUq064U3o6xXkQOQAAAAACAAAAAAAQZgAAAAEAACAAAABlQQ8OcONYBr9qUhH7NeKF8bZB6uCJa5uKhk97NdH93AAAAAAOgAAAAAIAACAAAAC7yQicDYV5DiNp0fHXVEDZ7IhOXOrsRUbcY0ziYYTlKSAAAACVDQ+ICHWooDDaUywJeUOV9sRg5c8q6/vizdq8WtPVbkAAAADciZskoSw3g6N9EpX/8FOv+FeExZFxsm03i8vYdDHUVmJvX33K03rqiYF2qzpYCaldQnRxFH9wH2ZEHeSRPeiG</value>
            </setting>
        </secure_password_store.Properties.Settings>
    </userSettings>
</configuration>

enter image description here

Full Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace secure_password_store
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Login_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                Properties.Settings.Default.username = textBox1.Text;
                Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
                Properties.Settings.Default.Save();
            }
            else if (checkBox1.Checked == false)
            {
                Properties.Settings.Default.username = "";
                Properties.Settings.Default.password = "";
                Properties.Settings.Default.Save();
            }
            MessageBox.Show("{\"data\": \"some data\"}","Login Message Alert",MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void DecryptString_Click(object sender, EventArgs e)
        {
            SecureString password = DecryptString(Properties.Settings.Default.password);
            string readable = ToInsecureString(password);
            textBox4.AppendText(readable + Environment.NewLine);
        }
        private void Form_Load(object sender, EventArgs e)
        {
            //textBox1.Text = "UserName";
            //textBox2.Text = "Password";
            if (Properties.Settings.Default.username != string.Empty)
            {
                textBox1.Text = Properties.Settings.Default.username;
                checkBox1.Checked = true;
                SecureString password = DecryptString(Properties.Settings.Default.password);
                string readable = ToInsecureString(password);
                textBox2.Text = readable;
            }
            groupBox1.Select();
        }


        static byte[] entropy = Encoding.Unicode.GetBytes("SaLtY bOy 6970 ePiC");

        public static string EncryptString(SecureString input)
        {
            byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(ToInsecureString(input)),entropy,DataProtectionScope.CurrentUser);
            return Convert.ToBase64String(encryptedData);
        }

        public static SecureString DecryptString(string encryptedData)
        {
            try
            {
                byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(encryptedData),entropy,DataProtectionScope.CurrentUser);
                return ToSecureString(Encoding.Unicode.GetString(decryptedData));
            }
            catch
            {
                return new SecureString();
            }
        }

        public static SecureString ToSecureString(string input)
        {
            SecureString secure = new SecureString();
            foreach (char c in input)
            {
                secure.AppendChar(c);
            }
            secure.MakeReadOnly();
            return secure;
        }

        public static string ToInsecureString(SecureString input)
        {
            string returnValue = string.Empty;
            IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
            try
            {
                returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
            }
            return returnValue;
        }

        private void EncryptString_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
            textBox3.AppendText(Properties.Settings.Default.password.ToString() + Environment.NewLine);
        }
    }
}

Parameter "stratify" from method "train_test_split" (scikit Learn)

Scikit-Learn is just telling you it doesn't recognise the argument "stratify", not that you're using it incorrectly. This is because the parameter was added in version 0.17 as indicated in the documentation you quoted.

So you just need to update Scikit-Learn.

How to execute a bash command stored as a string with quotes and asterisk

To eliminate the need for the cmd variable, you can do this:

eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'

Java OCR implementation

I recommend trying the Java OCR project on sourceforge.net. I originally developed it, and I have a blog posting on it.

Since I put it up on sourceforge, its functionality been expanded and improved quite a bit through the great work of a volunteer researcher/developer.

Give it a try, and if you don't like it, you can always improve it!

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

You can use function: wc_get_page_id( 'cart' ) to get the ID of the page. This function will use the page setup as 'cart' page and not the slug. Meaning it will keep working also when you setup a different url for your 'cart' on the settings page. This works for all kind of Woocommerce special page, like 'checkout', 'shop' etc.

example:

if (wc_get_page_id( 'cart' ) == get_the_ID()) {
  // Do something.
}

bash echo number of lines of file given in a bash variable without the file name

I normally use the 'back tick' feature of bash

export NUM_LINES=`wc -l filename`

Note the 'tick' is the 'back tick' e.g. ` not the normal single quote

What is the opposite of evt.preventDefault();

you can use this after "preventDefault" method

//Here evt.target return default event (eg : defult url etc)

var defaultEvent=evt.target;

//Here we save default event ..

if("true")
{
//activate default event..
location.href(defaultEvent);
}

How to generate a random string in Ruby

We've been using this on our code:

class String

  def self.random(length=10)
    ('a'..'z').sort_by {rand}[0,length].join
  end

end

The maximum length supported is 25 (we're only using it with the default anyway, so hasn't been a problem).

Someone mentioned that 'a'..'z' is suboptimal if you want to completely avoid generating offensive words. One of the ideas we had was removing vowels, but you still end up with WTFBBQ etc.

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

Column values from the SELECT statement are assigned into @low and @day local variables; the @adjustedLow value is not assigned into any variable and it causes the problem:

The problem is here:

select 
    top 1 @low = low
    , @day = day
    , @adjustedLow  -- causes error!
--select high
from 
    securityquote sq
...

Detailed explanation and workaround: SQL Server Error Messages - Msg 141 - A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.

Add a prefix string to beginning of each line

Here's a wrapped up example using the sed approach from this answer:

$ cat /path/to/some/file | prefix_lines "WOW: "

WOW: some text
WOW: another line
WOW: more text

prefix_lines

function show_help()
{
  IT=$(CAT <<EOF
    Usage: PREFIX {FILE}

    e.g.

    cat /path/to/file | prefix_lines "WOW: "

      WOW: some text
      WOW: another line
      WOW: more text
  )
  echo "$IT"
  exit
}

# Require a prefix
if [ -z "$1" ]
then
  show_help
fi

# Check if input is from stdin or a file
FILE=$2
if [ -z "$2" ]
then
  # If no stdin exists
  if [ -t 0 ]; then
    show_help
  fi
  FILE=/dev/stdin
fi

# Now prefix the output
PREFIX=$1
sed -e "s/^/$PREFIX/" $FILE

error: Unable to find vcvarsall.bat

I encountered this issue when I tried to install numpy library on my python 3.5. The solution is to install VS2015. I had VS2008, 2012, 2013, none of which is compatible with python 3.5. Apparently newer version of python has dependency on newer versions of VS.

Also make sure C++ Common Tools are installed with Visual Studio.

enter image description here

What techniques can be used to speed up C++ compilation times?

  • Upgrade your computer

    1. Get a quad core (or a dual-quad system)
    2. Get LOTS of RAM.
    3. Use a RAM drive to drastically reduce file I/O delays. (There are companies that make IDE and SATA RAM drives that act like hard drives).
  • Then you have all your other typical suggestions

    1. Use precompiled headers if available.
    2. Reduce the amount of coupling between parts of your project. Changing one header file usually shouldn't require recompiling your entire project.

What is the difference between tree depth and height?

The answer by Daniel A.A. Pelsmaeker and Yesh analogy is excellent. I would like to add a bit more from hackerrank tutorial. Hope it helps a bit too.

  • The depth(or level) of a node is its distance(i.e. no of edges) from tree's root node.
  • The height is number of edges between root node and furthest leaf.
  • height(node) = 1 + max(height(node.leftSubtree),height(node.rightSubtree)).
    Keep in mind the following points before reading the example ahead.
  • Any node has a height of 1.
  • Height of empty subtree is -1.
  • Height of single element tree or leaf node is 0.
    Example to calculate height of tree

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

For me, the following combination worked:
| Key Action Esc+ End result | |-----------------------------------------------------| | ?? Send Escape Sequence a Send ^[ a | | ?? Send Escape Sequence e Send ^[ e |

CSS way to horizontally align table

Although it might be heresy in today's world - in the past you would do the following non-css code. This works in everything up to and including today's browsers but - as I have said - it is heresy in today's world:

<center>
<table>
   ...
</table>
</center>

What you need is some way to tell that you want to center a table and the person is using an older browser. Then insert the "<center>" commands around the table. Otherwise - use css.

Surprisingly - if you want to center everything in the BODY area - you just can use the standard

text-align: center;

css command and in IE8 (at least) it will center everything on the page including tables.

How to install pandas from pip on windows cmd?

If you are a windows user:
make sure you added the script(dir) path to environment variables
C:\Python34\Scripts
for more how to set path vist

Session variables in ASP.NET MVC

Great answers from the guys but I would caution you against always relying on the Session. It is quick and easy to do so, and of course would work but would not be great in all cicrumstances.

For example if you run into a scenario where your hosting doesn't allow session use, or if you are on a web farm, or in the example of a shared SharePoint application.

If you wanted a different solution you could look at using an IOC Container such as Castle Windsor, creating a provider class as a wrapper and then keeping one instance of your class using the per request or session lifestyle depending on your requirements.

The IOC would ensure that the same instance is returned each time.

More complicated yes, if you need a simple solution just use the session.

Here are some implementation examples below out of interest.

Using this method you could create a provider class along the lines of:

public class CustomClassProvider : ICustomClassProvider
{
    public CustomClassProvider(CustomClass customClass)
    { 
        CustomClass = customClass;
    }

    public string CustomClass { get; private set; }
}

And register it something like:

public void Install(IWindsorContainer container, IConfigurationStore store)
{
    container.Register(
            Component.For<ICustomClassProvider>().UsingFactoryMethod(
                () => new CustomClassProvider(new CustomClass())).LifestylePerWebRequest());
    }

Named placeholders in string formatting

My answer is to:

a) use StringBuilder when possible

b) keep (in any form: integer is the best, speciall char like dollar macro etc) position of "placeholder" and then use StringBuilder.insert() (few versions of arguments).

Using external libraries seems overkill and I belive degrade performance significant, when StringBuilder is converted to String internally.

SQL Server - boolean literal?

You can use the values 'TRUE' and 'FALSE'. From https://docs.microsoft.com/en-us/sql/t-sql/data-types/bit-transact-sql:

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

Print string to text file

text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

If you use a context manager, the file is closed automatically for you

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

If you're using Python2.6 or higher, it's preferred to use str.format()

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

For python2.7 and higher you can use {} instead of {0}

In Python3, there is an optional file parameter to the print function

with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6 introduced f-strings for another alternative

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)

Is it possible to style a select box?

If have a solution without jQuery. A link where you can see a working example: http://www.letmaier.com/_selectbox/select_general_code.html (styled with more css)

The style-section of my solution:

<style>
#container { margin: 10px; padding: 5px; background: #E7E7E7; width: 300px; background: #ededed); }
#ul1 { display: none; list-style-type: none; list-style-position: outside; margin: 0px; padding: 0px; }
#container a {  color: #333333; text-decoration: none; }
#container ul li {  padding: 3px;   padding-left: 0px;  border-bottom: 1px solid #aaa;  font-size: 0.8em; cursor: pointer; }
#container ul li:hover { background: #f5f4f4; }
</style>

Now the HTML-code inside the body-tag:

<form>
<div id="container" onMouseOver="document.getElementById('ul1').style.display = 'block';" onMouseOut="document.getElementById('ul1').style.display = 'none';">
Select one entry: <input name="entrytext" type="text" disabled readonly>
<ul id="ul1">
    <li onClick="document.forms[0].elements['entrytext'].value='Entry 1'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 1</a></li>
    <li onClick="document.forms[0].elements['entrytext'].value='Entry 2'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 2</a></li>
    <li onClick="document.forms[0].elements['entrytext'].value='Entry 3'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 3</a></li>
</ul>
</div>
</form>

How to suppress warnings globally in an R Script

You want options(warn=-1). However, note that warn=0 is not the safest warning level and it should not be assumed as the current one, particularly within scripts or functions. Thus the safest way to temporary turn off warnings is:

oldw <- getOption("warn")
options(warn = -1)

[your "silenced" code]

options(warn = oldw)

Is there a max size for POST parameter content?

There may be a limit depending on server and/or application configuration. For Example, check

How do you convert a C++ string to an int?

in "stdapi.h"

StrToInt

This function tells you the result, and how many characters participated in the conversion.

Using wire or reg with input or output in Verilog

The Verilog code compiler you use will dictate what you have to do. If you use illegal syntax, you will get a compile error.

An output must also be declared as a reg only if it is assigned using a "procedural assignment". For example:

output reg a;
always @* a = b;

There is no need to declare an output as a wire.

There is no need to declare an input as a wire or reg.

how to sync windows time from a ntp time server in command

net stop w32time
w32tm /config /syncfromflags:manual /manualpeerlist:"0.it.pool.ntp.org 1.it.pool.ntp.org 2.it.pool.ntp.org 3.it.pool.ntp.org"
net start w32time
w32tm /config /update
w32tm /resync /rediscover

.BAT Sample File: https://gist.github.com/thedom85/dbeb58627adfb3d5c3af

I also recommend this program: http://www.timesynctool.com/

How to access my localhost from another PC in LAN?

after your pc connects to other pc use these 4 step:
4 steps:
1- Edit this file: httpd.conf
for that click on wamp server and select Apache and select httpd.conf
2- Find this text: Deny from all
in the below tag:

  <Directory "c:/wamp/www"><!-- maybe other url-->

    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
#    Require all granted
#   onlineoffline tag - don't remove
     Order Deny,Allow
    Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost
</Directory>

3- Change to: Deny from none
like this:

<Directory "c:/wamp/www">

    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
#    Require all granted
#   onlineoffline tag - don't remove
     Order Deny,Allow
    Deny from none
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

4- Restart Apache
Don't forget restart Apache or all servises!!!

Get Cell Value from a DataTable in C#

To get cell column name as well as cell value :

List<JObject> dataList = new List<JObject>();

for (int i = 0; i < dataTable.Rows.Count; i++)
{
    JObject eachRowObj = new JObject();

    for (int j = 0; j < dataTable.Columns.Count; j++)
    {
        string key = Convert.ToString(dataTable.Columns[j]);
        string value = Convert.ToString(dataTable.Rows[i].ItemArray[j]);

        eachRowObj.Add(key, value);

    }

    dataList.Add(eachRowObj);

}

Is it possible to reference one CSS rule within another?

You can use var() function.

The var() CSS function can be used to insert the value of a custom property (sometimes called a "CSS variable") instead of any part of a value of another property.

Example:

:root {
  --main-bg-color: yellow;
}

@media (prefers-color-scheme: dark) {
  :root {
    --main-bg-color: black;
  }
}

body {
  background-color: var(--main-bg-color);
}

Using If/Else on a data frame

Try this

frame$twohouses <- ifelse(frame$data>1, 2, 1)
 frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
6     2         2
7     3         2
8     1         1
9     4         2
10    3         2
11    2         2
12    4         2
13    0         1
14    1         1
15    2         2
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

How to export data to an excel file using PHPExcel

Try the below complete example for the same

<?php
  $objPHPExcel = new PHPExcel();
  $query1 = "SELECT * FROM employee";
  $exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
  $serialnumber=0;
  //Set header with temp array
  $tmparray =array("Sr.Number","Employee Login","Employee Name");
  //take new main array and set header array in it.
  $sheet =array($tmparray);

  while ($res1 = mysql_fetch_array($exec1))
  {
    $tmparray =array();
    $serialnumber = $serialnumber + 1;
    array_push($tmparray,$serialnumber);
    $employeelogin = $res1['employeelogin'];
    array_push($tmparray,$employeelogin);
    $employeename = $res1['employeename'];
    array_push($tmparray,$employeename);   
    array_push($sheet,$tmparray);
  }
   header('Content-type: application/vnd.ms-excel');
   header('Content-Disposition: attachment; filename="name.xlsx"');
  $worksheet = $objPHPExcel->getActiveSheet();
  foreach($sheet as $row => $columns) {
    foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
    }
  }

  //make first row bold
  $objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
  $objPHPExcel->setActiveSheetIndex(0);
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>

differences in application/json and application/x-www-form-urlencoded

The first case is telling the web server that you are posting JSON data as in:

{ Name : 'John Smith', Age: 23}

The second option is telling the web server that you will be encoding the parameters in the URL as in:

Name=John+Smith&Age=23

Prevent form redirect OR refresh on submit?

If you want to see the default browser errors being displayed, for example, those triggered by HTML attributes (showing up before any client-code JS treatment):

<input name="o" required="required" aria-required="true" type="text">

You should use the submit event instead of the click event. In this case a popup will be automatically displayed requesting "Please fill out this field". Even with preventDefault:

$('form').on('submit', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will show up a "Please fill out this field" pop-up before my_form_treatment

As someone mentioned previously, return false would stop propagation (i.e. if there are more handlers attached to the form submission, they would not be executed), but, in this case, the action triggered by the browser will always execute first. Even with a return false at the end.

So if you want to get rid of these default pop-ups, use the click event on the submit button:

$('form input[type=submit]').on('click', function(event) {
   event.preventDefault();
   my_form_treatment(this, event);
}); // -> this will NOT show any popups related to HTML attributes

How to replace all spaces in a string

takes care of multiple white spaces and replaces it for a single character

myString.replace(/\s+/g, "-")

http://jsfiddle.net/aC5ZW/340/

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

viewDidLoad is things you have to do once. viewWillAppear gets called every time the view appears. You should do things that you only have to do once in viewDidLoad - like setting your UILabel texts. However, you may want to modify a specific part of the view every time the user gets to view it, e.g. the iPod application scrolls the lyrics back to the top every time you go to the "Now Playing" view.

However, when you are loading things from a server, you also have to think about latency. If you pack all of your network communication into viewDidLoad or viewWillAppear, they will be executed before the user gets to see the view - possibly resulting a short freeze of your app. It may be good idea to first show the user an unpopulated view with an activity indicator of some sort. When you are done with your networking, which may take a second or two (or may even fail - who knows?), you can populate the view with your data. Good examples on how this could be done can be seen in various twitter clients. For example, when you view the author detail page in Twitterrific, the view only says "Loading..." until the network queries have completed.

How to increase the gap between text and underlining in CSS

just use

{
   text-decoration-line: underline;
   text-underline-offset: 2px;
}


How to get an MD5 checksum in PowerShell

Here is the snippet that I am using to get the MD5 for a given string:

$text = "text goes here..."
$md5  = [Security.Cryptography.MD5CryptoServiceProvider]::new()
$utf8 = [Text.UTF8Encoding]::UTF8
$bytes= $md5.ComputeHash($utf8.GetBytes($text))
$hash = [string]::Concat($bytes.foreach{$_.ToString("x2")}) 

Html helper for <input type="file" />

This is a little hacky I guess, but it results in the correct validation attributes etc being applied

@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))

Create a directory if it does not exist and then create the files in that directory as well

Trying to make this as short and simple as possible. Creates directory if it doesn't exist, and then returns the desired file:

/** Creates parent directories if necessary. Then returns file */
private static File fileWithDirectoryAssurance(String directory, String filename) {
    File dir = new File(directory);
    if (!dir.exists()) dir.mkdirs();
    return new File(directory + "/" + filename);
}

npm global path prefix

I managed to fix Vue Cli no command error by doing the following:

  • In terminal sudo nano ~/.bash_profile to edit your bash profile.
  • Add export PATH=$PATH:/Users/[your username]/.npm-packages/bin
  • Save file and restart terminal
  • Now you should be able to use vue create my-project and vue --version etc.

I did this after I installed the latest Vue Cli from https://cli.vuejs.org/

I generally use yarn, but I installed this globally with npm npm install -g @vue/cli. You can use yarn too if you'd like yarn global add @vue/cli

Note: you may have to uninstall it first globally if you already have it installed: npm uninstall -g vue-cli

Hope this helps!

Using Jasmine to spy on a function without an object

import * as saveAsFunctions from 'file-saver';
..........
....... 
let saveAs;
            beforeEach(() => {
                saveAs = jasmine.createSpy('saveAs');
            })
            it('should generate the excel on sample request details page', () => {
                spyOn(saveAsFunctions, 'saveAs').and.callFake(saveAs);
                expect(saveAsFunctions.saveAs).toHaveBeenCalled();
            })

This worked for me.

How to completely hide the navigation bar in iPhone / HTML5

The problem with all of the answers given so far is that on the something borrowed site, the Mac bar remains totally hidden when scrolling up, and the provided answers don't accomplish that.

If you just use scrollTo and then the user later scrolls up, the nav bar is revealed again, so it seems you have to put the whole site inside of a div and force scrolling to happen inside of that div rather than on the body which keeps the nav bar hidden during scrolling in any direction.

You can, however, still reveal the nav bar by touching near the top of the screen on apple devices.

How do you add PostgreSQL Driver as a dependency in Maven?

Depending on your PostgreSQL version you would need to add the postgresql driver to your pom.xml file.

For PostgreSQL 9.1 this would be:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>
    </dependencies>
</project>

You can get the code for the dependency (as well as any other dependency) from maven's central repository

If you are using postgresql 9.2+:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.1</version>
        </dependency>
    </dependencies>
</project>

You can check the latest versions and dependency snippets from:

Linux: where are environment variables stored?

It's stored in the process (shell) and since you've exported it, any processes that process spawns.

Doing the above doesn't store it anywhere in the filesystem like /etc/profile. You have to put it there explicitly for that to happen.

How to convert string to IP address and vice versa

The third inet_pton parameter is a pointer to an in_addr structure. After a successful inet_pton call, the in_addr structure will be populated with the address information. The structure's S_addr field contains the IP address in network byte order (reverse order).

Example : 

#include <arpa/inet.h>
uint32_t NodeIpAddress::getIPv4AddressInteger(std::string IPv4Address) {
    int result;
    uint32_t IPv4Identifier = 0;
    struct in_addr addr;
    // store this IP address in sa:
    result = inet_pton(AF_INET, IPv4Address.c_str(), &(addr));
    if (result == -1) {         
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4 Address. Due to invalid family of %d. WSA Error of %d"), IPv4Address.c_str(), AF_INET, result);
    }
    else if (result == 0) {
        gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4"), IPv4Address.c_str());
    }
    else {
        IPv4Identifier = ntohl(*((uint32_t *)&(addr)));
    }
    return IPv4Identifier;
}

HTML 5 video recording and storing a stream

The followin example shows how to capture and process video frames in HTML5:

_x000D_
_x000D_
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Capturing & Processing Video in HTML5</title>
</head>
<body>
    <div>
        <h2>Camera Preview</h2>
        <video id="cameraPreview" width="240" height="180" autoplay></video>
        <p>
            <button id="startButton" onclick="startCapture();">Start Capture</button>
            <button id="stopButton" onclick="stopCapture();">Stop Capture</button>
        </p>
    </div>

    <div>
        <h2>Processing Preview</h2>
        <canvas id="processingPreview" width="240" height="180"></canvas>
    </div>

    <div>
        <h2>Recording Preview</h2>
        <video id="recordingPreview" width="240" height="180" autoplay controls></video>
        <p>
            <a id="downloadButton">Download</a>
        </p>
    </div>

    <script>

    const ROI_X = 250;
    const ROI_Y = 150;
    const ROI_WIDTH = 240;
    const ROI_HEIGHT = 180;
    
    const FPS = 25;
    
    let cameraStream = null;
    let processingStream = null;
    let mediaRecorder = null;
    let mediaChunks = null;
    let processingPreviewIntervalId = null;

    function processFrame() {
        let cameraPreview = document.getElementById("cameraPreview");
        
        processingPreview
            .getContext('2d')
            .drawImage(cameraPreview, ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT, 0, 0, ROI_WIDTH, ROI_HEIGHT);
    }
    
    function generateRecordingPreview() {
        let mediaBlob = new Blob(mediaChunks, { type: "video/webm" });
        let mediaBlobUrl = URL.createObjectURL(mediaBlob);
        
        let recordingPreview = document.getElementById("recordingPreview");
        recordingPreview.src = mediaBlobUrl;

        let downloadButton = document.getElementById("downloadButton");
        downloadButton.href = mediaBlobUrl;
        downloadButton.download = "RecordedVideo.webm";
    }
        
    function startCapture() {
        const constraints = { video: true, audio: false };
        navigator.mediaDevices.getUserMedia(constraints)
        .then((stream) => {
            cameraStream = stream;
            
            let processingPreview = document.getElementById("processingPreview");
            processingStream = processingPreview.captureStream(FPS);
            
            mediaRecorder = new MediaRecorder(processingStream);
            mediaChunks = []
            
            mediaRecorder.ondataavailable = function(event) {
                mediaChunks.push(event.data);
                if(mediaRecorder.state == "inactive") {
                    generateRecordingPreview();
                }
            };
            
            mediaRecorder.start();
            
            let cameraPreview = document.getElementById("cameraPreview");
            cameraPreview.srcObject = stream;
        
            processingPreviewIntervalId = setInterval(processFrame, 1000 / FPS);
        })
        .catch((err) => {
            alert("No media device found!");
        });
    };
    
    function stopCapture() {
        if(cameraStream != null) {
            cameraStream.getTracks().forEach(function(track) {
                track.stop();
            });
        }
        
        if(processingStream != null) {
            processingStream.getTracks().forEach(function(track) {
                track.stop();
            });
        }
        
        if(mediaRecorder != null) {
            if(mediaRecorder.state == "recording") {
                mediaRecorder.stop();
            }
        }
        
        if(processingPreviewIntervalId != null) {
            clearInterval(processingPreviewIntervalId);
            processingPreviewIntervalId = null;
        }
    };
    </script>
</body>
</html>
_x000D_
_x000D_
_x000D_

How to create an empty file with Ansible?

Something like this (using the stat module first to gather data about it and then filtering using a conditional) should work:

- stat: path=/etc/nologin
  register: p

- name: create fake 'nologin' shell
  file: path=/etc/nologin state=touch owner=root group=sys mode=0555
  when: p.stat.exists is defined and not p.stat.exists

You might alternatively be able to leverage the changed_when functionality.

Returning http 200 OK with error within response body

I think people have put too much weight into the application logic versus protocol matter. The important thing is that the response should make sense. What if you have an API that serves a dynamic resource and a request is made for X which is derived from template Y with data Z and either Y or Z isn't currently available? Is that a business logic error or a technical error? The correct answer is, "who cares?"

Your API and your responses need to be intelligible and consistent. It should conform to some kind of spec, and that spec should define what a valid response is. Something that conforms to a valid response should yield a 200 code. Something that does not conform to a valid response should yield a 4xx or 5xx code indicative of why a valid response couldn't be generated.

If your spec's definition of a valid response permits { "error": "invalid ID" }, then it's a successful response. If your spec doesn't make that accommodation, it would be a poor decision to return that response with a 200 code.

I'd draw an analogy to calling a function parseFoo. What happens when you call parseFoo("invalid data")? Does it return an error result (maybe null)? Or does it throw an exception? Many will take a near-religious position on whether one approach or the other is correct, but ultimately it's up to the API specification.

"The status-code element is a three-digit integer code giving the result of the attempt to understand and satisfy the request"

Obviously there's a difference of opinion with regards to whether "successfully returning an error" constitutes an HTTP success or error. I see different people interpreting the same specs different ways. So pick a side, sure, but also accept that either way the whole world isn't going to agree with you. Me? I find myself somewhere in the middle, but I'll offer some commonsense considerations.

  1. If your server-side code catches an unexpected exception when dispatching a request, that sounds like the very definition of a 500 Internal Server Error. This seems to be OP's situation. The application should not return a 200 for unexpected errors, but also see point 3.
  2. If your server-side code should be able to gracefully handle a given invalid input, and it doesn't constitute an "exceptional" error condition, your spec should accommodate HTTP 200 responses that provide meaningful diagnostic information.
  3. Above all: Have a spec. Make it consistent. Stick to it.

In OP's situation, it sounds like you have a de-facto standard that unhandled exceptions yield a 200 with a distinguishable response body. It's not ideal, but if it's not breaking things and actively causing problems, you probably have bigger, more important problems to solve.

Generating matplotlib graphs without a running X server

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

copy the below content to file tomcat-users.xml

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary. It is
  strongly recommended that you do NOT use one of the users in the commented out
  section below since they are intended for use with the examples web
  application.
-->
<!--
  NOTE:  The sample user and role entries below are intended for use with the
  examples web application. They are wrapped in a comment and thus are ignored
  when reading this file. If you wish to configure these users for use with the
  examples web application, do not forget to remove the <!.. ..> that surrounds
  them. You will also need to set the passwords to something appropriate.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
  <user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
  <user username="role1" password="<must-be-changed>" roles="role1"/>
-->
<role rolename="manager-gui"/>
<role rolename="manager-script"/>

<user username="notadmin" password="not_real_pass" roles="manager-gui"/>
<user username="cargo" password="not_real_pass" roles="manager-script"/>


</tomcat-users>

I have tested, it just works!

enter image description here

Filtering a pyspark dataframe using isin by exclusion

df.filter((df.bar != 'a') & (df.bar != 'b'))

How can I get form data with JavaScript/jQuery?

This will append all form fields to the JavaScript object "res":

var res = {};
$("#form input, #form select, #form textarea").each(function(i, obj) {
    res[obj.name] = $(obj).val();
})

CodeIgniter : Unable to load the requested file:

An Error Was Encountered Unable to load the requested file:

Sometimes we face this error because the requested file doesn't exist in that directory.

Suppose we have a folder home in views directory and trying to load home_view.php file as:

$this->load->view('home/home_view', $data);// $data is array

If home_view.php file doesn't exist in views/home directory then it will raise an error.

An Error Was Encountered Unable to load the requested file: home\home_view.php

So how to fix this error go to views/home and check the home_view.php file exist if not then create it.

linq query to return distinct field values from a list of objects

I wanted to bind a particular data to dropdown and it should be distinct. I did the following:

List<ClassDetails> classDetails;
List<string> classDetailsData = classDetails.Select(dt => dt.Data).Distinct.ToList();
ddlData.DataSource = classDetailsData;
ddlData.Databind();

See if it helps

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

In my case, I only had read access to the .git/FETCH_HEAD file. I had to do "sudo chmod g+w .git/FETCH_HEAD" in order to be able to do a pull request.

How to check if a String contains any of some strings

If you need ContainsAny with a specific StringComparison (for example to ignore case) then you can use this String Extentions method.

public static class StringExtensions
{
    public static bool ContainsAny(this string input, IEnumerable<string> containsKeywords, StringComparison comparisonType)
    {
        return containsKeywords.Any(keyword => input.IndexOf(keyword, comparisonType) >= 0);
    }
}

Usage with StringComparison.CurrentCultureIgnoreCase:

var input = "My STRING contains Many Substrings";
var substrings = new[] {"string", "many substrings", "not containing this string" };
input.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// The statement above returns true.

”xyz”.ContainsAny(substrings, StringComparison.CurrentCultureIgnoreCase);
// This statement returns false.

What parameters should I use in a Google Maps URL to go to a lat-lon?

In May 2017 Google announced the Google Maps URLs API that allows to construct universal cross-platform links. Now you can open Google maps on web, Android or iOS using the same URL string in form:

https://www.google.com/maps/search/?api=1&parameters

There are several modes that you can use: search, directions, show map and show street view.

So you can use something like

https://www.google.com/maps/search/?api=1&query=58.698017,-152.522067

to open map and place marker on some lat and lng.

For further details please refer to:

https://developers.google.com/maps/documentation/urls/guide

Change bootstrap navbar collapse breakpoint without using LESS

2018 UPDATE

Bootstrap 4

Changing the navbar breakpoint is easier in Bootstrap 4 using the navbar-expand-* classes:

<nav class="navbar fixed-top navbar-expand-sm">..</nav>

  • navbar-expand-sm = mobile menu on xs screens <576px
  • navbar-expand-md = mobile menu on sm screens <768px
  • navbar-expand-lg = mobile menu on md screens <992px
  • navbar-expand-xl = mobile menu on lg screens <1200px
  • navbar-expand = never use mobile menu
  • (no expand class) = always use mobile menu

If you exclude navbar-expand-* the mobile menu will be used at all widths. Here's a demo of all 6 navbar states: Bootstrap 4 Navbar Example

You can also use a custom breakpoint (???px) by adding a little CSS. For example, here's 1300px..

@media (min-width: 1300px){
    .navbar-expand-custom {
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: flex-start;
    }
    .navbar-expand-custom .navbar-nav {
        flex-direction: row;
    }
    .navbar-expand-custom .navbar-nav .nav-link {
        padding-right: .5rem;
        padding-left: .5rem;
    }
    .navbar-expand-custom .navbar-collapse {
        display: flex!important;
    }
    .navbar-expand-custom .navbar-toggler {
        display: none;
    }
}

Bootstrap 4 Custom Navbar Breakpoint
Bootstrap 4 Navbar Breakpoint Examples


Bootstrap 3

For Bootstrap 3.3.x, here is the working CSS to override the navbar breakpoint. Change 991px to the pixel dimension of the point at which you want the navbar to collapse...

@media (max-width: 991px) {
  .navbar-header {
      float: none;
  }
  .navbar-left,.navbar-right {
      float: none !important;
  }
  .navbar-toggle {
      display: block;
  }
  .navbar-collapse {
      border-top: 1px solid transparent;
      box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
  }
  .navbar-fixed-top {
      top: 0;
      border-width: 0 0 1px;
  }
  .navbar-collapse.collapse {
      display: none!important;
  }
  .navbar-nav {
      float: none!important;
      margin-top: 7.5px;
  }
  .navbar-nav>li {
      float: none;
  }
  .navbar-nav>li>a {
      padding-top: 10px;
      padding-bottom: 10px;
  }
  .collapse.in{
      display:block !important;
  }
}

Working example for 991px: http://www.bootply.com/j7XJuaE5v6
Working example for 1200px: https://www.codeply.com/go/VsYaOLzfb4 (with search form)

Note: The above works for anything over 768px. If you need to change it to less than 768px the example of less than 768px is here.


Populate nested array in mongoose

For someone who has the problem with populate and also wants to do this:

  • chat with simple text & quick replies (bubbles)
  • 4 database collections for chat: clients, users, rooms, messasges.
  • same message DB structure for 3 types of senders: bot, users & clients
  • refPath or dynamic reference
  • populate with path and model options
  • use findOneAndReplace/replaceOne with $exists
  • create a new document if the fetched document doesn't exist

CONTEXT

Goal

  1. Save a new simple text message to the database & populate it with the user or client data (2 different models).
  2. Save a new quickReplies message to the database and populate it with the user or client data.
  3. Save each message its sender type: clients, users & bot.
  4. Populate only the messages who have the sender clients or users with its Mongoose Models. _sender type client models is clients, for user is users.

Message schema:

const messageSchema = new Schema({
    room: {
        type: Schema.Types.ObjectId,
        ref: 'rooms',
        required: [true, `Room's id`]
    },
    sender: {
         _id: { type: Schema.Types.Mixed },
        type: {
            type: String,
            enum: ['clients', 'users', 'bot'],
            required: [true, 'Only 3 options: clients, users or bot.']
        }
    },
    timetoken: {
        type: String,
        required: [true, 'It has to be a Nanosecond-precision UTC string']
    },
    data: {
        lang: String,
        // Format samples on https://docs.chatfuel.com/api/json-api/json-api
        type: {
            text: String,
            quickReplies: [
                {
                    text: String,
                    // Blocks' ids.
                    goToBlocks: [String]
                }
            ]
        }
    }

mongoose.model('messages', messageSchema);

SOLUTION

My server side API request

My code

Utility function (on chatUtils.js file) to get the type of message that you want to save:

/**
 * We filter what type of message is.
 *
 * @param {Object} message
 * @returns {string} The type of message.
 */
const getMessageType = message => {
    const { type } = message.data;
    const text = 'text',
        quickReplies = 'quickReplies';

    if (type.hasOwnProperty(text)) return text;
    else if (type.hasOwnProperty(quickReplies)) return quickReplies;
};

/**
 * Get the Mongoose's Model of the message's sender. We use
 * the sender type to find the Model.
 *
 * @param {Object} message - The message contains the sender type.
 */
const getSenderModel = message => {
    switch (message.sender.type) {
        case 'clients':
            return 'clients';
        case 'users':
            return 'users';
        default:
            return null;
    }
};

module.exports = {
    getMessageType,
    getSenderModel
};

My server side (using Nodejs) to get the request of saving the message:

app.post('/api/rooms/:roomId/messages/new', async (req, res) => {
        const { roomId } = req.params;
        const { sender, timetoken, data } = req.body;
        const { uuid, state } = sender;
        const { type } = state;
        const { lang } = data;

        // For more info about message structure, look up Message Schema.
        let message = {
            room: new ObjectId(roomId),
            sender: {
                _id: type === 'bot' ? null : new ObjectId(uuid),
                type
            },
            timetoken,
            data: {
                lang,
                type: {}
            }
        };

        // ==========================================
        //          CONVERT THE MESSAGE
        // ==========================================
        // Convert the request to be able to save on the database.
        switch (getMessageType(req.body)) {
            case 'text':
                message.data.type.text = data.type.text;
                break;
            case 'quickReplies':
                // Save every quick reply from quickReplies[].
                message.data.type.quickReplies = _.map(
                    data.type.quickReplies,
                    quickReply => {
                        const { text, goToBlocks } = quickReply;

                        return {
                            text,
                            goToBlocks
                        };
                    }
                );
                break;
            default:
                break;
        }

        // ==========================================
        //           SAVE THE MESSAGE
        // ==========================================
        /**
         * We save the message on 2 ways:
         * - we replace the message type `quickReplies` (if it already exists on database) with the new one.
         * - else, we save the new message.
         */
        try {
            const options = {
                // If the quickRepy message is found, we replace the whole document.
                overwrite: true,
                // If the quickRepy message isn't found, we create it.
                upsert: true,
                // Update validators validate the update operation against the model's schema.
                runValidators: true,
                // Return the document already updated.
                new: true
            };

            Message.findOneAndUpdate(
                { room: roomId, 'data.type.quickReplies': { $exists: true } },
                message,
                options,
                async (err, newMessage) => {
                    if (err) {
                        throw Error(err);
                    }

                    // Populate the new message already saved on the database.
                    Message.populate(
                        newMessage,
                        {
                            path: 'sender._id',
                            model: getSenderModel(newMessage)
                        },
                        (err, populatedMessage) => {
                            if (err) {
                                throw Error(err);
                            }

                            res.send(populatedMessage);
                        }
                    );
                }
            );
        } catch (err) {
            logger.error(
                `#API Error on saving a new message on the database of roomId=${roomId}. ${err}`,
                { message: req.body }
            );

            // Bad Request
            res.status(400).send(false);
        }
    });

TIPs:

For the database:

  • Every message is a document itself.
  • Instead of using refPath, we use the util getSenderModel that is used on populate(). This is because of the bot. The sender.type can be: users with his database, clients with his database and bot without a database. The refPath needs true Model reference, if not, Mongooose throw an error.
  • sender._id can be type ObjectId for users and clients, or null for the bot.

For API request logic:

  • We replace the quickReply message (Message DB has to have only one quickReply, but as many simple text messages as you want). We use the findOneAndUpdate instead of replaceOne or findOneAndReplace.
  • We execute the query operation (the findOneAndUpdate) and the populate operation with the callback of each one. This is important if you don't know if use async/await, then(), exec() or callback(err, document). For more info look the Populate Doc.
  • We replace the quick reply message with the overwrite option and without $set query operator.
  • If we don't find the quick reply, we create a new one. You have to tell to Mongoose this with upsert option.
  • We populate only one time, for the replaced message or the new saved message.
  • We return to callbacks, whatever is the message we've saved with findOneAndUpdate and for the populate().
  • In populate, we create a custom dynamic Model reference with the getSenderModel. We can use the Mongoose dynamic reference because the sender.type for bot hasn't any Mongoose Model. We use a Populating Across Database with model and path optins.

I've spend a lot of hours solving little problems here and there and I hope this will help someone!

Determine path of the executing script

Amazing there is no '$0' type structure in R! You can do it with a system() call to a bash script written in R:

write.table(c("readlink -e $0"), file="scriptpath.sh",col=F, row=F, quote=F)
thisscript <- system("sh scriptpath.sh", intern = TRUE)

Then just split out the scriptpath.sh name for other.R

splitstr <- rev(strsplit(thisscript, "\\/")[[1]])
otherscript <- paste0(paste(rev(splitstr[2:length(splitstr)]),collapse="/"),"/other.R")

Static method in a generic class?

Java doesn't know what T is until you instantiate a type.

Maybe you can execute static methods by calling Clazz<T>.doit(something) but it sounds like you can't.

The other way to handle things is to put the type parameter in the method itself:

static <U> void doIt(U object)

which doesn't get you the right restriction on U, but it's better than nothing....

warning: control reaches end of non-void function [-Wreturn-type]

You just need to return from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.

  /* .... */
  if (Date1 == Date2)  
     fprintf (stderr , "Indicating that the first date is equal to second date.\n"); 

  return 0;
}

JavaFX "Location is required." even though it is in the same package

If your problem is not Maven related and you get the same NullPointerException running this in a browser (while running it from the IDE is fine), try this:

-> Netbeans -> Right-Click Project -> Properties -> Build -> Deployment -> Check "Request unrestricted access (Enable signing, self-signed)"

This is due to the @FXML Annotation needing permission to inject the value from the FXML markup (see http://docs.oracle.com/javafx/2/fxml_get_started/fxml_deployment.htm )

I was running my App on JDK8u31 and it would never run without the certificate in Chrome / Firefox / IE.

JSON.Net Self referencing loop detected

This may help you.

public MyContext() : base("name=MyContext") 
{ 
    Database.SetInitializer(new MyContextDataInitializer()); 
    this.Configuration.LazyLoadingEnabled = false; 
    this.Configuration.ProxyCreationEnabled = false; 
} 

http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7

Error: Can't set headers after they are sent to the client

I had this same issue and realised it was because I was calling res.redirect without a return statement, so the next function was also being called immediately afterwards:

auth.annonymousOnly = function(req, res, next) {
    if (req.user) res.redirect('/');
    next();
};

Which should have been:

auth.annonymousOnly = function(req, res, next) {
    if (req.user) return res.redirect('/');
    next();
};

What is the preferred Bash shebang?

#!/bin/sh

as most scripts do not need specific bash feature and should be written for sh.

Also, this makes scripts work on the BSDs, which do not have bash per default.

how to stop a running script in Matlab

if you are running your matlab on linux, you can terminate the matlab by command in linux consule. first you should find the PID number of matlab by this code:

top

then you can use this code to kill matlab: kill

example: kill 58056

Install dependencies globally and locally using package.json

This is a bit old but I ran into the requirement so here is the solution I came up with.

The Problem:

Our development team maintains many .NET web application products we are migrating to AngularJS/Bootstrap. VS2010 does not lend itself easily to custom build processes and my developers are routinely working on multiple releases of our products. Our VCS is Subversion (I know, I know. I'm trying to move to Git but my pesky marketing staff is so demanding) and a single VS solution will include several separate projects. I needed my staff to have a common method for initializing their development environment without having to install the same Node packages (gulp, bower, etc.) several times on the same machine.

TL;DR:

  1. Need "npm install" to install the global Node/Bower development environment as well as all locally required packages for a .NET product.

  2. Global packages should be installed only if not already installed.

  3. Local links to global packages must be created automatically.

The Solution:

We already have a common development framework shared by all developers and all products so I created a NodeJS script to install the global packages when needed and create the local links. The script resides in "....\SharedFiles" relative to the product base folder:

/*******************************************************************************
* $Id: npm-setup.js 12785 2016-01-29 16:34:49Z sthames $
* ==============================================================================
* Parameters: 'links' - Create links in local environment, optional.
* 
* <p>NodeJS script to install common development environment packages in global
* environment. <c>packages</c> object contains list of packages to install.</p>
* 
* <p>Including 'links' creates links in local environment to global packages.</p>
* 
* <p><b>npm ls -g --json</b> command is run to provide the current list of 
* global packages for comparison to required packages. Packages are installed 
* only if not installed. If the package is installed but is not the required 
* package version, the existing package is removed and the required package is 
* installed.</p>.
*
* <p>When provided as a "preinstall" script in a "package.json" file, the "npm
* install" command calls this to verify global dependencies are installed.</p>
*******************************************************************************/
var exec = require('child_process').exec;
var fs   = require('fs');
var path = require('path');

/*---------------------------------------------------------------*/
/* List of packages to install and 'from' value to pass to 'npm  */
/* install'. Value must match the 'from' field in 'npm ls -json' */
/* so this script will recognize a package is already installed. */
/*---------------------------------------------------------------*/
var packages = 
  {
  "bower"                      :                      "[email protected]", 
  "event-stream"               :               "[email protected]",
  "gulp"                       :                       "[email protected]",
  "gulp-angular-templatecache" : "[email protected]",
  "gulp-clean"                 :                 "[email protected]", 
  "gulp-concat"                :                "[email protected]",
  "gulp-debug"                 :                 "[email protected]",
  "gulp-filter"                :                "[email protected]",
  "gulp-grep-contents"         :         "[email protected]",
  "gulp-if"                    :                    "[email protected]", 
  "gulp-inject"                :                "[email protected]", 
  "gulp-minify-css"            :            "[email protected]",
  "gulp-minify-html"           :           "[email protected]",
  "gulp-minify-inline"         :         "[email protected]",
  "gulp-ng-annotate"           :           "[email protected]",
  "gulp-processhtml"           :           "[email protected]",
  "gulp-rev"                   :                   "[email protected]",
  "gulp-rev-replace"           :           "[email protected]",
  "gulp-uglify"                :                "[email protected]",
  "gulp-useref"                :                "[email protected]",
  "gulp-util"                  :                  "[email protected]",
  "lazypipe"                   :                   "[email protected]",
  "q"                          :                          "[email protected]",
  "through2"                   :                   "[email protected]",

  /*---------------------------------------------------------------*/
  /* fork of 0.2.14 allows passing parameters to main-bower-files. */
  /*---------------------------------------------------------------*/
  "bower-main"                 : "git+https://github.com/Pyo25/bower-main.git" 
  }

/*******************************************************************************
* run */
/**
* Executes <c>cmd</c> in the shell and calls <c>cb</c> on success. Error aborts.
* 
* Note: Error code -4082 is EBUSY error which is sometimes thrown by npm for 
* reasons unknown. Possibly this is due to antivirus program scanning the file 
* but it sometimes happens in cases where an antivirus program does not explain 
* it. The error generally will not happen a second time so this method will call 
* itself to try the command again if the EBUSY error occurs.
* 
* @param  cmd  Command to execute.
* @param  cb   Method to call on success. Text returned from stdout is input.
*******************************************************************************/
var run = function(cmd, cb)
  {
  /*---------------------------------------------*/
  /* Increase the maxBuffer to 10MB for commands */
  /* with a lot of output. This is not necessary */
  /* with spawn but it has other issues.         */
  /*---------------------------------------------*/
  exec(cmd, { maxBuffer: 1000*1024 }, function(err, stdout)
    {
    if      (!err)                   cb(stdout);
    else if (err.code | 0 == -4082) run(cmd, cb);
    else throw err;
    });
  };

/*******************************************************************************
* runCommand */
/**
* Logs the command and calls <c>run</c>.
*******************************************************************************/
var runCommand = function(cmd, cb)
  {
  console.log(cmd);
  run(cmd, cb);
  }

/*******************************************************************************
* Main line
*******************************************************************************/
var doLinks  = (process.argv[2] || "").toLowerCase() == 'links';
var names    = Object.keys(packages);
var name;
var installed;
var links;

/*------------------------------------------*/
/* Get the list of installed packages for   */
/* version comparison and install packages. */
/*------------------------------------------*/
console.log('Configuring global Node environment...')
run('npm ls -g --json', function(stdout)
  {
  installed = JSON.parse(stdout).dependencies || {};
  doWhile();
  });

/*--------------------------------------------*/
/* Start of asynchronous package installation */
/* loop. Do until all packages installed.     */
/*--------------------------------------------*/
var doWhile = function()
  {
  if (name = names.shift())
    doWhile0();
  }

var doWhile0 = function()
  {
  /*----------------------------------------------*/
  /* Installed package specification comes from   */
  /* 'from' field of installed packages. Required */
  /* specification comes from the packages list.  */
  /*----------------------------------------------*/
  var current  = (installed[name] || {}).from;
  var required =   packages[name];

  /*---------------------------------------*/
  /* Install the package if not installed. */
  /*---------------------------------------*/
  if (!current)
    runCommand('npm install -g '+required, doWhile1);

  /*------------------------------------*/
  /* If the installed version does not  */
  /* match, uninstall and then install. */
  /*------------------------------------*/
  else if (current != required)
    {
    delete installed[name];
    runCommand('npm remove -g '+name, function() 
      {
      runCommand('npm remove '+name, doWhile0);
      });
    }

  /*------------------------------------*/
  /* Skip package if already installed. */
  /*------------------------------------*/
  else
    doWhile1();
  };

var doWhile1 = function()
  {
  /*-------------------------------------------------------*/
  /* Create link to global package from local environment. */
  /*-------------------------------------------------------*/
  if (doLinks && !fs.existsSync(path.join('node_modules', name)))
    runCommand('npm link '+name, doWhile);
  else
    doWhile();
  };

Now if I want to update a global tool for our developers, I update the "packages" object and check in the new script. My developers check it out and either run it with "node npm-setup.js" or by "npm install" from any of the products under development to update the global environment. The whole thing takes 5 minutes.

In addition, to configure the environment for the a new developer, they must first only install NodeJS and GIT for Windows, reboot their computer, check out the "Shared Files" folder and any products under development, and start working.

The "package.json" for the .NET product calls this script prior to install:

{ 
"name"                    : "Books",
"description"             : "Node (npm) configuration for Books Database Web Application Tools",
"version"                 : "2.1.1",
"private"                 : true,
"scripts":
  {
  "preinstall"            : "node ../../SharedFiles/npm-setup.js links",
  "postinstall"           : "bower install"
  },
"dependencies": {}
}

Notes

  • Note the script reference requires forward slashes even in a Windows environment.

  • "npm ls" will give "npm ERR! extraneous:" messages for all packages locally linked because they are not listed in the "package.json" "dependencies".

Edit 1/29/16

The updated npm-setup.js script above has been modified as follows:

  • Package "version" in var packages is now the "package" value passed to npm install on the command line. This was changed to allow for installing packages from somewhere other than the registered repository.

  • If the package is already installed but is not the one requested, the existing package is removed and the correct one installed.

  • For reasons unknown, npm will periodically throw an EBUSY error (-4082) when performing an install or link. This error is trapped and the command re-executed. The error rarely happens a second time and seems to always clear up.

Format Date/Time in XAML in Silverlight

you can also use just

StringFormat=d

in your datagrid column for date time showing

finally it will be

   <sdk:DataGridTextColumn  Binding="{Binding Path=DeliveryDate,StringFormat=d}" Header="Delivery date" Width="*" />

the out put will look like

enter image description here

Regular Expression to reformat a US phone number in Javascript

Possible solution:

function normalize(phone) {
    //normalize string and remove all unnecessary characters
    phone = phone.replace(/[^\d]/g, "");

    //check if number length equals to 10
    if (phone.length == 10) {
        //reformat and return phone number
        return phone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
    }

    return null;
}

var phone = '(123)4567890';
phone = normalize(phone); //(123) 456-7890

jQuery loop over JSON result from AJAX Success?

For anyone else stuck with this, it's probably not working because the ajax call is interpreting your returned data as text - i.e. it's not yet a JSON object.

You can convert it to a JSON object by manually using the parseJSON command or simply adding the dataType: 'json' property to your ajax call. e.g.

jQuery.ajax({
    type: 'POST',
    url: '<?php echo admin_url('admin-ajax.php'); ?>',
    data: data, 
    dataType: 'json', // ** ensure you add this line **
    success: function(data) {
        jQuery.each(data, function(index, item) {
            //now you can access properties using dot notation
        });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});

how to access master page control from content page

If you are trying to access an html element: this is an HTML Anchor...

My nav bar has items that are not list items (<li>) but rather html anchors (<a>)

See below: (This is the site master)

<nav class="mdl-navigation">
    <a class="mdl-navigation__link" href="" runat="server" id="liHome">Home</a>
    <a class="mdl-navigation__link" href="" runat="server" id="liDashboard">Dashboard</a>
</nav>

Now in your code behind for another page, for mine, it's the login page...

On PageLoad() define this:

HtmlAnchor lblMasterStatus = (HtmlAnchor)Master.FindControl("liHome");
lblMasterStatus.Visible =false;

HtmlAnchor lblMasterStatus1 = (HtmlAnchor)Master.FindControl("liDashboard");
lblMasterStatus1.Visible = false;

Now we have accessed the site masters controls, and have made them invisible on the login page.

Display open transactions in MySQL

By using this query you can see all open transactions.

List All:

SHOW FULL PROCESSLIST  

if you want to kill a hang transaction copy transaction id and kill transaction by using this command:

KILL <id>    // e.g KILL 16543

How can I dynamically add items to a Java array?

Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.

A bit similar to the PHP behaviour is this:

int[] addElement(int[] org, int added) {
    int[] result = Arrays.copyOf(org, org.length +1);
    result[org.length] = added;
    return result;
}

Then you can write:

x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);

System.out.println(Arrays.toString(x));

But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).

The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.

If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)

Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.

How to get the entire document HTML as a string?

I believe document.documentElement.outerHTML should return that for you.

According to MDN, outerHTML is supported in Firefox 11, Chrome 0.2, Internet Explorer 4.0, Opera 7, Safari 1.3, Android, Firefox Mobile 11, IE Mobile, Opera Mobile, and Safari Mobile. outerHTML is in the DOM Parsing and Serialization specification.

The MSDN page on the outerHTML property notes that it is supported in IE 5+. Colin's answer links to the W3C quirksmode page, which offers a good comparison of cross-browser compatibility (for other DOM features too).

background:none vs background:transparent what is the difference?

There is no difference between them.

If you don't specify a value for any of the half-dozen properties that background is a shorthand for, then it is set to its default value. none and transparent are the defaults.

One explicitly sets the background-image to none and implicitly sets the background-color to transparent. The other is the other way around.

Difference between Interceptor and Filter in Spring MVC

From HandlerIntercepter's javadoc:

HandlerInterceptor is basically similar to a Servlet Filter, but in contrast to the latter it just allows custom pre-processing with the option of prohibiting the execution of the handler itself, and custom post-processing. Filters are more powerful, for example they allow for exchanging the request and response objects that are handed down the chain. Note that a filter gets configured in web.xml, a HandlerInterceptor in the application context.

As a basic guideline, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.

With that being said:

So where is the difference between Interceptor#postHandle() and Filter#doFilter()?

postHandle will be called after handler method invocation but before the view being rendered. So, you can add more model objects to the view but you can not change the HttpServletResponse since it's already committed.

doFilter is much more versatile than the postHandle. You can change the request or response and pass it to the chain or even block the request processing.

Also, in preHandle and postHandle methods, you have access to the HandlerMethod that processed the request. So, you can add pre/post-processing logic based on the handler itself. For example, you can add a logic for handler methods that have some annotations.

What is the best practise in which use cases it should be used?

As the doc said, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.

How to split a string to 2 strings in C

For purposes such as this, I tend to use strtok_r() instead of strtok().

For example ...

int main (void) {
char str[128];
char *ptr;

strcpy (str, "123456 789asdf");
strtok_r (str, " ", &ptr);

printf ("'%s'  '%s'\n", str, ptr);
return 0;
}

This will output ...

'123456' '789asdf'

If more delimiters are needed, then loop.

Hope this helps.

How can I view array structure in JavaScript with alert()?

Better use Firebug (chrome console etc) and use console.dir()

How to create a simple checkbox in iOS?

On iOS there is the switch UI component instead of a checkbox, look into the UISwitch class. The property on (boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.

What is a mutex?

A Mutex is a mutually exclusive flag. It acts as a gate keeper to a section of code allowing one thread in and blocking access to all others. This ensures that the code being controled will only be hit by a single thread at a time. Just be sure to release the mutex when you are done. :)

GROUP_CONCAT ORDER BY

You can use SEPARATOR and ORDER BY inside the GROUP_CONCAT function in this way:

SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC SEPARATOR ',') 
AS views, group_concat(li.percentage ORDER BY li.percentage ASC SEPARATOR ',') FROM li
GROUP BY client_id;

Preferred way of getting the selected item of a JComboBox

The first method is right.

The second method kills kittens if you attempt to do anything with x after the fact other than Object methods.

how to display none through code behind

I believe this should work:

login_div.Attributes.Add("style","display:none");

Hibernate: How to fix "identifier of an instance altered from X to Y"?

In my particular case, this was caused by a method in my service implementation that needed the spring @Transactional(readOnly = true) annotation. Once I added that, the issue was resolved. Unusual though, it was just a select statement.

How to increase size of DOSBox window?

  • go to dosbox installation directory (on my machine that is C:\Program Files (x86)\DOSBox-0.74 ) as you see the version number is part of the installation directory name.

  • run "DOSBox 0.74 Options.bat"

  • the script starts notepad with configuration file: here change

    windowresolution=1600x800

    output=ddraw

(the resolution can't be changed if output=surface - that's the default).

  • safe configuration file changes.

How do I attach events to dynamic HTML elements with jQuery?

I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.

From http://api.jquery.com/live/

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.

See http://api.jquery.com/on/

So instead of...

$(".myclass").click( function() {
    // do something
});

You can write...

$('body').on('click', 'a.myclass', function() {
    // do something
});

This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.

The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:

$('ul').on('click', 'li', function() {
    alert( $(this).text() );
});

As long as the ul tag exists this will work (no li elements need exist yet).

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I had the same issue when I changed the home directory of one use. In my case it was because of selinux. I used the below to fix the issue:

selinuxenabled 0
setenforce 0

Filter items which array contains any of given values

There's also terms query which should save you some work. Here example from docs:

{
  "terms" : {
      "tags" : [ "blue", "pill" ],
      "minimum_should_match" : 1
  }
}

Under hood it constructs boolean should. So it's basically the same thing as above but shorter.

There's also a corresponding terms filter.

So to summarize your query could look like this:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "terms": {
        "tags": ["c", "d"]
      }
    }
  }
}

With greater number of tags this could make quite a difference in length.

Use latest version of Internet Explorer in the webbrowser control

You can try this link

try
{
    var IEVAlue =  9000; // can be: 9999 , 9000, 8888, 8000, 7000
    var targetApplication = Processes.getCurrentProcessName() + ".exe"; 
    var localMachine = Registry.LocalMachine;
    var parentKeyLocation = @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl";
    var keyName = "FEATURE_BROWSER_EMULATION";
    "opening up Key: {0} at {1}".info(keyName, parentKeyLocation);
    var subKey = localMachine.getOrCreateSubKey(parentKeyLocation,keyName,true);
    subKey.SetValue(targetApplication, IEVAlue,RegistryValueKind.DWord);
    return "all done, now try it on a new process".info();
}
catch(Exception ex)
{
    ex.log();
    "NOTE: you need to run this under no UAC".info();
}

Android java.lang.NoClassDefFoundError

Try going to Project -> Properties -> Java Build Path -> Order & Export And Confirm Android Private Libraries are checked for your project and for all other library projects you are using in your Application.

MySQL SELECT only not null values

MYSQL IS NOT NULL WITH JOINS AND SELECT, INSERT INTO, DELETE & LOGICAL OPERATOR LIKE OR , NOT

Using IS NOT NULL On Join Conditions

 SELECT * FROM users 
 LEFT JOIN posts ON post.user_id = users.id 
 WHERE user_id IS NOT NULL;

 Using IS NOT NULL With AND Logical Operator

 SELECT * FROM users 
 WHERE email_address IS NOT NULL 
 AND mobile_number IS NOT NULL;

Using IS NOT NULL With OR Logical Operator

 SELECT * FROM users 
 WHERE email_address IS NOT NULL 
 OR mobile_number IS NOT NULL;

Simple way to get element by id within a div tag?

Sample Html code   
 <div id="temp">
        F1 <input type="text" value="111"/><br/>
        F2 <input type="text" value="222"/><br/>
        F3 <input type="text" value="333"/><br/>
        Type <select>
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
        </select>
        <input type="button" value="Go" onclick="getVal()">
    </div>

Javascript

    function  getVal()
    {
        var test = document.getElementById("temp").getElementsByTagName("input");
        alert("Number of Input Elements "+test.length);
        for(var i=0;i<test.length;i++)
        {
          if(test[i].type=="text")
          {
            alert(test[i].value);
          }
       }
      test = document.getElementById("temp").getElementsByTagName("select");
      alert("Select box  "+test[0].options[test[0].selectedIndex].text);
    }

By providing different tag names we can get all the values from the div.

Can PHP cURL retrieve response headers AND body in a single request?

My way is

$response = curl_exec($ch);
$x = explode("\r\n\r\n", $v, 3);
$header=http_parse_headers($x[0]);
if ($header=['Response Code']==100){ //use the other "header"
    $header=http_parse_headers($x[1]);
    $body=$x[2];
}else{
    $body=$x[1];
}

If needed apply a for loop and remove the explode limit.

How can I get Android Wifi Scan Results into a list?

Find a complete working example below:

The code by @Android is very good but has few issues, namely:

  1. Populating to ListView code needs to be moved to onReceive of BroadCastReceiver where only the result will be available. In the case result is obtained at 2nd attempt.
  2. BroadCastReceiver needs to be unregistered after the results are obtained.
  3. size = size -1 seems unnecessary.

Find below the modified code of @Android as a working example:

WifiScanner.java which is the Main Activity

package com.arjunandroid.wifiscanner;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

public class WifiScanner extends Activity implements View.OnClickListener{


    WifiManager wifi;
    ListView lv;
    Button buttonScan;
    int size = 0;
    List<ScanResult> results;

    String ITEM_KEY = "key";
    ArrayList<String> arraylist = new ArrayList<>();
    ArrayAdapter adapter;

    /* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getActionBar().setTitle("Widhwan Setup Wizard");

        setContentView(R.layout.activity_wifi_scanner);

        buttonScan = (Button) findViewById(R.id.scan);
        buttonScan.setOnClickListener(this);
        lv = (ListView)findViewById(R.id.wifilist);


        wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi.isWifiEnabled() == false)
        {
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            wifi.setWifiEnabled(true);
        }
        this.adapter =  new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arraylist);
        lv.setAdapter(this.adapter);

        scanWifiNetworks();
    }

    public void onClick(View view)
    {
        scanWifiNetworks();
    }

    private void scanWifiNetworks(){

        arraylist.clear();
        registerReceiver(wifi_receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        wifi.startScan();

        Log.d("WifScanner", "scanWifiNetworks");

        Toast.makeText(this, "Scanning....", Toast.LENGTH_SHORT).show();

    }

    BroadcastReceiver wifi_receiver= new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context c, Intent intent)
        {
            Log.d("WifScanner", "onReceive");
            results = wifi.getScanResults();
            size = results.size();
            unregisterReceiver(this);

            try
            {
                while (size >= 0)
                {
                    size--;
                    arraylist.add(results.get(size).SSID);
                    adapter.notifyDataSetChanged();
                }
            }
            catch (Exception e)
            {
                Log.w("WifScanner", "Exception: "+e);

            }


        }
    };

}

activity_wifi_scanner.xml which is the layout file for the Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/wifilist"
        android:layout_width="match_parent"
        android:layout_height="312dp"
        android:layout_weight="0.97" />


    <Button
        android:id="@+id/scan"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="bottom"
        android:layout_margin="15dp"
        android:background="@android:color/holo_green_light"
        android:text="Scan Again" />
</LinearLayout>

Also as mentioned above, do not forget to add Wifi permissions in the AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 

jQuery - select the associated label element of a input field

You shouldn't rely on the order of elements by using prev or next. Just use the for attribute of the label, as it should correspond to the ID of the element you're currently manipulating:

var label = $("label[for='" + $(this).attr('id') + "']");

However, there are some cases where the label will not have for set, in which case the label will be the parent of its associated control. To find it in both cases, you can use a variation of the following:

var label = $('label[for="' + $(this).attr('id') + '"]');

if(label.length <= 0) {
    var parentElem = $(this).parent(),
        parentTagName = parentElem.get(0).tagName.toLowerCase();

    if(parentTagName == "label") {
        label = parentElem;
    }
}

I hope this helps!

What Makes a Method Thread-safe? What are the rules?

There is no hard and fast rule.

Here are some rules to make code thread safe in .NET and why these are not good rules:

  1. Function and all functions it calls must be pure (no side effects) and use local variables. Although this will make your code thread-safe, there is also very little amount of interesting things you can do with this restriction in .NET.
  2. Every function that operates on a common object must lock on a common thing. All locks must be done in same order. This will make the code thread safe, but it will be incredibly slow, and you might as well not use multiple threads.
  3. ...

There is no rule that makes the code thread safe, the only thing you can do is make sure that your code will work no matter how many times is it being actively executed, each thread can be interrupted at any point, with each thread being in its own state/location, and this for each function (static or otherwise) that is accessing common objects.

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

In C++ the finally is NOT required because of RAII.

RAII moves the responsibility of exception safety from the user of the object to the designer (and implementer) of the object. I would argue this is the correct place as you then only need to get exception safety correct once (in the design/implementation). By using finally you need to get exception safety correct every time you use an object.

Also IMO the code looks neater (see below).

Example:

A database object. To make sure the DB connection is used it must be opened and closed. By using RAII this can be done in the constructor/destructor.

C++ Like RAII

void someFunc()
{
    DB    db("DBDesciptionString");
    // Use the db object.

} // db goes out of scope and destructor closes the connection.
  // This happens even in the presence of exceptions.

The use of RAII makes using a DB object correctly very easy. The DB object will correctly close itself by the use of a destructor no matter how we try and abuse it.

Java Like Finally

void someFunc()
{
    DB      db = new DB("DBDesciptionString");
    try
    {
        // Use the db object.
    }
    finally
    {
        // Can not rely on finaliser.
        // So we must explicitly close the connection.
        try
        {
            db.close();
        }
        catch(Throwable e)
        {
           /* Ignore */
           // Make sure not to throw exception if one is already propagating.
        }
    }
}

When using finally the correct use of the object is delegated to the user of the object. i.e. It is the responsibility of the object user to correctly to explicitly close the DB connection. Now you could argue that this can be done in the finaliser, but resources may have limited availability or other constraints and thus you generally do want to control the release of the object and not rely on the non deterministic behavior of the garbage collector.

Also this is a simple example.
When you have multiple resources that need to be released the code can get complicated.

A more detailed analysis can be found here: http://accu.org/index.php/journals/236

Error while trying to retrieve text for error ORA-01019

Well,

Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!

Check if a string within a list contains a specific string with Linq

Thast should be easy enough

if( myList.Any( s => s.Contains(stringToCheck))){
  //do your stuff here
}

How to get names of enum entries?

There are already a lot of answers here but I figure I'll throw my solution onto the stack anyway.

TypeScript Playground

enum AccountType {
  Google = 'goo',
  Facebook = 'boo',
  Twitter = 'wit',
}

type Key = keyof typeof AccountType // "Google" | "Facebook" | "Twitter"

// this creates a POJO of the enum "reversed" using TypeScript's Record utility
const reversed = (Object.keys(AccountType) as Key[]).reduce((acc, key) => {
  acc[AccountType[key]] = key
  return acc
}, {} as Record<AccountType, string>)

For Clarity:

/*
 * reversed == {
 *   "goo": "Google",
 *   "boo": "Facebook",
 *   "wit": "Twitter",
 * }
 * reversed[AccountType.Google] === "Google" 
 */

Reference for TypeScript Record

A nice helper function:

const getAccountTypeName = (type: AccountType) => {
  return reversed[type]
};

// getAccountTypeName(AccountType.Twitter) === 'Twitter'

Setting user agent of a java URLConnection

Just for clarification: setRequestProperty("User-Agent", "Mozilla ...") now works just fine and doesn't append java/xx at the end! At least with Java 1.6.30 and newer.

I listened on my machine with netcat(a port listener):

$ nc -l -p 8080

It simply listens on the port, so you see anything which gets requested, like raw http-headers.

And got the following http-headers without setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Java/1.6.0_30
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

And WITH setRequestProperty:

GET /foobar HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive

As you can see the user agent was properly set.

Full example:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;


public class TestUrlOpener {

    public static void main(String[] args) throws IOException {
        URL url = new URL("http://localhost:8080/foobar");
        URLConnection hc = url.openConnection();
        hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

        System.out.println(hc.getContentType());
    }

}

Print empty line?

The two common to print a blank line in Python-

  1. The old school way:

    print "hello\n"

  2. Writing the word print alone would do that:

    print "hello"

    print

Count number of rows within each group

Create a new variable Count with a value of 1 for each row:

df1["Count"] <-1

Then aggregate dataframe, summing by the Count column:

df2 <- aggregate(df1[c("Count")], by=list(Year=df1$Year, Month=df1$Month), FUN=sum, na.rm=TRUE)

How do you properly determine the current script directory?

Here is a partial solution, still better than all published ones so far.

import sys, os, os.path, inspect

#os.chdir("..")

if '__file__' not in locals():
    __file__ = inspect.getframeinfo(inspect.currentframe())[0]

print os.path.dirname(os.path.abspath(__file__))

Now this works will all calls but if someone use chdir() to change the current directory, this will also fail.

Notes:

  • sys.argv[0] is not going to work, will return -c if you execute the script with python -c "execfile('path-tester.py')"
  • I published a complete test at https://gist.github.com/1385555 and you are welcome to improve it.

How can I avoid ResultSet is closed exception in Java?

Check whether you have declared the method where this code is executing as static. If it is static there may be some other thread resetting the ResultSet.

How to read a CSV file into a .NET Datatable

With Cinchoo ETL - an open source library, you can easily convert CSV file to DataTable with few lines of code.

using (var p = new ChoCSVReader(** YOUR CSV FILE **)
     .WithFirstLineHeader()
    )
{
    var dt = p.AsDataTable();
}

For more information, please visit codeproject article.

Hope it helps.

When to use self over $this?

DO NOT USE self::, use static::

There is another aspect of self:: that is worth mentioning. Annoyingly self:: refers to the scope at the point of definition not at the point of execution. Consider this simple class with two methods:

class Person
{

    public static function status()
    {
        self::getStatus();
    }

    protected static function getStatus()
    {
        echo "Person is alive";
    }

}

If we call Person::status() we will see "Person is alive" . Now consider what happens when we make a class that inherits from this:

class Deceased extends Person
{

    protected static function getStatus()
    {
        echo "Person is deceased";
    }

}

Calling Deceased::status() we would expect to see "Person is deceased" however what we see is "Person is alive" as the scope contains the original method definition when call to self::getStatus() was defined.

PHP 5.3 has a solution. the static:: resolution operator implements "late static binding" which is a fancy way of saying that it's bound to the scope of the class called. Change the line in status() to static::getStatus() and the results are what you would expect. In older versions of PHP you will have to find a kludge to do this.

See PHP Documentation

So to answer the question not as asked ...

$this-> refers to the current object (an instance of a class), whereas static:: refers to a class

pyplot axes labels for subplots

You can create a big subplot that covers the two subplots and then set the common labels.

import random
import matplotlib.pyplot as plt

x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]

fig = plt.figure()
ax = fig.add_subplot(111)    # The big subplot
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

# Turn off axis lines and ticks of the big subplot
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.tick_params(labelcolor='w', top=False, bottom=False, left=False, right=False)

ax1.loglog(x, y1)
ax2.loglog(x, y2)

# Set common labels
ax.set_xlabel('common xlabel')
ax.set_ylabel('common ylabel')

ax1.set_title('ax1 title')
ax2.set_title('ax2 title')

plt.savefig('common_labels.png', dpi=300)

common_labels.png

Another way is using fig.text() to set the locations of the common labels directly.

import random
import matplotlib.pyplot as plt

x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

ax1.loglog(x, y1)
ax2.loglog(x, y2)

# Set common labels
fig.text(0.5, 0.04, 'common xlabel', ha='center', va='center')
fig.text(0.06, 0.5, 'common ylabel', ha='center', va='center', rotation='vertical')

ax1.set_title('ax1 title')
ax2.set_title('ax2 title')

plt.savefig('common_labels_text.png', dpi=300)

common_labels_text.png

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

I've posted my jQuery plugin solution here: Frozen table header inside scrollable div

It does exactly what you want and is really lightweight and easy to use.

How to call two methods on button's onclick method in HTML or JavaScript?

<input type="button" onclick="functionA();functionB();" />

function functionA()
{

}

function functionB()
{

}

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

if you use Bootstrap 2.2.1 then maybe is this what you are looking for.

Sample file index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title></title>_x000D_
    <link href="Content/bootstrap.min.css" rel="stylesheet" />_x000D_
    <link href="Content/Site.css" rel="stylesheet" />_x000D_
</head>_x000D_
<body>_x000D_
    <menu>_x000D_
        <div class="navbar navbar-default navbar-fixed-top">_x000D_
            <div class="container">_x000D_
                <div class="navbar-header">_x000D_
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                    </button>_x000D_
                    <a class="navbar-brand" href="/">Application name</a>_x000D_
                </div>_x000D_
                <div class="navbar-collapse collapse">_x000D_
                    <ul class="nav navbar-nav">_x000D_
                        <li><a href="/">Home</a></li>_x000D_
                        <li><a href="/Home/About">About</a></li>_x000D_
                        <li><a href="/Home/Contact">Contact</a></li>_x000D_
                    </ul>_x000D_
                    <ul class="nav navbar-nav navbar-right">_x000D_
                        <li><a href="/Account/Register" id="registerLink">Register</a></li>_x000D_
                        <li><a href="/Account/Login" id="loginLink">Log in</a></li>_x000D_
                    </ul>_x000D_
_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </menu>_x000D_
_x000D_
    <nav>_x000D_
        <div class="col-md-2">_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
        </div>_x000D_
_x000D_
    </nav>_x000D_
    <content>_x000D_
       <div class="col-md-10">_x000D_
_x000D_
               <h2>About.</h2>_x000D_
               <h3>Your application description page.</h3>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <hr />_x000D_
       </div>_x000D_
    </content>_x000D_
_x000D_
    <footer>_x000D_
        <div class="navbar navbar-default navbar-fixed-bottom">_x000D_
            <div class="container" style="font-size: .8em">_x000D_
                <p class="navbar-text">_x000D_
                    &copy; Some info_x000D_
                </p>_x000D_
            </div>_x000D_
        </div>_x000D_
    </footer>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_ File Content/Site.css
_x000D_
_x000D_
body {_x000D_
    padding-bottom: 70px;_x000D_
    padding-top: 70px;_x000D_
}
_x000D_
_x000D_
_x000D_

How to make a website secured with https

What kind of business data? Trade secrets or just stuff that they don't want people to see but if it got out, it wouldn't be a big deal? If we are talking trade secrets, financial information, customer information and stuff that's generally confidential. Then don't even go down that route.

I'm wondering whether I need to use a secured connection (https) or just the forms authentication is enough.

Use a secure connection all the way.

Do I need to alter the code / Config

Yes. Well may be not. You may want to have an expert do this for you.

Is SSL and https one and the same...

Mostly yes. People usually refer to those things as the same thing.

Do I need to apply with someone to get some license or something.

You probably want to have your certificate signed by a certificate authority. It will cost you or your client a bit of money.

Do I need to make all my pages secured or only the login page...

Use https throughout. Performance is usually not an issue if the site is meant for internal users.

I was searching Internet for answer, but I was not able to get all these points... Any whitepaper or other references would also be helpful...

Start here for some pointers: http://www.owasp.org/index.php/Category:OWASP_Guide_Project

Note that SSL is a minuscule piece of making your web site secure once it is accessible from the internet. It does not prevent most sort of hacking.

How can I read pdf in python?

You can use textract module in python

Textract

for install

pip install textract

for read pdf

import textract
text = textract.process('path/to/pdf/file', method='pdfminer')

For detail Textract

Python regex for integer?

Regexp work on the character base, and \d means a single digit 0...9 and not a decimal number.

A regular expression that matches only integers with a sign could be for example

^[-+]?[0-9]+$

meaning

  1. ^ - start of string
  2. [-+]? - an optional (this is what ? means) minus or plus sign
  3. [0-9]+ - one or more digits (the plus means "one or more" and [0-9] is another way to say \d)
  4. $ - end of string

Note: having the sign considered part of the number is ok only if you need to parse just the number. For more general parsers handling expressions it's better to leave the sign out of the number: source streams like 3-2 could otherwise end up being parsed as a sequence of two integers instead of an integer, an operator and another integer. My experience is that negative numbers are better handled by constant folding of the unary negation operator at an higher level.

How to find length of dictionary values

To find all of the lengths of the values in a dictionary you can do this:

lengths = [len(v) for v in d.values()]

Rename column SQL Server 2008

Or you could just slow-click twice on the column in SQL Management Studio and rename it through the UI...

How do I find duplicate values in a table in Oracle?

Also u can try something like this to list all duplicate values in a table say reqitem

SELECT count(poid) 
FROM poitem 
WHERE poid = 50 
AND rownum < any (SELECT count(*)  FROM poitem WHERE poid = 50) 
GROUP BY poid 
MINUS
SELECT count(poid) 
FROM poitem 
WHERE poid in (50)
GROUP BY poid 
HAVING count(poid) > 1;

How do you express binary literals in Python?

>>> print int('01010101111',2)
687
>>> print int('11111111',2)
255

Another way.

Jenkins CI: How to trigger builds on SVN commit

You can use a post-commit hook.

Put the post-commit hook script in the hooks folder, create a wget_folder in your C:\ drive, and put the wget.exe file in this folder. Add the following code in the file called post-commit.bat

SET REPOS=%1   
SET REV=%2

FOR /f "tokens=*" %%a IN (  
'svnlook uuid %REPOS%'  
) DO (  
SET UUID=%%a  
)  

FOR /f "tokens=*" %%b IN (  
'svnlook changed --revision %REV% %REPOS%'  
) DO (  
SET POST=%%b   
)

echo %REPOS% ----- 1>&2

echo %REV% -- 1>&2

echo %UUID% --1>&2

echo %POST% --1>&2

C:\wget_folder\wget ^   
    --header="Content-Type:text/plain" ^   
    --post-data="%POST%" ^   
    --output-document="-" ^   
    --timeout=2 ^     
    http://localhost:9090/job/Test/build/%UUID%/notifyCommit?rev=%REV%    

where Test = name of the job

echo is used to see the value and you can also add exit 2 at the end to know about the issue and whether the post-commit hook script is running or not.

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

What exactly is the difference between Web API and REST API in MVC?

I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.

REST

It is neither an API nor a framework. It is just an architectural concept. You can find more details here.

RESTful

I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.

EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.

Web API

It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).

Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.

How can I change the default Mysql connection timeout when connecting through python?

Do:

con.query('SET GLOBAL connect_timeout=28800')
con.query('SET GLOBAL interactive_timeout=28800')
con.query('SET GLOBAL wait_timeout=28800')

Parameter meaning (taken from MySQL Workbench in Navigator: Instance > Options File > Tab "Networking" > Section "Timeout Settings")

  • connect_timeout: Number of seconds the mysqld server waits for a connect packet before responding with 'Bad handshake'
  • interactive_timeout Number of seconds the server waits for activity on an interactive connection before closing it
  • wait_timeout Number of seconds the server waits for activity on a connection before closing it

BTW: 28800 seconds are 8 hours, so for a 10 hour execution time these values should be actually higher.

Foreach loop, determine which is the last iteration of the loop

foreach (DataRow drow in ds.Tables[0].Rows)
            {
                cnt_sl1 = "<div class='col-md-6'><div class='Slider-img'>" +
                          "<div class='row'><img src='" + drow["images_path"].ToString() + "' alt='' />" +
                          "</div></div></div>";
                cnt_sl2 = "<div class='col-md-6'><div class='Slider-details'>" +
                          "<p>" + drow["situation_details"].ToString() + "</p>" +
                          "</div></div>";
                if (i == 0)
                {
                    lblSituationName.Text = drow["situation"].ToString();
                }
                if (drow["images_position"].ToString() == "0")
                {
                    content += "<div class='item'>" + cnt_sl1 + cnt_sl2 + "</div>";
                    cnt_sl1 = "";
                    cnt_sl2 = "";
                }
                else if (drow["images_position"].ToString() == "1")
                {
                    content += "<div class='item'>" + cnt_sl2 + cnt_sl1 + "</div>";
                    cnt_sl1 = "";
                    cnt_sl2 = "";
                }
                i++;
            }

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

With a button

bool _paused = false;

CupertinoButton(
  child: _paused ? Text('Play') : Text('Pause'),
  color: Colors.blue,
  onPressed: () {
    setState(() {
      _paused = !_paused;
    });
  },
),

docker command not found even though installed with apt-get

The Ubuntu package docker actually refers to a GUI application, not the beloved DevOps tool we've come out to look for.

The instructions for docker can be followed per instructions on the docker page here: https://docs.docker.com/engine/install/ubuntu/

=== UPDATED (thanks @Scott Stensland) ===

You now run the following install script to get docker:

`sudo curl -sSL https://get.docker.com/ | sh`
  • Note: review the script on the website and make sure you have the right link before continuing since you are running this as sudo.

This will run a script that installs docker. Note the last part of the script:

If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  `sudo usermod -aG docker stens`

Remember that you will have to log out and back in for this to take effect!

To update Docker run:

`sudo apt-get update && sudo apt-get upgrade`

For more details on what's going on, See the docker install documentation or @Scott Stensland's answer below

.

=== UPDATE: For those uncomfortable w/ sudo | sh ===

Some in the comments have mentioned that it a risk to run an arbitrary script as sudo. The above option is a convenience script from docker to make the task simple. However, for those that are security-focused but don't want to read the script you can do the following:

  1. Add Dependencies
sudo apt-get update; \
sudo apt-get install \
 apt-transport-https \
 ca-certificates \
 curl \
 gnupg-agent \
 software-properties-common
  1. Add docker gpg key

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

(Security check, verify key fingerprint 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88

$ sudo apt-key fingerprint 0EBFCD88

pub   rsa4096 2017-02-22 [SCEA]
      9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
uid           [ unknown] Docker Release (CE deb) <[email protected]>
sub   rsa4096 2017-02-22 [S]

)

  1. Setup Repository
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
  1. Install Docker
sudo apt-get update; \
sudo apt-get install docker-ce docker-ce-cli containerd.io

If you want to verify that it worked run: sudo docker run hello-world


The following explains why it is named like this: Why install docker on ubuntu should be `sudo apt-get install docker.io`?

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

Check if a Postgres JSON array contains a string

A small variation but nothing new infact. It's really missing a feature...

select info->>'name' from rabbits 
where '"carrots"' = ANY (ARRAY(
    select * from json_array_elements(info->'food'))::text[]);

Extend contigency table with proportions (percentages)

Here's a tidyverse version:

library(tidyverse)
data(diamonds)

(as.data.frame(table(diamonds$cut)) %>% rename(Count=1,Freq=2) %>% mutate(Perc=100*Freq/sum(Freq)))

Or if you want a handy function:

getPercentages <- function(df, colName) {
  df.cnt <- df %>% select({{colName}}) %>% 
    table() %>%
    as.data.frame() %>% 
    rename({{colName}} :=1, Freq=2) %>% 
    mutate(Perc=100*Freq/sum(Freq))
}

Now you can do:

diamonds %>% getPercentages(cut)

or this:

df=diamonds %>% group_by(cut) %>% group_modify(~.x %>% getPercentages(clarity))
ggplot(df,aes(x=clarity,y=Perc))+geom_col()+facet_wrap(~cut)

1114 (HY000): The table is full

This error also appears if the partition on which tmpdir resides fills up (due to an alter table or other

How to get the latest record in each group using GROUP BY?

You need to order them.

SELECT * FROM messages GROUP BY from_id ORDER BY timestamp DESC LIMIT 1

JDBC connection to MSSQL server in windows authentication mode

You need to enable the SQL Server TCP/IP Protocol in Sql Server Configuration Manager app. You can see the protocol in SQL Server Network Configuration.

Cross-browser window resize event - JavaScript / jQuery

Sorry to bring up an old thread, but if someone doesn't want to use jQuery you can use this:

function foo(){....};
window.onresize=foo;

Mipmap drawables for icons

The Android implementation of mipmaps in 4.3 is exactly the technique from 1983 explained in the Wikipedia article :)

Each bitmap image of the mipmap set is a downsized duplicate of the main texture, but at a certain reduced level of detail. Although the main texture would still be used when the view is sufficient to render it in full detail, the renderer will switch to a suitable mipmap image (...) when the texture is viewed from a distance or at a small size.

Although this is described as a technique for 3D graphics (as it mentions "viewing from a distance"), it applies just as well to 2D (translated as "drawn is a smaller space", i.e. "downscaled").

For a concrete Android example, imagine you have a View with a certain background drawable (in particular, a BitmapDrawable). You now use an animation to scale it to 0.15 of its original size. Normally, this would require downscaling the background bitmap for each frame. This "extreme" downscaling, however, may produce visual artifacts.

You can, however, provide a mipmap, which means that the image is already pre-rendered for a few specific scales (let's say 1.0, 0.5, and 0.25). Whenever the animation "crosses" the 0.5 threshold, instead of continuing to downscale the original, 1.0-sized image, it will switch to the 0.5 image and downscale it, which should provide a better result. And so forth as the animation continues.

This is a bit theoretical, since it's actually done by the renderer. According to the source of the Bitmap class, it's just a hint, and the renderer may or may not honor it.

/**
 * Set a hint for the renderer responsible for drawing this bitmap
 * indicating that it should attempt to use mipmaps when this bitmap
 * is drawn scaled down.
 *
 * If you know that you are going to draw this bitmap at less than
 * 50% of its original size, you may be able to obtain a higher
 * quality by turning this property on.
 * 
 * Note that if the renderer respects this hint it might have to
 * allocate extra memory to hold the mipmap levels for this bitmap.
 *
 * This property is only a suggestion that can be ignored by the
 * renderer. It is not guaranteed to have any effect.
 *
 * @param hasMipMap indicates whether the renderer should attempt
 *                  to use mipmaps
 *
 * @see #hasMipMap()
 */
public final void setHasMipMap(boolean hasMipMap) {
    nativeSetHasMipMap(mNativeBitmap, hasMipMap);
}

I'm not quite sure why this would be especially suitable for application icons, though. Although Android on tablets, as well as some launchers (e.g. GEL), request an icon "one density higher" to show it bigger, this is supposed to be done using the regular mechanism (i.e. drawable-xxxhdpi, &c).

multiple conditions for filter in spark data frames

For future references : we can use isInCollection to filter ,here is a example : Note : It will look for exact match

  def getSelectedTablesRows(allTablesInfoDF: DataFrame, tableNames: Seq[String]): DataFrame = {

    allTablesInfoDF.where(col("table_name").isInCollection(tableNames))

  }

How to Read from a Text File, Character by Character in C++

Assuming that temp is a char and textFile is a std::fstream derivative...

The syntax you're looking for is

textFile.get( temp );

Cannot find vcvarsall.bat when running a Python script

Note that there is a very simple solution.

  1. Download the software from http://www.microsoft.com/en-us/download/details.aspx?id=44266 and install it.

  2. Find the installing directory, it is something like "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python"

  3. Change the directory name "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0" to "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC"

  4. Add a new environment variable "VS90COMNTOOLS" and its value is "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC\VC"

Now everything is OK.

How to map calculated properties with JPA and Hibernate

Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.

Here is an example mapping

@EntityView(Order.class)
interface OrderSummary {
  Integer getId();
  @Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
  BigDecimal getOrderAmount();
  @Mapping("COUNT(orderPositions)")
  Long getItemCount();
}

Fetching this will generate a JPQL/HQL query similar to this

SELECT
  o.id,
  SUM(p.price * p.amount * p.tax),
  COUNT(p.id)
FROM
  Order o
LEFT JOIN
  o.orderPositions p
GROUP BY
  o.id

Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html

How to randomly select an item from a list?

You could just:

from random import randint

foo = ["a", "b", "c", "d", "e"]

print(foo[randint(0,4)])

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

You need to set JDK 1.5 to your project and also all dependent project or jar file should also compiled with JDK 1.5

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

You can also write it like this:

let elem: any;
elem = $("div.printArea");
elem.printArea();

How to refresh or show immediately in datagridview after inserting?

Try refreshing the datagrid after each insert

datagridview1.update();
datagridview1.refresh();  

Hope this helps you!

Mask for an Input to allow phone numbers?

you can use cleave.js

// phone (123) 123-4567
var cleavePhone = new Cleave('.input-phone', {
        //prefix: '(123)',
        delimiters: ['(',') ','-'],
        blocks: [0, 3, 3, 4]
});

demo: https://jsfiddle.net/emirM/a8fogse1/

MySQL: Curdate() vs Now()

Actually MySQL provide a lot of easy to use function in daily life without more effort from user side-

NOW() it produce date and time both in current scenario whereas CURDATE() produce date only, CURTIME() display time only, we can use one of them according to our need with CAST or merge other calculation it, MySQL rich in these type of function.

NOTE:- You can see the difference using query select NOW() as NOWDATETIME, CURDATE() as NOWDATE, CURTIME() as NOWTIME ;

Turning multi-line string into single comma-separated

Don't seen this simple solution with awk

awk 'b{b=b","}{b=b$2}END{print b}' infile

How to get element by innerText

You'll have to traverse by hand.

var aTags = document.getElementsByTagName("a");
var searchText = "SearchingText";
var found;

for (var i = 0; i < aTags.length; i++) {
  if (aTags[i].textContent == searchText) {
    found = aTags[i];
    break;
  }
}

// Use `found`.

How can I revert a single file to a previous version?

Extracted from here: http://git.661346.n2.nabble.com/Revert-a-single-commit-in-a-single-file-td6064050.html

 git revert <commit> 
 git reset 
 git add <path> 
 git commit ... 
 git reset --hard # making sure you didn't have uncommited changes earlier 

It worked very fine to me.

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

In Python 3.3, added new method timestamp:

import datetime
seconds_since_epoch = datetime.datetime.now().timestamp()

Your question stated that you needed milliseconds, which you can get like this:

milliseconds_since_epoch = datetime.datetime.now().timestamp() * 1000

If you use timestamp on a naive datetime object, then it assumed that it is in the local timezone. Use timezone-aware datetime objects if this is not what you intend to happen.

Handling JSON Post Request in Go

I was driving myself crazy with this exact problem. My JSON Marshaller and Unmarshaller were not populating my Go struct. Then I found the solution at https://eager.io/blog/go-and-json:

"As with all structs in Go, it’s important to remember that only fields with a capital first letter are visible to external programs like the JSON Marshaller."

After that, my Marshaller and Unmarshaller worked perfectly!

How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

In Java, how can I determine if a char array contains a particular character?

You can also define these chars as list of string. Then you can check if the characters is valid for accepted characters with list.Contains(x) method.

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

"sed" command in bash

sed is the Stream EDitor. It can do a whole pile of really cool things, but the most common is text replacement.

The s,%,$,g part of the command line is the sed command to execute. The s stands for substitute, the , characters are delimiters (other characters can be used; /, : and @ are popular). The % is the pattern to match (here a literal percent sign) and the $ is the second pattern to match (here a literal dollar sign). The g at the end means to globally replace on each line (otherwise it would only update the first match).

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

Get current batchfile directory

System read-only variable %CD% keeps the path of the caller of the batch, not the batch file location.

You can get the name of the batch script itself as typed by the user with %0 (e.g. scripts\mybatch.bat). Parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script (e.g. W:\scripts\) and %~f0 will return the full pathname (e.g. W:\scripts\mybatch.cmd).

You can refer to other files in the same folder as the batch script by using this syntax:

CALL %0\..\SecondBatch.cmd

This can even be used in a subroutine, Echo %0 will give the call label but, echo "%~nx0" will give you the filename of the batch script.

When the %0 variable is expanded, the result is enclosed in quotation marks.

More on batch parameters.

Warn user before leaving web page with unsaved changes

Check out the JavaScript onbeforeunload event. It's non-standard JavaScript introduced by Microsoft, however it works in most browsers and their onbeforeunload documentation has more information and examples.

'mvn' is not recognized as an internal or external command,

Add maven directory /bin to System variables under the name Path.

To check this, you can echo %PATH%

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

How do I run a batch file from my Java Application?

ProcessBuilder is the Java 5/6 way to run external processes.

How to set iframe size dynamically

I've found this to work the best across all browsers and devices (PC, tables & mobile).

<script type="text/javascript">
                      function iframeLoaded() {
                          var iFrameID = document.getElementById('idIframe');
                          if(iFrameID) {
                                // here you can make the height, I delete it first, then I make it again
                                iFrameID.height = "";
                                iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
                          }   
                      }
                    </script> 


<iframe id="idIframe" onload="iframeLoaded()" frameborder="0" src="yourpage.php" height="100%" width="100%" scrolling="no"></iframe>

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

If you are using hand inputted data, you can enter your data as mm:ss,0 or mm:ss.0 depending on your language/region selection instead of 00:mm:ss.

You need to specify your cell format as [m]:ss if you like to see all minutes seconds format instead of hours minutes seconds format.

How to remove leading zeros from alphanumeric text?

I made some benchmark tests and found, that the fastest way (by far) is this solution:

    private static String removeLeadingZeros(String s) {
      try {
          Integer intVal = Integer.parseInt(s);
          s = intVal.toString();
      } catch (Exception ex) {
          // whatever
      }
      return s;
    }

Especially regular expressions are very slow in a long iteration. (I needed to find out the fastest way for a batchjob.)

Change font color and background in html on mouseover

It would be great if you use :hover pseudo class over the onmouseover event

td:hover
{
   background-color:white
}

and for the default styling just use

td
{
  background-color:black
}

As you want to use these styling not over all the td elements then you need to specify the class to those elements and add styling to that class like this

.customTD
{
   background-color:black
}
.customTD:hover
{
  background-color:white;
}

You can also use :nth-child selector to select the td elements

Excel VBA Run-time error '13' Type mismatch

You would get a type mismatch if Sheets(name).Cells(4 + i, 57) contains a non-numeric value. You should validate the fields before you assume they are numbers and try to subtract from them.

Also, you should enable Option Strict so you are forced to explicitly convert your variables before trying to perform type-dependent operations on them such as subtraction. That will help you identify and eliminate issues in the future, too.    Unfortunately Option Strict is for VB.NET only. Still, you should look up best practices for explicit data type conversions in VBA.


Update:

If you are trying to go for the quick fix of your code, however, wrap the ** line and the one following it in the following condition:

If IsNumeric(Sheets(name).Cells(4 + i, 57))
    Sheets(name).Cells(4 + i, 58) = Sheets(name).Cells(4 + i, 57) - a
    x = Sheets(name).Cells(4 + i, 57) - a
End If

Note that your x value may not contain its expected value in the next iteration, however.

JavaScript DOM: Find Element Index In Container

Just pass the object reference to the following function and you will get the index

function thisindex(elm) 
{ 
    var the_li = elm; 
    var the_ul = elm.parentNode; 
    var li_list = the_ul.childNodes; 

    var count = 0; // Tracks the index of LI nodes

    // Step through all the child nodes of the UL
    for( var i = 0; i < li_list.length; i++ )
    {
        var node = li_list.item(i);
        if( node )
        {
        // Check to see if the node is a LI
            if( node.nodeName == "LI" )
            {
            // Increment the count of LI nodes
                count++;
            // Check to see if this node is the one passed in
                if( the_li == node )
                {
                    // If so, alert the current count
                    alert(count-1);
                }
            }
        }
    }
}

How does paintComponent work?

The internals of the GUI system call that method, and they pass in the Graphics parameter as a graphics context onto which you can draw.

error: src refspec master does not match any

This is happend to me once I forgot to add files. So I got the same error. All you need to do is add your files.

  1. Add your files => git add . or the name of the files you want to add. you supposed to init first your repo with git init.
  2. Commit your changes => git commit -m 'Initial Commit'.
  3. Now push your changes => git push -u origin master

How to redirect to a 404 in Rails?

The newly Selected answer submitted by Steven Soroka is close, but not complete. The test itself hides the fact that this is not returning a true 404 - it's returning a status of 200 - "success". The original answer was closer, but attempted to render the layout as if no failure had occurred. This fixes everything:

render :text => 'Not Found', :status => '404'

Here's a typical test set of mine for something I expect to return 404, using RSpec and Shoulda matchers:

describe "user view" do
  before do
    get :show, :id => 'nonsense'
  end

  it { should_not assign_to :user }

  it { should respond_with :not_found }
  it { should respond_with_content_type :html }

  it { should_not render_template :show }
  it { should_not render_with_layout }

  it { should_not set_the_flash }
end

This healthy paranoia allowed me to spot the content-type mismatch when everything else looked peachy :) I check for all these elements: assigned variables, response code, response content type, template rendered, layout rendered, flash messages.

I'll skip the content type check on applications that are strictly html...sometimes. After all, "a skeptic checks ALL the drawers" :)

http://dilbert.com/strips/comic/1998-01-20/

FYI: I don't recommend testing for things that are happening in the controller, ie "should_raise". What you care about is the output. My tests above allowed me to try various solutions, and the tests remain the same whether the solution is raising an exception, special rendering, etc.

Regex select all text between tags

You shouldn't be trying to parse html with regexes see this question and how it turned out.

In the simplest terms, html is not a regular language so you can't fully parse is with regular expressions.

Having said that you can parse subsets of html when there are no similar tags nested. So as long as anything between and is not that tag itself, this will work:

preg_match("/<([\w]+)[^>]*>(.*?)<\/\1>/", $subject, $matches);
$matches = array ( [0] => full matched string [1] => tag name [2] => tag content )

A better idea is to use a parser, like the native DOMDocument, to load your html, then select your tag and get the inner html which might look something like this:

$obj = new DOMDocument();
$obj -> load($html);
$obj -> getElementByTagName('el');
$value = $obj -> nodeValue();

And since this is a proper parser it will be able to handle nesting tags etc.

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

HTML5 Canvas background image

Make sure that in case your image is not in the dom, and you get it from local directory or server, you should wait for the image to load and just after that to draw it on the canvas.

something like that:

function drawBgImg() {
    let bgImg = new Image();
    bgImg.src = '/images/1.jpg';
    bgImg.onload = () => {
        gCtx.drawImage(bgImg, 0, 0, gElCanvas.width, gElCanvas.height);
    }
}

Access Https Rest Service using Spring RestTemplate

This is a solution with no deprecated class or method : (Java 8 approved)

CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);

RestTemplate restTemplate = new RestTemplate(requestFactory);

Important information : Using NoopHostnameVerifier is a security risk

What is char ** in C?

well, char * means a pointer point to char, it is different from char array.

char amessage[] = "this is an array";  /* define an array*/
char *pmessage = "this is a pointer"; /* define a pointer*/

And, char ** means a pointer point to a char pointer.

You can look some books about details about pointer and array.

How to update only one field using Entity Framework?

Combining several suggestions I propose the following:

    async Task<bool> UpdateDbEntryAsync<T>(T entity, params Expression<Func<T, object>>[] properties) where T : class
    {
        try
        {
            var entry = db.Entry(entity);
            db.Set<T>().Attach(entity);
            foreach (var property in properties)
                entry.Property(property).IsModified = true;
            await db.SaveChangesAsync();
            return true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("UpdateDbEntryAsync exception: " + ex.Message);
            return false;
        } 
    }

called by

UpdateDbEntryAsync(dbc, d => d.Property1);//, d => d.Property2, d => d.Property3, etc. etc.);

Or by

await UpdateDbEntryAsync(dbc, d => d.Property1);

Or by

bool b = UpdateDbEntryAsync(dbc, d => d.Property1).Result;

Open an image using URI in Android's default gallery image viewer

If your app targets Android N (7.0) and above, you should not use the answers above (of the "Uri.fromFile" method), because it won't work for you.

Instead, you should use a ContentProvider.

For example, if your image file is in external folder, you can use this (similar to the code I've made here) :

File file = ...;
final Intent intent = new Intent(Intent.ACTION_VIEW)//
                                    .setDataAndType(VERSION.SDK_INT >= VERSION_CODES.N ?
                                                    FileProvider.getUriForFile(this,getPackageName() + ".provider", file) : Uri.fromFile(file),
                            "image/*").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

manifest:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>

res/xml/provider_paths.xml :

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <!--<external-path name="external_files" path="."/>-->
    <external-path
        name="files_root"
        path="Android/data/${applicationId}"/>
    <external-path
        name="external_storage_root"
        path="."/>
</paths>

If your image is in the private path of the app, you should create your own ContentProvider, as I've created "OpenFileProvider" on the link.

What is SOA "in plain english"?

SOA is a buzzword that was invented by technology vendors to help sell their Enterprise Service Bus related technologies. The idea is that you make your little island applications in the enterprise (eg: accounting system, stock control system, etc) all expose services, so that they can be orchestrated flexibly into 'applications', or rather become parts of aggregate enterprise scoped business logic.

Basically a load of old bollocks that nearly never works, because it misses the point that the reasons why technology is the way it is in an organisation is down to culture, evolution, history of the firm, and the lock in is so high that any attempt to restructure the technology is bound to fail.

Python unittest - opposite of assertRaises?

If you pass an Exception class to assertRaises(), a context manager is provided. This can improve the readability of your tests:

# raise exception if Application created with bad data
with self.assertRaises(pySourceAidExceptions.PathIsNotAValidOne):
    application = Application("abcdef", "")

This allows you to test error cases in your code.

In this case, you are testing the PathIsNotAValidOne is raised when you pass invalid parameters to the Application constructor.

Jquery: Find Text and replace

I was looking for something similar and I use code that Doug Owings posted, but my text had some br tags and the code was erasing it.

So I use this: ( Just note that I replaced .text() to .html() )

Text:

< p class = "textcontent" > 
     Here some text replace me 
     < br > here an other text
     < br > here is more text 
< /p>

JS:

$('.textcontent').each(function() {

   var text = $(this).html();
   $(this).html(text.replace('replace me', 'I love this text')); 

});

Also if you want to edit several text create an array:

var replacetext = {
    "Text 0": "New Text 0",
    "Text 1": "New Text 1",
    "Text 2": "New Text 2",
    "Text 3": "New Text 3",
    "Text 4": "New Text 4"
};

$.each(replacetext, function(txtorig, txtnew) {
    var text = $('#parentid').html();
    $('#parentid').html(text.replace(txtorig, txtnew)); 
});

How to "comment-out" (add comment) in a batch/cmd?

No, plain old batch files use REM as a comment. ECHO is the command that prints something on the screen.

To "comment out" sections of the file you could use GOTO. An example of all these commands/techniques:

REM it starts here the section below can be safely erased once the file is customised
ECHO Hey you need to edit this file before running it!  Check the instructions inside
ECHO Now press ctrl-c to interrupt execution or enter to continue
PAUSE
REM erase the section above once you have customised the file
python executed1.py
ECHO Skipping some stuff now
GOTO End
python skipped1.py
python skipped2.py
:END
python executed2.py

What can I say? batch files are a relic of times long gone, they're clunky and ugly.

You can read more on this website.

EDIT: modified the example a bit to have it contain the elements you are apparently looking for.

Hiding button using jQuery

Try this:

$('input[name=Comanda]')
.click(
     function ()
     {
         $(this).hide();
     }
);

For doing everything else you can use something like this one:

$('input[name=Comanda]')
.click(
     function ()
     {
         $(this).hide();

         $(".ClassNameOfShouldBeHiddenElements").hide();
     }
);

For hidding any other elements based on their IDs, use this one:

$('input[name=Comanda]')
.click(
     function ()
     {
         $(this).hide();

         $("#FirstElement").hide();
         $("#SecondElement").hide();
         $("#ThirdElement").hide();
     }
);

Taking the record with the max date

SELECT mu_file, mudate
  FROM flightdata t_ext
 WHERE mudate = (SELECT MAX (mudate)
                     FROM flightdata where mudate < sysdate)

SVN - Checksum mismatch while updating

I found very nice solution, that SOLVED my problem. The trick is to edit the svn DB (wc.db).

The solution is described on this page : http://www.exchangeconcept.com/2015/01/svn-e155037-previous-operation-has-not-finished-run-cleanup-if-it-was-interrupted/

If link is down, just look and follow this instructions: enter image description here

I used sqlite tool from http://sqlitebrowser.org/.

Overflow:hidden dots at the end

Yes, via the text-overflow property in CSS 3. Caveat: it is not universally supported yet in browsers.

How can I read Chrome Cache files?

EDIT: The below answer no longer works see here


Chrome stores the cache as a hex dump. OSX comes with xxd installed, which is a command line tool for converting hex dumps. I managed to recover a jpg from my Chrome's HTTP cache on OSX using these steps:

  1. Goto: chrome://cache
  2. Find the file you want to recover and click on it's link.
  3. Copy the 4th section to your clipboard. This is the content of the file.
  4. Follow the steps on this gist to pipe your clipboard into the python script which in turn pipes to xxd to rebuild the file from the hex dump: https://gist.github.com/andychase/6513075

Your final command should look like:

pbpaste | python chrome_xxd.py | xxd -r - image.jpg

If you're unsure what section of Chrome's cache output is the content hex dump take a look at this page for a good guide: http://www.sparxeng.com/blog/wp-content/uploads/2013/03/chrome_cache_html_report.png

Image source: http://www.sparxeng.com/blog/software/recovering-images-from-google-chrome-browser-cache

More info on XXD: http://linuxcommand.org/man_pages/xxd1.html

Thanks to Mathias Bynens above for sending me in the right direction.

How large is a DWORD with 32- and 64-bit code?

No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.