Programs & Examples On #Autoeventwireup

How can I validate google reCAPTCHA v2 using javascript/jQuery?

The Google reCAPTCHA version 2 ASP.Net allows validating the Captcha response on the client side using its Callback functions. In this example, the Google new reCAPTCHA will be validated using ASP.Net RequiredField Validator.

<script type="text/javascript">
    var onloadCallback = function () {
        grecaptcha.render('dvCaptcha', {
            'sitekey': '<%=ReCaptcha_Key %>',
            'callback': function (response) {
                $.ajax({
                    type: "POST",
                    url: "Demo.aspx/VerifyCaptcha",
                    data: "{response: '" + response + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        var captchaResponse = jQuery.parseJSON(r.d);
                        if (captchaResponse.success) {
                            $("[id*=txtCaptcha]").val(captchaResponse.success);
                            $("[id*=rfvCaptcha]").hide();
                        } else {
                            $("[id*=txtCaptcha]").val("");
                            $("[id*=rfvCaptcha]").show();
                            var error = captchaResponse["error-codes"][0];
                            $("[id*=rfvCaptcha]").html("RECaptcha error. " + error);
                        }
                    }
                });
            }
        });
    };
</script>


    <asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />
    <asp:RequiredFieldValidator ID="rfvCaptcha" ErrorMessage="The CAPTCHA field is required." ControlToValidate="txtCaptcha"
        runat="server" ForeColor="Red" Display="Dynamic" />

    <br />
    <asp:Button ID="btnSubmit" Text="Submit" runat="server" />

Name does not exist in the current context

Jobs.aspx

This is the phyiscal file -> CodeFile="Jobs.aspx.cs"

This is the class which handles the events of the page -> Inherits="Members_Jobs"

Jobs.aspx.cs

This is the partial class which manages the page events -> public partial class Members_Jobs : System.Web.UI.Page

The other part of the partial class should be -> public partial class Members_Jobs this is usually the designer file.

you dont need to have partial classes and could declare your controls all in 1 class and not have a designer file.

EDIT 27/09/2013 11:37

if you are still having issues with this I would do as Bharadwaj suggested and delete the designer file. You can then right-click on the page, in the solution explorer, and there is an option, something like "Convert to Web Application", which will regenerate your designer file

How to send email in ASP.NET C#

If you want to generate your email bodies in razor, you can use Mailzory. Also, you can download the nuget package from here.

// template path
var viewPath = Path.Combine("Views/Emails", "hello.cshtml");
// read the content of template and pass it to the Email constructor
var template = File.ReadAllText(viewPath);

var email = new Email(template);

// set ViewBag properties
email.ViewBag.Name = "Johnny";
email.ViewBag.Content = "Mailzory Is Funny";

// send email
var task = email.SendAsync("[email protected]", "subject");
task.Wait()

How to refresh Gridview after pressed a button in asp.net

Before data bind change gridview databinding method, assign GridView.EditIndex to -1. It solved the same issue for me :

 gvTypes.EditIndex = -1;
 gvTypes.DataBind();

gvTypes is my GridView ID.

Adding a stylesheet to asp.net (using Visual Studio 2010)

The only thing you have to do is to add in the cshtml file, in the head, the following line:

        @Styles.Render("~/Content/Main.css")

The entire head will look somethink like that:

    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>HTML Page</title>
         @Styles.Render("~/Content/main.css")
    </head>

Hope it helps!!

Parser Error when deploy ASP.NET application

I've solve the issue. The solution is to not making virtual dir manualy and then copy app files here, but use 'Add Application...' option. Here is post that helped me http://social.msdn.microsoft.com/Forums/en-US/winformssetup/thread/7ad2acb0-42ca-4ee8-9161-681689b60dda/

A potentially dangerous Request.Form value was detected from the client

I faced this same problem while sending some email templates from aspx page to code behind....

So I tried to solve this by adding

 <httpRuntime requestValidationMode="2.0" />

