Programs & Examples On #Intellisense

IntelliSense is Microsoft's implementation of automatic [code-completion], best known for its use in the Microsoft Visual Studio integrated development environment.

Unity Scripts edited in Visual studio don't provide autocomplete

There is no auto-completion because the script says "Miscellaneous Files" instead of the of the name of the Project. Take a look at the image below that came from the video in your question:

enter image description here

The "Miscellaneous Files" message can happen for many reasons:

  1. It can happen when you open your Unity C# file from another folder instead of opening it from Unity Editor.

  2. This can also happen because Unity crashed while Visual Studio is still open therefore corrupting some files.

  3. It can happen because Unity was closed then re-opened but is no longer connected to Visual Studio. When Visual Studio is opened you get "Miscellaneous Files" and no auto-completion.

  4. This can happen when Visual Studio Tools for unity is not installed.

  5. When you create a script from Unity then quickly open it before Unity finish processing it or before the round icon animation stuff finish animating.


Most of the times, restarting Unity and Visual Studio should fix this.

I can't tell which one is causing the problem but I will cover the most likely solution to fix this.

Fix Part 1:

  1. Download and Install Visual Studio Tools for unity from this link. Do this while Unity and Visual Studio are both closed.

  2. From Unity Editor, go to Edit ? Preferences... ? External Tools. On the External Script Editor drop down menu, change that to Visual Studio 2015.

    enter image description here


Fix Part 2:

If newly created C# files are coming up as Miscellaneous then follow the instruction below:

  1. From Visual Studio, go to Tools ? Options... ? Tools for Unity ? Miscellaneous. Under Show connectivity icon, set it to true then restart Visual Studio.

    enter image description here

  2. When you re-start, connection icon should now be available in Visual Studio. Click it then choose the Unity instance to connect to. The red 'x' icon should now turn into a brown checkmark icon. Now, when you create a new C# file in Unity, it should open without saying Miscellaneous.

    enter image description here


Fix Part 3:

Still not fixed?

Re-import project then open C# Project.

  1. Close Visual Studio.

  2. From Unity, re-import project by going to Assets ? Reimport All.

    enter image description here

  3. Now, open the project in Visual Studio by going to Assets ? Open C# Project. This will reload the project and fix possible solution file problems.

    enter image description here


Fix Part 4:

Still not fixed?

Fix each C# file individually.

  1. Click on Show All Files icon.

    enter image description here

  2. Select the script that doesn't do auto-complete then right-click and select Include In Project.

    enter image description here


Fix Part 5:

Not fixed yet?

Credit goes to chrisvarnz for this particular solution which seems to have worked for multiple people.

  1. Close Visual Studio

  2. Go your project directory and delete all the generated Visual Studio files.

    These are the files extensions to delete:

    • .csproj
    • .user
    • .sln

    Example:

    Let's say that the name of your Project is called Target_Shoot, these are what the files to delete should look like:

    • Target_Shoot.csproj
    • Target_Shoot.Editor.csproj
    • Target_Shoot.Editor.csproj.user
    • Target_Shoot.Player.csproj
    • Target_Shoot.Player.csproj.user
    • Target_Shoot.sln

    Do not delete anything else.

  3. Double click on the script again from Unity which should generate new Visual Studio file then open Visual Studio. This may solve your problem.


Fix Part 6:

If not working, check if you are having this error:

The "GetReferenceNearestTargetFrameworkTask" task was not found

  1. Install Nuget PackageManager from here.

  2. Restart Visual Visual.

See this answer for more information.

Visual Studio displaying errors even if projects build

Delete the hidden file path = your solution\ .vs\ your solution Name \v15\ .suo

Why is SQL Server 2008 Management Studio Intellisense not working?

I don't want to suggest a product out of turn, since getting Intellisense running is probably the best option, but I've struggled with the accursed no intellisense on Management Studio for months. Reinstallation, CU7 update, refreshing caches, sacrificing chickens to pagan gods; nothing has helped.

I was about to pay for RedGate's SqlPrompt (pretty damned pricey, $195 US), when I found SqlComplete.

http://www.devart.com/dbforge/sql/sqlcomplete/?gclid=CN2xs_Lw7akCFcYZHAodpicXXw

There is a free version which does the basics, and the full version is only $50!

I'm a database architect, and while I can remember the commands, auto complete saves me heaps of time. If you're stuck and can't get Intellisense to work, try SqlComplete. It saved me hours of hassle.

Eclipse Intellisense?

I once had the same problem, and then I searched and found this and it worked for me:

I had got some of the boxes unchecked, so I checked them again, then it worked. Just go to

Windows > Preferences > Java > Editor > Content Assist > Advanced

and check the boxes which you want .

Cannot use Server.MapPath

Firt add a reference to System.web, if you don't have. Do that in the References folder.

You can then use Hosting.HostingEnvironment.MapPath(path);

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

It got frustrating for me as well but I figured out my own answer. Restarting did help but I found why I ran into trouble: I'd copied and pasted an ASP Panel with controls I'd need to re-use. I only had those in the first Div tag working. All others needed to be set up, so I said "Aha ... let me comment out the remaining Div Tags that aren't set up ..." and sure enough, intellisense came right back on.

So not only will it fail to work if the cursor is below a code error but it can fail to work if you're a copy / paste type like me.

Why does intellisense and code suggestion stop working when Visual Studio is open?

I am facing the same issue with Visual Studio 2015 Preview. I have closed that respective file and re-opened it. That fixes it for me :).

Visual Studio C# IntelliSense not automatically displaying

At the bottommost right look at the blue line where Ln, Col, Spaces, UTF, CRLF,..... here the language is specified. Check that your language and the language specified there are the same. In my case, it was Django Python while I was trying to use HTML.

Checking if a variable is an integer

Basically, an integer n is a power of three, if there exists an integer x such that n == 3x.

So to verify that you can use this functions

def is_power_of_three(n)
  return false unless n.positive?

  n == 3**(Math.log10(n)/Math.log10(3)).to_f.round(2)
end

How to have Ellipsis effect on Text

Use the numberOfLines parameter on a Text component:

<Text numberOfLines={1}>long long long long text<Text>

Will produce:

long long long…

(Assuming you have short width container.)


Use the ellipsizeMode parameter to move the ellipsis to the head or middle. tail is the default value.

<Text numberOfLines={1} ellipsizeMode='head'>long long long long text<Text>

Will produce:

…long long text

NOTE: The Text component should also include style={{ flex: 1 }} when the ellipsis needs to be applied relative to the size of its container. Useful for row layouts, etc.

Delete specific line from a text file?

This can be done in three steps:

// 1. Read the content of the file
string[] readText = File.ReadAllLines(path);

// 2. Empty the file
File.WriteAllText(path, String.Empty);

// 3. Fill up again, but without the deleted line
using (StreamWriter writer = new StreamWriter(path))
{
    foreach (string s in readText)
    {
        if (!s.Equals(lineToBeRemoved))
        {
            writer.WriteLine(s);
        }
    }
}

How can I wrap or break long text/word in a fixed width span?

Try following css with addition of white-space:

span {
    display: block;
    word-wrap:break-word;
    width: 50px;
    white-space: normal
}

fatal: The current branch master has no upstream branch

on a very simple side, once you have other branches, you can't just use for pushing a branch

git push

But you need to specify the branch now, even if you have checkout the branch you want to push, so

git push origin <feature_branch>

Where can be even the master branch

How can I disable mod_security in .htaccess file?

It is possible to do this, but most likely your host implemented mod_security for a reason. Be sure they approve of you disabling it for your own site.

That said, this should do it;

<IfModule mod_security.c>
  SecFilterEngine Off
  SecFilterScanPOST Off
</IfModule>

How to pass optional arguments to a method in C++?

Typically by setting a default value for a parameter:

int func(int a, int b = -1) { 
    std::cout << "a = " << a;
    if (b != -1)        
        std::cout << ", b = " << b;
    std::cout << "\n";
}

int main() { 
    func(1, 2);  // prints "a=1, b=2\n"
    func(3);     // prints "a=3\n"
    return 0;
}

Play/pause HTML 5 video using JQuery

As an extension of lonesomeday's answer, you can also use

$('#playMovie1').click(function(){
    $('#movie1')[0].play();
});

Notice that there is no get() or eq() jQuery function called. DOM's array used to call play() function. It's a shortcut to keep in mind.

Default value in Doctrine

You can do it using xml as well:

<field name="acmeOne" type="string" column="acmeOne" length="36">
    <options>
        <option name="comment">Your SQL field comment goes here.</option>
        <option name="default">Default Value</option>
    </options>
</field>

Java JTextField with input hint

If you still look for a solution, here's one that combined other answers (Bart Kiers and culmat) for your reference:

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;


public class HintTextField extends JTextField implements FocusListener
{

    private String hint;

    public HintTextField ()
    {
        this("");
    }

    public HintTextField(final String hint)
    {
        setHint(hint);
        super.addFocusListener(this);
    }

    public void setHint(String hint)
    {
        this.hint = hint;
        setUI(new HintTextFieldUI(hint, true));
        //setText(this.hint);
    }


    public void focusGained(FocusEvent e)
    {
        if(this.getText().length() == 0)
        {
            super.setText("");
        }
    }

    public void focusLost(FocusEvent e)
    {
        if(this.getText().length() == 0)
        {
            setHint(hint);
        }
    }

    public String getText()
    {
        String typed = super.getText();
        return typed.equals(hint)?"":typed;
    }
}

class HintTextFieldUI extends javax.swing.plaf.basic.BasicTextFieldUI implements FocusListener
{

    private String hint;
    private boolean hideOnFocus;
    private Color color;

    public Color getColor()
    {
        return color;
    }

    public void setColor(Color color)
    {
        this.color = color;
        repaint();
    }

    private void repaint()
    {
        if(getComponent() != null)
        {
            getComponent().repaint();
        }
    }

    public boolean isHideOnFocus()
    {
        return hideOnFocus;
    }

    public void setHideOnFocus(boolean hideOnFocus)
    {
        this.hideOnFocus = hideOnFocus;
        repaint();
    }

    public String getHint()
    {
        return hint;
    }

    public void setHint(String hint)
    {
        this.hint = hint;
        repaint();
    }

    public HintTextFieldUI(String hint)
    {
        this(hint, false);
    }

    public HintTextFieldUI(String hint, boolean hideOnFocus)
    {
        this(hint, hideOnFocus, null);
    }

    public HintTextFieldUI(String hint, boolean hideOnFocus, Color color)
    {
        this.hint = hint;
        this.hideOnFocus = hideOnFocus;
        this.color = color;
    }


    protected void paintSafely(Graphics g)
    {
        super.paintSafely(g);
        JTextComponent comp = getComponent();
        if(hint != null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus())))
        {
            if(color != null)
            {
                g.setColor(color);
            }
            else
            {
                g.setColor(Color.gray);
            }
            int padding = (comp.getHeight() - comp.getFont().getSize()) / 2;
            g.drawString(hint, 5, comp.getHeight() - padding - 1);
        }
    }


    public void focusGained(FocusEvent e)
    {
        if(hideOnFocus) repaint();

    }


    public void focusLost(FocusEvent e)
    {
        if(hideOnFocus) repaint();
    }

    protected void installListeners()
    {
        super.installListeners();
        getComponent().addFocusListener(this);
    }

    protected void uninstallListeners()
    {
        super.uninstallListeners();
        getComponent().removeFocusListener(this);
    }
}



Usage:
HintTextField field = new HintTextField();
field.setHint("Here's a hint");

How do you set the max number of characters for an EditText in Android?

You can use a InputFilter, that's the way:

EditText myEditText = (EditText) findViewById(R.id.editText1);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(10); //Filter to 10 characters
myEditText .setFilters(filters);

T-SQL: Opposite to string concatenation - how to split string into multiple records

Slight modification of the solution above so it works with variable-length delimiters.

create FUNCTION dbo.fn_Split2 (@sep nvarchar(10), @s nvarchar(4000))
RETURNS table
AS
RETURN (
    WITH Pieces(pn, start, stop) AS (
      SELECT 1, 1, CHARINDEX(@sep, @s)
      UNION ALL
      SELECT pn + 1, stop + (datalength(@sep)/2), CHARINDEX(@sep, @s, stop + (datalength(@sep)/2))
      FROM Pieces
      WHERE stop > 0
    )
    SELECT pn,
      SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 4000 END) AS s
    FROM Pieces
  )

NB: I've used datalength() since len() reports incorrectly if there are trailing spaces.

How do I install Python OpenCV through Conda?

The following command works for me too. I am using an embedded IPython Notebook in Anaconda.

conda install -c https://conda.binstar.org/menpo opencv

How can I verify if a Windows Service is running

Here you get all available services and their status in your local machine.

ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
    Console.WriteLine(service.ServiceName+"=="+ service.Status);
}

You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

Writing to a file in a for loop

That is because you are opening , writing and closing the file 10 times inside your for loop

myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()

You should open and close your file outside for loop.

myfile = open('xyz.txt', 'w')
for line in lines:
    var1, var2 = line.split(",");
    myfile.write("%s\n" % var1)