in my web config under enter code here` but that did not helped me unless I putted

ValidateRequest="false"

attrribute in the page directive of the aspx page.

How to make script execution wait until jquery is loaded

I have found that suggested solution only works while minding asynchronous code. Here is the version that would work in either case:

document.addEventListener('DOMContentLoaded', function load() {
    if (!window.jQuery) return setTimeout(load, 50);
    //your synchronous or asynchronous jQuery-related code
}, false);

asp.net: Invalid postback or callback argument

You can also fill you data in the prerender event. This way you can keep your validation and stay secure. Here is an example using a repeater.

protected void Page_PreRender(object sender, EventArgs e)
     {
        List<Objects.User> users = Application.User.GetAllUsers();

        Repeater1.DataSource = users;
        Repeater1.DataBind();
      }

Get text of label with jquery

Try this

var g = $('#<%=Label1.ClientID%>').text();

Getting Textbox value in Javascript

The ID you are trying is an serverside.

That is going to render in the browser differently.

try to get the ID by watching the html in the Browser.

var TestVar = document.getElementById('ctl00_ContentColumn_txt_model_code').value;

this may works.

Or do that ClientID method. That also works but ultimately the browser will get the same thing what i had written.

How to dynamically add rows to a table in ASP.NET?

ASP.NET WebForms doesn't work this way. What you have above is just normal HTML, so ASP.NET isn't going to give you any facility to add/remove items. What you'll want to do is use a Repeater control, or possibly a GridView. These controls will be available in the code-behind. For example, the Repeater would expose an "Items" property upon which you can add new items (rows). In the code-front (the .aspx file) you'd provide an ItemTemplate that stubs out what the body rows would look like. There are plenty of tutorials on the web for repeaters, so I suggest you google that to obtain further information.

How to give ASP.NET access to a private key in a certificate in the certificate store?

If you are trying to load a cert from a .pfx file in IIS the solution may be as simple as enabling this option for the Application Pool.

Right click on the App Pool and select Advanced Settings.

Then enable Load User Profile


enter image description here

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

You can always refractor the namespace and it will update all the pages at the same time. Highlight the namespace, right click and select refractor from the drop down menu.

Get POST data in C#/ASP.NET

The following is OK in HTML4, but not in XHTML. Check your editor.

<input type=button value="Submit" />

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

In my case runat="server" was missing in the asp:content tag. I know it's stupid, but someone might have removed from the code in the build I got.

It worked for me. Someone may face the same thing. Hence shared.

How to return XML in ASP.NET?

Below is an example of the correct way I think. At least it is what I use. You need to do Response.Clear to get rid of any headers that are already populated. You need to pass the correct ContentType of text/xml. That is the way you serve xml. In general you want to serve it as charset UTF-8 as that is what most parsers are expecting. But I don't think it has to be that. But if you change it make sure to change your xml document declaration and indicate the charset in there. You need to use the XmlWriter so you can actually write in UTF-8 and not whatever charset is the default. And to have it properly encode your xml data in UTF-8.

   ' -----------------------------------------------------------------------------
   ' OutputDataSetAsXML
   '
   ' Description: outputs the given dataset as xml to the response object
   '
   ' Arguments:
   '    dsSource           - source data set
   '
   ' Dependencies:
   '
   ' History
   ' 2006-05-02 - WSR : created
   '
   Private Sub OutputDataSetAsXML(ByRef dsSource As System.Data.DataSet)

      Dim xmlDoc As System.Xml.XmlDataDocument
      Dim xmlDec As System.Xml.XmlDeclaration
      Dim xmlWriter As System.Xml.XmlWriter

      ' setup response
      Me.Response.Clear()
      Me.Response.ContentType = "text/xml"
      Me.Response.Charset = "utf-8"
      xmlWriter = New System.Xml.XmlTextWriter(Me.Response.OutputStream, System.Text.Encoding.UTF8)

      ' create xml data document with xml declaration
      xmlDoc = New System.Xml.XmlDataDocument(dsSource)
      xmlDoc.DataSet.EnforceConstraints = False
      xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", Nothing)
      xmlDoc.PrependChild(xmlDec)

      ' write xml document to response
      xmlDoc.WriteTo(xmlWriter)
      xmlWriter.Flush()
      xmlWriter.Close()
      Response.End()

   End Sub
   ' -----------------------------------------------------------------------------

Check if inputs form are empty jQuery

$('input[type="text"]').get().some(item => item.value !== '');

How to specify the port an ASP.NET Core application is hosted on?

Alternative solution is to use a hosting.json in the root of the project.

{
  "urls": "http://localhost:60000"
}

And then in Program.cs

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", true)
        .Build();

    var host = new WebHostBuilder()
        .UseKestrel(options => options.AddServerHeader = false)
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

Split string into array of character strings

If the original string contains supplementary Unicode characters, then split() would not work, as it splits these characters into surrogate pairs. To correctly handle these special characters, a code like this works:

String[] chars = new String[stringToSplit.codePointCount(0, stringToSplit.length())];
for (int i = 0, j = 0; i < stringToSplit.length(); j++) {
    int cp = stringToSplit.codePointAt(i);
    char c[] = Character.toChars(cp);
    chars[j] = new String(c);
    i += Character.charCount(cp);
}

Simple proof that GUID is not unique

A GUID is theoretically non-unique. Here's your proof:

  • GUID is a 128 bit number
  • You cannot generate 2^128 + 1 or more GUIDs without re-using old GUIDs

However, if the entire power output of the sun was directed at performing this task, it would go cold long before it finished.

GUIDs can be generated using a number of different tactics, some of which take special measures to guarantee that a given machine will not generate the same GUID twice. Finding collisions in a particular algorithm would show that your particular method for generating GUIDs is bad, but would not prove anything about GUIDs in general.

How to delete the last row of data of a pandas dataframe

stats = pd.read_csv("C:\\py\\programs\\second pandas\\ex.csv")

The Output of stats:

       A            B          C
0   0.120064    0.785538    0.465853
1   0.431655    0.436866    0.640136
2   0.445904    0.311565    0.934073
3   0.981609    0.695210    0.911697
4   0.008632    0.629269    0.226454
5   0.577577    0.467475    0.510031
6   0.580909    0.232846    0.271254
7   0.696596    0.362825    0.556433
8   0.738912    0.932779    0.029723
9   0.834706    0.002989    0.333436

just use skipfooter=1

skipfooter : int, default 0

Number of lines at bottom of file to skip

stats_2 = pd.read_csv("C:\\py\\programs\\second pandas\\ex.csv", skipfooter=1, engine='python')

Output of stats_2

       A          B            C
0   0.120064    0.785538    0.465853
1   0.431655    0.436866    0.640136
2   0.445904    0.311565    0.934073
3   0.981609    0.695210    0.911697
4   0.008632    0.629269    0.226454
5   0.577577    0.467475    0.510031
6   0.580909    0.232846    0.271254
7   0.696596    0.362825    0.556433
8   0.738912    0.932779    0.029723

jquery if div id has children

This snippet will determine if the element has children using the :parent selector:

if ($('#myfav').is(':parent')) {
    // do something
}

Note that :parent also considers an element with one or more text nodes to be a parent.

Thus the div elements in <div>some text</div> and <div><span>some text</span></div> will each be considered a parent but <div></div> is not a parent.

Adding text to a cell in Excel using VBA

You can also use the cell property.

Cells(1, 1).Value = "Hey, what's up?"

Make sure to use a . before Cells(1,1).Value as in .Cells(1,1).Value, if you are using it within With function. If you are selecting some sheet.

Any way to exit bash script, but not quitting the terminal

Actually, I think you might be confused by how you should run a script.

If you use sh to run a script, say, sh ./run2.sh, even if the embedded script ends with exit, your terminal window will still remain.

However if you use . or source, your terminal window will exit/close as well when subscript ends.

for more detail, please refer to What is the difference between using sh and source?

How can I enable the Windows Server Task Scheduler History recording?

Here is where I found it on a Windows 2008R2 server. Elevated Task Scheduler Click on "Task Scheduler Library" It appears as an option on the right hand "Actions" panel.

enter image description here

Declaring an enum within a class

In general, I always put my enums in a struct. I have seen several guidelines including "prefixing".

enum Color
{
  Clr_Red,
  Clr_Yellow,
  Clr_Blue,
};

Always thought this looked more like C guidelines than C++ ones (for one because of the abbreviation and also because of the namespaces in C++).

So to limit the scope we now have two alternatives:

  • namespaces
  • structs/classes

I personally tend to use a struct because it can be used as parameters for template programming while a namespace cannot be manipulated.

Examples of manipulation include:

template <class T>
size_t number() { /**/ }

which returns the number of elements of enum inside the struct T :)

Type.GetType("namespace.a.b.ClassName") returns null

If the assembly is referenced and the Class visible :

typeof(namespace.a.b.ClassName)

GetType returns null because the type is not found, with typeof, the compiler may help you to find out the error.

How do I plot list of tuples in Python?

With gnuplot using gplot.py

from gplot import *

l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

gplot.log('y')
gplot(*zip(*l))

enter image description here

Inline CSS styles in React: how to implement a:hover?

This is a universal wrapper for hover written in typescript. The component will apply style passed via props 'hoverStyle' on hover event.

import React, { useState } from 'react';

export const Hover: React.FC<{
  style?: React.CSSProperties;
  hoverStyle: React.CSSProperties;
}> = ({ style = {}, hoverStyle, children }) => {
  const [isHovered, setHovered] = useState(false);
  const calculatedStyle = { ...style, ...(isHovered ? hoverStyle : {}) };
  return (
    <div
      style={calculatedStyle}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      {children}
    </div>
  );
};    

TypeScript typed array usage

You have an error in your syntax here:

this._possessions = new Thing[100]();

This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:

this._possessions = [];

Of the array constructor if you want to set the length:

this._possessions = new Array(100);

I have created a brief working example you can try in the playground.

module Entities {  

    class Thing {

    }        

    export class Person {
        private _name: string;
        private _possessions: Thing[];
        private _mostPrecious: Thing;

        constructor (name: string) {
            this._name = name;
            this._possessions = [];
            this._possessions.push(new Thing())
            this._possessions[100] = new Thing();
        }
    }
}

How can my iphone app detect its own version number?

Read the info.plist file of your app and get the value for key CFBundleShortVersionString. Reading info.plist will give you an NSDictionary object

Install .ipa to iPad with or without iTunes

Use iFunBox. It's free, Mac/Win compatible. Just make an ad hoc build and save somewhere. Install from iFunBox. I load all my test ad hoc release builds on my devices for testing before release using this method. Who has time to fiddle around with iTunes?

must appear in the GROUP BY clause or be used in an aggregate function

SELECT t1.cname, t1.wmname, t2.max
FROM makerar t1 JOIN (
    SELECT cname, MAX(avg) max
    FROM makerar
    GROUP BY cname ) t2
ON t1.cname = t2.cname AND t1.avg = t2.max;

Using rank() window function:

SELECT cname, wmname, avg
FROM (
    SELECT cname, wmname, avg, rank() 
    OVER (PARTITION BY cname ORDER BY avg DESC)
    FROM makerar) t
WHERE rank = 1;

Note

Either one will preserve multiple max values per group. If you want only single record per group even if there is more than one record with avg equal to max you should check @ypercube's answer.

Printing leading 0's in C

More flexible.. Here's an example printing rows of right-justified numbers with fixed widths, and space-padding.

//---- Header
std::string getFmt ( int wid, long val )
{  
  char buf[64];
  sprintf ( buf, "% *ld", wid, val );
  return buf;
}
#define FMT (getFmt(8,x).c_str())

//---- Put to use
printf ( "      COUNT     USED     FREE\n" );
printf ( "A: %s %s %s\n", FMT(C[0]), FMT(U[0]), FMT(F[0]) );
printf ( "B: %s %s %s\n", FMT(C[1]), FMT(U[1]), FMT(F[1]) );
printf ( "C: %s %s %s\n", FMT(C[2]), FMT(U[2]), FMT(F[2]) );

//-------- Output
      COUNT     USED     FREE
A:      354   148523     3283
B: 54138259 12392759   200391
C:    91239     3281    61423

The function and macro are designed so the printfs are more readable.

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

issue = “UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.”

And this worked for me

import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Qt5Agg')

Pass multiple values with onClick in HTML link

function ReAssign(valautionId, userName) {
   var valautionId 
   var userName 
 alert(valautionId);
 alert(userName);
  }

<a href=# onclick="return ReAssign('valuationId','user')">Re-Assign</a>

How do I use Notepad++ (or other) with msysgit?

Update 2010-2011:

zumalifeguard's solution (upvoted) is simpler than the original one, as it doesn't need anymore a shell wrapper script.

As I explain in "How can I set up an editor to work with Git on Windows?", I prefer a wrapper, as it is easier to try and switch editors, or change the path of one editor, without having to register said change with a git config again.
But that is just me.


Additional information: the following solution works with Cygwin, while the zuamlifeguard's solution does not.


Original answer.

The following:

C:\prog\git>git config --global core.editor C:/prog/git/npp.sh

C:/prog/git/npp.sh:
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"

does work. Those commands are interpreted as shell script, hence the idea to wrap any windows set of commands in a sh script.
(As Franky comments: "Remember to save your .sh file with Unix style line endings or receive mysterious error messages!")

More details on the SO question How can I set up an editor to work with Git on Windows?

Note the '-multiInst' option, for ensuring a new instance of notepad++ for each call from Git.

Note also that, if you are using Git on Cygwin (and want to use Notepad++ from Cygwin), then scphantm explains in "using Notepad++ for Git inside Cygwin" that you must be aware that:

git is passing it a cygwin path and npp doesn't know what to do with it

So the script in that case would be:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$(cygpath -w "$*")"

Multiple lines for readability:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar \
  -nosession -noPlugin "$(cygpath -w "$*")"

With "$(cygpath -w "$*")" being the important part here.

Val commented (and then deleted) that you should not use -notabbar option:

It makes no good to disable the tab during rebase, but makes a lot of harm to general Notepad usability since -notab becomes the default setting and you must Settings>Preferences>General>TabBar> Hide>uncheck every time you start notepad after rebase. This is hell. You recommended the hell.

So use rather:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession -noPlugin "$(cygpath -w "$*")"

That is:

#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession \
  -noPlugin "$(cygpath -w "$*")"

If you want to place the script 'npp.sh' in a path with spaces (as in 'c:\program files\...',), you have three options:

  • Either try to quote the path (single or double quotes), as in:

    git config --global core.editor 'C:/program files/git/npp.sh'
    
  • or try the shortname notation (not fool-proofed):

    git config --global core.editor C:/progra~1/git/npp.sh
    
  • or (my favorite) place 'npp.sh' in a directory part of your %PATH% environment variable. You would not have then to specify any path for the script.

    git config --global core.editor npp.sh
    
  • Steiny reports in the comments having to do:

    git config --global core.editor '"C:/Program Files (x86)/Git/scripts/npp.sh"'
    

Spring Boot War deployed to Tomcat

public class Application extends SpringBootServletInitializer {}

just extends the SpringBootServletInitializer. It will works in your AWS/tomcat

How to do Select All(*) in linq to sql

using (MyDataContext dc = new MyDataContext())
{
    var rows = from myRow in dc.MyTable
               select myRow;
}

OR

using (MyDataContext dc = new MyDataContext())
{
    var rows = dc.MyTable.Select(row => row);
}

Assign an initial value to radio button as checked

You can use the checked attribute for this:

<input type="radio" checked="checked">

invalid_client in google oauth2

Check your Project name on Google APIs console. you choose another project you created. I was same error. my mistake was choosing diffirent project.

Converting pixels to dp

The best answer comes from the Android framework itself: just use this equality...

public static int dpToPixels(final DisplayMetrics display_metrics, final float dps) {
    final float scale = display_metrics.density;
    return (int) (dps * scale + 0.5f);
}

(converts dp to px)

How to use the start command in a batch file?

I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?

Basically, you use the /B and /C options:

START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1

How can I find the number of elements in an array?

Actually, there is no proper way to count the elements in a dynamic integer array. However, the sizeof command works properly in Linux, but it does not work properly in Windows. From a programmer's point of view, it is not recommended to use sizeof to take the number of elements in a dynamic array. We should keep track of the number of elements when making the array.

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

An example taken form here:

When an Employee entity object is removed, the remove operation is cascaded to the referenced Address entity object. In this regard, orphanRemoval=true and cascade=CascadeType.REMOVE are identical, and if orphanRemoval=true is specified, CascadeType.REMOVE is redundant.

The difference between the two settings is in the response to disconnecting a relationship. For example, such as when setting the address field to null or to another Address object.

  • If orphanRemoval=true is specified the disconnected Address instance is automatically removed. This is useful for cleaning up dependent objects (e.g. Address) that should not exist without a reference from an owner object (e.g. Employee).

  • If only cascade=CascadeType.REMOVE is specified, no automatic action is taken since disconnecting a relationship is not a remove operation.

To avoid dangling references as a result of orphan removal, this feature should only be enabled for fields that hold private non shared dependent objects.

I hope this makes it more clear.

How to access static resources when mapping a global front controller servlet on /*

I've run into this also and never found a great solution. I ended up mapping my servlet one level higher in the URL hierarchy:

<servlet-mapping>       
  <servlet-name>home</servlet-name>             
  <url-pattern>/app/*</url-pattern>     
</servlet-mapping>

And now everything at the base context (and in your /res directory) can be served up by your container.

Possible reasons for timeout when trying to access EC2 instance

To enable ssh access from the Internet for instances in a VPC subnet do the following:

  • Attach an Internet gateway to your VPC.
  • Ensure that your subnet's route table points to the Internet gateway.
  • Ensure that instances in your subnet have a globally unique IP address (public IPv4 address, Elastic IP address, or IPv6 address).
  • Ensure that your network access control (at VPC Level) and security group rules (at ec2 level) allow the relevant traffic to flow to and from your instance. Ensure your network Public IP address is enabled for both. By default, Network AcL allow all inbound and outbound traffic except explicitly configured otherwise

SQL Stored Procedure set variables using SELECT

select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
    from table1
    where IsCurrent = 1

How to fill DataTable with SQL Table

You can fill your data table like the below code.I am also fetching the connections at runtime using a predefined XML file that has all the connection.

  public static DataTable Execute_Query(string connection, string query)
    {
        Logger.Info("Execute Query has been called for connection " + connection);
        connection = "Data Source=" + Connections.run_singlevalue(connection, "server") + ";Initial Catalog=" + Connections.run_singlevalue(connection, "database") + ";User ID=" + Connections.run_singlevalue(connection, "username") + ";Password=" + Connections.run_singlevalue(connection, "password") + ";Connection Timeout=30;";
        DataTable dt = new DataTable();
        try
        {
            using (SqlConnection con = new SqlConnection(connection))
            {
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    con.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.SelectCommand.CommandTimeout = 1800;
                        da.Fill(dt);
                    }
                    con.Close();
                }
            }
            Logger.Info("Execute Query success");
            return dt;
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message);
            return null;
        }
    }   

Convert.ToDateTime: how to set format

You should probably use either DateTime.ParseExact or DateTime.TryParseExact instead. They allow you to specify specific formats. I personally prefer the Try-versions since I think they produce nicer code for the error cases.

Clang vs GCC - which produces faster binaries?

The fact that Clang compiles code faster may not be as important as the speed of the resulting binary. However, here is a series of benchmarks.

Partial Dependency (Databases)

A FD (functional dependency) that holds in a relation is partial when removing one of the determining attributes gives a FD that holds in the relation. A FD that isn't partial is full.

Eg: If {A,B} ? {C} but also {A} ? {C} then {C} is partially functionally dependent on {A,B}.

Eg: Here's a relation value where that example condition holds. (A FD holds in a relation variable when it holds in every value that can arise.)

A  B  C
1  1  1
1  2  1
2  1  1

The non-trivial FDs that hold: {A,B} determines {C}, {B,C}, {A,C} & {A,B,C}; {A}, {B} & {} also determine {C}. Of those: {A,B} ? {C} is partial per {A} ? {C}, {B} ? {C} & {} ? {C}; {A} ? {C} & {B} ? {C} are partial per {} ? {C}; the others are full.

A functional dependency X ? Y is a full functional dependency if removal of any attribute A from X means that the dependency does not hold any more; that is, for any attribute A e X, (X – {A}) does not functionally determine Y. A functional dependency X ? Y is a partial dependency if some attribute A e X can be removed from X and the dependency still holds; that is, for some A e X, (X – {A}) ? Y.

-- FUNDAMENTALS OF Database Systems SIXTH EDITION Ramez Elmasri & Navathe

Notice that whether a FD is full vs partial doesn't depend on CKs (candidate keys), let alone one CK that you might be calling the PK (primary key).

(A definition of 2NF is that every non-CK attribute is fully functionally determined by every CK. Observe that the only CK is {A,B} & the only non-CK attribute C is partially dependent on it so this value is not in 2NF & indeed it is the lossless join of components/projections onto {A,B} & {A,C}, onto {A,B} & {B,C} & onto {A,B} & {C}.)

(Beware that that textbook's definition of "transitive FD" does not define the same sort of thing as the standard definition of "transitive FD".)

Where IN clause in LINQ

public List<Requirement> listInquiryLogged()
{
    using (DataClassesDataContext dt = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
    {
        var inq = new int[] {1683,1684,1685,1686,1687,1688,1688,1689,1690,1691,1692,1693};
        var result = from Q in dt.Requirements
                     where inq.Contains(Q.ID)
                     orderby Q.Description
                     select Q;

        return result.ToList<Requirement>();
    }
}

String.format() to format double in java

If you want to format it with manually set symbols, use this:

DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator('.');
decimalFormatSymbols.setGroupingSeparator(',');
DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", decimalFormatSymbols);
System.out.println(decimalFormat.format(1237516.2548)); //1,237,516.25

Locale-based formatting is preferred, though.

.NET: Simplest way to send POST with data and read response

Personally, I think the simplest approach to do an http post and get the response is to use the WebClient class. This class nicely abstracts the details. There's even a full code example in the MSDN documentation.

http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx

In your case, you want the UploadData() method. (Again, a code sample is included in the documentation)

http://msdn.microsoft.com/en-us/library/tdbbwh0a(VS.80).aspx

UploadString() will probably work as well, and it abstracts it away one more level.

http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadstring(VS.80).aspx

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

If you don't have non-ASCII characters (codepoints 128 and above) in your file, UTF-8 without BOM is the same as ASCII, byte for byte - so Notepad++ will guess wrong.

What you need to do is to specify the character encoding when serving the AJAX response - e.g. with PHP, you'd do this:

header('Content-Type: application/json; charset=utf-8');

The important part is to specify the charset with every JS response - else IE will fall back to user's system default encoding, which is wrong most of the time.

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

I was facing the same issue, I was using tomcat 8.5 with Java 10.Finally I installed Java 8(1.8.0_171) and it's working fine without any issues

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

In .net 4.0 Microsoft removed the ability to add DLLs to the Assembly simply by dragging and dropping.

Instead you need to use gacutil.exe, or create an installer to do it. Microsoft actually doesn’t recommend using gacutil, but I went that route anyway.

To use gacutil on a development machine go to:
Start -> programs -> Microsoft Visual studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010)

Then use these commands to uninstall and Reinstall respectively. Note I did NOT include .dll in the uninstall command.
gacutil /u myDLL
gacutil /i "C:\Program Files\Custom\myDLL.dll"

To use Gacutil on a non-development machine you will have to copy the executable and config file from your dev machine to the production machine. It looks like there are a few different versions of Gacutil. The one that worked for me, I found here:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe.config

Copy the files here or to the appropriate .net folder;
C:\Windows\Microsoft.NET\Framework\v4.0.30319

Then use these commands to uninstall and reinstall respectively
"C:\Users\BHJeremy\Desktop\Installing to the Gac in .net 4.0\gacutil.exe" /u "myDLL"

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\gacutil.exe" /i "C:\Program Files\Custom\myDLL.dll"

Git: How to remove file from index without deleting files from any repository

The above solutions work fine for most cases. However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.

Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.

https://help.github.com/articles/remove-sensitive-data/

You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.

To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.

It looked intimidating at first, but really, was easy and worked like a charm ! :-)

adding multiple entries to a HashMap at once in one statement

Here's a simple class that will accomplish what you want

import java.util.HashMap;

public class QuickHash extends HashMap<String,String> {
    public QuickHash(String...KeyValuePairs) {
        super(KeyValuePairs.length/2);
        for(int i=0;i<KeyValuePairs.length;i+=2)
            put(KeyValuePairs[i], KeyValuePairs[i+1]);
    }
}

And then to use it

Map<String, String> Foo=QuickHash(
    "a", "1",
    "b", "2"
);

This yields {a:1, b:2}

How to make the checkbox unchecked by default always

This is browser specific behavior and is a way for making filling up forms more convenient to users (like reloading the page when an error has been encountered and not losing what they just typed). So there is no sure way to disable this across browsers short of setting the default values on page load using javascript.

Firefox though seems to disable this feature when you specify the header:

Cache-Control: no-store

See this question.

Converting String array to java.util.List

First Step you need to create a list instance through Arrays.asList();

String[] args = new String[]{"one","two","three"};
List<String> list = Arrays.asList(args);//it converts to immutable list

Then you need to pass 'list' instance to new ArrayList();

List<String> newList=new ArrayList<>(list);

How to solve static declaration follows non-static declaration in GCC C code?

I had a similar issue , The function name i was using matched one of the inbuilt functions declared in one of the header files that i included in the program.Reading through the compiler error message will tell you the exact header file and function name.Changing the function name solved this issue for me

Convert a space delimited string to list

states_list = states.split(' ')

In regards to your edit:

from random import choice
random_state = choice(states_list)

How to find out the server IP address (using JavaScript) that the browser is connected to?

Try this as a shortcut, not as a definitive solution (see comments):

<script type="text/javascript">
    var ip = location.host;
    alert(ip);
</script>

This solution cannot work in some scenarios but it can help for quick testing. Regards

Execute Python script via crontab

Just use crontab -e and follow the tutorial here.

Look at point 3 for a guide on how to specify the frequency.

Based on your requirement, it should effectively be:

*/10 * * * * /usr/bin/python script.py

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

Getting the index of a particular item in array

try Array.FindIndex(myArray, x => x.Contains("author"));

Extract column values of Dataframe as List in Apache Spark

With Spark 2.x and Scala 2.11

I'd think of 3 possible ways to convert values of a specific column to List.

Common code snippets for all the approaches

import org.apache.spark.sql.SparkSession

val spark = SparkSession.builder.getOrCreate    
import spark.implicits._ // for .toDF() method

val df = Seq(
    ("first", 2.0),
    ("test", 1.5), 
    ("choose", 8.0)
  ).toDF("id", "val")

Approach 1

df.select("id").collect().map(_(0)).toList
// res9: List[Any] = List(one, two, three)

What happens now? We are collecting data to Driver with collect() and picking element zero from each record.

This could not be an excellent way of doing it, Let's improve it with next approach.


Approach 2

df.select("id").rdd.map(r => r(0)).collect.toList 
//res10: List[Any] = List(one, two, three)

How is it better? We have distributed map transformation load among the workers rather than single Driver.

I know rdd.map(r => r(0)) does not seems elegant you. So, let's address it in next approach.


Approach 3

df.select("id").map(r => r.getString(0)).collect.toList 
//res11: List[String] = List(one, two, three)

Here we are not converting DataFrame to RDD. Look at map it won't accept r => r(0)(or _(0)) as the previous approach due to encoder issues in DataFrame. So end up using r => r.getString(0) and it would be addressed in the next versions of Spark.

Conclusion

All the options give the same output but 2 and 3 are effective, finally 3rd one is effective and elegant(I'd think).

Databricks notebook

Should functions return null or an empty object?

To put what others have said in a pithier manner...

Exceptions are for Exceptional circumstances

If this method is pure data access layer, I would say that given some parameter that gets included in a select statement, it would expect that I may not find any rows from which to build an object, and therefore returning null would be acceptable as this is data access logic.

On the other hand, if I expected my parameter to reflect a primary key and I should only get one row back, if I got more than one back I would throw an exception. 0 is ok to return null, 2 is not.

Now, if I had some login code that checked against an LDAP provider then checked against a DB to get more details and I expected those should be in sync at all times, I might toss the exception then. As others said, it's business rules.

Now I'll say that is a general rule. There are times where you may want to break that. However, my experience and experiments with C# (lots of that) and Java(a bit of that) has taught me that it is much more expensive performance wise to deal with exceptions than to handle predictable issues via conditional logic. I'm talking to the tune of 2 or 3 orders of magnitude more expensive in some cases. So, if it's possible your code could end up in a loop, then I would advise returning null and testing for it.

There is an error in XML document (1, 41)

Agreed with the answer from sll, but experienced another hurdle which was having specified a namespace in the attributes, when receiving the return xml that namespace wasn't included and thus failed finding the class.

i had to find a workaround to specifying the namespace in the attribute and it worked.

ie.

[Serializable()]
    [XmlRoot("Patient", Namespace = "http://www.xxxx.org/TargetNamespace")]
    public class Patient

generated

<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.xxxx.org/TargetNamespace">

but I had to change it to

[Serializable()]
[XmlRoot("Patient")]
public class Patient

which generated to

<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

This solved my problem, hope it helps someone else.

Import multiple csv files into pandas and concatenate into one DataFrame

An alternative to darindaCoder's answer:

path = r'C:\DRO\DCL_rawdata_files'                     # use your path
all_files = glob.glob(os.path.join(path, "*.csv"))     # advisable to use os.path.join as this makes concatenation OS independent

df_from_each_file = (pd.read_csv(f) for f in all_files)
concatenated_df   = pd.concat(df_from_each_file, ignore_index=True)
# doesn't create a list, nor does it append to one

MySQL, create a simple function

MySQL function example:

Open the mysql terminal:

el@apollo:~$ mysql -u root -pthepassword yourdb
mysql>

Drop the function if it already exists

mysql> drop function if exists myfunc;
Query OK, 0 rows affected, 1 warning (0.00 sec)

Create the function

mysql> create function hello(id INT)
    -> returns CHAR(50)
    -> return 'foobar';
Query OK, 0 rows affected (0.01 sec)

Create a simple table to test it out with

mysql> create table yar (id INT);
Query OK, 0 rows affected (0.07 sec)

Insert three values into the table yar

mysql> insert into yar values(5), (7), (9);
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0

Select all the values from yar, run our function hello each time:

mysql> select id, hello(5) from yar;
+------+----------+
| id   | hello(5) |
+------+----------+
|    5 | foobar   |
|    7 | foobar   |
|    9 | foobar   |
+------+----------+
3 rows in set (0.01 sec)

Verbalize and internalize what just happened:

You created a function called hello which takes one parameter. The parameter is ignored and returns a CHAR(50) containing the value 'foobar'. You created a table called yar and added three rows to it. The select statement runs the function hello(5) for each row returned by yar.

Is it possible to create static classes in PHP (like in C#)?

you can have those "static"-like classes. but i suppose, that something really important is missing: in php you don't have an app-cycle, so you won't get a real static (or singleton) in your whole application...

see Singleton in PHP

Difference between onStart() and onResume()

Reference to http://developer.android.com/training/basics/activity-lifecycle/starting.html

onResume() Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it. Always followed by onPause().

onPause() Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns. Followed either by onResume() if the activity returns back to the front, or by onStop() if it becomes invisible to the user.

Uploading files to file server using webclient class

when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.

When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).

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

It appears that it is possible to track a smart phone without using GPS.

Sources:

Primary: "PinMe: Tracking a Smartphone User around the World"

Secondary: "How to Track a Cellphone Without GPS—or Consent"

I have not yet found a link to the team's final code. When I do I will post, if another has not done so.

How to save an image to localStorage and display it on the next page?

I have come up with the same issue, instead of storing images, that eventually overflow the local storage, you can just store the path to the image. something like:

let imagen = ev.target.getAttribute('src');
arrayImagenes.push(imagen);

bootstrap multiselect get selected values

the solution what I found to work in my case

$('#multiselect1').multiselect({
    selectAllValue: 'multiselect-all',
    enableCaseInsensitiveFiltering: true,
    enableFiltering: true,
    maxHeight: '300',
    buttonWidth: '235',
    onChange: function(element, checked) {
        var brands = $('#multiselect1 option:selected');
        var selected = [];
        $(brands).each(function(index, brand){
            selected.push([$(this).val()]);
        });

        console.log(selected);
    }
}); 

What is the "right" way to iterate through an array in Ruby?

This will iterate through all the elements:

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }

Prints:

1
2
3
4
5
6

This will iterate through all the elements giving you the value and the index:

array = ["A", "B", "C"]
array.each_with_index {|val, index| puts "#{val} => #{index}" }

Prints:

A => 0
B => 1
C => 2

I'm not quite sure from your question which one you are looking for.

Using an authorization header with Fetch in React Native

Example fetch with authorization header:

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

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Since the name is likely to change in future versions of Android (currently the latest is AppCompatActivity but it will probably change at some point), I believe a good thing to have is a class Activity that extends AppCompatActivity and then all your activities extend from that one. If tomorrow, they change the name to AppCompatActivity2 for instance you will have to change it just in one place.

typedef struct vs struct definitions

In C, the type specifier keywords of structures, unions and enumerations are mandatory, ie you always have to prefix the type's name (its tag) with struct, union or enum when referring to the type.

You can get rid of the keywords by using a typedef, which is a form of information hiding as the actual type of an object will no longer be visible when declaring it.

It is therefore recommended (see eg the Linux kernel coding style guide, Chapter 5) to only do this when you actually want to hide this information and not just to save a few keystrokes.

An example of when you should use a typedef would be an opaque type which is only ever used with corresponding accessor functions/macros.

change cursor to finger pointer

You can do this in CSS:

a.menu_links {
    cursor: pointer;
}

This is actually the default behavior for links. You must have either somehow overridden it elsewhere in your CSS, or there's no href attribute in there (it's missing from your example).

Parsing XML with namespace in Python via 'ElementTree'

Note: This is an answer useful for Python's ElementTree standard library without using hardcoded namespaces.

To extract namespace's prefixes and URI from XML data you can use ElementTree.iterparse function, parsing only namespace start events (start-ns):

>>> from io import StringIO
>>> from xml.etree import ElementTree
>>> my_schema = u'''<rdf:RDF xml:base="http://dbpedia.org/ontology/"
...     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
...     xmlns:owl="http://www.w3.org/2002/07/owl#"
...     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
...     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
...     xmlns="http://dbpedia.org/ontology/">
... 
...     <owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
...         <rdfs:label xml:lang="en">basketball league</rdfs:label>
...         <rdfs:comment xml:lang="en">
...           a group of sports teams that compete against each other
...           in Basketball
...         </rdfs:comment>
...     </owl:Class>
... 
... </rdf:RDF>'''
>>> my_namespaces = dict([
...     node for _, node in ElementTree.iterparse(
...         StringIO(my_schema), events=['start-ns']
...     )
... ])
>>> from pprint import pprint
>>> pprint(my_namespaces)
{'': 'http://dbpedia.org/ontology/',
 'owl': 'http://www.w3.org/2002/07/owl#',
 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
 'xsd': 'http://www.w3.org/2001/XMLSchema#'}

Then the dictionary can be passed as argument to the search functions:

root.findall('owl:Class', my_namespaces)

React - How to get parameter value from query string?

In the component where you need to access the parameters you can use

this.props.location.state.from.search

which will reveal the whole query string (everything after the ? sign)

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

What does "Changes not staged for commit" mean

It's another way of Git telling you:

Hey, I see you made some changes, but keep in mind that when you write pages to my history, those changes won't be in these pages.

Changes to files are not staged if you do not explicitly git add them (and this makes sense).

So when you git commit, those changes won't be added since they are not staged. If you want to commit them, you have to stage them first (ie. git add).

Add new field to every document in a MongoDB collection

if you are using mongoose try this,after mongoose connection

async ()=> await Mongoose.model("collectionName").updateMany({}, {$set: {newField: value}})

How can I find the maximum value and its index in array in MATLAB?

This will return the maximum value in a matrix

max(M1(:))

This will return the row and the column of that value

[x,y]=ind2sub(size(M1),max(M1(:)))

For minimum just swap the word max with min and that's all.

Correct way to try/except using Python requests module?

One additional suggestion to be explicit. It seems best to go from specific to general down the stack of errors to get the desired error to be caught, so the specific ones don't get masked by the general one.

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)

Http Error: 404 Client Error: Not Found for url: http://www.google.com/blahblah

vs

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)     

OOps: Something Else 404 Client Error: Not Found for url: http://www.google.com/blahblah

curl.h no such file or directory

sudo apt-get install curl-devel

sudo apt-get install libcurl-dev

(will install the default alternative)

OR

sudo apt-get install libcurl4-openssl-dev

(the OpenSSL variant)

OR

sudo apt-get install libcurl4-gnutls-dev

(the gnutls variant)

How to retrieve an Oracle directory path?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

How do I write a compareTo method which compares objects?

Consider using the Comparator interface described here which uses generics so you can avoid casting Object to Student.

As Eugene Retunsky said, your first part is the correct way to compare Strings. Also if the lastNames are equal I think you meant to compare firstNames, in which case just use compareTo in the same way.

plot a circle with pyplot

Hello I have written a code for drawing a circle. It will help for drawing all kind of circles. The image shows the circle with radius 1 and center at 0,0 The center and radius can be edited of any choice.

## Draw a circle with center and radius defined
## Also enable the coordinate axes
import matplotlib.pyplot as plt
import numpy as np
# Define limits of coordinate system
x1 = -1.5
x2 = 1.5
y1 = -1.5
y2 = 1.5

circle1 = plt.Circle((0,0),1, color = 'k', fill = False, clip_on = False)
fig, ax = plt.subplots()
ax.add_artist(circle1)
plt.axis("equal")
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.xlim(left=x1)
plt.xlim(right=x2)
plt.ylim(bottom=y1)
plt.ylim(top=y2)
plt.axhline(linewidth=2, color='k')
plt.axvline(linewidth=2, color='k')

##plt.grid(True)
plt.grid(color='k', linestyle='-.', linewidth=0.5)
plt.show()

Good luck

Making a button invisible by clicking another button in HTML

$( "#btn1" ).click(function() {
 $('#btn2').css('display','none');
});

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

How do I convert a Swift Array to a String?

If you question is something like this: tobeFormattedString = ["a", "b", "c"] Output = "abc"

String(tobeFormattedString)

How to flush output after each `echo` call?

One thing that is not often mentionned is gzip compression that keeps turned ON because of details in various hosting environments.

Here is a modern approach, working with PHP-FPM as Fast CGI, which does not need .htaccess rewrite rule or environment variable :

In php.ini or .user.ini :

output_buffering = 0
zlib.output_compression = 0
implicit_flush = true
output_handler = 

In PHP script :

header('Content-Encoding: none'); // Disable gzip compression
ob_end_flush(); // Stop buffer
ob_implicit_flush(1); // Implicit flush at each output command

See this comment on official PHP doc for ob_end_flush() need.

How do include paths work in Visual Studio?

To use Windows SDK successfully you need not only make include files available to your projects but also library files and executables (tools). To set all these directories you should use WinSDK Configuration Tool.

How can I customize the tab-to-space conversion factor?

When using TypeScript, the default tab width is always two regardless of what it says in the toolbar. You have to set "prettier.tabWidth" in your user settings to change it.

Ctrl + P, Type ? user settings, add:

"prettier.tabWidth": 4

Ajax - 500 Internal Server Error

Had the very same problem, then I remembered that for security reasons ASP doesn't expose the entire error or stack trace when accessing your site/service remotely, same as not being able to test a .asmx web service remotely, so I remoted into the sever and monitored my dev tools, and only then did I get the notorious message "Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dep...".

So log on the server and debug from there.

onclick open window and specific size

window.open('http://somelocation.com','mywin','width=500,height=500');

Npm Error - No matching version found for

If none of this did not help, then try to swap ^ in "^version" to ~ "~version".

How to import and use image in a Vue single file component?

As simple as:

<template>
    <div id="app">
        <img src="./assets/logo.png">
    </div>
</template>
    
<script>
    export default {
    }
</script>
    
<style lang="css">
</style> 

Taken from the project generated by vue cli.

If you want to use your image as a module, do not forget to bind data to your Vuejs component:

<template>
    <div id="app">
        <img :src="image"/>
    </div>
</template>
    
<script>
    import image from "./assets/logo.png"
    
    export default {
        data: function () {
            return {
                image: image
            }
        }
    }
</script>
    
<style lang="css">
</style>

And a shorter version:

<template>
    <div id="app">
        <img :src="require('./assets/logo.png')"/>
    </div>
</template>
    
<script>
    export default {
    }
</script>
    
<style lang="css">
</style> 

Return a value if no rows are found in Microsoft tSQL

@hai-phan's answer using LEFT JOIN is the key, but it might be a bit hard to follow. I had a complicated query that may also return nothing. I just simplified his answer to my need. It's easy to apply to query with many columns.

;WITH CTE AS (
  -- SELECT S.Id, ...
  -- FROM Sites S WHERE Id = @SiteId
  -- EXCEPT SOME CONDITION.
  -- Whatever your query is
)
SELECT CTE.* -- If you want something else instead of NULL, use COALESCE.
FROM (SELECT @SiteId AS ID) R
LEFT JOIN CTE ON CTE.Id = R.ID

Update: This answer on SqlServerCentral is the best. It utilizes this feature of MAX - "MAX returns NULL when there is no row to select."

SELECT ISNULL(MAX(value), 0) FROM table WHERE Id = @SiteId

Format price in the current locale and currency

By this code for formating price in product list

echo Mage::helper('core')->currency($_product->getPrice());

Converting datetime.date to UTC timestamp in Python

  • Assumption 1: You're attempting to convert a date to a timestamp, however since a date covers a 24 hour period, there isn't a single timestamp that represents that date. I'll assume that you want to represent the timestamp of that date at midnight (00:00:00.000).

  • Assumption 2: The date you present is not associated with a particular time zone, however you want to determine the offset from a particular time zone (UTC). Without knowing the time zone the date is in, it isn't possible to calculate a timestamp for a specific time zone. I'll assume that you want to treat the date as if it is in the local system time zone.

First, you can convert the date instance into a tuple representing the various time components using the timetuple() member:

dtt = d.timetuple() # time.struct_time(tm_year=2011, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)

You can then convert that into a timestamp using time.mktime:

ts = time.mktime(dtt) # 1293868800.0

You can verify this method by testing it with the epoch time itself (1970-01-01), in which case the function should return the timezone offset for the local time zone on that date:

d = datetime.date(1970,1,1)
dtt = d.timetuple() # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=-1)
ts = time.mktime(dtt) # 28800.0

28800.0 is 8 hours, which would be correct for the Pacific time zone (where I'm at).

HTML img align="middle" doesn't align an image

You don't need align="center" and float:left. Remove both of these. margin: 0 auto is sufficient.

How to copy only a single worksheet to another workbook using vba

To copy a sheet to a workbook called TARGET:

Sheets("xyz").Copy After:=Workbooks("TARGET.xlsx").Sheets("abc")

This will put the copied sheet xyz in the TARGET workbook after the sheet abc Obviously if you want to put the sheet in the TARGET workbook before a sheet, replace Before for After in the code.

To create a workbook called TARGET you would first need to add a new workbook and then save it to define the filename:

Application.Workbooks.Add (xlWBATWorksheet)
ActiveWorkbook.SaveAs ("TARGET")

However this may not be ideal for you as it will save the workbook in a default location e.g. My Documents.

Hopefully this will give you something to go on though.

How to define two fields "unique" as couple

Django 2.2+

Using the constraints features UniqueConstraint is preferred over unique_together.

From the Django documentation for unique_together:

Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.

For example:

class Volume(models.Model):
    id = models.AutoField(primary_key=True)
    journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
    volume_number = models.CharField('Volume Number', max_length=100)
    comments = models.TextField('Comments', max_length=4000, blank=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
        ]

Add a background image to shape in XML Android

This is a circle shape with icon inside:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ok_icon"/>
    <item>
        <shape
                android:shape="oval">
            <solid android:color="@color/transparent"/>
            <stroke android:width="2dp" android:color="@color/button_grey"/>
        </shape>
    </item>
</layer-list>

Resource interpreted as Document but transferred with MIME type application/zip

In my case the file name was too long, and got the same error. Once shortened below 200 chars worked fine. (limit might be 250?)

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

All previous answers are correct but here is a simple and quick way if you only need one icon in one place to change it's color:

   <p style="color:green">Time icon: <span class="glyphicon glyphicon-time" ></span></p>  

enter image description here

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

An error has occured. Please see log file - eclipse juno

For STS on MacOS, i followed the following steps:

  1. Go to the STS directory from terminal:

    cd /Users/karan.verma/Documents/sts-bundle/STS.app/Contents/MacOS

  2. Start STS

    ./STS

STS started, but all my imported projects were removed.

How to switch from POST to GET in PHP CURL

Solved: The problem lies here:

I set POST via both _CUSTOMREQUEST and _POST and the _CUSTOMREQUEST persisted as POST while _POST switched to _HTTPGET. The Server assumed the header from _CUSTOMREQUEST to be the right one and came back with a 411.

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');

CSS smooth bounce animation

Here is code not using the percentage in the keyframes. Because you used percentages the animation does nothing a long time.

  • 0% translate 0px
  • 20% translate 0px
  • etc.

How does this example work:

  1. We set an animation. This is a short hand for animation properties.
  2. We immediately start the animation since we use from and to in the keyframes. from is = 0% and to is = 100%
  3. We can now control how fast it will bounce by setting the animation time: animation: bounce 1s infinite alternate; the 1s is how long the animation will last.

_x000D_
_x000D_
.ball {_x000D_
  margin-top: 50px;_x000D_
  border-radius: 50%;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  background-color: cornflowerblue;_x000D_
  border: 2px solid #999;_x000D_
  animation: bounce 1s infinite alternate;_x000D_
  -webkit-animation: bounce 1s infinite alternate;_x000D_
}_x000D_
@keyframes bounce {_x000D_
  from {_x000D_
    transform: translateY(0px);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateY(-15px);_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
  from {_x000D_
    transform: translateY(0px);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateY(-15px);_x000D_
  }_x000D_
}
_x000D_
<div class="ball"></div>
_x000D_
_x000D_
_x000D_

Programmatically change the height and width of a UIImageView Xcode Swift

Hey i figured it out shortly after. For some reason I was just having a brain fart.

image.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.2)

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

Change column type in pandas

this below code will change datatype of column.

df[['col.name1', 'col.name2'...]] = df[['col.name1', 'col.name2'..]].astype('data_type')

in place of data type you can give your datatype .what do you want like str,float,int etc.

Run Java Code Online

Ideone is the best site for the online code running, debugging and it provides extra performance stats also.

Without Sign Up, you can run code upto of maximum 5 sec, and for signup, upto a max of 15 sec. And for Signup, the code management and history is also too good.

However, it has some maximum amount of submissions per month for registered users.

www.ideone.com

It supports more than 40 languages, and is integrated with SPOJ and RecruitCoders.

doGet and doPost in Servlets

Both GET and POST are used by the browser to request a single resource from the server. Each resource requires a separate GET or POST request.

  1. The GET method is most commonly (and is the default method) used by browsers to retrieve information from servers. When using the GET method the 3rd section of the request packet, which is the request body, remains empty.

The GET method is used in one of two ways: When no method is specified, that is when you or the browser is requesting a simple resource such as an HTML page, an image, etc. When a form is submitted, and you choose method=GET on the HTML tag. If the GET method is used with an HTML form, then the data collected through the form is sent to the server by appending a "?" to the end of the URL, and then adding all name=value pairs (name of the html form field and value entered in that field) separated by an "&" Example: GET /sultans/shop//form1.jsp?name=Sam%20Sultan&iceCream=vanilla HTTP/1.0 optional headeroptional header<< empty line >>>

The name=value form data will be stored in an environment variable called QUERY_STRING. This variable will be sent to a processing program (such as JSP, Java servlet, PHP etc.)

  1. The POST method is used when you create an HTML form, and request method=POST as part of the tag. The POST method allows the client to send form data to the server in the request body section of the request (as discussed earlier). The data is encoded and is formatted similar to the GET method, except that the data is sent to the program through the standard input.

Example: POST /sultans/shop//form1.jsp HTTP/1.0 optional headeroptional header<< empty line >>> name=Sam%20Sultan&iceCream=vanilla

When using the post method, the QUERY_STRING environment variable will be empty. Advantages/Disadvantages of GET vs. POST

Advantages of the GET method: Slightly faster Parameters can be entered via a form or by appending them after the URL Page can be bookmarked with its parameters

Disadvantages of the GET method: Can only send 4K worth of data. (You should not use it when using a textarea field) Parameters are visible at the end of the URL

Advantages of the POST method: Parameters are not visible at the end of the URL. (Use for sensitive data) Can send more that 4K worth of data to server

Disadvantages of the POST method: Can cannot be bookmarked with its data

How to use <md-icon> in Angular Material?

All md- prefixes are now mat- prefixes as of time of writing this!

Put this in your html head:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Import in our module:

import { MatIconModule } from '@angular/material';

Use in your code:

<mat-icon>face</mat-icon>

Here is the latest documentation:

https://material.angular.io/components/icon/overview

Change default date time format on a single database in SQL Server

You could use SET DATEFORMAT, like in this example

declare @dates table (orig varchar(50) ,parsed datetime)

SET DATEFORMAT ydm;

insert into @dates
select '2008-09-01','2008-09-01'

SET DATEFORMAT ymd;
insert into @dates
select '2008-09-01','2008-09-01'

select * from @dates

You would need to specify the dateformat in the code when you parse your XML data

How can I tell jaxb / Maven to generate multiple schema packages?

i have solved with:

                        <removeOldOutput>false</removeOldOutput>
                        <clearOutputDir>false</clearOutputDir>
                        <forceRegenerate>true</forceRegenerate>

add this to each configuration ;)

WebView and HTML5 <video>

A-M's is similar to what the BrowerActivity does. for FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams (768, 512);

I think we can use

FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
            FrameLayout.LayoutParams.FILL_PARENT) 

instead.

Another issue I met is if the video is playing, and user clicks the back button, next time, you go to this activity(singleTop one) and can not play the video. to fix this, I called the

try { 
    mCustomVideoView.stopPlayback();  
    mCustomViewCallback.onCustomViewHidden();
} catch(Throwable e) { //ignore }

in the activity's onBackPressed method.

Attach IntelliJ IDEA debugger to a running Java process

Also, don't forget you need to add "-Xdebug" flag in app JAVA_OPTS if you want connect in debug mode.

Get the device width in javascript

You can get the device screen width via the screen.width property.
Sometimes it's also useful to use window.innerWidth (not typically found on mobile devices) instead of screen width when dealing with desktop browsers where the window size is often less than the device screen size.

Typically, when dealing with mobile devices AND desktop browsers I use the following:

 var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;

What is the correct way to restore a deleted file from SVN?

If you're using Tortoise SVN, you should be able to revert changes from just that revision into your working copy (effectively performing a reverse-merge), then do another commit to re-add the file. Steps to follow are:

  1. Browse to folder in working copy where you deleted the file.
  2. Go to repo-browser.
  3. Browse to revision where you deleted the file.
  4. In the change list, find the file you deleted.
  5. Right click on the file and go to "Revert changes from this revision".
  6. This will restore the file to your working copy, keeping history.
  7. Commit the file to add it back into your repository.

Calculating the distance between 2 points

You can use the below formula to find the distance between the 2 points:

distance*distance = ((x2 - x1)*(x2 - x1)) + ((y2 - y1)*(y2 - y1))

How can apply multiple background color to one div

With :after and :before you can do that.

HTML:

<div class="a"> </div>
<div class="b"> </div>
<div class="c"> </div>

CSS:

div {
    height: 100px;
    position: relative;
}
.a {
    background: #9C9E9F;
}
.b {
    background: linear-gradient(to right, #9c9e9f, #f6f6f6);
}
.a:after, .c:before, .c:after {
    content: '';
    width: 50%;
    height: 100%;
    top: 0;
    right: 0;
    display: block;
    position: absolute;
}
.a:after {
    background: #f6f6f6;    
}
.c:before {
    background: #9c9e9f;
    left: 0;
}
.c:after {
    background: #33CCFF;
    right: 0;
    height: 80%;
}

And a demo.

PHP Try and Catch for SQL Insert

    $sql = "INSERT INTO   customer(FIELDS)VALUES(VALUES)";
    mysql_query($sql);
    if (mysql_errno())
    {
            echo "<script>alert('License already registered');location.replace('customerform.html');</script>";
    }   

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

As @Agam said,

You need this statement in your driver file: from AthleteList import AtheleteList

gitignore all files of extension in directory

I believe the simplest solution would be to use find. I do not like to have multiple .gitignore hanging around in sub-directories and I prefer to manage a unique, top-level .gitignore. To do so you could simply append the found files to your .gitignore. Supposing that /public/static/ is your project/git home I would use something like:

find . -type f -name *.js | cut -c 3- >> .gitignore

I found that cutting out the ./ at the beginning is often necessary for git to understand which files to avoid. Therefore the cut -c 3-.

Original purpose of <input type="hidden">?

The values of form elements including type='hidden' are submitted to the server when the form is posted. input type="hidden" values are not visible in the page. Maintaining User IDs in hidden fields, for example, is one of the many uses.

SO uses a hidden field for the upvote click.

<input value="16293741" name="postId" type="hidden">

Using this value, the server-side script can store the upvote.

Synchronizing a local Git repository with a remote one

You can use git hooks for that. Just create a hook that pushes changed to the other repo after an update.

Of course you might get merge conflicts so you have to figure how to deal with them.

jquery datatables hide column

Hope this will help you. I am using this solution for Search on some columns but i don't want to display them on frontend.

$(document).ready(function() {
        $('#example').dataTable({
            "scrollY": "500px",
            "scrollCollapse": true,
            "scrollX": false,
            "bPaginate": false,
            "columnDefs": [
                { 
                    "width": "30px", 
                    "targets": 0,
                },
                { 
                    "width": "100px", 
                    "targets": 1,
                },
                { 
                    "width": "100px", 
                    "targets": 2,
                },              
                { 
                    "width": "76px",
                    "targets": 5, 
                },
                { 
                    "width": "80px", 
                    "targets": 6,
                },
                {
                    "targets": [ 7 ],
                    "visible": false,
                    "searchable": true
                },
                {
                    "targets": [ 8 ],
                    "visible": false,
                    "searchable": true
                },
                {
                    "targets": [ 9 ],
                    "visible": false,
                    "searchable": true
                },
              ]
        });
    });

Why my regexp for hyphenated words doesn't work?

A couple of things:

  1. Your regexes need to be anchored by separators* or you'll match partial words, as is the case now
  2. You're not using the proper syntax for a non-capturing group. It's (?: not (:?

If you address the first problem, you won't need groups at all.

*That is, a blank or beginning/end of string.

error: package javax.servlet does not exist

In my case, migrating a Spring 3.1 app up to 3.2.7, my solution was similar to Matthias's but a bit different -- thus why I'm documenting it here:

In my POM I found this dependency and changed it from 6.0 to 7.0:

    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>

Then later in the POM I upgraded this plugin from 6.0 to 7.0:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    ...
                    <configuration>
                        ...
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax</groupId>
                                <artifactId>javaee-endorsed-api</artifactId>
                                <version>7.0</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>

jquery save json data object in cookie

You can serialize the data as JSON, like this:

$.cookie("basket-data", JSON.stringify($("#ArticlesHolder").data()));

Then to get it from the cookie:

$("#ArticlesHolder").data(JSON.parse($.cookie("basket-data")));

This relies on JSON.stringify() and JSON.parse() to serialize/deserialize your data object, for older browsers (IE<8) include json2.js to get the JSON functionality. This example uses the jQuery cookie plugin

Is there any advantage of using map over unordered_map in case of trivial keys?

Reasons have been given in other answers; here is another.

std::map (balanced binary tree) operations are amortized O(log n) and worst case O(log n). std::unordered_map (hash table) operations are amortized O(1) and worst case O(n).

How this plays out in practice is that the hash table "hiccups" every once in a while with an O(n) operation, which may or may not be something your application can tolerate. If it can't tolerate it, you'd prefer std::map over std::unordered_map.

Build query string for System.Net.HttpClient get

The RFC 6570 URI Template library I'm developing is capable of performing this operation. All encoding is handled for you in accordance with that RFC. At the time of this writing, a beta release is available and the only reason it's not considered a stable 1.0 release is the documentation doesn't fully meet my expectations (see issues #17, #18, #32, #43).

You could either build a query string alone:

UriTemplate template = new UriTemplate("{?params*}");
var parameters = new Dictionary<string, string>
  {
    { "param1", "value1" },
    { "param2", "value2" },
  };
Uri relativeUri = template.BindByName(parameters);

Or you could build a complete URI:

UriTemplate template = new UriTemplate("path/to/item{?params*}");
var parameters = new Dictionary<string, string>
  {
    { "param1", "value1" },
    { "param2", "value2" },
  };
Uri baseAddress = new Uri("http://www.example.com");
Uri relativeUri = template.BindByName(baseAddress, parameters);

How to remove the arrows from input[type="number"] in Opera

Those arrows are part of the Shadow DOM, which are basically DOM elements on your page which are hidden from you. If you're new to the idea, a good introductory read can be found here.

For the most part, the Shadow DOM saves us time and is good. But there are instances, like this question, where you want to modify it.

You can modify these in Webkit now with the right selectors, but this is still in the early stages of development. The Shadow DOM itself has no unified selectors yet, so the webkit selectors are proprietary (and it isn't just a matter of appending -webkit, like in other cases).

Because of this, it seems likely that Opera just hasn't gotten around to adding this yet. Finding resources about Opera Shadow DOM modifications is tough, though. A few unreliable internet sources I've found all say or suggest that Opera doesn't currently support Shadow DOM manipulation.

I spent a bit of time looking through the Opera website to see if there'd be any mention of it, along with trying to find them in Dragonfly...neither search had any luck. Because of the silence on this issue, and the developing nature of the Shadow DOM + Shadow DOM manipulation, it seems to be a safe conclusion that you just can't do it in Opera, at least for now.

What charset does Microsoft Excel use when saving files?

Russian Edition offers CSV, CSV (Macintosh) and CSV (DOS).

When saving in plain CSV, it uses windows-1251.

I just tried to save French word Résumé along with the Russian text, it saved it in HEX like 52 3F 73 75 6D 3F, 3F being the ASCII code for question mark.

When I opened the CSV file, the word, of course, became unreadable (R?sum?)

Check if a row exists using old mysql_* API

This ought to do the trick: just limit the result to 1 row; if a row comes back the $lectureName is Assigned, otherwise it's Available.

function checkLectureStatus($lectureName)
{
    $con = connectvar();
    mysql_select_db("mydatabase", $con);
    $result = mysql_query(
        "SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");

    if(mysql_fetch_array($result) !== false)
        return 'Assigned';
    return 'Available';
}

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

Converting a date string to a DateTime object using Joda Time library

DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").parseDateTime("04/02/2011 20:27:05");

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

In my case, CSS did not fix the issue. I noticed the problem while using jQuery re-render a button.

$("#myButton").html("text")

Try this

$("#myButton").html("<span>text</span>")

Defining a HTML template to append using JQuery

Add somewhere in body

<div class="hide">
<a href="#" class="list-group-item">
    <table>
        <tr>
            <td><img src=""></td>
            <td><p class="list-group-item-text"></p></td>
        </tr>
    </table>
</a>
</div>

then create css

.hide { display: none; }

and add to your js

$('#output').append( $('.hide').html() );

How do I use cx_freeze?

You can change the setup.py code to this:

    from cx_freeze import setup, Executable
    setup( name = "foo",
           version = "1.1",
           description = "Description of the app here.",
           executables = [Executable("foo.py")]
         )

I am sure it will work. I have tried it on both windows 7 as well as ubuntu 12.04

Spring Boot + JPA : Column name annotation ignored

you have to follow some naming strategy when you work with spring jpa. The column name should be in lowercase or uppercase.

@Column(name="TESTNAME")
private String testName;

or

@Column(name="testname")
private String testName;

keep in mind that, if you have your column name "test_name" format in the database then you have to follow the following way

@Column(name="TestName")
private String testName;

or

@Column(name="TEST_NAME")
private String testName;

or

@Column(name="test_name")
private String testName;

Directory.GetFiles: how to get only filename, not full path?

You can use System.IO.Path.GetFileName to do this.

E.g.,

string[] files = Directory.GetFiles(dir);
foreach(string file in files)
    Console.WriteLine(Path.GetFileName(file));

While you could use FileInfo, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles unless you need the additional functionality of the FileInfo class.

rsync - mkstemp failed: Permission denied (13)

If you're on a Raspberry pi or other Unix systems with sudo you need to tell the remote machine where rsync and sudo programs are located.

I put in the full path to be safe.

Here's my example:

rsync --stats -paogtrh --progress --omit-dir-times --delete --rsync-path='/usr/bin/sudo /usr/bin/rsync'  /mnt/drive0/ [email protected]:/mnt/drive0/

Difference between scaling horizontally and vertically for databases

Let's start with the need for scaling that is increasing resources so that your system can now handle more requests than it earlier could.

When you realise your system is getting slow and is unable to handle the current number of requests, you need to scale the system.

This provides you with two options. Either you increase the resources in the server which you are using currently, i.e, increase the amount of RAM, CPU, GPU and other resources. This is known as vertical scaling.

Vertical scaling is typically costly. It does not make the system fault tolerant, i.e if you are scaling application running with single server, if that server goes down, your system will go down. Also the amount of threads remains the same in vertical scaling. Vertical scaling may require your system to go down for a moment when process takes place. Increasing resources on a server requires a restart and put your system down.

Another solution to this problem is increasing the amount of servers present in the system. This solution is highly used in the tech industry. This will eventually decrease the request per second rate in each server. If you need to scale the system, just add another server, and you are done. You would not be required to restart the system. Number of threads in each system decreases leading to high throughput. To segregate the requests, equally to each of the application server, you need to add load balancer which would act as reverse proxy to the web servers. This whole system can be called as a single cluster. Your system may contain a large number of requests which would require more amount of clusters like this.

Hope you get the whole concept of introducing scaling to the system.

How To Pass GET Parameters To Laravel From With GET Method ?

The simplest way is just to accept the incoming request, and pull out the variables you want in the Controller:

Route::get('search', ['as' => 'search', 'uses' => 'SearchController@search']);

and then in SearchController@search:

class SearchController extends BaseController {

    public function search()
    {
        $category = Input::get('category', 'default category');
        $term = Input::get('term', false);

        // do things with them...
    }
}

Usefully, you can set defaults in Input::get() in case nothing is passed to your Controller's action.

As joe_archer says, it's not necessary to put these terms into the URL, and it might be better as a POST (in which case you should update your call to Form::open() and also your search route in routes.php - Input::get() remains the same)

Disabled href tag

Variant that suits me:

<script>
  function locker(){
    if ($("a").hasClass("locked")) {
         $("a").removeClass('locked').addClass('unlocked');
         $("a").attr("onClick","return false");
    } else {
         $("a").css("onclick","true");
         $("a").removeClass('unlocked').addClass('locked');
         $("a").attr("onClick","");
    }
  }
</script>

<button onclick="locker()">unlock</button>

<a href="http://some.site.com" class="locked">
  <div> 
      .... 
  <div>
</a>

Android emulator: How to monitor network traffic?

There are two ways to capture network traffic directly from an Android emulator:

  1. Copy and run an ARM-compatible tcpdump binary on the emulator, writing output to the SD card, perhaps (e.g. tcpdump -s0 -w /sdcard/emulator.cap).

  2. Run emulator -tcpdump emulator.cap -avd my_avd to write all the emulator's traffic to a local file on your PC

In both cases you can then analyse the pcap file with tcpdump or Wireshark as normal.

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

Abstract variables in Java?

No, Java doesn't support abstract variables. It doesn't really make a lot of sense, either.

What specific change to the "implementation" of a variable to you expect a sub class to do?

When I have a abstract String variable in the base class, what should the sub class do to make it non-abstract?

How can I get enum possible values in a MySQL database?

MySQL Reference

If you want to determine all possible values for an ENUM column, use SHOW COLUMNS FROM tbl_name LIKE enum_col and parse the ENUM definition in the Type column of the output.

You would want something like:

$sql = "SHOW COLUMNS FROM `table` LIKE 'column'";
$result = $db->query($sql);
$row = $result->fetchRow();
$type = $row['Type'];
preg_match('/enum\((.*)\)$/', $type, $matches);
$vals = explode(',', $matches[1]);

This will give you the quoted values. MySQL always returns these enclosed in single quotes. A single quote in the value is escaped by a single quote. You can probably safely call trim($val, "'") on each of the array elements. You'll want to convert '' into just '.

The following will return $trimmedvals array items without quotes:

$trimmedvals = array();
foreach($vals as $key => $value) {
$value=trim($value, "'");
$trimmedvals[] = $value;
}

Why are primes important in cryptography?

Because nobody knows a fast algorithm to factorize an integer into its prime factors. Yet, it is very easy to check if a set of prime factors multiply to a certain integer.

How to convert int to char with leading zeros?

Data type "int" cannot be more than 10 digits, additionally the "Len()" function works on ints, so there's no need to convert the int to a string before calling the len() function.

Lastly, you are not taking into account the case where the size of your int > the total number of digits you want it padded to (@intLen).

Therefore, a more concise / correct solution is:

CREATE FUNCTION rf_f_CIntToChar(@intVal Int, @intLen Int) RETURNS nvarchar(10)
AS
BEGIN
    IF @intlen > 20 SET @intlen = 20
    IF @intlen < LEN(@intVal) RETURN RIGHT(CONVERT(nvarchar(10), @intVal), @intlen)
    RETURN REPLICATE('0', @intLen - LEN(@intVal)) + CONVERT(nvarchar(10), @intVal)
END

Bad Request - Invalid Hostname IIS7

Check your local hosts file (C:\Windows\System32\drivers\etc\hosts for example). In my case I had previously used this to point a URL to a dev box and then forgotten about it. When I then reused the same URL I kept getting Bad Request (Invalid Hostname) because the traffic was going to the wrong server.

Writing MemoryStream to Response Object

First We Need To Write into our Memory Stream and then with the help of Memory Stream method "WriteTo" we can write to the Response of the Page as shown in the below code.

   MemoryStream filecontent = null;
   filecontent =//CommonUtility.ExportToPdf(inputXMLtoXSLT);(This will be your MemeoryStream Content)
   Response.ContentType = "image/pdf";
   string headerValue = string.Format("attachment; filename={0}", formName.ToUpper() + ".pdf");
   Response.AppendHeader("Content-Disposition", headerValue);

   filecontent.WriteTo(Response.OutputStream);

   Response.End();

FormName is the fileName given,This code will make the generated PDF file downloadable by invoking a PopUp.

Opening new window in HTML for target="_blank"

You don't have that kind of control with a bare a tag. But you can hook up the tag's onclick handler to call window.open(...) with the right parameters. See here for examples: https://developer.mozilla.org/En/DOM/Window.open

I still don't think you can force window over tab directly though-- that depends on the browser and the user's settings.

Convert spark DataFrame column to python list

A possible solution is using the collect_list() function from pyspark.sql.functions. This will aggregate all column values into a pyspark array that is converted into a python list when collected:

mvv_list   = df.select(collect_list("mvv")).collect()[0][0]
count_list = df.select(collect_list("count")).collect()[0][0] 

How to plot two histograms together in R?

That image you linked to was for density curves, not histograms.

If you've been reading on ggplot then maybe the only thing you're missing is combining your two data frames into one long one.

So, let's start with something like what you have, two separate sets of data and combine them.

carrots <- data.frame(length = rnorm(100000, 6, 2))
cukes <- data.frame(length = rnorm(50000, 7, 2.5))

# Now, combine your two dataframes into one.  
# First make a new column in each that will be 
# a variable to identify where they came from later.
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'

# and combine into your new data frame vegLengths
vegLengths <- rbind(carrots, cukes)

After that, which is unnecessary if your data is in long format already, you only need one line to make your plot.

ggplot(vegLengths, aes(length, fill = veg)) + geom_density(alpha = 0.2)

enter image description here

Now, if you really did want histograms the following will work. Note that you must change position from the default "stack" argument. You might miss that if you don't really have an idea of what your data should look like. A higher alpha looks better there. Also note that I made it density histograms. It's easy to remove the y = ..density.. to get it back to counts.

ggplot(vegLengths, aes(length, fill = veg)) + 
   geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')

enter image description here

Changing text color onclick

A rewrite of the answer by Sarfraz would be something like this, I think:

<script>

    document.getElementById('change').onclick = changeColor;   

    function changeColor() {
        document.body.style.color = "purple";
        return false;
    }   

</script>

You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );

Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc(); the function would actually execute when the handler is being set.

And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)

How to convert a string from uppercase to lowercase in Bash?

If you define your variable using declare (old: typeset) then you can state the case of the value throughout the variable's use.

$ declare -u FOO=AbCxxx
$ echo $FOO
ABCXXX

"-l" does lc.

Delete the last two characters of the String

An alternative solution would be to use some sort of regex:

for example:

    String s = "apple car 04:48 05:18 05:46 06:16 06:46 07:16 07:46 16:46 17:16 17:46 18:16 18:46 19:16";
    String results=  s.replaceAll("[0-9]", "").replaceAll(" :", ""); //first removing all the numbers then remove space followed by :
    System.out.println(results); // output 9
    System.out.println(results.length());// output "apple car"

How to modify JsonNode in Java?

You need to get ObjectNode type object in order to set values. Take a look at this

How to check cordova android version of a cordova/phonegap project?

Recent versions of Cordova have the version number in www/cordova.js.

How do I mock an open used in a with statement (using the Mock framework in Python)?

I might be a bit late to the game, but this worked for me when calling open in another module without having to create a new file.

test.py

import unittest
from mock import Mock, patch, mock_open
from MyObj import MyObj

class TestObj(unittest.TestCase):
    open_ = mock_open()
    with patch.object(__builtin__, "open", open_):
        ref = MyObj()
        ref.save("myfile.txt")
    assert open_.call_args_list == [call("myfile.txt", "wb")]

MyObj.py

class MyObj(object):
    def save(self, filename):
        with open(filename, "wb") as f:
            f.write("sample text")

By patching the open function inside the __builtin__ module to my mock_open(), I can mock writing to a file without creating one.

Note: If you are using a module that uses cython, or your program depends on cython in any way, you will need to import cython's __builtin__ module by including import __builtin__ at the top of your file. You will not be able to mock the universal __builtin__ if you are using cython.

How do I implement Toastr JS?

Toastr is a very nice component, and you can show messages with theses commands:

// for success - green box
toastr.success('Success messages');

// for errors - red box
toastr.error('errors messages');

// for warning - orange box
toastr.warning('warning messages');

// for info - blue box
toastr.info('info messages');

If you want to provide a title on the toastr message, just add a second argument:

// for info - blue box
toastr.success('The process has been saved.', 'Success');

you also can change the default behaviour using something like this:

toastr.options.timeOut = 3000; // 3s

See more on the github of the project.

Edits

A sample of use:

$(document).ready(function() {

    // show when page load
    toastr.info('Page Loaded!');

    $('#linkButton').click(function() {
       // show when the button is clicked
       toastr.success('Click Button');

    });

});

and a html:

<a id='linkButton'>Show Message</a>

Disabling tab focus on form elements

My case may not be typical but what I wanted to do was to have certain columns in a TABLE completely "inert": impossible to tab into them, and impossible to select anything in them. I had found class "unselectable" from other SO answers:

.unselectable {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

This actually prevents the user using the mouse to put the focus in the TD ... but I couldn't find a way on SO to prevent tabbing into cells. The TDs in my TABLE actually each has a DIV as their sole child, and using console.log I found that in fact the DIVs would get the focus (without the focus first being obtained by the TDs).

My solution involves keeping track of the "previously focused" element (anywhere on the page):

window.currFocus = document;
//Catch any bubbling focusin events (focus does not bubble)
$(window).on('focusin', function () {
  window.prevFocus = window.currFocus;
  window.currFocus = document.activeElement;
});

I can't really see how you'd get by without a mechanism of this kind... jolly useful for all sorts of purposes ... and of course it'd be simple to transform it into a stack of recently focused elements, if you wanted that...

The simplest answer is then just to do this (to the sole DIV child in every newly created TD):

...
jqNewCellDiv[ 0 ].classList.add( 'unselectable' );
jqNewCellDiv.focus( function() {
    window.prevFocus.focus();
});         

So far so good. It should be clear that this would work if you just have a TD (with no DIV child). Slight issue: this just stops tabbing dead in its tracks. Clearly if the table has any more cells on that row or rows below the most obvious action you'd want is to making tabbing tab to the next non-unselectable cell ... either on the same row or, if there are other rows, on the row below. If it's the very end of the table it gets a bit more tricky: i.e. where should tabbing go then. But all good clean fun.

Function to calculate distance between two coordinates

Great-circle distance - From chord length

Here's an elegant solution applying the strategy design pattern; I hope it's readable enough.

TwoPointsDistanceCalculatorStrategy.js:

module.exports = () =>

class TwoPointsDistanceCalculatorStrategy {

    constructor() {}

    calculateDistance({ point1Coordinates, point2Coordinates }) {}
};

GreatCircleTwoPointsDistanceCalculatorStrategy.js:

module.exports = ({ TwoPointsDistanceCalculatorStrategy }) =>

class GreatCircleTwoPointsDistanceCalculatorStrategy extends TwoPointsDistanceCalculatorStrategy {

    constructor() {
        super();
    }

    /**
     * Following the algorithm documented here: 
     * https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulas
     * 
     * @param {object} inputs
     * @param {array} inputs.point1Coordinates
     * @param {array} inputs.point2Coordinates
     * 
     * @returns {decimal} distance in kelometers
     */
    calculateDistance({ point1Coordinates, point2Coordinates }) {

        const convertDegreesToRadians = require('../convert-degrees-to-radians');
        const EARTH_RADIUS = 6371;   // in kelometers

        const [lat1 = 0, lon1 = 0] = point1Coordinates;
        const [lat2 = 0, lon2 = 0] = point2Coordinates;

        const radianLat1 = convertDegreesToRadians({ degrees: lat1 });
        const radianLon1 = convertDegreesToRadians({ degrees: lon1 });
        const radianLat2 = convertDegreesToRadians({ degrees: lat2 });
        const radianLon2 = convertDegreesToRadians({ degrees: lon2 });

        const centralAngle = _computeCentralAngle({ 
            lat1: radianLat1, lon1: radianLon1, 
            lat2: radianLat2, lon2: radianLon2, 
        });

        const distance = EARTH_RADIUS * centralAngle;

        return distance;
    }
};


/**
 * 
 * @param {object} inputs
 * @param {decimal} inputs.lat1
 * @param {decimal} inputs.lon1
 * @param {decimal} inputs.lat2
 * @param {decimal} inputs.lon2
 * 
 * @returns {decimal} centralAngle
 */
function _computeCentralAngle({ lat1, lon1, lat2, lon2 }) {

    const chordLength = _computeChordLength({ lat1, lon1, lat2, lon2 });
    const centralAngle = 2 * Math.asin(chordLength / 2);

    return centralAngle;
}


/**
 * 
 * @param {object} inputs
 * @param {decimal} inputs.lat1
 * @param {decimal} inputs.lon1
 * @param {decimal} inputs.lat2
 * @param {decimal} inputs.lon2
 * 
 * @returns {decimal} chordLength
 */
function _computeChordLength({ lat1, lon1, lat2, lon2 }) {

    const { sin, cos, pow, sqrt } = Math;

    const ?X = cos(lat2) * cos(lon2) - cos(lat1) * cos(lon1);
    const ?Y = cos(lat2) * sin(lon2) - cos(lat1) * sin(lon1);
    const ?Z = sin(lat2) - sin(lat1);

    const ?XSquare = pow(?X, 2);
    const ?YSquare = pow(?Y, 2);
    const ?ZSquare = pow(?Z, 2);

    const chordLength = sqrt(?XSquare + ?YSquare + ?ZSquare);

    return chordLength;
}

convert-degrees-to-radians.js:

module.exports = function convertDegreesToRadians({ degrees }) {

    return degrees * Math.PI / 180;
};

This's following the Great-circle distance - From chord length, documented here.

How do I check if an HTML element is empty using jQuery?

JavaScript

var el= document.querySelector('body'); 
console.log(el);
console.log('Empty : '+ isEmptyTag(el));
console.log('Having Children : '+ hasChildren(el));


function isEmptyTag(tag) { 
    return (tag.innerHTML.trim() === '') ? true : false ;
}
function hasChildren(tag) {
    //return (tag.childElementCount !== 0) ? true : false ; // Not For IE
    //return (tag.childNodes.length !== 0) ? true : false ; // Including Comments
    return (tag.children.length !== 0) ? true : false ; // Only Elements
}

try using any of this!

document.getElementsByTagName('div')[0];
document.getElementsByClassName('topbar')[0];

document.querySelectorAll('div')[0];
document.querySelector('div'); // gets the first element.
?

how to avoid extra blank page at end while printing?

Solution described here helped me (webarchive link).

First of all, you can add border to all elements to see what causes a new page to be appended (maybe some margins, paddings, etc).

div { border: 1px solid black;}

And the solution itself was to add the following styles:

html, body { height: auto; }

MySQL JDBC Driver 5.1.33 - Time Zone Issue

If you are using Maven, you can just set another MySQL connector version (I had the same error, so i changed from 6.0.2 to 5.1.39) in pom.xml:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>

As reported in another answers, this issue has been fixed in versions 6.0.3 or above, so you can use the updated version:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.3</version>
</dependency>

Maven will automatically re-build your project after you save the pom.xml file.

How to implement a ViewPager with different Fragments / Layouts

Create new instances in your fragments and do like so in your Activity

 private class SlidePagerAdapter extends FragmentStatePagerAdapter {
    public SlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch(position){
            case 0:
                return Fragment1.newInstance();
            case 1:
                return Fragment2.newInstance();
            case 2:
                return Fragment3.newInstance();
            case 3:
                return Fragment4.newInstance();


            default: break;

        }
        return null;
    }

How can I set an SQL Server connection string?

sa is a system administrator account which comes with SQL Server by default. As you know might already know, you can use two ways to log in to SQL Server.

screen shot of SQL Server Management Studio

Therefore there are connection strings which suitable for each scenario (such as Windows authentication, localdb, etc.). Use SQL Server Connection Strings for ASP.NET Web Applications to build your connection string. These are XML tags. You just need a value of connectionString.

Given URL is not allowed by the Application configuration

I was getting this error when trying to run my test web page directly from "file:///C:/webtests/myfile.htm". To fix it, I didn't have to make any changes to my App Settings. Instead, I just had to host my HTML file on an actual server and then hit it like: "http://localhost/myfile.htm".

Hope that helps someone.

How to check if spark dataframe is empty?

You can do it like:

val df = sqlContext.emptyDataFrame
if( df.eq(sqlContext.emptyDataFrame) )
    println("empty df ")
else 
    println("normal df")

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

It might be related to corruption in Angular Packages or incompatibility of packages.

Please follow the below steps to solve the issue.

Update

ASP.NET Boilerplate suggests here to use yarn because npm has some problems. It is slow and can not consistently resolve dependencies, yarn solves those problems and it is compatible to npm as well.

How to check if $? is not equal to zero in unix shell scripting?

put set -o pipefail at start of any script, to return any failure

incase you do, and the test fails but the tee doesnt. By default $? just takes the last commands success, in this case the "tee" command

test | tee /tmp/dump
[ $? -ne 0 ] && echo "failed"

Removing leading zeroes from a field in a SQL statement

You can use this:

SELECT REPLACE(LTRIM(REPLACE('000010A', '0', ' ')),' ', '0')

Disabling submit button until all fields have values

DEMO: http://jsfiddle.net/kF2uK/2/

function buttonState(){
    $("input").each(function(){
        $('#register').attr('disabled', 'disabled');
        if($(this).val() == "" ) return false;
        $('#register').attr('disabled', '');
    })
}

$(function(){
    $('#register').attr('disabled', 'disabled');
    $('input').change(buttonState);
})

Blocking device rotation on mobile web pages

Simple Javascript code to make mobile browser display either in portrait or landscape..

(Even though you have to enter html code twice in the two DIVs (one for each mode), arguably this will load faster than using javascript to change the stylesheet...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Mobile Device</title>
<script type="text/javascript">
// Detect whether device supports orientationchange event, otherwise fall back to
// the resize event.
var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    if(window.orientation==0)
    {
      document.getElementById('portrait').style.display = '';
      document.getElementById('landscape').style.display = 'none';
    }
    else if(window.orientation==90)
    {
      document.getElementById('portrait').style.display = 'none';
      document.getElementById('landscape').style.display = '';
    }
}, false);
</script>
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no" />
</head>
<body>
<div id="portrait" style="width:100%;height:100%;font-size:20px;">Portrait</div>
<div id="landscape" style="width:100%;height:100%;font-size:20px;">Landscape</div>

<script type="text/javascript">
if(window.orientation==0)
{
  document.getElementById('portrait').style.display = '';
  document.getElementById('landscape').style.display = 'none';
}
else if(window.orientation==90)
{
  document.getElementById('portrait').style.display = 'none';
  document.getElementById('landscape').style.display = '';
}
</script>
</body>
</html>

Tested and works on Android HTC Sense and Apple iPad.

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

How to force a hover state with jQuery?

You will have to use a class, but don't worry, it's pretty simple. First we'll assign your :hover rules to not only apply to physically-hovered links, but also to links that have the classname hovered.

a:hover, a.hovered { color: #ccff00; }

Next, when you click #btn, we'll toggle the .hovered class on the #link.

$("#btn").click(function() {
   $("#link").toggleClass("hovered");
});

If the link has the class already, it will be removed. If it doesn't have the class, it will be added.

"The page you are requesting cannot be served because of the extension configuration." error message

In case this helps anyone, I was getting this error when attempting to run aspnet_regiis.exe:

Operation failed with 0x8007000B

An attempt was made to load a program with an incorrect format

As it turns out, the server was running 2008 64 bit and I was trying to run the 32 bit version of the utility. Running the version found in \Windows\Microsoft.NET\Framework64\v2.0.50727 fixed the issue.

c:\Windows\Microsoft.NET\Framework64\v2.0.50727>aspnet_regiis.exe -i

Delete all rows in table

Truncate table is faster than delete * from XXX. Delete is slow because it works one row at a time. There are a few situations where truncate doesn't work, which you can read about on MSDN.

CSS Div width percentage and padding without breaking layout

You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.

An example:

width: calc((100%) - (32px))

Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.

_x000D_
_x000D_
.outer {_x000D_
  width: 200px;_x000D_
  height: 120px;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  height: 40px;_x000D_
  top: 30px;_x000D_
  position: relative;_x000D_
  padding: 16px;_x000D_
  background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
  width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
  <div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
  <div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Pure CSS multi-level drop-down menu

<div class="example" align="center">
    <div class="menuholder">
        <ul class="menu slide">
            <li><a href="index.php?id=1" class="blue">Home</a></li>
        <li><a href="index.php?id=14" class="blue">About Us</a></li>
            <li><a href="index.php?id=4" class="blue">Mens</a>
                <div class="subs">
                    <dl>
                        <dd><a href="index.php?id=15">Coats & Jackets</a></dd>
                        <dd><a href="index.php?id=22">Chinos</a></dd>
                        <dd><a href="index.php?id=23">Jeans</a></dd>
                        <dd><a href="index.php?id=24">Jumpers & Cardigans</a></dd>
                        <dd><a href="index.php?id=25">Linen</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=26">Polo Shirts</a></dd>
                        <dd><a href="index.php?id=16">Shirts Casual</a></dd>
                        <dd><a href="index.php?id=27">Shirts Formal</a></dd>
                        <dd><a href="index.php?id=28">Shorts</a></dd>
                        <dd><a href="index.php?id=18">Sportswear</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=19">Tops & T-Shirts</a></dd>
                        <dd><a href="index.php?id=20">Trousers Casual</a></dd>
                        <dd><a href="index.php?id=29">Trousers Formal</a></dd>
                        <dd><a href="index.php?id=30">Nightwear</a></dd>
                        <dd><a href="index.php?id=17">Socks</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=21">Underwear</a></dd>
                        <dd><a href="index.php?id=31">Swimwear</a></dd>
                    </dl>
                </div>
            </li>
            <!--menu-->
                        <li><a href="index.php?id=5" class="blue">Ladie's</a>
                <div class="subs">
                    <dl>
                          <dd><a href="index.php?id=32">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=33">Dresses</a></dd>
                          <dd><a href="index.php?id=34">Jeans</a></dd>
                          <dd><a href="index.php?id=35">Jumpers & Cardigans</a></dd>
                          <dd><a href="index.php?id=36">Jumpsuits</a></dd>
                    </dl>
                    <dl>
                        <dd><a href="index.php?id=37">Leggings & Jeggings</a></dd>
                          <dd><a href="index.php?id=38">Linen</a></dd>
                          <dd><a href="index.php?id=39">Lingerie & Underwear</a></dd>
                          <dd><a href="index.php?id=40">Maternity Wear</a></dd>
                          <dd><a href="index.php?id=41">Nightwear</a></dd>
                    </dl>
                    <dl>
                     <dd><a href="index.php?id=42">Shorts</a></dd>
                          <dd><a href="index.php?id=43">Skirts</a></dd>
                          <dd><a href="index.php?id=44">Sportswear</a></dd>
                          <dd><a href="index.php?id=45">Suits & Tailoring</a></dd>
                          <dd><a href="index.php?id=46">Swimwear & Beachwear</a></dd>
                    </dl>
                    <dl>
                          <dd><a href="index.php?id=47">Thermals</a></dd>
                          <dd><a href="index.php?id=48">Tops & T-Shirts</a></dd>
                          <dd><a href="index.php?id=49">Trousers & Chinos</a></dd>
                          <dd><a href="index.php?id=50">Socks</a></dd>
                    </dl>
                </div>
            </li><!--menu end-->
                        <!--menu-->
                        <li><a href="index.php?id=7" class="blue">Girls</a>
                <div class="subs">
                    <dl>
                            <dd><a href="index.php?id=51">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=52">Dresses</a></dd>
                          <dd><a href="index.php?id=53">Jeans</a></dd>
                          <dd><a href="index.php?id=54">Joggers & Sweatshirts</a></dd>
                          <dd><a href="index.php?id=55">Jumpers & Cardigans</a></dd>
                    </dl>
                    <dl>
                                <dd><a href="index.php?id=56">Jumpsuits & Playsuits</a></dd>
                              <dd><a href="index.php?id=57">Leggings</a></dd>
                              <dd><a href="index.php?id=58">Nightwear</a></dd>
                              <dd><a href="index.php?id=59">Shorts</a></dd>
                              <dd><a href="index.php?id=60">Skirts</a></dd>
                    </dl>
                    <dl>
                              <dd><a href="index.php?id=61">Swimwear</a></dd>
                              <dd><a href="index.php?id=62">Tops & T-Shirts</a></dd>
                              <dd><a href="index.php?id=63">Trousers & Jeans</a></dd>
                              <dd><a href="index.php?id=64">Socks</a></dd>
                              <dd><a href="index.php?id=65">Underwear</a></dd>
                    </dl>
                    <dl>

                    </dl>
                </div>
            </li><!--menu end-->
                            <!--menu-->
                        <li><a href="index.php?id=8" class="blue">Boys</a>
                <div class="subs">
                    <dl>
                        <dd><a href="index.php?id=66">Coats & Jackets</a></dd>
                          <dd><a href="index.php?id=67">Jeans</a></dd>
                          <dd><a href="index.php?id=68">Joggers & Sweatshirts</a></dd>
                          <dd><a href="index.php?id=69">Jumpers & Cardigans</a></dd>
                          <dd><a href="index.php?id=70">Nightwear</a></dd>
                    </dl>
                    <dl>
                            <dd><a href="index.php?id=71">Shirts</a></dd>
                          <dd><a href="index.php?id=72">Shorts</a></dd>
                          <dd><a href="index.php?id=73">Sportswear</a></dd>
                          <dd><a href="index.php?id=74">Swimwear</a></dd>
                          <dd><a href="index.php?id=75">T-Shirts & Polo Shirts</a></dd>
                    </dl>
                    <dl>
                          <dd><a href="index.php?id=76">Trousers & Jeans</a></dd>
                          <dd><a href="index.php?id=77">Socks</a></dd>
                          <dd><a href="index.php?id=78">Underwear</a></dd>
                    </dl>
                    <dl>

                    </dl>
                </div>
            </li><!--menu end-->
            <!--menu-->
             <li><a href="index.php?id=9" class="blue">Toddlers</a>
                <div class="subs">
                    <dl>
                      <dd><a href="index.php?id=79">Newborn</a></dd>
                      <dd><a href="index.php?id=80">0-2 Years</a></dd>
                    </dl>                 
                </div>
            </li><!--menu end-->
            <!--menu-->
             <li><a href="index.php?id=10" class="blue">Accessories</a>
                <div class="subs">
                    <dl>
                          <dd><a href="index.php?id=81">Shoes</a></dd>
                          <dd><a href="index.php?id=82">Ties</a></dd>
                          <dd><a href="index.php?id=83">Caps</a></dd>
                          <dd><a href="index.php?id=84">Belts</a></dd>
                    </dl>                 
                </div>
            </li><!--menu end-->
            <li><a href="index.php?id=13" class="blue">Contact Us</a></li>
        </ul>
        <div class="back"></div>
        <div class="shadow"></div>
    </div>
    <div style="clear:both"></div>
</div>

CSS 3 Coding- Copy and Paste

<style>

body{margin:0px;}
.example {
    width:980px;
    height:40px;
    margin:0px auto;
 position:absolute;
 margin-bottom:60px;
 top:95px;
}

.menuholder {
    float:left;
    font:normal bold 11px/35px verdana, sans-serif;
    overflow:hidden;
    position:relative;
}
.menuholder .shadow {
    -moz-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    -o-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    -webkit-box-shadow:0 0 20px rgba(0, 0, 0, 1);
    background:#888;
    box-shadow:0 0 20px rgba(0, 0, 0, 1);
    height:10px;
    left:5%;
    position:absolute;
    top:-9px;
    width:100%;
    z-index:100;
}
.menuholder .back {
    -moz-transition-duration:.4s;
    -o-transition-duration:.4s;
    -webkit-transition-duration:.4s;
    background-color:rgba(0, 0, 0, 0.88);
    height:0;
    width:980px; /*100%*/
}
.menuholder:hover div.back {
    height:280px;
}
ul.menu {
    display:block;
    float:left;
    list-style:none;
    margin:0;
    padding:0 125px;
    position:relative;
}
ul.menu li {
    float:left;
    margin:0 10px 0 0;
}
ul.menu li > a {
    -moz-border-radius:0 0 10px 10px;
    -moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -moz-transition:all 0.3s ease-in-out;
    -o-border-radius:0 0 10px 10px;
    -o-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -o-transition:all 0.3s ease-in-out;
    -webkit-border-bottom-left-radius:10px;
    -webkit-border-bottom-right-radius:10px;
    -webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    -webkit-transition:all 0.3s ease-in-out;
    border-radius:0 0 10px 10px;
    box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
    color:#eee;
    display:block;
    padding:0 10px;
    text-decoration:none;
    transition:all 0.3s ease-in-out;
}
ul.menu li a.red {
    background:#a00;
}
ul.menu li a.orange {
    background:#da0;
}
ul.menu li a.yellow {
    background:#aa0;
}
ul.menu li a.green {
    background:#060;
}
ul.menu li a.blue {
    background:#073263;
}
ul.menu li a.violet {
    background:#682bc2;
}
.menu li div.subs {
    left:0;
    overflow:hidden;
    position:absolute;
    top:35px;
    width:0;
}
.menu li div.subs dl {
    -moz-transition-duration:.2s;
    -o-transition-duration:.2s;
    -webkit-transition-duration:.2s;
    float:left;
    margin:0 130px 0 0;
    overflow:hidden;
    padding:40px 0 5% 2%;
    width:0;
}
.menu dt {
    color:#fc0;
    font-family:arial, sans-serif;
    font-size:12px;
    font-weight:700;
    height:20px;
    line-height:20px;
    margin:0;
    padding:0 0 0 10px;
    white-space:nowrap;
}
.menu dd {
    margin:0;
    padding:0;
    text-align:left;
}
.menu dd a {
    background:transparent;
    color:#fff;
    font-size:12px;
    height:20px;
    line-height:20px;
    padding:0 0 0 10px;
    text-align:left;
    white-space:nowrap;
    width:80px;
}
.menu dd a:hover {
    color:#fc0;
}
.menu li:hover div.subs dl {
    -moz-transition-delay:0.2s;
    -o-transition-delay:0.2s;
    -webkit-transition-delay:0.2s;
    margin-right:2%;
    width:21%;
}
ul.menu li:hover > a,ul.menu li > a:hover {
    background:#aaa;
    color:#fff;
    padding:10px 10px 0;
}
ul.menu li a.red:hover,ul.menu li:hover a.red {
    background:#c00;
}
ul.menu li a.orange:hover,ul.menu li:hover a.orange {
    background:#fc0;
}
ul.menu li a.yellow:hover,ul.menu li:hover a.yellow {
    background:#cc0;
}
ul.menu li a.green:hover,ul.menu li:hover a.green {
    background:#080;
}
ul.menu li a.blue:hover,ul.menu li:hover a.blue {
    background:#00c;
}
ul.menu li a.violet:hover,ul.menu li:hover a.violet {
background:#8a2be2;
}
.menu li:hover div.subs,.menu li a:hover div.subs {
    width:100%;
}

Uses for the '&quot;' entity in HTML

It is likely because they used a single function for escaping attributes and text nodes. &amp; doesn't do any harm so why complicate your code and make it more error-prone by having two escaping functions and having to pick between them?

How to check if iframe is loaded or it has a content?

Try this.

<script>
function checkIframeLoaded() {
    // Get a handle to the iframe element
    var iframe = document.getElementById('i_frame');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if loading is complete
    if (  iframeDoc.readyState  == 'complete' ) {
        //iframe.contentWindow.alert("Hello");
        iframe.contentWindow.onload = function(){
            alert("I am loaded");
        };
        // The loading is complete, call the function we want executed once the iframe is loaded
        afterLoading();
        return;
    } 

    // If we are here, it is not loaded. Set things up so we check   the status again in 100 milliseconds
    window.setTimeout(checkIframeLoaded, 100);
}

function afterLoading(){
    alert("I am here");
}
</script>

<body onload="checkIframeLoaded();"> 

How do I serialize a C# anonymous type to a JSON string?

You could use Newtonsoft.Json.

var warningJSON = JsonConvert.SerializeObject(new {
                warningMessage = "You have been warned..."
            });

Remove all padding and margin table HTML and CSS

I find the most perfectly working answer is this

.noBorder {
    border: 0px;
    padding:0; 
    margin:0;
    border-collapse: collapse;
}

How to find a min/max with Ruby

In addition to the provided answers, if you want to convert Enumerable#max into a max method that can call a variable number or arguments, like in some other programming languages, you could write:

def max(*values)
 values.max
end

Output:

max(7, 1234, 9, -78, 156)
=> 1234

This abuses the properties of the splat operator to create an array object containing all the arguments provided, or an empty array object if no arguments were provided. In the latter case, the method will return nil, since calling Enumerable#max on an empty array object returns nil.

If you want to define this method on the Math module, this should do the trick:

module Math
 def self.max(*values)
  values.max
 end
end

Note that Enumerable.max is, at least, two times slower compared to the ternary operator (?:). See Dave Morse's answer for a simpler and faster method.

Read entire file in Scala?

you can also use Path from scala io to read and process files.

import scalax.file.Path

Now you can get file path using this:-

val filePath = Path("path_of_file_to_b_read", '/')
val lines = file.lines(includeTerminator = true)

You can also Include terminators but by default it is set to false..

Send raw ZPL to Zebra printer via USB

Install an share your printer: \localhost\zebra Send ZPL as text, try with copy first:

copy file.zpl \localhost\zebra

very simple, almost no coding.

Returning Promises from Vuex actions

Just for an information on a closed topic: you don’t have to create a promise, axios returns one itself:

Ref: https://forum.vuejs.org/t/how-to-resolve-a-promise-object-in-a-vuex-action-and-redirect-to-another-route/18254/4

Example:

    export const loginForm = ({ commit }, data) => {
      return axios
        .post('http://localhost:8000/api/login', data)
        .then((response) => {
          commit('logUserIn', response.data);
        })
        .catch((error) => {
          commit('unAuthorisedUser', { error:error.response.data });
        })
    }

Another example:

    addEmployee({ commit, state }) {       
      return insertEmployee(state.employee)
        .then(result => {
          commit('setEmployee', result.data);
          return result.data; // resolve 
        })
        .catch(err => {           
          throw err.response.data; // reject
        })
    }

Another example with async-await

    async getUser({ commit }) {
        try {
            const currentUser = await axios.get('/user/current')
            commit('setUser', currentUser)
            return currentUser
        } catch (err) {
            commit('setUser', null)
            throw 'Unable to fetch current user'
        }
    },

AngularJS: How to clear query parameters in the URL?

The accepted answer worked for me, but I needed to dig a little deeper to fix the problems with the back button.

What I noticed is that if I link to a page using <a ui-sref="page({x: 1})">, then remove the query string using $location.search('x', null), I don't get an extra entry in my browser history, so the back button takes me back to where I started. Although I feel like this is wrong because I don't think that Angular should automatically remove this history entry for me, this is actually the desired behaviour for my particular use-case.

The problem is that if I link to the page using <a href="/page/?x=1"> instead, then remove the query string in the same way, I do get an extra entry in my browser history, so I have to click the back button twice to get back to where I started. This is inconsistent behaviour, but actually this seems more correct.

I can easily fix the problem with href links by using $location.search('x', null).replace(), but then this breaks the page when you land on it via a ui-sref link, so this is no good.

After a lot of fiddling around, this is the fix I came up with:

In my app's run function I added this:

$rootScope.$on('$locationChangeSuccess', function () {
    $rootScope.locationPath = $location.path();
});

Then I use this code to remove the query string parameter:

$location.search('x', null);

if ($location.path() === $rootScope.locationPath) {
    $location.replace();
}

How to do the Recursive SELECT query in MySQL?

The accepted answer by @Meherzad only works if the data is in a particular order. It happens to work with the data from the OP question. In my case, I had to modify it to work with my data.

Note This only works when every record's "id" (col1 in the question) has a value GREATER THAN that record's "parent id" (col3 in the question). This is often the case, because normally the parent will need to be created first. However if your application allows changes to the hierarchy, where an item may be re-parented somewhere else, then you cannot rely on this.

This is my query in case it helps someone; note it does not work with the given question because the data does not follow the required structure described above.

select t.col1, t.col2, @pv := t.col3 col3
from (select * from table1 order by col1 desc) t
join (select @pv := 1) tmp
where t.col1 = @pv

The difference is that table1 is being ordered by col1 so that the parent will be after it (since the parent's col1 value is lower than the child's).

Start new Activity and finish current one in Android?

You can use finish() method or you can use:

android:noHistory="true"

And then there is no need to call finish() anymore.

<activity android:name=".ClassName" android:noHistory="true" ... />

Div show/hide media query

I'm not sure, what you mean as the 'mobile width'. But in each case, the CSS @media can be used for hiding elements in the screen width basis. See some example:

<div id="my-content"></div>

...and:

@media screen and (min-width: 0px) and (max-width: 400px) {
  #my-content { display: block; }  /* show it on small screens */
}

@media screen and (min-width: 401px) and (max-width: 1024px) {
  #my-content { display: none; }   /* hide it elsewhere */
}

Some truly mobile detection is kind of hard programming and rather difficult. Eventually see the: http://detectmobilebrowsers.com/ or other similar sources.

Using sed, how do you print the first 'N' characters of a line?

Don't use sed, use cut:

grep .... | cut -c 1-N

If you MUST use sed:

grep ... | sed -e 's/^\(.\{12\}\).*/\1/'

Why does 2 mod 4 = 2?

Modulo is the remainder, not division.

2 / 4 = 0R2
2 % 4 = 2

The sign % is often used for the modulo operator, in lieu of the word mod.

For x % 4, you get the following table (for 1-10)

 x x%4
------
 1  1
 2  2
 3  3
 4  0
 5  1
 6  2
 7  3
 8  0
 9  1
10  2

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

anaconda - graphviz - can't import after installation

To install graphviz,

conda install -c anaconda graphviz
pip install graphviz

If conda command not found. Follow these:

export PATH=~/anaconda/bin:$PATH
conda --version # to check your conda version

Difference between conda and pip installation,
refer this stackoverflow answer

Autocompletion of @author in Intellij

One more option, not exactly what you asked, but can be useful:

Go to Settings -> Editor -> File and code templates -> Includes tab (on the right). There is a template header for the new files, you can use the username here:

/**
 * @author myname
 */

For system username use:

/**
 * @author ${USER}
 */

Screen shot from Intellij 2016.02