myfile.close()
text_file.close()

You should also notice to use write and not writelines.

writelines writes a list of lines to your file.

Also you should check out the answers posted by folks here that uses with statement. That is the elegant way to do file read/write operations in Python

Android TextView Text not getting wrapped

I put this attribute:

android:inputType="textMultiLine"

into my TextView and it has wrapping line and user can "Enter" for a new line.

============================================================

When you come to this post, you may want to create a Big TextView which can display multiple lines so these attributes may also needed

android:layout_height="Xdp" //where X is a number depends on how big Textview you want
android:gravity="top" //in order to make your text start from the top of your TextView.

How to return a value from try, catch, and finally?

To return a value when using try/catch you can use a temporary variable, e.g.

public static double add(String[] values) {
    double sum = 0.0;
    try {
        int length = values.length;
        double arrayValues[] = new double[length];
        for(int i = 0; i < length; i++) {
            arrayValues[i] = Double.parseDouble(values[i]);
            sum += arrayValues[i];
        }
    } catch(NumberFormatException e) {
        e.printStackTrace();
    } catch(RangeException e) {
        throw e;
    } finally {
        System.out.println("Thank you for using the program!");
    }
    return sum;
}

Else you need to have a return in every execution path (try block or catch block) that has no throw.

How get sound input from microphone in python, and process it on the fly?

I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .

It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .

... and a lot of other examples as well ...

Django: Calling .update() on a single model instance retrieved by .get()?

As of Django 1.5, there is an update_fields property on model save. eg:

obj.save(update_fields=['field1', 'field2', ...])

https://docs.djangoproject.com/en/dev/ref/models/instances/

I prefer this approach because it doesn't create an atomicity problem if you have multiple web app instances changing different parts of a model instance.

Java ArrayList clear() function

data.removeAll(data); will do the work, I think.

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

Maybe you wrongly set permission on python3. For instance if for the file permission is set like

`os.chmod('spam.txt', 0777)` --> This will lead to SyntaxError 

This syntax was used in Python2. Now if you change like: os.chmod('spam.txt', 777) --> This is still worst!! Your permission will be set wrongly since are not on "octal" but on decimal.

Afterwards you will get permission Error if you try for instance to remove the file: PermissionError: [WinError 5] Access is denied:

Solution for python3 is quite easy: os.chmod('spam.txt', 0o777) --> The syntax is now ZERO and o "0o"

Determine a string's encoding in C#

My finally working approach is to try potential candidates of expected encodings by detecting invalid characters in the strings created from the byte array by the encodings. If I don't encounter invalid characters, I suppose the tested encoding works fine for the tested data.

For me, having only Latin and German special characters to consider, in order to determine the proper encoding for a byte array, I try to detect invalid characters in a string with this method:

    /// <summary>
    /// detect invalid characters in string, use to detect improper encoding
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static bool DetectInvalidChars(string s)
    {
        const string specialChars = "\r\n\t .,;:-_!\"'?()[]{}&%$§=*+~#@|<>äöüÄÖÜß/\\^€";
        return s.Any(ch => !(
            specialChars.Contains(ch) ||
            (ch >= '0' && ch <= '9') ||
            (ch >= 'a' && ch <= 'z') ||
            (ch >= 'A' && ch <= 'Z')));
    }

(NB: if you have other Latin-based languages to consider, you might want to adapt the specialChars const string in the code)

Then I use it like this (I only expect UTF-8 or Default encoding):

        // determine encoding by detecting invalid characters in string
        var invoiceXmlText = Encoding.UTF8.GetString(invoiceXmlBytes); // try utf-8 first
        if (StringFuncs.DetectInvalidChars(invoiceXmlText))
            invoiceXmlText = Encoding.Default.GetString(invoiceXmlBytes); // fallback to default

select count(*) from table of mysql in php

For mysqli users, the code will look like this:

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

$result = $mysqli->query("SELECT COUNT(*) AS Students_count FROM Students")->fetch_array();
var_dump($result['Students_count']);

or:

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

$result = $mysqli->query("SELECT COUNT(*) FROM Students")->fetch_array();
var_dump($result[0]);

Unit testing void methods?

As always: test what the method is supposed to do!

Should it change global state (uuh, code smell!) somewhere?

Should it call into an interface?

Should it throw an exception when called with the wrong parameters?

Should it throw no exception when called with the right parameters?

Should it ...?

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

Do not put the src folder in the WEB-INF directory!!

How can I run a program from a batch file without leaving the console open after the program starts?

My solution to do this from the GUI:

  1. Create a shortcut to the program you want to run;

  2. Edit the shortcut's properties;

  3. Change the TARGET field to %COMSPEC% /C "START "" "PROGRAMNAME"";

  4. Change the RUN field to minimized.

Ready! See how you like it...

PS: Program parameters can be inserted in between the two final quotation marks; the PROGRAMNAME string can be either a filename, a relative or an absolute path -- if you put in an absolute path and erase the drive letter and semicolon, then this will work in a thumbdrive no matter what letter the host computer assigns to it... (also, if you place the shortcut in the same folder and precede the program filename in PROGRAMNAME with the %CD% variable, paths will always match; same trick can be used in START IN field).

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

@bogatron has it right, you can use where, it's worth noting that you can do this natively in pandas:

df1 = df.where(pd.notnull(df), None)

Note: this changes the dtype of all columns to object.

Example:

In [1]: df = pd.DataFrame([1, np.nan])

In [2]: df
Out[2]: 
    0
0   1
1 NaN

In [3]: df1 = df.where(pd.notnull(df), None)

In [4]: df1
Out[4]: 
      0
0     1
1  None

Note: what you cannot do recast the DataFrames dtype to allow all datatypes types, using astype, and then the DataFrame fillna method:

df1 = df.astype(object).replace(np.nan, 'None')

Unfortunately neither this, nor using replace, works with None see this (closed) issue.


As an aside, it's worth noting that for most use cases you don't need to replace NaN with None, see this question about the difference between NaN and None in pandas.

However, in this specific case it seems you do (at least at the time of this answer).

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):

The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:

[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }

Will output the following if it is over the character limit: "Address can have a max of 100 characters"

The placeholders I am aware of are:

  • {0} = Property Name
  • {1} = Max Length
  • {2} = Min Length

Much thanks to bloudraak for initially pointing this out.

jQuery remove all list items from an unordered list

this worked for me with minimal code

$(my_list).remove('li');

SQL permissions for roles

SQL-Server follows the principle of "Least Privilege" -- you must (explicitly) grant permissions.

'does it mean that they wont be able to update 4 and 5 ?'

If your users in the doctor role are only in the doctor role, then yes.

However, if those users are also in other roles (namely, other roles that do have access to 4 & 5), then no.

More Information: http://msdn.microsoft.com/en-us/library/bb669084%28v=vs.110%29.aspx

System.currentTimeMillis vs System.nanoTime

Update by Arkadiy: I've observed more correct behavior of System.currentTimeMillis() on Windows 7 in Oracle Java 8. The time was returned with 1 millisecond precision. The source code in OpenJDK has not changed, so I do not know what causes the better behavior.


David Holmes of Sun posted a blog article a couple years ago that has a very detailed look at the Java timing APIs (in particular System.currentTimeMillis() and System.nanoTime()), when you would want to use which, and how they work internally.

Inside the Hotspot VM: Clocks, Timers and Scheduling Events - Part I - Windows

One very interesting aspect of the timer used by Java on Windows for APIs that have a timed wait parameter is that the resolution of the timer can change depending on what other API calls may have been made - system wide (not just in the particular process). He shows an example where using Thread.sleep() will cause this resolution change.

Avoid synchronized(this) in Java?

I'll cover each point separately.

  1. Some evil code may steal your lock (very popular this one, also has an "accidentally" variant)

    I'm more worried about accidentally. What it amounts to is that this use of this is part of your class' exposed interface, and should be documented. Sometimes the ability of other code to use your lock is desired. This is true of things like Collections.synchronizedMap (see the javadoc).

  2. All synchronized methods within the same class use the exact same lock, which reduces throughput

    This is overly simplistic thinking; just getting rid of synchronized(this) won't solve the problem. Proper synchronization for throughput will take more thought.

  3. You are (unnecessarily) exposing too much information

    This is a variant of #1. Use of synchronized(this) is part of your interface. If you don't want/need this exposed, don't do it.

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

Tool to generate JSON schema from JSON data

For the offline tools that support multiple inputs, the best I've seen so far is https://github.com/wolverdude/GenSON/ I'd like to see a tool that takes filenames on standard input because I have thousands of files. However, I run out of open file descriptors, so make sure the files are closed. I'd also like to see JSON Schema generators that handle recursion. I am now working on generating Java classes from JSON objects in hopes of going to JSON Schema from my Java classes. Here is my GenSON script if you are curious or want to identify bugs in it.

#!/bin/sh
ulimit -n 4096
rm x3d*json
cat /dev/null > x3d.json
find ~/Downloads/www.web3d.org/x3d/content/examples -name '*json' -      print| xargs node goodJSON.js | xargs python bin/genson.py -i 2 -s     x3d.json >> x3d.json
split -p '^{' x3d.json x3d.json
python bin/genson.py -i 2 -s x3d.jsonaa -s x3d.jsonab /Users/johncarlson/Downloads/www.web3d.org/x3d/content/examples/X3dForWebAuthors/Chapter02-GeometryPrimitives/Box.json > x3dmerge.json 

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

Because python's math library is a thin wrapper around the C math library which returns floats.

how to set start value as "0" in chartjs?

Please add this option:

//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,

(Reference: Chart.js)

N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion

How to handle authentication popup with Selenium WebDriver using Java

I faced this issue a number of times in my application.

We can generally handle this with the below 2 approaches.

  1. Pass the username and password in url itself

  2. You can create an AutoIT Script and call script before opening the url.

Please check the below article in which I have mentioned both ways:
Handle Authentication/Login window in Selenium Webdriver

How to get PID of process I've just started within java program?

the jnr-process project provides this capability.

It is part of the java native runtime used by jruby and can be considered a prototype for a future java-FFI

Accessing all items in the JToken

You can cast your JToken to a JObject and then use the Properties() method to get a list of the object properties. From there, you can get the names rather easily.

Something like this:

string json =
@"{
    ""ADDRESS_MAP"":{

        ""ADDRESS_LOCATION"":{
            ""type"":""separator"",
            ""name"":""Address"",
            ""value"":"""",
            ""FieldID"":40
        },
        ""LOCATION"":{
            ""type"":""locations"",
            ""name"":""Location"",
            ""keyword"":{
                ""1"":""LOCATION1""
            },
            ""value"":{
                ""1"":""United States""
            },
            ""FieldID"":41
        },
        ""FLOOR_NUMBER"":{
            ""type"":""number"",
            ""name"":""Floor Number"",
            ""value"":""0"",
            ""FieldID"":55
        },
        ""self"":{
            ""id"":""2"",
            ""name"":""Address Map""
        }
    }
}";

JToken outer = JToken.Parse(json);
JObject inner = outer["ADDRESS_MAP"].Value<JObject>();

List<string> keys = inner.Properties().Select(p => p.Name).ToList();

foreach (string k in keys)
{
    Console.WriteLine(k);
}

Output:

ADDRESS_LOCATION
LOCATION
FLOOR_NUMBER
self

How to run ~/.bash_profile in mac terminal

No need to start, it would automatically executed while you startup your mac terminal / bash. Whenever you do a change, you may need to restart the terminal.

~ is the default path for .bash_profile

html5: display video inside canvas

Using canvas to display Videos

Displaying a video is much the same as displaying an image. The minor differences are to do with onload events and the fact that you need to render the video every frame or you will only see one frame not the animated frames.

The demo below has some minor differences to the example. A mute function (under the video click mute/sound on to toggle sound) and some error checking to catch IE9+ and Edge if they don't have the correct drivers.

Keeping answers current.

The previous answers by user372551 is out of date (December 2010) and has a flaw in the rendering technique used. It uses the setTimeout and a rate of 33.333..ms which setTimeout will round down to 33ms this will cause the frames to be dropped every two seconds and may drop many more if the video frame rate is any higher than 30. Using setTimeout will also introduce video shearing created because setTimeout can not be synced to the display hardware.

There is currently no reliable method that can determine a videos frame rate unless you know the video frame rate in advance you should display it at the maximum display refresh rate possible on browsers. 60fps

The given top answer was for the time (6 years ago) the best solution as requestAnimationFrame was not widely supported (if at all) but requestAnimationFrame is now standard across the Major browsers and should be used instead of setTimeout to reduce or remove dropped frames, and to prevent shearing.

The example demo.

Loads a video and set it to loop. The video will not play until the you click on it. Clicking again will pause. There is a mute/sound on button under the video. The video is muted by default.

Note users of IE9+ and Edge. You may not be able to play the video format WebM as it needs additional drivers to play the videos. They can be found at tools.google.com Download IE9+ WebM support

_x000D_
_x000D_
// This code is from the example document on stackoverflow documentation. See HTML for link to the example._x000D_
// This code is almost identical to the example. Mute has been added and a media source. Also added some error handling in case the media load fails and a link to fix IE9+ and Edge support._x000D_
// Code by Blindman67._x000D_
_x000D_
_x000D_
// Original source has returns 404_x000D_
// var mediaSource = "http://video.webmfiles.org/big-buck-bunny_trailer.webm";_x000D_
// New source from wiki commons. Attribution in the leading credits._x000D_
var mediaSource = "http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv"_x000D_
_x000D_
var muted = true;_x000D_
var canvas = document.getElementById("myCanvas"); // get the canvas from the page_x000D_
var ctx = canvas.getContext("2d");_x000D_
var videoContainer; // object to hold video and associated info_x000D_
var video = document.createElement("video"); // create a video element_x000D_
video.src = mediaSource;_x000D_
// the video will now begin to load._x000D_
// As some additional info is needed we will place the video in a_x000D_
// containing object for convenience_x000D_
video.autoPlay = false; // ensure that the video does not auto play_x000D_
video.loop = true; // set the video to loop._x000D_
video.muted = muted;_x000D_
videoContainer = {  // we will add properties as needed_x000D_
     video : video,_x000D_
     ready : false,   _x000D_
};_x000D_
// To handle errors. This is not part of the example at the moment. Just fixing for Edge that did not like the ogv format video_x000D_
video.onerror = function(e){_x000D_
    document.body.removeChild(canvas);_x000D_
    document.body.innerHTML += "<h2>There is a problem loading the video</h2><br>";_x000D_
    document.body.innerHTML += "Users of IE9+ , the browser does not support WebM videos used by this demo";_x000D_
    document.body.innerHTML += "<br><a href='https://tools.google.com/dlpage/webmmf/'> Download IE9+ WebM support</a> from tools.google.com<br> this includes Edge and Windows 10";_x000D_
    _x000D_
 }_x000D_
video.oncanplay = readyToPlayVideo; // set the event to the play function that _x000D_
                                  // can be found below_x000D_
function readyToPlayVideo(event){ // this is a referance to the video_x000D_
    // the video may not match the canvas size so find a scale to fit_x000D_
    videoContainer.scale = Math.min(_x000D_
                         canvas.width / this.videoWidth, _x000D_
                         canvas.height / this.videoHeight); _x000D_
    videoContainer.ready = true;_x000D_
    // the video can be played so hand it off to the display function_x000D_
    requestAnimationFrame(updateCanvas);_x000D_
    // add instruction_x000D_
    document.getElementById("playPause").textContent = "Click video to play/pause.";_x000D_
    document.querySelector(".mute").textContent = "Mute";_x000D_
}_x000D_
_x000D_
function updateCanvas(){_x000D_
    ctx.clearRect(0,0,canvas.width,canvas.height); _x000D_
    // only draw if loaded and ready_x000D_
    if(videoContainer !== undefined && videoContainer.ready){ _x000D_
        // find the top left of the video on the canvas_x000D_
        video.muted = muted;_x000D_
        var scale = videoContainer.scale;_x000D_
        var vidH = videoContainer.video.videoHeight;_x000D_
        var vidW = videoContainer.video.videoWidth;_x000D_
        var top = canvas.height / 2 - (vidH /2 ) * scale;_x000D_
        var left = canvas.width / 2 - (vidW /2 ) * scale;_x000D_
        // now just draw the video the correct size_x000D_
        ctx.drawImage(videoContainer.video, left, top, vidW * scale, vidH * scale);_x000D_
        if(videoContainer.video.paused){ // if not playing show the paused screen _x000D_
            drawPayIcon();_x000D_
        }_x000D_
    }_x000D_
    // all done for display _x000D_
    // request the next frame in 1/60th of a second_x000D_
    requestAnimationFrame(updateCanvas);_x000D_
}_x000D_
_x000D_
function drawPayIcon(){_x000D_
     ctx.fillStyle = "black";  // darken display_x000D_
     ctx.globalAlpha = 0.5;_x000D_
     ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
     ctx.fillStyle = "#DDD"; // colour of play icon_x000D_
     ctx.globalAlpha = 0.75; // partly transparent_x000D_
     ctx.beginPath(); // create the path for the icon_x000D_
     var size = (canvas.height / 2) * 0.5;  // the size of the icon_x000D_
     ctx.moveTo(canvas.width/2 + size/2, canvas.height / 2); // start at the pointy end_x000D_
     ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 + size);_x000D_
     ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 - size);_x000D_
     ctx.closePath();_x000D_
     ctx.fill();_x000D_
     ctx.globalAlpha = 1; // restore alpha_x000D_
}    _x000D_
_x000D_
function playPauseClick(){_x000D_
     if(videoContainer !== undefined && videoContainer.ready){_x000D_
          if(videoContainer.video.paused){                                 _x000D_
                videoContainer.video.play();_x000D_
          }else{_x000D_
                videoContainer.video.pause();_x000D_
          }_x000D_
     }_x000D_
}_x000D_
function videoMute(){_x000D_
    muted = !muted;_x000D_
 if(muted){_x000D_
         document.querySelector(".mute").textContent = "Mute";_x000D_
    }else{_x000D_
         document.querySelector(".mute").textContent= "Sound on";_x000D_
    }_x000D_
_x000D_
_x000D_
}_x000D_
// register the event_x000D_
canvas.addEventListener("click",playPauseClick);_x000D_
document.querySelector(".mute").addEventListener("click",videoMute)
_x000D_
body {_x000D_
    font :14px  arial;_x000D_
    text-align : center;_x000D_
    background : #36A;_x000D_
}_x000D_
h2 {_x000D_
    color : white;_x000D_
}_x000D_
canvas {_x000D_
    border : 10px white solid;_x000D_
    cursor : pointer;_x000D_
}_x000D_
a {_x000D_
  color : #F93;_x000D_
}_x000D_
.mute {_x000D_
    cursor : pointer;_x000D_
    display: initial;   _x000D_
}
_x000D_
<h2>Basic Video & canvas example</h2>_x000D_
<p>Code example from Stackoverflow Documentation HTML5-Canvas<br>_x000D_
<a href="https://stackoverflow.com/documentation/html5-canvas/3689/media-types-and-the-canvas/14974/basic-loading-and-playing-a-video-on-the-canvas#t=201607271638099201116">Basic loading and playing a video on the canvas</a></p>_x000D_
<canvas id="myCanvas" width = "532" height ="300" ></canvas><br>_x000D_
<h3><div id = "playPause">Loading content.</div></h3>_x000D_
<div class="mute"></div><br>_x000D_
<div style="font-size:small">Attribution in the leading credits.</div><br>
_x000D_
_x000D_
_x000D_

Canvas extras

Using the canvas to render video gives you additional options in regard to displaying and mixing in fx. The following image shows some of the FX you can get using the canvas. Using the 2D API gives a huge range of creative possibilities.

Image relating to answer Fade canvas video from greyscale to color Video filters "Lighten", "Black & white", "Sepia", "Saturate", and "Negative"

See video title in above demo for attribution of content in above inmage.

VBA test if cell is in a range

Determine if a cell is within a range using VBA in Microsoft Excel:

From the linked site (maintaining credit to original submitter):

VBA macro tip contributed by Erlandsen Data Consulting offering Microsoft Excel Application development, template customization, support and training solutions

Function InRange(Range1 As Range, Range2 As Range) As Boolean
    ' returns True if Range1 is within Range2
    InRange = Not (Application.Intersect(Range1, Range2) Is Nothing)
End Function


Sub TestInRange()
    If InRange(ActiveCell, Range("A1:D100")) Then
        ' code to handle that the active cell is within the right range
        MsgBox "Active Cell In Range!"
    Else
        ' code to handle that the active cell is not within the right range
        MsgBox "Active Cell NOT In Range!"
    End If
End Sub

What datatype to use when storing latitude and longitude data in SQL databases?

In vanilla Oracle, the feature called LOCATOR (a crippled version of Spatial) requires that the coordinate data be stored using the datatype of NUMBER (no precision). When you try to create Function Based Indexes to support spatial queries it'll gag otherwise.

How do I make a WinForms app go Full Screen

And for the menustrip-question, try set

MenuStrip1.Parent = Nothing

when in fullscreen mode, it should then disapear.

And when exiting fullscreenmode, reset the menustrip1.parent to the form again and the menustrip will be normal again.

How to get full file path from file name?

private const string BulkSetPriceFile = "test.txt";
...
var fullname = Path.GetFullPath(BulkSetPriceFile);

Spring MVC - How to return simple String as JSON in Rest Controller

Simply unregister the default StringHttpMessageConverter instance:

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
  /**
   * Unregister the default {@link StringHttpMessageConverter} as we want Strings
   * to be handled by the JSON converter.
   *
   * @param converters List of already configured converters
   * @see WebMvcConfigurationSupport#addDefaultHttpMessageConverters(List)
   */
  @Override
  protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.stream()
      .filter(c -> c instanceof StringHttpMessageConverter)
      .findFirst().ifPresent(converters::remove);
  }
}

Tested with both controller action handler methods and controller exception handlers:

@RequestMapping("/foo")
public String produceFoo() {
  return "foo";
}

@ExceptionHandler(FooApiException.class)
public String fooException(HttpServletRequest request, Throwable e) {
  return e.getMessage();
}

Final notes:

  • extendMessageConverters is available since Spring 4.1.3, if are running on a previous version you can implement the same technique using configureMessageConverters, it just takes a little bit more work.
  • This was one approach of many other possible approaches, if your application only ever returns JSON and no other content types, you are better off skipping the default converters and adding a single jackson converter. Another approach is to add the default converters but in different order so that the jackson converter is prior to the string one. This should allow controller action methods to dictate how they want String to be converted depending on the media type of the response.

Matplotlib: ValueError: x and y must have same first dimension

You should make x and y numpy arrays, not lists:

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
              0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
              0.478,0.335,0.365,0.424,0.390,0.585,0.511])

With this change, it produces the expect plot. If they are lists, m * x will not produce the result you expect, but an empty list. Note that m is anumpy.float64 scalar, not a standard Python float.

I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:

In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]

while multiplying a list with a float gives an error (as I think it should):

In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'

The weird thing is that multiplying a Python list with a Numpy scalar apparently works:

In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []

In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]

In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]

So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:

In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123,  2.123,  3.123])

ERROR 1044 (42000): Access denied for 'root' With All Privileges

First, Identify the user you are logged in as:

 select user();
 select current_user();

The result for the first command is what you attempted to login as, the second is what you actually connected as. Confirm that you are logged in as root@localhost in mysql.

Grant_priv to root@localhost. Here is how you can check.

mysql> SELECT host,user,password,Grant_priv,Super_priv FROM mysql.user;
+-----------+------------------+-------------------------------------------+------------+------------+
| host      | user             | password                                  | Grant_priv | Super_priv |
+-----------+------------------+-------------------------------------------+------------+------------+
| localhost | root             | ***************************************** | N          | Y          |
| localhost | debian-sys-maint | ***************************************** | Y          | Y          |
| localhost | staging          | ***************************************** | N          | N          |
+-----------+------------------+-------------------------------------------+------------+------------+

You can see that the Grant_priv is set to N for root@localhost. This needs to be Y. Below is how to fixed this:

UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
GRANT ALL ON *.* TO 'root'@'localhost';

I logged back in, it was fine.

plot different color for different categorical levels using matplotlib

Using Altair.

from altair import *
import pandas as pd

df = datasets.load_dataset('iris')
Chart(df).mark_point().encode(x='petalLength',y='sepalLength', color='species')

enter image description here

Limit String Length

From php 4.0.6 , there is a function for the exact same thing

function mb_strimwidth can be used for your requirement

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
//Hello W...
?>

It does have more options though,here is the documentation for this mb_strimwidth

How do I disable text selection with CSS or JavaScript?

<div 
 style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;" 
 unselectable="on"
 onselectstart="return false;" 
 onmousedown="return false;">
    Blabla
</div>

Portable way to get file size (in bytes) in shell?

Even though du usually prints disk usage and not actual data size, GNU coreutils du can print file's "apparent size" in bytes:

du -b FILE

But it won't work under BSD, Solaris, macOS, ...

How to access html form input from asp.net code behind

It should normally be done with Request.Form["elementName"].

For example, if you have <input type="text" name="email" /> then you can use Request.Form["email"] to access its value.

Append text to input field

There are two options. Ayman's approach is the most simple, but I would add one extra note to it. You should really cache jQuery selections, there is no reason to call $("#input-field-id") twice:

var input = $( "#input-field-id" );
input.val( input.val() + "more text" );

The other option, .val() can also take a function as an argument. This has the advantange of easily working on multiple inputs:

$( "input" ).val( function( index, val ) {
    return val + "more text";
});

CSS float right not working correctly

Here is one way of doing it.

If you HTML looks like this:

<div>Contact Details
    <button type="button" class="edit_button">My Button</button>
</div>

apply the following CSS:

div {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: gray;
    overflow: auto;
}
.edit_button {
    float: right;
    margin: 0 10px 10px 0; /* for demo only */
}

The trick is to apply overflow: auto to the div, which starts a new block formatting context. The result is that the floated button is enclosed within the block area defined by the div tag.

You can then add margins to the button if needed to adjust your styling.

In the original HTML and CSS, the floated button was out of the content flow so the border of the div would be positioned with respect to the in-flow text, which does not include any floated elements.

See demo at: http://jsfiddle.net/audetwebdesign/AGavv/

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

My problem was very similar (produces same problem). After refactoring variable name by "refactor -> rename" option in Android Studio (from "value" to "myValue") i found changes in manifest file, too. Meta-data "value" pool has changed to "myValue".

<meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:myValue="@string/facebook_app_id"/>

After revert file everything seams to be ok again.

<meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id"/>

I hope, it will help someone!

Create a batch file to run an .exe with an additional parameter

in batch file abc.bat

cd c:\user\ben_dchost\documents\
executible.exe -flag1 -flag2 -flag3 

I am assuming that your executible.exe is present in c:\user\ben_dchost\documents\ I am also assuming that the parameters it takes are -flag1 -flag2 -flag3

Edited:

For the command you say you want to execute, do:

cd C:\Users\Ben\Desktop\BGInfo\
bginfo.exe dc_bginfo.bgi
pause

Hope this helps

What are the differences between "git commit" and "git push"?

Well, basically git commit puts your changes into your local repo, while git push sends your changes to the remote location. Since git is a distributed version control system, the difference is that commit will commit changes to your local repository, whereas push will push changes up to a remote repo

source Google

http://gitref.org/basic/ this link will be very useful too

https://git-scm.com/docs/git-commit

Changing the text on a label

Use the config method to change the value of the label:

top = Tk()

l = Label(top)
l.pack()

l.config(text = "Hello World", width = "50")

How to stick a footer to bottom in css?

The following css property will do it

position: fixed;

I hope this help.

Angular get object from array by Id

CASE - 1

Using array.filter() We can get an array of objects which will match with our condition.
see the working example.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function filter(){
  console.clear();
  var filter_id = document.getElementById("filter").value;
  var filter_array = questions.filter(x => x.id == filter_id);
  console.log(filter_array);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
}
_x000D_
<div>
  <label for="filter"></label>
  <input id="filter" type="number" name="filter" placeholder="Enter id which you want to filter">
  <button onclick="filter()">Filter</button>
</div>
_x000D_
_x000D_
_x000D_

CASE - 2

Using array.find() we can get first matched item and break the iteration.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function find(){
  console.clear();
  var find_id = document.getElementById("find").value;
  var find_object = questions.find(x => x.id == find_id);
  console.log(find_object);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
  width: 200px;
}
_x000D_
<div>
  <label for="find"></label>
  <input id="find" type="number" name="find" placeholder="Enter id which you want to find">
  <button onclick="find()">Find</button>
</div>
_x000D_
_x000D_
_x000D_

Angular 2: How to call a function after get a response from subscribe http.post

Update your get_categories() method to return the total (wrapped in an observable):

// Note that .subscribe() is gone and I've added a return.
get_categories(number) {
  return this.http.post( url, body, {headers: headers, withCredentials:true})
    .map(response => response.json());
}

In search_categories(), you can subscribe the observable returned by get_categories() (or you could keep transforming it by chaining more RxJS operators):

// send_categories() is now called after get_categories().
search_categories() {
  this.get_categories(1)
    // The .subscribe() method accepts 3 callbacks
    .subscribe(
      // The 1st callback handles the data emitted by the observable.
      // In your case, it's the JSON data extracted from the response.
      // That's where you'll find your total property.
      (jsonData) => {
        this.send_categories(jsonData.total);
      },
      // The 2nd callback handles errors.
      (err) => console.error(err),
      // The 3rd callback handles the "complete" event.
      () => console.log("observable complete")
    );
}

Note that you only subscribe ONCE, at the end.

Like I said in the comments, the .subscribe() method of any observable accepts 3 callbacks like this:

obs.subscribe(
  nextCallback,
  errorCallback,
  completeCallback
);

They must be passed in this order. You don't have to pass all three. Many times only the nextCallback is implemented:

obs.subscribe(nextCallback);

Class has no member named

I had similar problem. My header file which included the definition of the class wasn't working. I wasn't able to use the member functions of that class. So i simply copied my class to another header file. Now its working all ok.

invalid_client in google oauth2

Set/change your product name, I had this issue until I created a product name as same as project name.

The product name can be set in the Consent screen section of the Google Developers Console for your project. Look under APIs & auth in the left navigation and select Consent screen. You need also to set your email address in the box above the product name.

How to reduce the space between <p> tags?

Replace <p> </p> with &nbsp;
Add as many &nbsp; as needed.

I solved the same problem by this. Just sharing it.

Explanation of "ClassCastException" in Java

Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:

Cast the String "1" to an int -> no problem

Cast the String "abc" to an int -> raises a ClassCastException

Or think of a class diagram with Animal.class, Dog.class and Cat.class

Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because its a dog.
Cat c = (Dog) a; // Raises class cast exception; you can't cast a dog to a cat.

Qt: How do I handle the event of the user pressing the 'X' (close) button?

If you have a QMainWindow you can override closeEvent method.

#include <QCloseEvent>
void MainWindow::closeEvent (QCloseEvent *event)
{
    QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME,
                                                                tr("Are you sure?\n"),
                                                                QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                                                QMessageBox::Yes);
    if (resBtn != QMessageBox::Yes) {
        event->ignore();
    } else {
        event->accept();
    }
}


If you're subclassing a QDialog, the closeEvent will not be called and so you have to override reject():

void MyDialog::reject()
{
    QMessageBox::StandardButton resBtn = QMessageBox::Yes;
    if (changes) {
        resBtn = QMessageBox::question( this, APP_NAME,
                                        tr("Are you sure?\n"),
                                        QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                        QMessageBox::Yes);
    }
    if (resBtn == QMessageBox::Yes) {
        QDialog::reject();
    }
}

PHP class: Global variable as property in class

If you want to access a property from inside a class you should:

private $classNumber = 8;

ListBox with ItemTemplate (and ScrollBar!)

ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...

If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...

HTH

Android Eclipse - Could not find *.apk

Mine was caused by this problem (incompatibility between ADT and SDK), and was fixed thus:

  • Eclipse > Help
  • Install New Software
  • Add 'https://dl-ssl.google.com/android/eclipse/' to 'Work With' section and press enter
  • After developer tools appears on the list, check it and click Next
  • Restart eclipse once download is finished

Why can't I reference System.ComponentModel.DataAnnotations?

If using .NET Core or .NET Standard

use:

Manage NuGet Packages..

Use Manage NuGet Packages

instead of:

Add Reference...

Don't use Add Reference

SQL keys, MUL vs PRI vs UNI

Let's understand in simple words

  • PRI - It's a primary key, and used to identify records uniquely.
  • UNI - It's a unique key, and also used to identify records uniquely. It looks similar like primary key but a table can have multiple unique keys and unique key can have one null value, on the other hand table can have only one primary key and can't store null as a primary key.
  • MUL - It's doesn't have unique constraint and table can have multiple MUL columns.

Note: These keys have more depth as a concept but this is good to start.

Is there a way to make text unselectable on an HTML page?

If it looks bad you can use CSS to change the appearance of selected sections.

Failed to load resource under Chrome

It is due to ad-blocker.When project files names contains words like 'ad' then ad-blockers also block theses files to load.

Best solution is that never save any files with these name keys.

Loop through columns and add string lengths as new columns

For the sake of completeness, there is also a data.table solution:

library(data.table)
result <- setDT(df)[, paste0(names(df), "_length") := lapply(.SD, stringr::str_length)]
result
#      col1     col2 col1_length col2_length
#1:     abc adf qqwe           3           8
#2:    abcd        d           4           1
#3:       a        e           1           1
#4: abcdefg        f           7           1

Python class returning value

Use __new__ to return value from a class.

As others suggest __repr__,__str__ or even __init__ (somehow) CAN give you what you want, But __new__ will be a semantically better solution for your purpose since you want the actual object to be returned and not just the string representation of it.

Read this answer for more insights into __str__ and __repr__ https://stackoverflow.com/a/19331543/4985585

class MyClass():
    def __new__(cls):
        return list() #or anything you want

>>> MyClass()
[]   #Returns a true list not a repr or string

Android Calling JavaScript functions in WebView

activity_main.xml

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

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

MainActivity.java


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.bluapp.androidview.R;

public class WebViewActivity3 extends AppCompatActivity {
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view3);
        webView = (WebView) findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("file:///android_asset/webview1.html");


        webView.setWebViewClient(new WebViewClient(){
            public void onPageFinished(WebView view, String weburl){
                webView.loadUrl("javascript:testEcho('Javascript function in webview')");
            }
        });
    }
}

assets file

<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>WebView1</title>
<meta forua="true" http-equiv="Cache-Control" content="max-age=0"/>
</head>

<body style="background-color:#212121">
<script type="text/javascript">
function testEcho(p1){
document.write(p1);
}
</script>
</body>

</html>

Asynchronous Requests with Python requests

Note

The below answer is not applicable to requests v0.13.0+. The asynchronous functionality was moved to grequests after this question was written. However, you could just replace requests with grequests below and it should work.

I've left this answer as is to reflect the original question which was about using requests < v0.13.0.


To do multiple tasks with async.map asynchronously you have to:

  1. Define a function for what you want to do with each object (your task)
  2. Add that function as an event hook in your request
  3. Call async.map on a list of all the requests / actions

Example:

from requests import async
# If using requests > v0.13.0, use
# from grequests import async

urls = [
    'http://python-requests.org',
    'http://httpbin.org',
    'http://python-guide.org',
    'http://kennethreitz.com'
]

# A simple task to do to each response object
def do_something(response):
    print response.url

# A list to hold our things to do via async
async_list = []

for u in urls:
    # The "hooks = {..." part is where you define what you want to do
    # 
    # Note the lack of parentheses following do_something, this is
    # because the response will be used as the first argument automatically
    action_item = async.get(u, hooks = {'response' : do_something})

    # Add the task to our list of things to do via async
    async_list.append(action_item)

# Do our list of things to do via async
async.map(async_list)

How to upgrade docker-compose to latest version

Based on @eric-johnson's answer, I'm currently using this in a script:

#!/bin/bash
compose_version=$(curl https://api.github.com/repos/docker/compose/releases/latest | jq .name -r)
output='/usr/local/bin/docker-compose'
curl -L https://github.com/docker/compose/releases/download/$compose_version/docker-compose-$(uname -s)-$(uname -m) -o $output
chmod +x $output
echo $(docker-compose --version)

it grabs the latest version from the GitHub api.

How is the default submit button on an HTML form determined?

I think this post would help if someone wants to do it with jQuery:

http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/

The basic solution is:

$(function() {
    $("form input").keypress(function (e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        $('input[type=submit].default').click();
        return false;
    } else {
        return true;
    }
    });
});

and another I liked was:

jQuery(document).ready(function() {
$("form input, form select").live('keypress', function (e) {
if ($(this).parents('form').find('button[type=submit].default, input[type=submit].default').length <= 0)
return true;

if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$(this).parents('form').find('button[type=submit].default, input[type=submit].default').click();
return false;
} else {
return true;
}
});
}); 

Installing a local module using npm?

npm pack + package.json

This is what worked for me:

STEP 1: In module project, execute npm pack:

This will build a <package-name>-<version>.tar.gz file.

STEP 2: Move the file to the consumer project

Ideally you can put all such files in a tmp folder in your consumer-project root:

STEP 3: Refer it in your package.json:

"dependencies": {
  "my-package": "file:/./tmp/my-package-1.3.3.tar.gz"
}

STEP 4: Install the packages:

npm install or npm i or yarn

Now, your package would be available in your consumer-project's node_modules folder.

Good Luck...

Pipenv: Command Not Found

That happens because you are not installing it globally (system wide). For it to be available in your path you need to install it using sudo, like this:

$ sudo pip install pipenv

Action bar navigation modes are deprecated in Android L

The new Toolbar cannot be used for inflating multiple line objects, so it is impossible to add Tabs to it.
If you want to use a Toolbar like a TabWidget you can insert some Tab Objects to it, but only with the old Holo style.

Here there is a custom Library that uses v7 Toolbar like TabWidget with the new Material Design animations, but it uses the same methods from the old ActionBar Tabs, so you can attach your ViewPager to it.

Comparing date part only without comparing time in JavaScript

This is the way I do it:

var myDate  = new Date($('input[name=frequency_start]').val()).setHours(0,0,0,0);
var today   = new Date().setHours(0,0,0,0);
if(today>myDate){
    jAlert('Please Enter a date in the future','Date Start Error', function(){
        $('input[name=frequency_start]').focus().select();
    });
}

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

Check if an array is empty or exists

This is what I use. The first condition covers truthy, which has both null and undefined. Second condition checks for an empty array.

if(arrayName && arrayName.length > 0){
    //do something.
}

or thanks to tsemer's comment I added a second version

if(arrayName && arrayName.length)

Then I made a test for the second condition, using Scratchpad in Firefox:

_x000D_
_x000D_
var array1;_x000D_
var array2 = [];_x000D_
var array3 = ["one", "two", "three"];_x000D_
var array4 = null;_x000D_
_x000D_
console.log(array1);_x000D_
console.log(array2);_x000D_
console.log(array3);_x000D_
console.log(array4);_x000D_
_x000D_
if (array1 && array1.length) {_x000D_
  console.log("array1! has a value!");_x000D_
}_x000D_
_x000D_
if (array2 && array2.length) {_x000D_
  console.log("array2! has a value!");_x000D_
}_x000D_
_x000D_
if (array3 && array3.length) {_x000D_
  console.log("array3! has a value!");_x000D_
}_x000D_
_x000D_
if (array4 && array4.length) {_x000D_
  console.log("array4! has a value!");_x000D_
}
_x000D_
_x000D_
_x000D_

which also proves that if(array2 && array2.length) and if(array2 && array2.length > 0) are exactly doing the same

How to use Apple's new San Francisco font on a webpage

Last tested in 2015

Should use this solution as a last choice, when other solutions don't work.


Original answer:

Work on macOS Chrome/Safari

body { font-family: '.SFNSDisplay-Regular', sans-serif; }

Git merge reports "Already up-to-date" though there is a difference

Faced this scenario using Git Bash.

Our repository has multiple branches and each branch has a different commit cycle and merge happens once in a while. Old_Branch was used as a parent for New_Branch

Old_Branch was updated with some changes which required to be merged with New_Branch

Was using below pull command without any branch to get all sources from all branches.

git pull origin

Strangely this doesn't pull all the commits from all the branches. Had thought it so as the indicated shows almost all branches and tags.

So to fix this had checked out the Old_Branch pulled the latest using

git checkout Old_Branch

git pull origin Old_Branch

Now checked out New_Branch

git checkout New_Branch

Pulled it to be sure

git pull origin New_Branch

git merge Old_Branch

And viola got conflicts to fix from Old_Branch to New_Branch :) which was expected

MySQL: Insert record if not exists in table

Brian Hooper : You almost hit the point but you have an error in your synatx. Your insert will never work. I tested on my database and here is the right answer:

INSERT INTO podatki (datum,ura,meritev1,meritev1_sunki,impulzi1,meritev2,meritev2_sunki,impulzi2)
            SELECT '$datum', '$ura', '$meritve1','$sunki1','$impulzi1','$meritve2','$sunki2','$impulzi2'
                FROM dual
                WHERE NOT EXISTS (SELECT datum,ura
                                      FROM podatki
                                      WHERE datum='$datum' and ura='$ura'

I'm giving you my example of y table. Insert is almost the same like Bian Hooper wrote, except that I put the select FROM DUAL ont from other table. Cind regards, Ivan

New Array from Index Range Swift

This works for me:

var test = [1, 2, 3]
var n = 2
var test2 = test[0..<n]

Your issue could be with how you're declaring your array to begin with.

EDIT:

To fix your function, you have to cast your Slice to an array:

func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
    var newNumbers = Array(numbers[0..<position])
    return newNumbers
}

// test
aFunction([1, 2, 3], 2) // returns [1, 2]

SDK Location not found Android Studio + Gradle

If none of the answers work for you which happened to me on macbook pro in one of the projects you can always try to run Android Studio with an alias command passing sdk.dir with each run:

alias studio='launchctl setenv ANDROID_HOME '\''/Users/username/Library/Android/sdk'\'' && open -a '\''Android Studio'\'''

How to add \newpage in Rmarkdown in a smart way?

Simply \newpage or \pagebreak will work, e.g.

hello world
\newpage
```{r, echo=FALSE}
1+1
```
\pagebreak
```{r, echo=FALSE}
plot(1:10)
```

This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.

C: convert double to float, preserving decimal point precision

float and double don't store decimal places. They store binary places: float is (assuming IEEE 754) 24 significant bits (7.22 decimal digits) and double is 53 significant bits (15.95 significant digits).

Converting from double to float will give you the closest possible float, so rounding won't help you. Goining the other way may give you "noise" digits in the decimal representation.

#include <stdio.h>

int main(void) {
    double orig = 12345.67;
    float f = (float) orig;
    printf("%.17g\n", f); // prints 12345.669921875
    return 0;
}

To get a double approximation to the nice decimal value you intended, you can write something like:

double round_to_decimal(float f) {
    char buf[42];
    sprintf(buf, "%.7g", f); // round to 7 decimal digits
    return atof(buf);
}

Is it possible to listen to a "style change" event?

Things have moved on a bit since the question was asked - it is now possible to use a MutationObserver to detect changes in the 'style' attribute of an element, no jQuery required:

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
        console.log('style changed!');
    });    
});

var target = document.getElementById('myId');
observer.observe(target, { attributes : true, attributeFilter : ['style'] });

The argument that gets passed to the callback function is a MutationRecord object that lets you get hold of the old and new style values.

Support is good in modern browsers including IE 11+.

Can scripts be inserted with innerHTML?

Use $(parent).html(code) instead of parent.innerHTML = code.

The following also fixes scripts that use document.write and scripts loaded via src attribute. Unfortunately even this doesn't work with Google AdSense scripts.

var oldDocumentWrite = document.write;
var oldDocumentWriteln = document.writeln;
try {
    document.write = function(code) {
        $(parent).append(code);
    }
    document.writeln = function(code) {
        document.write(code + "<br/>");
    }
    $(parent).html(html); 
} finally {
    $(window).load(function() {
        document.write = oldDocumentWrite
        document.writeln = oldDocumentWriteln
    })
}

Source

How to change the URI (URL) for a remote Git repository?

To change the remote upstream: git remote set-url origin <url>


To add more upstreams: git remote add newplace <url>

So you can choose where to work git push origin <branch> or git push newplace <branch>

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Find the folder containing the shared library libopencv_core.so.2.4 using the following command line.

sudo find / -name "libopencv_core.so.2.4*"

Then I got the result:

 /usr/local/lib/libopencv_core.so.2.4.

Create a file called /etc/ld.so.conf.d/opencv.conf and write to it the path to the folder where the binary is stored.For example, I wrote /usr/local/lib/ to my opencv.conf file. Run the command line as follows.

sudo ldconfig -v

Try to run the command again.

Correct path for img on React.js

In create-react-app relative paths for images don't seem to work. Instead, you can import an image:

import logo from './logo.png' // relative path to image 

class Nav extends Component { 
    render() { 
        return ( 
            <img src={logo} alt={"logo"}/> 
        )  
    }
}

how to parse json using groovy

That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:

JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }

If you know it's a single-element Map then you can directly access the link:

def data = userJson.values().iterator().next()
String link = data.link

And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:

String id = '212315952136472'
...
String link = userJson[id].link

Regex remove all special characters except numbers?

Use the global flag:

var name = name.replace(/[^a-zA-Z ]/g, "");
                                    ^

If you don't want to remove numbers, add it to the class:

var name = name.replace(/[^a-zA-Z0-9 ]/g, "");

How to var_dump variables in twig templates?

you can use dump function and print it like this

{{ dump(MyVar) }}

but there is one nice thing too, if you don't set any argument to dump function, it will print all variables are available, like

{{ dump() }}

In Angular, What is 'pathmatch: full' and what effect does it have?

The path-matching strategy, one of 'prefix' or 'full'. Default is 'prefix'.

By default, the router checks URL elements from the left to see if the URL matches a given path, and stops when there is a match. For example, '/team/11/user' matches 'team/:id'.

The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.

Source : https://angular.io/api/router/Route#properties

TypeError: tuple indices must be integers, not str

TL;DR: add the parameter cursorclass=MySQLdb.cursors.DictCursor at the end of your MySQLdb.connect.


I had a working code and the DB moved, I had to change the host/user/pass. After this change, my code stopped working and I started getting this error. Upon closer inspection, I copy-pasted the connection string on a place that had an extra directive. The old code read like:

 conn = MySQLdb.connect(host="oldhost",
                        user="olduser",
                        passwd="oldpass",
                        db="olddb", 
                        cursorclass=MySQLdb.cursors.DictCursor)

Which was replaced by:

 conn = MySQLdb.connect(host="newhost",
                        user="newuser",
                        passwd="newpass",
                        db="newdb")

The parameter cursorclass=MySQLdb.cursors.DictCursor at the end was making python allow me to access the rows using the column names as index. But the poor copy-paste eliminated that, yielding the error.

So, as an alternative to the solutions already presented, you can also add this parameter and access the rows in the way you originally wanted. ^_^ I hope this helps others.

How to use table variable in a dynamic sql statement?

On SQL Server 2008+ it is possible to use Table Valued Parameters to pass in a table variable to a dynamic SQL statement as long as you don't need to update the values in the table itself.

So from the code you posted you could use this approach for @TSku but not for @RelPro

Example syntax below.

CREATE TYPE MyTable AS TABLE 
( 
Foo int,
Bar int
);
GO


DECLARE @T AS MyTable;

INSERT INTO @T VALUES (1,2), (2,3)

SELECT *,
        sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
FROM @T

EXEC sp_executesql
  N'SELECT *,
        sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
    FROM @T',
  N'@T MyTable READONLY',
  @T=@T 

The physloc column is included just to demonstrate that the table variable referenced in the child scope is definitely the same one as the outer scope rather than a copy.

How to update primary key

If you are sure that this change is suitable for the environment you're working in: set the FK conditions on the secondary tables to UPDATE CASCADING.

For example, if using SSMS as GUI:

  1. right click on the key
  2. select Modify
  3. Fold out 'INSERT And UPDATE Specific'
  4. For 'Update Rule', select Cascade.
  5. Close the dialog and save the key.

When you then update a value in the PK column in your primary table, the FK references in the other tables will be updated to point at the new value, preserving data integrity.

How can I lock a file using java (if possible)

FileChannel.lock is probably what you want.

try (
    FileInputStream in = new FileInputStream(file);
    java.nio.channels.FileLock lock = in.getChannel().lock();
    Reader reader = new InputStreamReader(in, charset)
) {
    ...
}

(Disclaimer: Code not compiled and certainly not tested.)

Note the section entitled "platform dependencies" in the API doc for FileLock.

How to execute a MySQL command from a shell script?

You forgot -p or --password= (the latter is better readable):

mysql -h "$server_name" "--user=$user" "--password=$password" "--database=$database_name" < "filename.sql"

(The quotes are unnecessary if you are sure that your credentials/names do not contain space or shell-special characters.)

Note that the manpage, too, says that providing the credentials on the command line is insecure. So follow Bill's advice about my.cnf.

Does Python have an ordered set?

For many purposes simply calling sorted will suffice. For example

>>> s = set([0, 1, 2, 99, 4, 40, 3, 20, 24, 100, 60])
>>> sorted(s)
[0, 1, 2, 3, 4, 20, 24, 40, 60, 99, 100]

If you are going to use this repeatedly, there will be overhead incurred by calling the sorted function so you might want to save the resulting list, as long as you're done changing the set. If you need to maintain unique elements and sorted, I agree with the suggestion of using OrderedDict from collections with an arbitrary value such as None.

How can you program if you're blind?

This blog post has some information about how the Visual Studio team is making their product accessible:

Visual Studio Core Team's Accessibility Lab Tour Activity

Many programmers use Emacspeak:

Emacspeak --The Complete Audio Desktop

Streaming video from Android camera to server

This is hardly a full answer, but webRTC may be what you're looking for. Here's some quick examples of webRTC in action: http://www.webrtc.org/reference-apps

If you want Android specific code, it exists! http://www.webrtc.org/native-code/android

Showing an image from console in Python

Why not just display it in the user's web browser?

Search text in stored procedure in SQL Server

Please take this as a "dirty" alternative but this saved my behind many times especially when I was not familiar with the DB project. Sometimes you are trying to search for a string within all SPs and forget that some of the related logic may have been hiding between Functions and Triggers or it can be simply worded differently than you thought.

From your MSSMS you may right click your DB and select Tasks -> Generate Scripts wizard to output all the SPs, Fns and Triggers into a single .sql file.

enter image description here

Make sure to select Triggers too!

enter image description here

Then just use Sublime or Notepad to search for the string you need to find. I know this may be quite inefficient and paranoid approach but it works :)

Meaning of Open hashing and Closed hashing

You have an array that is the "hash table".

In Open Hashing each cell in the array points to a list containg the collisions. The hashing has produced the same index for all items in the linked list.

In Closed Hashing you use only one array for everything. You store the collisions in the same array. The trick is to use some smart way to jump from collision to collision unitl you find what you want. And do this in a reproducible / deterministic way.

Static Vs. Dynamic Binding in Java

The compiler only knows that the type of "a" is Animal; this happens at compile time, because of which it is called static binding (Method overloading). But if it is dynamic binding then it would call the Dog class method. Here is an example of dynamic binding.

public class DynamicBindingTest {

    public static void main(String args[]) {
        Animal a= new Dog(); //here Type is Animal but object will be Dog
        a.eat();       //Dog's eat called because eat() is overridden method
    }
}

class Animal {

    public void eat() {
        System.out.println("Inside eat method of Animal");
    }
}

class Dog extends Animal {

    @Override
    public void eat() {
        System.out.println("Inside eat method of Dog");
    }
}

Output: Inside eat method of Dog

Pyspark: Exception: Java gateway process exited before sending the driver its port number

In my case it was because I wrote SPARK_DRIVER_MEMORY=10 instead of SPARK_DRIVER_MEMORY=10g in spark-env.sh

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

Pessimistic locking is generally not recommended and it's very costly in terms of performance on database side. The problem that you have mentioned (the code part) a few things are not clear such as:

  • If your code is being accessed by multiple threads at the same time.
  • How are you creating session object (not sure if you are using Spring)?

Hibernate Session objects are NOT thread-safe. So if there are multiple threads accessing the same session and trying to update the same database entity, your code can potentially end up in an error situation like this.

So what happens here is that more than one thread tries to update the same entity, one thread succeeds and when the next thread goes to commit the data, it sees that its already been modified and ends up throwing StaleObjectStateException.

EDIT:

There is a way to use Pessimistic Locking in Hibernate. Check out this link. But there seems to be some issue with this mechanism. I came across posting a bug in hibernate (HHH-5275), however. The scenario mentioned in the bug is as follows:

Two threads are reading the same database record; one of those threads should use pessimistic locking thereby blocking the other thread. But both threads can read the database record causing the test to fail.

This is very close to what you are facing. Please try this if this does not work, the only way I can think of is using Native SQL queries where you can achieve pessimistic locking in postgres database with SELECT FOR UPDATE query.

How to use a PHP class from another file?

use

require_once(__DIR__.'/_path/_of/_filename.php');

This will also help in importing files in from different folders. Try extends method to inherit the classes in that file and reuse the functions

Bootstrap 3: Text overlay on image

try the following example. Image overlay with text on image. demo

<div class="thumbnail">
  <img src="https://s3.amazonaws.com/discount_now_staging/uploads/ed964a11-e089-4c61-b927-9623a3fe9dcb/direct_uploader_2F50cc1daf-465f-48f0-8417-b04ac68a999d_2FN_19_jewelry.jpg" alt="..."   />
  <div class="caption post-content">  
  </div> 
  <div class="details">
    <h3>Robots!</h3>
    <p>Lorem ipsum dolor sit amet</p>   
  </div>  
</div>

css

.post-content {
    background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
    opacity: 0.5;
    top:0;
    left:0;
    min-width: 500px;
    min-height: 500px; 
    position: absolute;
    color: #ffffff; 
}

.thumbnail{
    position:relative;

}
.details {
    position: absolute; 
    z-index: 2; 
    top: 0;
    color: #ffffff; 
}

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

Seen on the Udacity deep learning foundation course:

df = pd.read_csv('my.csv')
...
regr = LinearRegression()
regr.fit(df[['column x']], df[['column y']])

MySQL: View with Subquery in the FROM Clause Limitation

It appears to be a known issue.

http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html

http://bugs.mysql.com/bug.php?id=16757

Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example

SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)

can be re-written as

SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID

or

SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)

can be

SELECT FOO.* FROM FOO 
LEFT OUTER JOIN FOO2 
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL

Convert a float64 to an int in Go

Simply casting to an int truncates the float, which if your system internally represent 2.0 as 1.9999999999, you will not get what you expect. The various printf conversions deal with this and properly round the number when converting. So to get a more accurate value, the conversion is even more complicated than you might first expect:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    floats := []float64{1.9999, 2.0001, 2.0}
    for _, f := range floats {
        t := int(f)
        s := fmt.Sprintf("%.0f", f)
        if i, err := strconv.Atoi(s); err == nil {
            fmt.Println(f, t, i)
        } else {
            fmt.Println(f, t, err)
        }
    }
}

Code on Go Playground

converting list to json format - quick and easy way

I've done something like before using the JavaScript serialization class:

using System.Web.Script.Serialization;

And:

JavaScriptSerializer jss = new JavaScriptSerializer();

string output = jss.Serialize(ListOfMyObject);
Response.Write(output);
Response.Flush();
Response.End();

How do I run a Python script from C#?

Set WorkingDirectory or specify the full path of the python script in the Argument

ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:\\Python27\\python.exe";
//start.WorkingDirectory = @"D:\script";
start.Arguments = string.Format("D:\\script\\test.py -a {0} -b {1} ", "some param", "some other param");
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
    using (StreamReader reader = process.StandardOutput)
    {
        string result = reader.ReadToEnd();
        Console.Write(result);
    }
}

ESLint not working in VS Code?

For me, i did accidentally disable ESLint when some prompt was shown by it.

Doing below steps fixed it for me

  1. Shift + Command + P and select ESLint: Disabled ESLint
  2. Close vscode
  3. Shift + Command + P and select ESLint: Show Output Channel

Microsoft Azure: How to create sub directory in a blob container

Wanted to add the UI portal Way to do as well. In case you want to create the folder structure, you would have to do it with the complete path for each file.

enter image description here

You need to Click on Upload Blob, Expand the Advanced and put it the path saying "Upload to Folder"

So Lets say you have a folder assets you want to upload and the content of the folder look like below

enter image description here

And if you have a folder under js folder with name main.js, you need to type in the path "assets/js" in upload to folder. Now This has to be done for each file. In case you have a lot of file, its recommended you do it programmatically.

error TS2339: Property 'x' does not exist on type 'Y'

Starting with TypeScript 2.2 using dot notation to access indexed properties is allowed. You won't get error TS2339 on your example.

See Dotted property for types with string index signatures in TypeScript 2.2 release note.

How to check currently internet connection is available or not in android

Use the method checkConnectivity:

  if (checkConnectivity()){
    //do something 

    }

Method to check your connectivity:

private boolean checkConnectivity() {
        boolean enabled = true;

        ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();

        if ((info == null || !info.isConnected() || !info.isAvailable())) {
                            Toast.makeText(getApplicationContext(), "Sin conexión a Internet...", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }

        return false;
    }

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

The problem is that you are trying to set the value of SecondTextField after checking every single character in the original string. You should do the conversion "on the side", one character at a time, and only then set the result into the SecondTextField.

As you go through the original string, start composing the output from an empty string. Keep appending the character in the opposite case until you run out of characters. Once the output is ready, set it into SecondTextField.

You can make an output a String, set it to an empty string "", and append characters to it as you go. This will work, but that is an inefficient approach. A better approach would be using a StringBuilder class, which lets you change the string without throwing away the whole thing.

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

Notice the repetition of Book in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)- it screams for a class type.

class Book {
  int number;
  String title;
  String language;
  int price;
}

Now you can simply have:

Book[] books = new Books[3];

If you want arrays, you can declare it as object array an insert Integer and String into it:

Object books[3][4]

Check if AJAX response data is empty/blank/null/undefined/0

The following correct answer was provided in the comment section of the question by Felix Kling:

if (!$.trim(data)){   
    alert("What follows is blank: " + data);
}
else{   
    alert("What follows is not blank: " + data);
}

Node.js: How to read a stream into a buffer?

Overall I don't see anything that would break in your code.

Two suggestions:

The way you are combining Buffer objects is a suboptimal because it has to copy all the pre-existing data on every 'data' event. It would be better to put the chunks in an array and concat them all at the end.

var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
  var buf = Buffer.concat(bufs);
}

For performance, I would look into if the S3 library you are using supports streams. Ideally you wouldn't need to create one large buffer at all, and instead just pass the stdout stream directly to the S3 library.

As for the second part of your question, that isn't possible. When a function is called, it is allocated its own private context, and everything defined inside of that will only be accessible from other items defined inside that function.

Update

Dumping the file to the filesystem would probably mean less memory usage per request, but file IO can be pretty slow so it might not be worth it. I'd say that you shouldn't optimize too much until you can profile and stress-test this function. If the garbage collector is doing its job you may be overoptimizing.

With all that said, there are better ways anyway, so don't use files. Since all you want is the length, you can calculate that without needing to append all of the buffers together, so then you don't need to allocate a new Buffer at all.

var pause_stream = require('pause-stream');

// Your other code.

var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
  var contentLength = bufs.reduce(function(sum, buf){
    return sum + buf.length;
  }, 0);

  // Create a stream that will emit your chunks when resumed.
  var stream = pause_stream();
  stream.pause();
  while (bufs.length) stream.write(bufs.shift());
  stream.end();

  var headers = {
      'Content-Length': contentLength,
      // ...
  };

  s3.putStream(stream, ....);

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Where is this year() function from?

You could also use the reshape2 package for this task:

require(reshape2)
df_melt <- melt(df1, id = c("date", "year", "month"))
dcast(df_melt, year + month ~ variable, sum)
#  year month         x1           x2
1  2000     1  -80.83405 -224.9540159
2  2000     2 -223.76331 -288.2418017
3  2000     3 -188.83930 -481.5601913
4  2000     4 -197.47797 -473.7137420
5  2000     5 -259.07928 -372.4563522

How can I show figures separately in matplotlib?

With Matplotlib prior to version 1.0.1, show() should only be called once per program, even if it seems to work within certain environments (some backends, on some platforms, etc.).

The relevant drawing function is actually draw():

import matplotlib.pyplot as plt

plt.plot(range(10))  # Creates the plot.  No need to save the current figure.
plt.draw()  # Draws, but does not block
raw_input()  # This shows the first figure "separately" (by waiting for "enter").

plt.figure()  # New window, if needed.  No need to save it, as pyplot uses the concept of current figure
plt.plot(range(10, 20))
plt.draw()
# raw_input()  # If you need to wait here too...

# (...)

# Only at the end of your program:
plt.show()  # blocks

It is important to recognize that show() is an infinite loop, designed to handle events in the various figures (resize, etc.). Note that in principle, the calls to draw() are optional if you call matplotlib.ion() at the beginning of your script (I have seen this fail on some platforms and backends, though).

I don't think that Matplotlib offers a mechanism for creating a figure and optionally displaying it; this means that all figures created with figure() will be displayed. If you only need to sequentially display separate figures (either in the same window or not), you can do like in the above code.

Now, the above solution might be sufficient in simple cases, and for some Matplotlib backends. Some backends are nice enough to let you interact with the first figure even though you have not called show(). But, as far as I understand, they do not have to be nice. The most robust approach would be to launch each figure drawing in a separate thread, with a final show() in each thread. I believe that this is essentially what IPython does.

The above code should be sufficient most of the time.

PS: now, with Matplotlib version 1.0.1+, show() can be called multiple times (with most backends).

ASP.Net MVC: Calling a method from a view

You should not call a controller from the view.

Add a property to your view model, set it in the controller, and use it in the view.

Here is an example:

MyViewModel.cs:

public class MyViewModel
{   ...
    public bool ShowAdmin { get; set; }
}

MyController.cs:

public ViewResult GetAdminMenu()
    {
        MyViewModelmodel = new MyViewModel();            

        model.ShowAdmin = userHasPermission("Admin"); 

        return View(model);
    }

MyView.cshtml:

@model MyProj.ViewModels.MyViewModel


@if (@Model.ShowAdmin)
{
   <!-- admin links here-->
}

..\Views\Shared\ _Layout.cshtml:

    @using MyProj.ViewModels.Common;
....
    <div>    
        @Html.Action("GetAdminMenu", "Layout")
    </div>

How do I add a library project to Android Studio?

This is how it works for me in Android Studio 1.5+

In the project where you want to add external library project, go to menu File -> New -> *Import new Module**, navigate to the library project which you want to add to your project, select to add 'library' module in your project. You will get settings.gradle in your projects, beside app, included library, something like this:

include ':app', ':library'

Add in build.gradle(Module :app) in the dependencies section:

Compile project(':library')

Rebuild the project, and that's it.

*You can add as many libraries (modules) as you want. In that case in settings.gradle you will have:

 include ':app', ':lib1', ':lib2', ...

And in build.gradle, you'll need to have:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // Some other dependencies...

    compile project(':lib1')
    compile project(':lib2')
    ...
}

How to list all available Kafka brokers in a cluster?

On MacOS, can try:

brew tap let-us-go/zkcli
brew install zkcli

zkcli ls /brokers/ids
zkcli get /brokers/ids/1

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

NVARCHAR can store Unicode characters and takes 2 bytes per character.

How to make flexbox items the same size?

You could add flex-basis: 100% to achieve this.

Updated Example

.header {
  display: flex;
}

.item {
  flex-basis: 100%;
  text-align: center;
  border: 1px solid black;
}

For what it's worth, you could also use flex: 1 for the same results as well.

The shorthand of flex: 1 is the same as flex: 1 1 0, which is equivalent to:

.item {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 0;
  text-align: center;
  border: 1px solid black;
}

Append a dictionary to a dictionary

The answer I want to give is "use collections.ChainMap", but I just discovered that it was only added in Python 3.3: https://docs.python.org/3.3/library/collections.html#chainmap-objects

You can try to crib the class from the 3.3 source though: http://hg.python.org/cpython/file/3.3/Lib/collections/init.py#l763

Here is a less feature-full Python 2.x compatible version (same author): http://code.activestate.com/recipes/305268-chained-map-lookups/

Instead of expanding/overwriting one dictionary with another using dict.merge, or creating an additional copy merging both, you create a lookup chain that searches both in order. Because it doesn't duplicate the mappings it wraps ChainMap uses very little memory, and sees later modifications to any sub-mapping. Because order matters you can also use the chain to layer defaults (i.e. user prefs > config > env).

What's the difference between align-content and align-items?

according to what I understood from here:

when you use align-item or justify-item, you are adjusting "the content inside a grid item along the column axis or row axis respectively.

But: if you use align-content or justify-content, you are setting the position a grid along the column axis or the row axis. it occurs when you have a grid in a bigger container and width or height are inflexible (using px).

Writing a pandas DataFrame to CSV file

Sometimes you face these problems if you specify UTF-8 encoding also. I recommend you to specify encoding while reading file and same encoding while writing to file. This might solve your problem.

Base64 PNG data to HTML5 canvas

By the looks of it you need to actually pass drawImage an image object like so

_x000D_
_x000D_
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
  ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

I've tried it in chrome and it works fine.

Turn off display errors using file "php.ini"

It is not enough in case of PHP fpm. It was one more configuration file which can enable display_error. You should find www.conf. In my case it is in directory /etc/php/7.1/fpm/pool.d/

You should find php_flag[display_errors] = on and disable it, php_flag[display_errors] = off. This should solve the issue.

How to draw polygons on an HTML5 canvas?

To make a simple hexagon without the need for a loop, Just use the beginPath() function. Make sure your canvas.getContext('2d') is the equal to ctx if not it will not work.

I also like to add a variable called times that I can use to scale the object if I need to.This what I don't need to change each number.

     // Times Variable 

     var times = 1;

    // Create a shape

    ctx.beginPath();
    ctx.moveTo(99*times, 0*times);
    ctx.lineTo(99*times, 0*times);
    ctx.lineTo(198*times, 50*times);
    ctx.lineTo(198*times, 148*times);
    ctx.lineTo(99*times, 198*times);
    ctx.lineTo(99*times, 198*times);
    ctx.lineTo(1*times, 148*times);
    ctx.lineTo(1*times,57*times);
    ctx.closePath();
    ctx.clip();
    ctx.stroke();

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

Since you're only dealing with a 3x3 matrix of possible locations, it'd be pretty easy to just write a search through all possibilities without taxing you computing power. For each open space, compute through all the possible outcomes after that marking that space (recursively, I'd say), then use the move with the most possibilities of winning.

Optimizing this would be a waste of effort, really. Though some easy ones might be:

  • Check first for possible wins for the other team, block the first one you find (if there are 2 the games over anyway).
  • Always take the center if it's open (and the previous rule has no candidates).
  • Take corners ahead of sides (again, if the previous rules are empty)

Removing cordova plugins from the project

  • access the folder
  • list the plugins (cordova plugin list)
  • ionic cordova plugin remove "pluginName"

Should be fine!

How to reference Microsoft.Office.Interop.Excel dll?

If you have VS 2013 Express and you cant find Microsoft.Office namespace, try this ('Microsoft Excel 12.0 Object Library' if you want to use Office 2007)

enter image description here

What's the difference between display:inline-flex and display:flex?

You can display flex items inline, providing your assumption is based on wanting flexible inline items in the 1st place. Using flex implies a flexible block level element.

The simplest approach is to use a flex container with its children set to a flex property. In terms of code this looks like this:

.parent{
   display: inline-flex;
}

.children{
   flex: 1;
}

flex: 1 denotes a ratio, similar to percentages of a element's width.

Check these two links in order to see simple live Flexbox examples:

  1. https://njbenjamin.com/bundle-3.htm
  2. https://njbenjamin.com/bundle-4.htm

If you use the 1st example:

https://njbenjamin.com/flex/index_1.htm

You can play around with your browser console, to change the display of the container element between flex and inline-flex.

.NET Events - What are object sender & EventArgs e?

  1. 'sender' is called object which has some action perform on some control

  2. 'event' its having some information about control which has some behavoiur and identity perform by some user.when action will generate by occuring for event add it keep within array is called event agrs

How to receive serial data using android bluetooth

The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.

How to create permanent PowerShell Aliases

UPDATED - January 2021

It's possible to store in a profile.ps1 file any PowerShell code to be executed each time PowerShell starts. There are at least 6 different paths where to store the code depending on which user has to execute it. We will consider only 2 of them: the "all users" and the "only your user" paths (follow the previous link for further options).

To answer your question, you only have to create a profile.ps1 file containing the code you want to be executed, that is:

New-Alias Goto Set-Location

and save it in the proper path:

  • "$Home\Documents" (usually C:\Users<yourname>\Documents): Only your user will execute the code. This is the reccomanded place.
    You can quickly find your profile location by running echo $profile in PowerShell
  • $PsHome (C:\Windows\System32\WindowsPowerShell\v1.0): Every user will execute the code.

IMPORTANT: Remember you need to restart your PowerShell instances to apply the changes.

TIPS

  • If both paths contain a profile.ps1 file, the all-users one is executed first, then the user-specific one. This means the user-specific commands will overwrite variables in case of duplicates or conflicts.

  • Always put the code in the user-specific profile if there is no need to extend its execution to every user. This is safer because you don't pollute other users' space (usually, you don't want to do that).
    Another advantage is that you don't need administrator rights to add the file to your user-space (you do for anything in C:\Windows\System32).

  • If you really need to execute the profile code for every user, mind that the $PsHome path is different for 32bit and 64bit instances of PowerShell. You should consider both environments if you want to always execute the profile code.
    The paths are:

    • C:\Windows\System32\WindowsPowerShell\v1.0 for the 64bit environment
    • C:\Windows\SysWow64\WindowsPowerShell\v1.0 for the 32bit one (Yeah I know, the folder naming is counterintuitive, but it's correct).

Replace \n with <br />

For some reason using python3 I had to escape the "\"-sign

somestring.replace('\\n', '')

Hope this helps someone else!

How to merge two arrays in JavaScript and de-duplicate items

var arr1 = [1, 3, 5, 6];
var arr2 = [3, 6, 10, 11, 12];
arr1.concat(arr2.filter(ele => !arr1.includes(ele)));
console.log(arr1);

output :- [1, 3, 5, 6, 10, 11, 12]

MongoDb query condition on comparing 2 fields

In case performance is more important than readability and as long as your condition consists of simple arithmetic operations, you can use aggregation pipeline. First, use $project to calculate the left hand side of the condition (take all fields to left hand side). Then use $match to compare with a constant and filter. This way you avoid javascript execution. Below is my test in python:

import pymongo
from random import randrange

docs = [{'Grade1': randrange(10), 'Grade2': randrange(10)} for __ in range(100000)]

coll = pymongo.MongoClient().test_db.grades
coll.insert_many(docs)

Using aggregate:

%timeit -n1 -r1 list(coll.aggregate([
    {
        '$project': {
            'diff': {'$subtract': ['$Grade1', '$Grade2']},
            'Grade1': 1,
            'Grade2': 1
        }
    },
    {
        '$match': {'diff': {'$gt': 0}}
    }
]))

1 loop, best of 1: 192 ms per loop

Using find and $where:

%timeit -n1 -r1 list(coll.find({'$where': 'this.Grade1 > this.Grade2'}))

1 loop, best of 1: 4.54 s per loop

How to read a line from a text file in c/c++?

im not really that good at C , but i believe this code should get you complete single line till the end...

 #include<stdio.h>

 int main()   
{      
  char line[1024];    
  FILE *f=fopen("filename.txt","r");    
  fscanf(*f,"%[^\n]",line);    
  printf("%s",line);    
 }    

Django Rest Framework File Upload

Finally I am able to upload image using Django. Here is my working code

views.py

class FileUploadView(APIView):
    parser_classes = (FileUploadParser, )

    def post(self, request, format='jpg'):
        up_file = request.FILES['file']
        destination = open('/Users/Username/' + up_file.name, 'wb+')
        for chunk in up_file.chunks():
            destination.write(chunk)
        destination.close()  # File should be closed only after all chuns are added

        # ...
        # do some stuff with uploaded file
        # ...
        return Response(up_file.name, status.HTTP_201_CREATED)

urls.py

urlpatterns = patterns('', 
url(r'^imageUpload', views.FileUploadView.as_view())

curl request to upload

curl -X POST -S -H -u "admin:password" -F "[email protected];type=image/jpg" 127.0.0.1:8000/resourceurl/imageUpload

Java POI : How to read Excel cell value and not the formula computing it?

If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:

CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);

At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345") instead of a fractional value (e.g. "12345.0"). Note that setCellType is available in interface Cell(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase. Obviously, it would be nicer either to have getRawValue in the Cell interface or at least to be able use getStringCellValue on non STRING cell types. Unfortunately, all replacements of setCellType mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).

useState set method not reflecting change immediately

useEffect has its own state/lifecycle, it will not update until you pass a function in parameters or effect destroyed.

object and array spread or rest will not work inside useEffect.

React.useEffect(() => {
    console.log("effect");
    (async () => {
        try {
            let result = await fetch("/query/countries");
            const res = await result.json();
            let result1 = await fetch("/query/projects");
            const res1 = await result1.json();
            let result11 = await fetch("/query/regions");
            const res11 = await result11.json();
            setData({
                countries: res,
                projects: res1,
                regions: res11
            });
        } catch {}
    })(data)
}, [setData])
# or use this
useEffect(() => {
    (async () => {
        try {
            await Promise.all([
                fetch("/query/countries").then((response) => response.json()),
                fetch("/query/projects").then((response) => response.json()),
                fetch("/query/regions").then((response) => response.json())
            ]).then(([country, project, region]) => {
                // console.log(country, project, region);
                setData({
                    countries: country,
                    projects: project,
                    regions: region
                });
            })
        } catch {
            console.log("data fetch error")
        }
    })()
}, [setData]);

Default username password for Tomcat Application Manager

The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:

<?xml version='1.0' encoding='utf-8'?>  
<tomcat-users>  
    <role rolename="tomcat"/>  
    <role rolename="role1"/>  
    <role rolename="manager"/>  
    <user username="tomcat" password="tomcat" roles="tomcat"/>  
    <user username="both" password="tomcat" roles="tomcat,role1"/>  
    <user username="role1" password="tomcat" roles="role1"/>  
    <user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>  
</tomcat-users>  

It works for me very well

How to detect Esc Key Press in React and how to handle it

Another way to accomplish this in a functional component, is to use useEffect and useFunction, like this:

import React, { useEffect } from 'react';

const App = () => {


  useEffect(() => {
    const handleEsc = (event) => {
       if (event.keyCode === 27) {
        console.log('Close')
      }
    };
    window.addEventListener('keydown', handleEsc);

    return () => {
      window.removeEventListener('keydown', handleEsc);
    };
  }, []);

  return(<p>Press ESC to console log "Close"</p>);
}

Instead of console.log, you can use useState to trigger something.

how to make password textbox value visible when hover an icon

Try This :

In HTML and JS :

_x000D_
_x000D_
// Convert Password Field To Text On Hover._x000D_
  var passField = $('input[type=password]');_x000D_
  $('.show-pass').hover(function() {_x000D_
      passField.attr('type', 'text');_x000D_
  }, function() {_x000D_
    passField.attr('type', 'password');_x000D_
  })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!-- An Input PassWord Field With Eye Font-Awesome Class -->_x000D_
<input type="password" placeholder="Type Password">_x000D_
      <i class="show-pass fa fa-eye fa-lg"></i>
_x000D_
_x000D_
_x000D_

How do I iterate through each element in an n-dimensional matrix in MATLAB?

You could make a recursive function do the work

  • Let L = size(M)
  • Let idx = zeros(L,1)
  • Take length(L) as the maximum depth
  • Loop for idx(depth) = 1:L(depth)
  • If your depth is length(L), do the element operation, else call the function again with depth+1

Not as fast as vectorized methods if you want to check all the points, but if you don't need to evaluate most of them it can be quite a time saver.

Updating Anaconda fails: Environment Not Writable Error

I was also suffered by same problem. I resolved the problem by reinstalling anaconda(While installation at this time I selected "just for me" as user) and my problem was solved.Try the same

How do I connect to a MySQL Database in Python?

This is Mysql DB connection

from flask import Flask, render_template, request
from flask_mysqldb import MySQL

app = Flask(__name__)


app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'MyDB'

mysql = MySQL(app)


@app.route('/', methods=['GET', 'POST']) 
def index():
    if request.method == "POST":
        details = request.form
        cur = mysql.connection.cursor()
        cur.execute ("_Your query_")
        mysql.connection.commit()
        cur.close()
        return 'success'
    return render_template('index.html')


if __name__ == '__main__':
    app.run()

Tomcat Servlet: Error 404 - The requested resource is not available

this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.

Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output

Make copy of an array

If you want to make a copy of:

int[] a = {1,2,3,4,5};

This is the way to go:

int[] b = Arrays.copyOf(a, a.length);

Arrays.copyOf may be faster than a.clone() on small arrays. Both copy elements equally fast but clone() returns Object so the compiler has to insert an implicit cast to int[]. You can see it in the bytecode, something like this:

ALOAD 1
INVOKEVIRTUAL [I.clone ()Ljava/lang/Object;
CHECKCAST [I
ASTORE 2

C# equivalent to Java's charAt()?

Console.WriteLine allows the user to specify a position in a string.

See sample:

string str = "Tigger"; Console.WriteLine( str[0] ); //returns "T"; Console.WriteLine( str[2] ); //returns "g";

There you go!

Box-Shadow on the left side of the element only

box-shadow: inset 10px 0 0 0 red;

Excel Create Collapsible Indented Row Hierarchies

A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

Android: Pass data(extras) to a fragment

great answer by @Rarw. Try using a bundle to pass information from one fragment to another

Finding last occurrence of substring in string, replacing that

I would use a regex:

import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]

jQuery UI Color Picker

Make sure you have jQuery UI base and the color picker widget included on your page (as well as a copy of jQuery 1.3):

<link rel="stylesheet" href="http://dev.jquery.com/view/tags/ui/latest/themes/flora/flora.all.css" type="text/css" media="screen" title="Flora (Default)">

<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.core.js"></script>

<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.colorpicker.js"></script>

If you have those included, try posting your source so we can see what's going on.

c# Image resizing to different size while preserving aspect ratio

Here's a less specific extension method that works with Image rather than doing the loading and saving for you. It also allows you to specify interpolation method and correctly renders edges when you use NearestNeighbour interpolation.

The image will be rendered within the bounds of the area you specify so you always know your output width and height. e.g:

Scaled within bounds

namespace YourApp
{
    #region Namespaces
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Drawing.Drawing2D;
    #endregion

    /// <summary>Generic helper functions related to graphics.</summary>
    public static class ImageExtensions
    {
        /// <summary>Resizes an image to a new width and height value.</summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="newWidth">The width of the new image.</param>
        /// <param name="newHeight">The height of the new image.</param>
        /// <param name="mode">Interpolation mode.</param>
        /// <param name="maintainAspectRatio">If true, the image is centered in the middle of the returned image, maintaining the aspect ratio of the original image.</param>
        /// <returns>The new image. The old image is unaffected.</returns>
        public static Image ResizeImage(this Image image, int newWidth, int newHeight, InterpolationMode mode = InterpolationMode.Default, bool maintainAspectRatio = false)
        {
            Bitmap output = new Bitmap(newWidth, newHeight, image.PixelFormat);

            using (Graphics gfx = Graphics.FromImage(output))
            {
                gfx.Clear(Color.FromArgb(0, 0, 0, 0));
                gfx.InterpolationMode = mode;
                if (mode == InterpolationMode.NearestNeighbor)
                {
                    gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    gfx.SmoothingMode = SmoothingMode.HighQuality;
                }

                double ratioW = (double)newWidth / (double)image.Width;
                double ratioH = (double)newHeight / (double)image.Height;
                double ratio = ratioW < ratioH ? ratioW : ratioH;
                int insideWidth = (int)(image.Width * ratio);
                int insideHeight = (int)(image.Height * ratio);

                gfx.DrawImage(image, new Rectangle((newWidth / 2) - (insideWidth / 2), (newHeight / 2) - (insideHeight / 2), insideWidth, insideHeight));
            }

            return output;
        }
    }
}

jQuery trigger file input

adardesign nailed it regarding the file input element being ignored when it is hidden. I also noticed many people shifting element size to 0, or pushing it out of bounds with positioning and overflow adjustments. These are all great ideas.
An alternative way that also seems to work perfectly well is to just set the opacity to 0. Then you can always just set the position to keep it from offsetting other elements as hide does. It just seems a little unnecessary to shift an element nearly 10K pixels in any direction.

Here's a little example for those who want one:

input[type='file']{
    position:absolute;
    opacity:0;
    /* For IE8 "Keep the IE opacity settings in this order for max compatibility" */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
    /* For IE5 - 7 */
    filter: alpha(opacity=0);
}

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

Git submodule update

To address the --rebase vs. --merge option:

Let's say you have super repository A and submodule B and want to do some work in submodule B. You've done your homework and know that after calling

git submodule update

you are in a HEAD-less state, so any commits you do at this point are hard to get back to. So, you've started work on a new branch in submodule B

cd B
git checkout -b bestIdeaForBEver
<do work>

Meanwhile, someone else in project A has decided that the latest and greatest version of B is really what A deserves. You, out of habit, merge the most recent changes down and update your submodules.

<in A>
git merge develop
git submodule update

Oh noes! You're back in a headless state again, probably because B is now pointing to the SHA associated with B's new tip, or some other commit. If only you had:

git merge develop
git submodule update --rebase

Fast-forwarded bestIdeaForBEver to b798edfdsf1191f8b140ea325685c4da19a9d437.
Submodule path 'B': rebased into 'b798ecsdf71191f8b140ea325685c4da19a9d437'

Now that best idea ever for B has been rebased onto the new commit, and more importantly, you are still on your development branch for B, not in a headless state!

(The --merge will merge changes from beforeUpdateSHA to afterUpdateSHA into your working branch, as opposed to rebasing your changes onto afterUpdateSHA.)

Difference between `npm start` & `node app.js`, when starting app?

The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.

Also, I didn't understand when the accepted answer said "it defaults to node server.js". I think the documentation clarifies the default behavior:

npm-start

Start a package

Synopsis

npm start [-- <args>]

Description

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

In summary, running npm start could do one of two things:

  1. npm start {command_name}: Run an arbitrary command (i.e. if such command is specified in the start property of package.json's scripts object)
  2. npm start: Else if no start property exists (or no command_name is passed): Run node server.js, (which may not be appropriate, for example the OP doesn't have server.js; the OP runs nodeapp.js )
  3. I said I would list only 2 items, but are other possibilities (i.e. error cases). For example, if there is no package.json in the directory where you run npm start, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'

Setting initial values on load with Select2 with Ajax

var elem = $("#container").find("[name=elemMutliOption]");
for (var i = 0; i < arrDynamicList.length; i++)
{
   elem.find("option[value=" + arrDynamicList[i] + "]").attr("selected", "selected");
}
elem.select2().trigger("change");

This will work for people who are using the same view for multiple section in the page, with that being said it will work the same way for auto-setting defaults in your page OR better a EDIT page.

The "FOR" goes through the array that has existing options already loaded in the DOM.

Vertical Tabs with JQuery?

I wouldn't expect vertical tabs to need different Javascript from horizontal tabs. The only thing that would be different is the CSS for presenting the tabs and content on the page. JS for tabs generally does no more than show/hide/maybe load content.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I had a similar use case where I wanted to test a Spring Boot configured repository in isolation (in my case without Spring Security autoconfiguration which was failing my test). @SpringApplicationConfiguration uses SpringApplicationContextLoader and that has a JavaDoc stating

Can be used to test non-web features (like a repository layer) or start an fully-configured embedded servlet container.

However, like yourself, I could not work out how you are meant to configure the test to only test the repository layer using the main configuration entry point i.e. using your approach of @SpringApplicationConfiguration(classes = Application.class).

My solution was to create a completely new application context exclusive for testing. So in src/test/java I have two files in a sub-package called repo

  1. RepoIntegrationTest.java
  2. TestRepoConfig.java

where RepoIntegrationTest.java has

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestRepoConfig.class)
public class RepoIntegrationTest {

and TestRepoConfig.java has

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class TestRepoConfig {

It got me out of trouble but it would be really useful if anyone from the Spring Boot team could provide an alternative recommended solution

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

datetime.replace() will provide the best options. Also, it provides facility for replacing day, year, and month.

Suppose we have a datetime object and date is represented as: "2017-05-04"

>>> from datetime import datetime
>>> date = datetime.strptime('2017-05-04',"%Y-%m-%d")
>>> print(date)
2017-05-04 00:00:00
>>> date = date.replace(minute=59, hour=23, second=59, year=2018, month=6, day=1)
>>> print(date)
2018-06-01 23:59:59

Parse JSON response using jQuery

I was hanging out on Google, then I found your question and it's very simple to parse JSON response into normal HTML. Just use this little JavaScript code:

<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>

<script>

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;

</script>

</body>
</html>

How can I get name of element with jQuery?

var name = $('#myElement').attr('name');

How do I print colored output with Python 3?

It is very simple with colorama, just do this:

import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")

And here is the running result in Python3 REPL:

And call this to reset the color settings:

print(Style.RESET_ALL)

To avoid printing an empty line write this:

print(f"{Fore.BLUE}Hello World{Style.RESET_ALL}")

How do I prevent DIV tag starting a new line?

You can simply use:

#contentInfo_new br {display:none;}

How to overcome root domain CNAME restrictions?

I see readytocloud.com is hosted on Apache 2.2.

There is a much simpler and more efficient way to redirect the non-www site to the www site in Apache.

Add the following rewrite rules to the Apache configs (either inside the virtual host or outside. It doesn't matter):

RewriteCond %{HTTP_HOST} ^readytocloud.com [NC]
RewriteRule ^/$ http://www.readytocloud.com/ [R=301,L]

Or, the following rewrite rules if you want a 1-to-1 mapping of URLs from the non-www site to the www site:

RewriteCond %{HTTP_HOST} ^readytocloud.com [NC]
RewriteRule (.*) http://www.readytocloud.com$1 [R=301,L]

Note, the mod_rewrite module needs to be loaded for this to work. Luckily readytocloud.com is runing on a CentOS box, which by default loads mod_rewrite.

We have a client server running Apache 2.2 with just under 3,000 domains and nearly 4,000 redirects, however, the load on the server hover around 0.10 - 0.20.

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

For me,

I did not install that nib in required target.

Step 1: Click on your nib in Project Navigator (i.e. In First left tab)

Step 2: Go to File Inspector (i.e. In First right tab)

Step 3: Go to Target membership and tick on target in which you want to use your nib.

Find and Replace Inside a Text File from a Bash Command

Be careful if you replace URLs with "/" character.

An example of how to do it:

sed -i "s%http://domain.com%http://www.domain.com/folder/%g" "test.txt"

Extracted from: http://www.sysadmit.com/2015/07/linux-reemplazar-texto-en-archivos-con-sed.html

Hide Button After Click (With Existing Form on Page)

CSS code:

.hide{
display:none;
}

.show{
display:block;
}

Html code:

<button onclick="block_none()">Check Availability</button>

Javascript Code:

function block_none(){
 document.getElementById('hidden-div').classList.add('show');
document.getElementById('button-id').classList.add('hide');
}

Can you find all classes in a package using reflection?

Yeah using few API's you can, here is how I like doing it, faced this problem which I was using hibernate core & had to find classes which where annotated with a certain annotation.

Make these an custom annotation using which you will mark which classes you want to be picked up.

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface EntityToBeScanned {

}

Then mark your class with it like

@EntityToBeScanned 
public MyClass{

}

Make this utility class which has the following method

public class ClassScanner {

    public static Set<Class<?>> allFoundClassesAnnotatedWithEntityToBeScanned(){
        Reflections reflections = new Reflections(".*");
        Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(EntityToBeScanned.class);
        return annotated;
    }

}

Call the allFoundClassesAnnotatedWithEntityToBeScanned() method to get a Set of Classes found.

You will need libs given below

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>21.0</version>
    </dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.22.0-CR1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.reflections/reflections -->
<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.10</version>
</dependency>

CodeIgniter 404 Page Not Found, but why?

Your folder/file structure seems a little odd to me. I can't quite figure out how you've got this laid out.

Hello I am using CodeIgniter for two applications (a public and an admin app).

This sounds to me like you've got two separate CI installations. If this is the case, I'd recommend against it. Why not just handle all admin stuff in an admin controller? If you do want two separate CI installations, make sure they are definitely distinct entities and that the two aren't conflicting with one another. This line:

$system_folder = "../system";
$application_folder = "../application/admin"; (this line exists of course twice)

And the place you said this exists (/admin/index.php...or did you mean /admin/application/config?) has me scratching my head. You have admin/application/admin and a system folder at the top level?

Serializing an object to JSON

Just to keep it backward compatible I load Crockfords JSON-library from cloudflare CDN if no native JSON support is given (for simplicity using jQuery):

function winHasJSON(){
  json_data = JSON.stringify(obj);
  // ... (do stuff with json_data)
}
if(typeof JSON === 'object' && typeof JSON.stringify === 'function'){
  winHasJSON();
} else {
  $.getScript('//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min.js', winHasJSON)
}

Checking Maven Version

On terminal type mvn -v and the output will look like the image shown below

enter image description here

How to style the menu items on an Android action bar

I did this way:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="android:actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="actionMenuTextColor">@color/colorAccent</item>
</style>

<style name="MenuTextAppearance" >
    <item name="android:textAppearance">@android:style/TextAppearance.Large</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
</style>

Kubernetes how to make Deployment to update image

kubectl rollout restart deployment myapp

This is the current way to trigger a rolling update and leave the old replica sets in place for other operations provided by kubectl rollout like rollbacks.