Programs & Examples On #Routedata

Get current controller in view

You are still in the context of your CategoryController even though you're loading a PartialView from your Views/News folder.

Mock HttpContext.Current in Test Init Method

Below Test Init will also do the job.

[TestInitialize]
public void TestInit()
{
  HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
  YourControllerToBeTestedController = GetYourToBeTestedController();
}

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

I found a solution for ajax issue noted by Lion_cl.

global.asax:

protected void Application_Error()
    {           
        if (HttpContext.Current.Request.IsAjaxRequest())
        {
            HttpContext ctx = HttpContext.Current;
            ctx.Response.Clear();
            RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
            rc.RouteData.Values["action"] = "AjaxGlobalError";

            // TODO: distinguish between 404 and other errors if needed
            rc.RouteData.Values["newActionName"] = "WrongRequest";

            rc.RouteData.Values["controller"] = "ErrorPages";
            IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
            IController controller = factory.CreateController(rc, "ErrorPages");
            controller.Execute(rc);
            ctx.Server.ClearError();
        }
    }

ErrorPagesController

public ActionResult AjaxGlobalError(string newActionName)
    {
        return new AjaxRedirectResult(Url.Action(newActionName), this.ControllerContext);
    }

AjaxRedirectResult

public class AjaxRedirectResult : RedirectResult
{
    public AjaxRedirectResult(string url, ControllerContext controllerContext)
        : base(url)
    {
        ExecuteResult(controllerContext);
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            JavaScriptResult result = new JavaScriptResult()
            {
                Script = "try{history.pushState(null,null,window.location.href);}catch(err){}window.location.replace('" + UrlHelper.GenerateContentUrl(this.Url, context.HttpContext) + "');"
            };

            result.ExecuteResult(context);
        }
        else
        {
            base.ExecuteResult(context);
        }
    }
}

AjaxRequestExtension

public static class AjaxRequestExtension
{
    public static bool IsAjaxRequest(this HttpRequest request)
    {
        return (request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest");
    }
}

HttpContext.Current.Session is null when routing requests

The config section seems sound as it works if when pages are accessed normally. I've tried the other configurations suggested but the problem is still there.

I doubt the problem is in the Session provider since it works without the routing.

How can I align button in Center or right using IONIC framework?

Ultimately, we are trying to get to this.

<div style="display: flex; justify-content: center;">
    <button ion-button>Login</button>
</div>

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

By deleting all emulator, sometime memory will not be reduce to our expectation. So open below mention path in you c drive

C:\Users{Username}.android\avd

In this avd folder, you can able to see all the avd's which you created earlier. So you need to delete all avd's that will remove all the unused spaces grab by your emulator's. Than create the fresh emulator for you works.

Calling jQuery method from onClick attribute in HTML

Don't do this!

Stay away from putting the events inline with the elements! If you don't, you're missing the point of JQuery (or one of the biggest ones at least).

The reason why it's easy to define click() handlers one way and not the other is that the other way is simply not desirable. Since you're just learning JQuery, stick to the convention. Now is not the time in your learning curve for JQuery to decide that everyone else is doing it wrong and you have a better way!

How does the "this" keyword work?

this use for Scope just like this

  <script type="text/javascript" language="javascript">
$('#tbleName tbody tr').each(function{
var txt='';
txt += $(this).find("td").eq(0).text();
\\same as above but synatx different
var txt1='';
 txt1+=$('#tbleName tbody tr').eq(0).text();
alert(txt1)
});
</script>

value of txt1 and txt is same in Above example $(this)=$('#tbleName tbody tr') is Same

Static way to get 'Context' in Android?

No, I don't think there is. Unfortunately, you're stuck calling getApplicationContext() from Activity or one of the other subclasses of Context. Also, this question is somewhat related.

How to access Anaconda command prompt in Windows 10 (64-bit)

After installing Anaconda3 on your system you need to add Anaconda to the PATH environment variable. This will allow you to access Anaconda with the 'conda' command from cmd.exe or PowerShell.

The link I provided below go through the three major issues with not recognized error. Which are:

  1. Environment PATH for Conda is not set
  2. Environment PATH is incorrectly added
  3. Anaconda version is older than the version of the Anaconda Navigator

LINK: https://appuals.com/fix-conda-is-not-recognized-as-an-internal-or-external-command-operable-program-or-batch-file/

My issue was resolved following the steps for issue #2 Environment PATH is incorrectly added. I did not have all three file paths in my variable environment.

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

How to avoid 'undefined index' errors?

Figure out what keys are in the $output array, and fill the missing ones in with empty strings.

$keys = array_keys($output);
$desired_keys = array('author', 'new_icon', 'admin_link', 'etc.');

foreach($desired_keys as $desired_key){
   if(in_array($desired_key, $keys)) continue;  // already set
   $output[$desired_key] = '';
}

Remove a specific character using awk or sed

Use sed's substitution: sed 's/"//g'

s/X/Y/ replaces X with Y.

g means all occurrences should be replaced, not just the first one.

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

Alter and Assign Object Without Side Effects

Try this instead:

var myArray = [];

myArray.push({ id: 0, value: 1 });
myArray.push({ id: 2, value: 3 });

or will this not work for your situation?

SQL Server 2000: How to exit a stored procedure?

Its because you have no BEGIN and END statements. You shouldn't be seeing the prints, or errors running this statement, only Statement Completed (or something like that).

for loop in Python

If you want to write a loop in Python which prints some integer no etc, then just copy and paste this code, it'll work a lot

# Display Value from 1 TO 3  
for i in range(1,4):
    print "",i,"value of loop"

# Loop for dictionary data type
  mydata = {"Fahim":"Pakistan", "Vedon":"China", "Bill":"USA"  }  
  for user, country in mydata.iteritems():
    print user, "belongs to " ,country

pass **kwargs argument to another function with **kwargs

The ** syntax tells Python to collect keyword arguments into a dictionary. The save2 is passing it down as a non-keyword argument (a dictionary object). The openX is not seeing any keyword arguments so the **args doesn't get used. It's instead getting a third non-keyword argument (the dictionary). To fix that change the definition of the openX function.

def openX(filename, mode, kwargs):
    pass

Group query results by month and year in postgresql

I can't believe the accepted answer has so many upvotes -- it's a horrible method.

Here's the correct way to do it, with date_trunc:

   SELECT date_trunc('month', txn_date) AS txn_month, sum(amount) as monthly_sum
     FROM yourtable
 GROUP BY txn_month

It's bad practice but you might be forgiven if you use

 GROUP BY 1

in a very simple query.

You can also use

 GROUP BY date_trunc('month', txn_date)

if you don't want to select the date.

How do I get the full path to a Perl script that is executing?

Have you tried:

$ENV{'SCRIPT_NAME'}

or

use FindBin '$Bin';
print "The script is located in $Bin.\n";

It really depends on how it's being called and if it's CGI or being run from a normal shell, etc.

Save matplotlib file to a directory

You can use the following code

name ='mypic'
plt.savefig('path_to_file/{}'.format(name))

If you want to save in same folder where your code lies,ignore the path_to_file and just format with name. If you have folder name 'Images' in the just one level outside of your python script, you can use,

name ='mypic'
plt.savefig('Images/{}'.format(name))

The default file type in saving is '.png' file format. If you want to save in loop, then you can use the unique name for each file such as counter of the for loop. If i is the counter,

plt.savefig('Images/{}'.format(i))

Hope this helps.

Auto height div with overflow and scroll when needed

Try this:
CSS:

#content {
  margin: 0 auto;
  border: 1px solid red;
  width:800px;
  position:absolute;
  bottom:0px;
  top:0px;
  overflow:auto
}

HTML:

<body>
<div id="content">
...content goes here...
</div>
<body>

If you don't like absolute positioning in this case, just can play with making a parent and child div to this one, both with position:relative.

EDIT: Below should work (I just put the css inline for the moment):

<div style="margin:0 auto; width:800px; height:100%; overflow:hidden">
<div style="border: 1px solid red; width:800px; position:absolute; bottom:0px; top:0px; overflow:auto">
...content goes here...
</div>
</div>

Adding to the classpath on OSX

To specify a classpath for a single Java process, you can add a classpath option when you run the Java command.

In you command line. Use java -cp "path/to/your/jar:." main rather than just java main

The option tells Java where to search for libraries.

What's the difference between ISO 8601 and RFC 3339 Date Formats?

You shouldn't have to care that much. RFC 3339, according to itself, is a set of standards derived from ISO 8601. There's quite a few minute differences though, and they're all outlined in RFC 3339. I could go through them all here, but you'd probably do better just reading the document for yourself in the event you're worried:

http://tools.ietf.org/html/rfc3339

Undefined reference to static class member

Regarding the second question: push_ref takes reference as a parameter, and you cannot have a reference to static const memeber of a class/struct. Once you call static_cast, a temporary variable is created. And a reference to this object can be passed, everything works just fine.

Or at least my colleague who resolved this said so.

Generate a random double in a range

This question was asked before Java 7 release but now, there is another possible way using Java 7 (and above) API:

double random = ThreadLocalRandom.current().nextDouble(min, max);

nextDouble will return a pseudorandom double value between the minimum (inclusive) and the maximum (exclusive). The bounds are not necessarily int, and can be double.

Get Line Number of certain phrase in file Python

listStr = open("file_name","mode")

if "search element" in listStr:
    print listStr.index("search element")  # This will gives you the line number

Custom domain for GitHub project pages

I just discovered, after a bit of frustration, that if you're using PairNIC, all you have to do is enable the "Web Forwarding" setting under "Custom DNS" and supply the username.github.io/project address and it will automatically set up both the apex and subdomain records for you. It appears to do exactly what's suggested in the accepted answer. However, it won't let you do the exact same thing by manually adding records. Very strange. Anyway, it took me a while to figure that out, so I thought I'd share to save everyone else the trouble.

Is there a Java API that can create rich Word documents?

After a little more research, I came across iText, a PDF and RTF-file creation API. I think I can use the RTF generation to create a Doc-readable file that can then be edited using Doc and re-saved.

Anyone have any experience with iText, used in this fashion?

How to add a scrollbar to an HTML5 table?

A year or so has passed since the question was asked, but I wasn't satisfied with the answers. I fiddled for a while, and here is a code that:

  • works in IE8+ and all other browsers;
  • is very easy to understand;
  • lines up the cell borders perfectly (fixed-width cells);
  • fixes the head while the body scrolls;
  • automatically adapts to touch screens.

Live demo here: http://jsbin.com/bagaro/1/edit?html,output.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Scrollabe table</title>
    <!-- Substantially simplified and improved version of the table on
    http://www.cssbakery.com/2010/12/css-scrolling-tables-with-fixed.html -->
    <script>
        if ('ontouchstart' in window || (window.DocumentTouch && document instanceof DocumentTouch)) {
            document.documentElement.className += ' touchScreen';
        }
    </script>
    <style>
        /* BASICS: */
    * {
        padding: 0;
        margin: 0;
        box-sizing: border-box; /* in case block elements are used inside table cells */
    }
    html {
        font-size: 62.5%; /* standardizes older IEs */
    }
    body {
        font: normal 1.3em Verdana; /* = 13px */
    }
    table {
        border-collapse: collapse;
        table-layout: fixed;
        empty-cells: show;
    }
    td {
        border: 1px solid black;
        padding: 4px;
    }
        /* SCROLL TABLE ESSENTIALS (+ SOME ADDITIONAL CSS): */
    div#scrollTableContainer {
        width: 617px;
        margin: 40px; /* just for presentation purposes */
        border: 1px solid black;
    }
    .touchScreen div#scrollTableContainer {
        width: 600px; /* touch devices do not form scrollbars (= 17 px wide) */
    }
    #tHeadContainer {
        background: #CC3600;
        color: white;
        font-weight: bold;
    }
    #tBodyContainer {
        height: 240px;
        overflow-y: scroll;
    }
    .touchScreen #tBodyContainer {
        -webkit-overflow-scrolling: touch; /* smooths scrolling on touch screens */
    }
        /* FINER LAYOUT MATTERS: */
    tr:first-child td {
        border-top: 0;
    }
    #tBody tr.lastRow td {
        border-bottom: 0;
    }
    td:first-child {
        min-width: 108px; /* Firefox needs min- and max-widths */
        max-width: 108px;
        border-left: 0;
    }
    td:first-child + td {
        min-width: 125px;
        max-width: 125px;
    }
    td:first-child + td + td {
        min-width: 90px;
        max-width: 90px;
    }
    td:first-child + td + td + td {
        min-width: 95px;
        max-width: 95px;
    }
    td:first-child + td + td + td + td {
        width: 180px; /* here, Firefox messes up with only min- and max-widths */
        border-right: 0;
    }
        /* AND SOME CSS TO INFORM TOUCH SCREEN USERS: */
    p#touchDeviceText {
        display: none;
    }
    .touchScreen p#touchDeviceText {
        display: block;
    }
    </style>
</head>
<body>
    <p id="touchDeviceText">This table is scrollable</p>
    <div id="scrollTableContainer">
        <div id="tHeadContainer">
            <table id="tHead">
                <tr>
                    <td>Name</td>
                    <td>Operator</td>
                    <td>Began operation</td>
                    <td>Tonnage</td>
                    <td>Status</td>
                </tr>
            </table>
        </div><!-- tHeadContainer -->
        <div id="tBodyContainer">
            <table id="tBody">
                <tr>
                    <td>Seabourne Sun</td>
                    <td>Seabourn Cruise Line</td>
                    <td>1988</td>
                    <td>?</td>
                    <td>Ended service in 2002, currently operating as Prinsendam</td>
                </tr>
                <tr>
                    <td>Adventures of the Seas</td>
                    <td>Royal Caribbean International</td>
                    <td>2001</td>
                    <td>138,000</td>
                    <td>Operating</td>
                </tr>
                <tr>
                    <td>Oceanic Independence</td>
                    <td>American Hawaiian Cruises / American Global Line</td>
                    <td>1974</td>
                    <td>23,719</td>
                    <td>Named formerly (1951-1974) and subsequently renamed (1982-2006) the Independence, renamed the Oceanic (2006), sold for scrap in 2008 but remains in mothballs</td>
                </tr>
                <tr>
                    <td>Cunard Ambassador</td>
                    <td>Cunard Line</td>
                    <td>1972</td>
                    <td>14,160</td>
                    <td>Burnt 1974, rebuilt into a livestock carrier, renamed Linda Clausen, later Procyon, Raslan. Scrapped 1984 after a second fire.</td>
                </tr>
                <tr>
                    <td>Aegean Beauty</td>
                    <td>Voyages to Antiquity</td>
                    <td>1973</td>
                    <td>11,563</td>
                    <td>Formerly Aegean Dolphin and Aegean I. Operating</td>
                </tr>
                <tr>
                    <td>Serenade of the Seas</td>
                    <td>Royal Caribbean International</td>
                    <td>2003</td>
                    <td>90,090</td>
                    <td>Operating</td>
                </tr>
                <tr>
                    <td>Queen Elizabeth 2</td>
                    <td>Cunard Line</td>
                    <td>1969</td>
                    <td>70,327</td>
                    <td>Left fleet in November 2008</td>
                </tr>
                <tr>
                    <td>National Geographic Endeavour</td>
                    <td>Lindblad Expeditions</td>
                    <td>1996</td>
                    <td></td>
                    <td>Operating, also known as Endeavour</td>
                </tr>
                <tr class="lastRow">
                    <td>Liberty of the Seas</td>
                    <td>Royal Caribbean International</td>
                    <td>2007</td>
                    <td>154,407</td>
                    <td>Operating</td>
                </tr>
            </table>
        </div><!-- tBodyContainer -->
    </div><!-- scrollTableContainer -->
</body>
</html>

X11/Xlib.h not found in Ubuntu

Presume he's using the tutorial from http://www.arcsynthesis.org/gltut/ along with premake4.3 :-)

sudo apt-get install libx11-dev ................. for X11/Xlib.h
sudo apt-get install mesa-common-dev........ for GL/glx.h
sudo apt-get install libglu1-mesa-dev ..... for GL/glu.h
sudo apt-get install libxrandr-dev ........... for X11/extensions/Xrandr.h
sudo apt-get install libxi-dev ................... for X11/extensions/XInput.h

After which I could build glsdk_0.4.4 and examples without further issue.

CSS Background Image Not Displaying

Basically the problem is with file path. The forward slash in the beginning of the url makes it look for the file at the root. Removing that, it will be a path relative to this css file - like this: background-image: url(img/debut_dark.png);

If you are using Atom, copying the project path of image sometimes includes forward slash in the copied path so be careful.

How to copy and paste code without rich text formatting?

Just for reference, under Mac OS X, you can use ? Command+? Shift+? Shift+V to paste without formatting or with the "current" format.

Note: in some apps it's ? Command+? Shift+? Alt+V (see "Edit" Menu ? "Paste and Match Style")

Use PPK file in Mac Terminal to connect to remote connection over SSH

There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.

Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.

Copy the PEM file to your Mac and set it to be read-only by your user:

chmod 400 <private-key-filename>.pem

Then you should be able to use ssh to connect to your remote server

ssh -i <private-key-filename>.pem username@hostname

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

In my case here is what I did to cause the diverged message: I did git push but then did git commit --amend to add something to the commit message. Then I also did another commit.

So in my case that simply meant origin/master was out of date. Because I knew no-one else was touching origin/master, the fix was trivial: git push -f (where -f means force)

SQL join: selecting the last records in a one-to-many relationship

Please try this,

SELECT 
c.Id,
c.name,
(SELECT pi.price FROM purchase pi WHERE pi.Id = MAX(p.Id)) AS [LastPurchasePrice]
FROM customer c INNER JOIN purchase p 
ON c.Id = p.customerId 
GROUP BY c.Id,c.name;

Enterprise app deployment doesn't work on iOS 7.1

Further the previous answers about Dropbox, I implemented the following files tree such as only the PLIST file has to be uploaded to Dropbox:

  1. upload the ipa file to your server in http (no change here)
  2. upload the provisioning (.mobileprovision) file to your server in http (no change here)
  3. upload the plist file to your dropbox (no change to do inside the plist file as the URLs are in absolute)
  4. use the option "Share the link with Dropbox" which copies the link to your clipboard. This link has to be copied into your html file into the itms-servivces URL's query after changing the part www.dropbox.com by dl.dropboxusercontent.com. Note I URL encoded the link as suggested by @Mike but I don't test without to do it. Now the itms-services URL's query should look like this: itms-services://?action=download-manifest&url=https%3A%2F%2Fdl.dropboxusercontent.com%2Fs%2FYourShortDropboxLink.plist

  5. upload the html file to your server in http. Note the html file contains both links to ipa and provisioning files.

  6. access to your html file from your device and now the ipa can be installed by OTA like usually.

From now, only the ipa file has to be changed to provide next app versions by OTA to your beta testers. Until Apple is yet changing the security rules.

I join here after the very simple HTML file I'm using:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>iPhone app for test</title>
</head>
<body>
<h1>iPhone app for test</h1>
<br/>
<ul>
    <li><a href="http://www.yourdomain.com/with/directories/provision/v.last/yourprovision_adhoc.mobileprovision">
            Install Provisioning File</a></li>
    <li><a href="itms-services://?action=download-manifest&url=https%3A%2F%2Fdl.dropboxusercontent.com%2Fs%2FYourShortDropboxLink.plist">
            Install Application</a></li>
</ul>
</body>
</html>

Uncompress tar.gz file

Try this:

tar -zxvf file.tar.gz

jquery AJAX and json format

You aren't actually sending JSON. You are passing an object as the data, but you need to stringify the object and pass the string instead.

Your dataType: "json" only tells jQuery that you want it to parse the returned JSON, it does not mean that jQuery will automatically stringify your request data.

Change to:

$.ajax({
        type: "POST",
        url: hb_base_url + "consumer",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({
            first_name: $("#namec").val(),
            last_name: $("#surnamec").val(),
            email: $("#emailc").val(),
            mobile: $("#numberc").val(),
            password: $("#passwordc").val()
        }),
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
        }
});

How to secure MongoDB with username and password

after you create new user, please don't forget to grant read/write/root permission to the user. you can try the

cmd: db.grantRolesToUser('yourNewUsername',[{ role: "root", db: "admin" }])

Why I've got no crontab entry on OS X when using vim?

The use of cron on OS X is discouraged. launchd is used instead. Try man launchctl to get started. You have to create special XML files that define your jobs and put them in a special place with certain permissions.

You'll usually just need to figure out launchctl load

http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/launchctl.1.html

http://nb.nathanamy.org/2012/07/schedule-jobs-using-launchd/

Edit

If you really do want to use cron on OS X, check out this answer: https://superuser.com/a/243944/2449

What is the meaning of prepended double colon "::"?

"::" represents scope resolution operator. Functions/methods which have same name can be defined in two different classes. To access the methods of a particular class scope resolution operator is used.

How do I test if a recordSet is empty? isNull?

If Not temp_rst1 Is Nothing Then ...

How to set variable from a SQL query?

Select @ModelID =m.modelid 
From   MODELS m
Where  m.areaid = 'South Coast'

In this case if you have two or more results returned then your result is the last record. So be aware of this if you might have two more records returned as you might not see the expected result.

File changed listener in Java

There is a commercial cross-desktop library for files and folders watching called JxFileWatcher. It can be downloaded from here: http://www.teamdev.com/jxfilewatcher/

Also you can see it in action online: http://www.teamdev.com/jxfilewatcher/onlinedemo/

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

How can I use SUM() OVER()

Seems like you expected the query to return running totals, but it must have given you the same values for both partitions of AccountID.

To obtain running totals with SUM() OVER (), you need to add an ORDER BY sub-clause after PARTITION BY …, like this:

SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)

But remember, not all database systems support ORDER BY in the OVER clause of a window aggregate function. (For instance, SQL Server didn't support it until the latest version, SQL Server 2012.)

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

Inline IF Statement in C#

The literal answer is:

return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);

Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:

return (value == 1
    ? Periods.VariablePeriods
    : (value == 2
        ? Periods.FixedPeriods
        : Periods.Unknown));

If you add more values an inline if will become unreadable and a switch would be preferred:

switch (value)
{
case 1:
    return Periods.VariablePeriods;
case 2:
    return Periods.FixedPeriods;
}

The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.

PHP write file from input to txt

use fwrite() instead of file_put_contents()

Search for "does-not-contain" on a DataFrame in pandas

I hope the answers are already posted

I am adding the framework to find multiple words and negate those from dataFrame.

Here 'word1','word2','word3','word4' = list of patterns to search

df = DataFrame

column_a = A column name from from DataFrame df

Search_for_These_values = ['word1','word2','word3','word4'] 

pattern = '|'.join(Search_for_These_values)

result = df.loc[~(df['column_a'].str.contains(pattern, case=False)]

Run a controller function whenever a view is opened/shown

For example to @Michael Trouw,

inside your controller put this code. this will run everytime when this state is entered or active, you do not need to worry about disabling cache and it's a better approach.

.controller('exampleCtrl',function($scope){
$scope.$on('$ionicView.enter', function(){
        // Any thing you can think of
        alert("This function just ran away");   
    });
})

You can have more examples of flexibility like $ionicView.beforeEnter -> which runs before a view is shown. And there are some more to it.

jQuery change URL of form submit

Send the data from the form:

$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
  type: "PUT"
  url: url
  dataType: "script"
  data: postData

Using Python's ftplib to get a directory listing, portably

This is from Python docs

>>> from ftplib import FTP_TLS
>>> ftps = FTP_TLS('ftp.python.org')
>>> ftps.login()           # login anonymously before securing control 
channel
>>> ftps.prot_p()          # switch to secure data connection
>>> ftps.retrlines('LIST') # list directory content securely
total 9
drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
-rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg

What is the difference between class and instance methods?

In Objective-C all methods start with either a "-" or "+" character. Example:

@interface MyClass : NSObject
// instance method
- (void) instanceMethod;

+ (void) classMethod;
@end

The "+" and "-" characters specify whether a method is a class method or an instance method respectively.

The difference would be clear if we call these methods. Here the methods are declared in MyClass.

instance method require an instance of the class:

MyClass* myClass = [[MyClass alloc] init];
[myClass instanceMethod];

Inside MyClass other methods can call instance methods of MyClass using self:

-(void) someMethod
{
    [self instanceMethod];
}

But, class methods must be called on the class itself:

[MyClass classMethod];

Or:

MyClass* myClass = [[MyClass alloc] init];
[myClass class] classMethod];

This won't work:

// Error
[myClass classMethod];
// Error
[self classMethod];

Is there an XSLT name-of element?

<xsl:value-of select="name(.)" /> : <xsl:value-of select="."/>

I get conflicting provisioning settings error when I try to archive to submit an iOS app

For those coming from Ionic or Cordova, you can try the following: Disconnect your ios devices from the computer before ios cordova build ios --release (seems to change the targeted device for xcode signing).

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

Try:

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

How to test if JSON object is empty in Java

Try /*string with {}*/ string.trim().equalsIgnoreCase("{}")), maybe there is some extra spaces or something

How do you get the current project directory from C# code when creating a custom MSBuild task?

using System;
using System.IO;

// This will get the current WORKING directory (i.e. \bin\Debug)
string workingDirectory = Environment.CurrentDirectory;
// or: Directory.GetCurrentDirectory() gives the same result

// This will get the current PROJECT bin directory (ie ../bin/)
string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;

// This will get the current PROJECT directory
string projectDirectory = Directory.GetParent(workingDirectory).Parent.Parent.FullName;

How to wrap text of HTML button with fixed width?

You can force it (browser permitting, I imagine) by inserting line breaks in the HTML source, like this:

<INPUT value="Line 1
Line 2">

Of course working out where to place the line breaks is not necessarily trivial...

If you can use an HTML <BUTTON> instead of an <INPUT>, such that the button label is the element's content rather than its value attribute, placing that content inside a <SPAN> with a width attribute that is a few pixels narrower than that of the button seems to do the trick (even in IE6 :-).

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

Found the script below in this github issue. Works great for me.

#!/usr/bin/env ruby
port = ARGV.first || 3000
system("sudo echo kill-server-on #{port}")

pid = `sudo lsof -iTCP -sTCP:LISTEN -n -P | grep #{port} | awk '{ print $2 }' | head -n 1`.strip
puts "PID: #{pid}"
`kill -9 #{pid}` unless pid.empty?

You can either run it in irb or inside a ruby file.

For the latter, create server_killer.rb then run it with ruby server_killer.rb

Unable to ping vmware guest from another vmware guest

I just ran into the exact same problem while configuring my server 2008 and windows 7 vm's in VMware workstation 9. what helped is disabling the firewall and running the following command at the windows command prompt

netsh firewall set icmpsetting 8 enable

at that point I was able to ping one VM then both once I performed the command on both. this differnce between our scenarios is I have my VM configured using Bridged connections

How to Split Image Into Multiple Pieces in Python

This is my script tools, it is very sample to splite css-sprit image into icons:

Usage: split_icons.py img dst_path width height
Example: python split_icons.py icon-48.png gtliu 48 48

Save code into split_icons.py :

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
import glob
from PIL import Image

def Usage():
    print '%s img dst_path width height' % (sys.argv[0])
    sys.exit(1)

if len(sys.argv) != 5:
    Usage()

src_img = sys.argv[1]
dst_path = sys.argv[2]

if not os.path.exists(sys.argv[2]) or not os.path.isfile(sys.argv[1]):
    print 'Not exists', sys.argv[2], sys.argv[1]
    sys.exit(1)

w, h = int(sys.argv[3]), int(sys.argv[4])
im = Image.open(src_img)
im_w, im_h = im.size
print 'Image width:%d height:%d  will split into (%d %d) ' % (im_w, im_h, w, h)
w_num, h_num = int(im_w/w), int(im_h/h)

for wi in range(0, w_num):
    for hi in range(0, h_num):
        box = (wi*w, hi*h, (wi+1)*w, (hi+1)*h)
        piece = im.crop(box)
        tmp_img = Image.new('L', (w, h), 255)
        tmp_img.paste(piece)
        img_path = os.path.join(dst_path, "%d_%d.png" % (wi, hi))
        tmp_img.save(img_path)

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

Example:

perfdb-# \df information_schema.*;

List of functions
        Schema      |        Name        | Result data type | Argument data types |  Type  
 information_schema | _pg_char_max_length   | integer | typid oid, typmod integer | normal
 information_schema | _pg_char_octet_length | integer | typid oid, typmod integer | normal
 information_schema | _pg_datetime_precision| integer | typid oid, typmod integer | normal
 .....
 information_schema | _pg_numeric_scale     | integer | typid oid, typmod integer | normal
 information_schema | _pg_truetypid         | oid     | pg_attribute, pg_type     | normal
 information_schema | _pg_truetypmod        | integer | pg_attribute, pg_type     | normal
(11 rows)

How to crop an image using C#?

I was looking for a easy and FAST function with no additional libary to do the job. I tried Nicks solution, but i needed 29,4 sec to "extract" 1195 images of an atlas file. So later i managed this way and needed 2,43 sec to do the same job. Maybe this will be helpful.

// content of the Texture class
public class Texture
{
    //name of the texture
    public string name { get; set; }
    //x position of the texture in the atlas image
    public int x { get; set; }
    //y position of the texture in the atlas image
    public int y { get; set; }
    //width of the texture in the atlas image
    public int width { get; set; }
    //height of the texture in the atlas image
    public int height { get; set; }
}

Bitmap atlasImage = new Bitmap(@"C:\somepicture.png");
PixelFormat pixelFormat = atlasImage.PixelFormat;

foreach (Texture t in textureList)
{
     try
     {
           CroppedImage = new Bitmap(t.width, t.height, pixelFormat);
           // copy pixels over to avoid antialiasing or any other side effects of drawing
           // the subimages to the output image using Graphics
           for (int x = 0; x < t.width; x++)
               for (int y = 0; y < t.height; y++)
                   CroppedImage.SetPixel(x, y, atlasImage.GetPixel(t.x + x, t.y + y));
           CroppedImage.Save(Path.Combine(workingFolder, t.name + ".png"), ImageFormat.Png);
     }
     catch (Exception ex)
     {
          // handle the exception
     }
}

Binding to static property

Look at my project CalcBinding, which provides to you writing complex expressions in Path property value, including static properties, source properties, Math and other. So, you can write this:

<TextBox Text="{c:Binding local:VersionManager.FilterString}"/>

Goodluck!

Extract data from log file in specified range of time

You can use sed for this. For example:

$ sed -n '/Feb 23 13:55/,/Feb 23 14:00/p' /var/log/mail.log
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: connect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: lost connection after CONNECT from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: disconnect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie pop3d: Connection, ip=[::ffff:127.0.0.1]
...

How it works

The -n switch tells sed to not output each line of the file it reads (default behaviour).

The last p after the regular expressions tells it to print lines that match the preceding expression.

The expression '/pattern1/,/pattern2/' will print everything that is between first pattern and second pattern. In this case it will print every line it finds between the string Feb 23 13:55 and the string Feb 23 14:00.

More info here.

How to get cumulative sum

Without using any type of JOIN cumulative salary for a person fetch by using follow query:

SELECT * , (
  SELECT SUM( salary ) 
  FROM  `abc` AS table1
  WHERE table1.ID <=  `abc`.ID
    AND table1.name =  `abc`.Name
) AS cum
FROM  `abc` 
ORDER BY Name

Run a string as a command within a Bash script

You can use eval to execute a string:

eval $illcommando

How to check if element has any children in Javascript?

You can check if the element has child nodes element.hasChildNodes(). Beware in Mozilla this will return true if the is whitespace after the tag so you will need to verify the tag type.

https://developer.mozilla.org/En/DOM/Node.hasChildNodes

Extract digits from a string in Java

Use regular expression to match your requirement.

String num,num1,num2;
String str = "123-456-789";
String regex ="(\\d+)";
Matcher matcher = Pattern.compile( regex ).matcher( str);
while (matcher.find( ))
{
num = matcher.group();     
System.out.print(num);                 
}

How to execute an SSIS package from .NET?

So there is another way you can actually fire it from any language. The best way I think, you can just create a batch file which will call your .dtsx package.

Next you call the batch file from any language. As in windows platform, you can run batch file from anywhere, I think this will be the most generic approach for your purpose. No code dependencies.

Below is a blog for more details..

https://www.mssqltips.com/sqlservertutorial/218/command-line-tool-to-execute-ssis-packages/

Happy coding.. :)

Thanks, Ayan

How to get the first and last date of the current year?

You can get the current year using DATEPART function, from the current date obtained using getUTCDate()

SELECT 
    '01/01/' + CONVERT(VARCHAR(4), DATEPART(yy, getUTCDate())), 
    '31/12/' + CONVERT(VARCHAR(4), DATEPART(yy, getUTCDate()))

'innerText' works in IE, but not in Firefox

A really simple line of Javascript can get the "non-taggy" text in all main browsers...

var myElement = document.getElementById('anyElementId');
var myText = (myElement.innerText || myElement.textContent);

How can I find which tables reference a given table in Oracle SQL Developer?

Replace [Your TABLE] with emp in the query below

select owner,constraint_name,constraint_type,table_name,r_owner,r_constraint_name
  from all_constraints 
 where constraint_type='R'
   and r_constraint_name in (select constraint_name 
                               from all_constraints 
                              where constraint_type in ('P','U') 
                                and table_name='[YOUR TABLE]');

Change the background color of CardView programmatically

What you are looking for is:

CardView card = ...
card.setCardBackgroundColor(color);

In XML

 card_view:cardBackgroundColor="@android:color/white"

Update: in XML

app:cardBackgroundColor="@android:color/white"

How to get year/month/day from a date object?

Here is a cleaner way getting Year/Month/Day with template literals:

_x000D_
_x000D_
var date = new Date();_x000D_
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;_x000D_
console.log(formattedDate);
_x000D_
_x000D_
_x000D_

Getting number of days in a month

  • int days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);


if you want to find days in this year and present month then this is best

How to add google-services.json in Android?

WINDOWS

  1. Open Terminal window in Android Studio (Alt+F12 or View->Tool Windows->Terminal). Then type

"move file_path/google-services.json app/"

without double quotes.

eg

move C:\Users\siva\Downloads\google-services.json app/

LINUX

  1. Open Android Studio Terminal and type this

scp file_path/google-services.json app/

eg:

scp '/home/developer/Desktop/google-services.json' 'app/'

Uncaught TypeError: Cannot read property 'value' of undefined

Try this, It always works, and you will get NO TypeError:

try{

    var i1 = document.getElementById('i1');
    var i2 = document.getElementById('i2');
    var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
    if(  __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
    if(  __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }

}catch(e){
    if(e){
    // If fails, Do something else
    }
}

How do you run CMD.exe under the Local System Account?

  1. Download psexec.exe from Sysinternals.
  2. Place it in your C:\ drive.
  3. Logon as a standard or admin user and use the following command: cd \. This places you in the root directory of your drive, where psexec is located.
  4. Use the following command: psexec -i -s cmd.exe where -i is for interactive and -s is for system account.
  5. When the command completes, a cmd shell will be launched. Type whoami; it will say 'system"
  6. Open taskmanager. Kill explorer.exe.
  7. From an elevated command shell type start explorer.exe.
  8. When explorer is launched notice the name "system" in start menu bar. Now you can delete some files in system32 directory which as admin you can't delete or as admin you would have to try hard to change permissions to delete those files.

Users who try to rename or deleate System files in any protected directory of windows should know that all windows files are protected by DACLS while renaming a file you have to change the owner and replace TrustedInstaller which owns the file and make any user like a user who belongs to administrator group as owner of file then try to rename it after changing the permission, it will work and while you are running windows explorer with kernel privilages you are somewhat limited in terms of Network access for security reasons and it is still a research topic for me to get access back

The first day of the current month in php using date_modify as DateTime object

using date method, we should be able to get the result. ie; date('N/D/l', mktime(0, 0, 0, month, day, year));

For Example

echo date('N', mktime(0, 0, 0, 7, 1, 2017));   // will return 6
echo date('D', mktime(0, 0, 0, 7, 1, 2017));   // will return Sat
echo date('l', mktime(0, 0, 0, 7, 1, 2017));   // will return Saturday

JQuery select2 set default value from an option in list?

One way to accomplish this is...

$('select').select2().select2('val', $('.select2 option:eq(1)').val());

So basically you first initalize the plugin then specify the default value using the 'val' parameter. The actual value is taken from the specified option, in this case #1. So the selected value from this example would be "bar".

<select class=".select2">
  <option id="foo">Some Text</option>
  <option id="bar">Other Text</option>
</select>

Hope this is useful to someone else.

Java Array Sort descending?

for a list

Collections.sort(list, Collections.reverseOrder());

for an array

Arrays.sort(array, Collections.reverseOrder());

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

All those answers didnt help me, BUT I found another solution.

I had an Entity A containing a List of Entity B. Entity B contained a List of Entity C.

I was trying to update Entity A and B. It worked. But when updating Entity C, I got the mentioned error. In entity B I had an annotation like this:

@OneToMany(mappedBy = "entity_b", cascade = [CascadeType.ALL] , orphanRemoval = true)
var c: List<EntityC>?,

I simply removed orphanRemoval and the update worked.

What are abstract classes and abstract methods?

An abstract method is a method signature declaration with no body. For instance:

public abstract class Shape {
    . . .

    public abstract double getArea();
    public abstract double getPerimeter();
}

The methods getArea() and getPerimeter() are abstract. Because the Shape class has an abstract method, it must be declared abstract as well. A class may also be declared abstract without any abstract methods. When a class is abstract, an instance of it cannot be created; one can only create instances of (concrete) subclasses. A concrete class is a class that is not declared abstract (and therefore has no abstract methods and implements all inherited abstract methods). For instance:

public class Circle extends Shape {
    public double radius;
    . . .

    public double getArea() {
        return Math.PI * radius * radius;
    }

    public double getPerimeter() {
        return 2.0 * Math.PI * radius;
    }
}

There are many reasons to do this. One would be to write a method that would be the same for all shapes but that depends on shape-specific behavior that is unknown at the Shape level. For instance, one could write the method:

public abstract class Shape {
    . . .

    public void printArea(PrintStream out) {
        out.println("The area is " + getArea());
    }
}

Admittedly, this is a contrived example, but it shows the basic idea: define concrete behavior in terms of unspecified behavior.

Another reason for having an abstract class is so you can partially implement an interface. All methods declared in an interface are inherited as abstract methods by any class that implements the interface. Sometimes you want to provide a partial implementation of an interface in a class and leave the details to subclasses; the partial implementation must be declared abstract.

Ternary operator in PowerShell

If you're just looking for a syntactically simple way to assign/return a string or numeric based on a boolean condition, you can use the multiplication operator like this:

"Condition is "+("true"*$condition)+("false"*!$condition)
(12.34*$condition)+(56.78*!$condition)

If you're only ever interested in the result when something is true, you can just omit the false part entirely (or vice versa), e.g. a simple scoring system:

$isTall = $true
$isDark = $false
$isHandsome = $true

$score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
"Score = $score"
# or
# "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"

Note that the boolean value should not be the leading term in the multiplication, i.e. $condition*"true" etc. won't work.

PHP Fatal Error Failed opening required File

It's not actually an Apache related question. Nor even a PHP related one. To understand this error you have to distinguish a path on the virtual server from a path in the filesystem.

require operator works with files. But a path like this

                          /common/configs/config_templates.inc.php

only exists on the virtual HTTP server, while there is no such path in the filesystem. The correct filesystem path would be

/home/viapics1/public_html/common/configs/config_templates.inc.php

where

/home/viapics1/public_html

part is called the Document root and it connects the virtual world with the real one. Luckily, web-servers usually have the document root in a configuration variable that they share with PHP. So if you change your code to something like this

require_once $_SERVER['DOCUMENT_ROOT'].'/common/configs/config_templates.inc.php';

it will work from any file placed in any directory!

Update: eventually I wrote an article that explains the difference between relative and absolute paths, in the file system and on the web server, which explains the matter in detail, and contains some practical solutions. Like, such a handy variable doesn't exist when you run your script from a command line. In this case a technique called "a single entry point" is to the rescue. You may refer to the article above for the details as well.

You should not use <Link> outside a <Router>

Whenever you try to show a Link on a page thats outside the BrowserRouter you will get that error.

This error message is essentially saying that any component that is not a child of our <Router> cannot contain any React Router related components.

You need to migrate your component hierarchy to how you see it in the first answer above. For anyone else reviewing this post who may need to look at more examples.

Let's say you have a Header.jscomponent that looks like this:

import React from 'react';
import { Link } from 'react-router-dom';

const Header = () => {
    return (
        <div className="ui secondary pointing menu">
            <Link to="/" className="item">
                Streamy
            </Link>
            <div className="right menu">
                <Link to="/" className="item">
                    All Streams
                </Link>
            </div>
        </div>
    );
};

export default Header;

And your App.js file looks like this:

import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';

const App = () => {
  return (
    <div className="ui container">
      <Header />
      <BrowserRouter>
        <div>
        <Route path="/" exact component={StreamList} />
        <Route path="/streams/new" exact component={StreamCreate} />
        <Route path="/streams/edit" exact component={StreamEdit} />
        <Route path="/streams/delete" exact component={StreamDelete} />
        <Route path="/streams/show" exact component={StreamShow} />
        </div> 
      </BrowserRouter>
    </div>
  );
};

export default App;

Notice that the Header.js component is making use of the Link tag from react-router-dom but the componet was placed outside the <BrowserRouter>, this will lead to the same error as the one experience by the OP. In this case, you can make the correction in one move:

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';

const App = () => {
  return (
    <div className="ui container">
      <BrowserRouter>
        <div>
        <Header />
        <Route path="/" exact component={StreamList} />
        <Route path="/streams/new" exact component={StreamCreate} />
        <Route path="/streams/edit" exact component={StreamEdit} />
        <Route path="/streams/delete" exact component={StreamDelete} />
        <Route path="/streams/show" exact component={StreamShow} />
        </div> 
      </BrowserRouter>
    </div>
  );
};

export default App;

Please review carefully and ensure you have the <Header /> or whatever your component may be inside of not only the <BrowserRouter> but also inside of the <div>, otherwise you will also get the error that a Router may only have one child which is referring to the <div> which is the child of <BrowserRouter>. Everything else such as Route and components must go within it in the hierarchy.

So now the <Header /> is a child of the <BrowserRouter> within the <div> tags and it can successfully make use of the Link element.

Error when trying vagrant up

With me I got an error when run vagrant up is (I used Macbook pro, Mac OS: 10.12.1):

An error occurred while downloading the remote file. The error message, if any, is reproduced below. Please fix this error and try again. Couldn't open file...

I tried to delete the Vagrantfile in my folder and run:

vagrant init hashicorp/precise64

then:

vagrant up

It can solved my problem. Hope this can help for someone who face the same problem.

Python dict how to create key or append an element to key?

Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most "pythonic", and commented the pros and cons that might not be obvious at first glance:

Using collections.defaultdict:

import collections
dict_x = collections.defaultdict(list)

...

dict_x[key].append(value)

Pros: Probably best performance. Cons: Not available in Python 2.4.x.

Using dict().setdefault():

dict_x = {}

...

dict_x.setdefault(key, []).append(value)

Cons: Inefficient creation of unused list()s.

Using try ... except:

dict_x = {}

...

try:
    values = dict_x[key]
except KeyError:
    values = dict_x[key] = []
values.append(value)

Or:

try:
    dict_x[key].append(value)
except KeyError:
    dict_x[key] = [value]

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

By changing

compile 'com.google.android.gms:play-services:8.1.0'

to only needed files, the problem can be solved This Issue is generated because of exceeding files in th build.gradle file.

How to cast from List<Double> to double[] in Java?

As per your question,

List<Double> frameList =  new ArrayList<Double>();
  1. First you have to convert List<Double> to Double[] by using

    Double[] array = frameList.toArray(new Double[frameList.size()]);
    
  2. Next you can convert Double[] to double[] using

    double[] doubleArray = ArrayUtils.toPrimitive(array);
    

You can directly use it in one line:

double[] array = ArrayUtils.toPrimitive(frameList.toArray(new Double[frameList.size()]));

Angular 2: 404 error occur when I refresh through the browser

If you're running Angular 2 through ASP.NET Core 1 in Visual Studio 2015, you might find this solution from Jürgen Gutsch helpful. He describes it in a blog post. It was the best solution for me. Place the C# code provided below in your Startup.cs public void Configure() just before app.UseStaticFiles();

app.Use( async ( context, next ) => {
    await next();

    if( context.Response.StatusCode == 404 && !Path.HasExtension( context.Request.Path.Value ) ) {
        context.Request.Path = "/index.html";
        await next();
    }
});

Disable ScrollView Programmatically?

I don't have enough points to comment on an answer, but I wanted to say that mikec's answer worked for me except that I had to change it to return !isScrollable like so:

mScroller.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      return !isScrollable;
    }
});

Checking whether a variable is an integer or not

you can do this by:

name = 'Bob'
if type(name) == str:
    print 'this works'
else:
    print 'this does not work'

and it will return 'this works'... but if you change name to int(1) then it will return 'this does not work' because it is now a string... you can also try:

name = int(5)
if type(name) == int:
    print 'this works'
else:
    print 'this does not work'

and the same thing will happen

How do I use NSTimer?

there are a couple of ways of using a timer:

1) scheduled timer & using selector

NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
                      target: self
                      selector:@selector(onTick:)
                      userInfo: nil repeats:NO];
  • if you set repeats to NO, the timer will wait 2 seconds before running the selector and after that it will stop;
  • if repeat: YES, the timer will start immediatelly and will repeat calling the selector every 2 seconds;
  • to stop the timer you call the timer's -invalidate method: [t invalidate];

As a side note, instead of using a timer that doesn't repeat and calls the selector after a specified interval, you could use a simple statement like this:

[self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];

this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;

2) self-scheduled timer

NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
                              interval: 1
                              target: self
                              selector:@selector(onTick:)
                              userInfo:nil repeats:YES];

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
  • this will create a timer that will start itself on a custom date specified by you (in this case, after a minute), and repeats itself every one second

3) unscheduled timer & using invocation

NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];

NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
                      invocation:inv 
                      repeats:YES];

and after that, you start the timer manually whenever you need like this:

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];



And as a note, onTick: method looks like this:

-(void)onTick:(NSTimer *)timer {
   //do smth
}

How do I get the unix timestamp in C as an int?

With second precision, you can print tv_sec field of timeval structure that you get from gettimeofday() function. For example:

#include <sys/time.h>
#include <stdio.h>

int main()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    printf("Seconds since Jan. 1, 1970: %ld\n", tv.tv_sec);
    return 0;
}

Example of compiling and running:

$ gcc -Wall -o test ./test.c 
$ ./test 
Seconds since Jan. 1, 1970: 1343845834

Note, however, that its been a while since epoch and so long int is used to fit a number of seconds these days.

There are also functions to print human-readable times. See this manual page for details. Here goes an example using ctime():

#include <time.h>
#include <stdio.h>

int main()
{
    time_t clk = time(NULL);
    printf("%s", ctime(&clk));
    return 0;
}

Example run & output:

$ gcc -Wall -o test ./test.c 
$ ./test 
Wed Aug  1 14:43:23 2012
$ 

How to store a command in a variable in a shell script?

For bash, store your command like this:

command="ls | grep -c '^'"

Run your command like this:

echo $command | bash

Set the space between Elements in Row Flutter

To make an exact spacing, I use Padding. An example with two images:

Row(
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: <Widget>[
      Expanded(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Image.asset('images/user1.png'),
        ),
      ),
      Expanded(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Image.asset('images/user2.png'),
        ),
      )
    ],
  ),

How to POST a FORM from HTML to ASPX page

You sure can. Create an HTML page with the form in it that will contain the necessary components from the login.aspx page (i.e. username, etc), and make sure they have the same IDs. For you action, make sure it's a post.

You might have to do some code on the login.aspx page in the Page_Load function to read the form (in the Request.Form object) and call the appropriate functions to log the user in, but other than that, you should have access to the form, and can do what you want with it.

Center image using text-align center?

On the container holding image you can use a CSS 3 Flexbox to perfectly center the image inside, both vertically and horizontally.

Let's assume you have <div class="container"> as the image holder:

Then as CSS you have to use:

.container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

And this will make all your content inside this div perfectly centered.

How do I make the first letter of a string uppercase in JavaScript?

There is a very simple way to implement it by replace. For ECMAScript 6:

'foo'.replace(/^./, str => str.toUpperCase())

Result:

'Foo'

Android Gradle Apache HttpClient does not exist?

Add this library into build.gradle

 android {
      useLibrary 'org.apache.http.legacy'
 }

How to get first 5 characters from string

You can use the substr function like this:

echo substr($myStr, 0, 5);

The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

How to do relative imports in Python?

This is solved 100%:

  • app/
    • main.py
  • settings/
    • local_setings.py

Import settings/local_setting.py in app/main.py:

main.py:

import sys
sys.path.insert(0, "../settings")


try:
    from local_settings import *
except ImportError:
    print('No Import')

Padding is invalid and cannot be removed?

I had this error and was explicitly setting the blocksize: aesManaged.BlockSize = 128;

Once I removed that, it worked.

Floating elements within a div, floats outside of div. Why?

As Lucas says, what you are describing is the intended behaviour for the float property. What confuses many people is that float has been pushed well beyond its original intended usage in order to make up for shortcomings in the CSS layout model.

Have a look at Floatutorial if you'd like to get a better understanding of how this property works.

What is the difference between a definition and a declaration?

Stages of an executable generation:

(1) pre-processor -> (2) translator/compiler -> (3) linker

In stage 2 (translator/compiler), declaration statements in our code tell to the compiler that these things we are going to use in future and you can find definition later, meaning is :

translator make sure that : what is what ? means declaration

and (3) stage (linker) needs definition to bind the things

Linker make sure that : where is what ? means definition

What does the "More Columns than Column Names" error mean?

It uses commas as separators. So you can either set sep="," or just use read.csv:

x <- read.csv(file="http://www.irs.gov/file_source/pub/irs-soi/countyinflow1011.csv")
dim(x)
## [1] 113593      9

The error is caused by spaces in some of the values, and unmatched quotes. There are no spaces in the header, so read.table thinks that there is one column. Then it thinks it sees multiple columns in some of the rows. For example, the first two lines (header and first row):

State_Code_Dest,County_Code_Dest,State_Code_Origin,County_Code_Origin,State_Abbrv,County_Name,Return_Num,Exmpt_Num,Aggr_AGI
00,000,96,000,US,Total Mig - US & For,6973489,12948316,303495582

And unmatched quotes, for example on line 1336 (row 1335) which will confuse read.table with the default quote argument (but not read.csv):

01,089,24,033,MD,Prince George's County,13,30,1040

Install pdo for postgres Ubuntu

Try the packaged pecl version instead (the advantage of the packaged installs is that they're easier to upgrade):

apt-get install php5-dev
pecl install pdo
pecl install pdo_pgsql

or, if you just need a driver for PHP, but that it doesn't have to be the PDO one:

apt-get install php5-pgsql

Otherwise, that message most likely means you need to install a more recent libpq package. You can check which version you have by running:

dpkg -s libpq-dev

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

What is the difference between i++ & ++i in a for loop?

Here's a sample class:

public class Increment
{
    public static void main(String [] args)
    {
        for (int i = 0; i < args.length; ++i)
        {
            System.out.println(args[i]);
        }
    }
}

If I disassemble this class using javap.exe I get this:

Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_0
   1:   istore_1
   2:   iload_1
   3:   aload_0
   4:   arraylength
   5:   if_icmpge       23
   8:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   11:  aload_0
   12:  iload_1
   13:  aaload
   14:  invokevirtual   #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   17:  iinc    1, 1
   20:  goto    2
   23:  return

}

If I change the loop so it uses i++ and disassemble again I get this:

Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_0
   1:   istore_1
   2:   iload_1
   3:   aload_0
   4:   arraylength
   5:   if_icmpge       23
   8:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   11:  aload_0
   12:  iload_1
   13:  aaload
   14:  invokevirtual   #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   17:  iinc    1, 1
   20:  goto    2
   23:  return

}

When I compare the two, TextPad tells me that the two are identical.

What this says is that from the point of view of the generated byte code there's no difference in a loop. In other contexts there is a difference between ++i and i++, but not for loops.

How do you use subprocess.check_output() in Python?

Adding on to the one mentioned by @abarnert

a better one is to catch the exception

import subprocess
try:
    py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)  
    #print('py2 said:', py2output)
    print "here"
except subprocess.CalledProcessError as e:
    print "Calledprocerr"

this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting

python: can't open file 'py2.py': [Errno 2] No such file or directory

Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

How to implement a queue using two stacks?

Keep 2 stacks, let's call them inbox and outbox.

Enqueue:

  • Push the new element onto inbox

Dequeue:

  • If outbox is empty, refill it by popping each element from inbox and pushing it onto outbox

  • Pop and return the top element from outbox

Using this method, each element will be in each stack exactly once - meaning each element will be pushed twice and popped twice, giving amortized constant time operations.

Here's an implementation in Java:

public class Queue<E>
{

    private Stack<E> inbox = new Stack<E>();
    private Stack<E> outbox = new Stack<E>();

    public void queue(E item) {
        inbox.push(item);
    }

    public E dequeue() {
        if (outbox.isEmpty()) {
            while (!inbox.isEmpty()) {
               outbox.push(inbox.pop());
            }
        }
        return outbox.pop();
    }

}

Difference between jar and war in Java

A .war file has a specific structure in terms of where certain files will be. Other than that, yes, it's just a .jar.

Detecting negative numbers

I assume that the main idea is to find if number is negative and display it in correct format.

For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.

$profitLoss = 25000 - 55000;

$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY); 
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)

Here also a reference to why brackets are used for negative numbers: http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

how does array[100] = {0} set the entire array to 0?

Implementation is up to compiler developers.

If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements.

How to iterate using ngFor loop Map containing key as string and values as map iteration

If you are using Angular 6.1 or later, the most convenient way is to use KeyValuePipe

   @Component({
      selector: 'keyvalue-pipe',
      template: `<span>
        <p>Object</p>
        <div *ngFor="let item of object | keyvalue">
          {{item.key}}:{{item.value}}
        </div>
        <p>Map</p>
        <div *ngFor="let item of map | keyvalue">
          {{item.key}}:{{item.value}}
        </div>
      </span>`
    })
    export class KeyValuePipeComponent {
      object: Record<number, string> = {2: 'foo', 1: 'bar'};
      map = new Map([[2, 'foo'], [1, 'bar']]);
    }

Add ripple effect to my button with button background color?

When you use android:background, you are replacing much of the styling and look and feel of a button with a blank color.

Update: As of the version 23.0.0 release of AppCompat, there is a new Widget.AppCompat.Button.A colored style which uses your theme's colorButtonNormal for the disabled color and colorAccent for the enabled color.

This allows you apply it to your button directly via

<Button
 ...
style="@style/Widget.AppCompat.Button.Colored" />

You can use a drawable in your v21 directory for your background such as:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight">
<item android:drawable="?attr/colorPrimary"/>
</ripple>

This will ensure your background color is ?attr/colorPrimary and has the default ripple animation using the default ?attr/colorControlHighlight (which you can also set in your theme if you'd like).

Note: you'll have to create a custom selector for less than v21:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/primaryPressed"            android:state_pressed="true"/>
<item android:drawable="@color/primaryFocused" android:state_focused="true"/>
<item android:drawable="@color/primary"/>
</selector>

Git Ignores and Maven targets

It is possible to use patterns in a .gitignore file. See the gitignore man page. The pattern */target/* should ignore any directory named target and anything under it. Or you may try */target/** to ignore everything under target.

How to change the status bar color in Android?

If you want to change the status bar color programmatically (and provided the device has Android 5.0). This is a simple way to change statusBarColor from any Activity and very easy methods when differents fragments have different status bar color.

 /**
 * @param colorId id of color
 * @param isStatusBarFontDark Light or Dark color
 */
fun updateStatusBarColor(@ColorRes colorId: Int, isStatusBarFontDark: Boolean = true) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val window = window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.statusBarColor = ContextCompat.getColor(this, colorId)
        setSystemBarTheme(isStatusBarFontDark)
    }
}

/** Changes the System Bar Theme.  */
@RequiresApi(api = Build.VERSION_CODES.M)
private fun setSystemBarTheme(isStatusBarFontDark: Boolean) {
    // Fetch the current flags.
    val lFlags = window.decorView.systemUiVisibility
    // Update the SystemUiVisibility depending on whether we want a Light or Dark theme.
    window.decorView.systemUiVisibility = if (isStatusBarFontDark) lFlags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() else lFlags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}

windows batch file rename

as Itsproinc said, the REN command works!

but if your file path/name has spaces, use quotes " "

example:

ren C:\Users\&username%\Desktop\my file.txt not my file.txt

add " "

ren "C:\Users\&username%\Desktop\my file.txt" "not my file.txt"

hope it helps

How to create a foreign key in phpmyadmin

To be able to create a relation, the table Storage Engine must be InnoDB. You can edit in Operations tab. Storage Engine Configuration

Then, you need to be sure that the id column in your main table has been indexed. It should appear at Index section in Structure tab.

Index list

Finally, you could see the option Relations View in Structure tab. When edditing, you will be able to select the parent column in foreign table to create the relation.

enter image description here

See attachments. I hope this could be useful for anyone.

Conversion hex string into ascii in bash command line

The values you provided are UTF-8 values. When set, the array of:

declare -a ARR=(0xA7 0x9B 0x46 0x8D 0x1E 0x52 0xA7 0x9B 0x7B 0x31 0xD2)

Will be parsed to print the plaintext characters of each value.

for ((n=0; n < ${#ARR[*]}; n++)); do echo -e "\u${ARR[$n]//0x/}"; done

And the output will yield a few printable characters and some non-printable characters as shown here:

enter image description here

For converting hex values to plaintext using the echo command:

echo -e "\x<hex value here>"

And for converting UTF-8 values to plaintext using the echo command:

echo -e "\u<UTF-8 value here>"

And then for converting octal to plaintext using the echo command:

echo -e "\0<octal value here>"

When you have encoding values you aren't familiar with, take the time to check out the ranges in the common encoding schemes to determine what encoding a value belongs to. Then conversion from there is a snap.

HTTP GET request in JavaScript?

A copy-paste modern version ( using fetch and arrow function ) :

//Option with catch
fetch( textURL )
   .then(async r=> console.log(await r.text()))
   .catch(e=>console.error('Boo...' + e));

//No fear...
(async () =>
    console.log(
            (await (await fetch( jsonURL )).json())
            )
)();

A copy-paste classic version:

let request = new XMLHttpRequest();
request.onreadystatechange = function () {
    if (this.readyState === 4) {
        if (this.status === 200) {
            document.body.className = 'ok';
            console.log(this.responseText);
        } else if (this.response == null && this.status === 0) {
            document.body.className = 'error offline';
            console.log("The computer appears to be offline.");
        } else {
            document.body.className = 'error';
        }
    }
};
request.open("GET", url, true);
request.send(null);

Does Python's time.time() return the local or UTC timestamp?

There is no such thing as an "epoch" in a specific timezone. The epoch is well-defined as a specific moment in time, so if you change the timezone, the time itself changes as well. Specifically, this time is Jan 1 1970 00:00:00 UTC. So time.time() returns the number of seconds since the epoch.

Find size of Git repository

UPDATE git 1.8.3 introduced a more efficient way to get a rough size: git count-objects -vH (see answer by @VonC)

For different ideas of "complete size" you could use:

git bundle create tmp.bundle --all
du -sh tmp.bundle

Close (but not exact:)

git gc
du -sh .git/

With the latter, you would also be counting:

  • hooks
  • config (remotes, push branches, settings (whitespace, merge, aliases, user details etc.)
  • stashes (see Can I fetch a stash from a remote repo into a local branch? also)
  • rerere cache (which can get considerable)
  • reflogs
  • backups (from filter-branch, e.g.) and various other things (intermediate state from rebase, bisect etc.)

How to use class from other files in C# with visual studio?

It would be more beneficial for us if we could see the actual project structure, as the classes alone do not say that much.

Assuming that both .cs files are in the same project (if they are in different projects inside the same solution, you'd have to add a reference to the project containing Class2.cs), you can click on the Class2 occurrence in your code that is underlined in red and press CTRL + . (period) or click on the blue bar that should be there. The first option appearing will then add the appropriate using statement automatically. If there is no such menu, it may indicate that there is something wrong with the project structure or a reference missing.

You could try making Class2 public, but it sounds like this can't be a problem here, since by default what you did is internal class Class2 and thus Class2 should be accessible if both are living in the same project/assembly. If you are referencing a different assembly or project wherein Class2 is contained, you have to make it public in order to access it, as internal classes can't be accessed from outside their assembly.

As for renaming: You can click Program.cs in the Solution Explorer and press F2 to rename it. It will then open up a dialog window asking you if the class Program itself and all references thereof should be renamed as well, which is usually what you want. Or you could just rename the class Program in the declaration and again open up the menu with the small blue bar (or, again, CTRL+.) and do the same, but it won't automatically rename the actual file accordingly.

Edit after your question edit: I have never used this option you used, but from quick checking I think that it's really not inside the same project then. Do the following when adding new classes to a project: In the Solution Explorer, right click the project you created and select [Add] -> [Class] or [Add] -> [New Item...] and then select 'Class'. This will automatically make the new class part of the project and thus the assembly (the assembly is basically the 'end product' after building the project). For me, there is also the shortcut Alt+Shift+C working to create a new class.

Can I change the name of `nohup.out`?

For some reason, the above answer did not work for me; I did not return to the command prompt after running it as I expected with the trailing &. Instead, I simply tried with

nohup some_command > nohup2.out&

and it works just as I want it to. Leaving this here in case someone else is in the same situation. Running Bash 4.3.8 for reference.

How to rename a table in SQL Server?

To rename a table in SQL Server, use the sp_rename command:

exec sp_rename 'schema.old_table_name', 'new_table_name'

CSS: Change image src on img:hover

You can't change img tag's src attribute using CSS. Possible using Javascript onmouseover() event handler.

HTML:

<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover='hover()'/>

Javascript:

function hover() {
  document.getElementById("my-img").src = "http://dummyimage.com/100x100/eb00eb/fff";
}

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

The remote host closed the connection. The error code is 0x800704CD

As m.edmondson mentioned, "The remote host closed the connection." occurs when a user or browser cancels something, or the network connection drops etc. It doesn't necessarily have to be a file download however, just any request for any resource that results in a response to the client. Basically the error means that the response could not be sent because the server can no longer talk to the client(browser).

There are a number of steps that you can take in order to stop it happening. If you are manually sending something in the response with a Response.Write, Response.Flush, returning data from a web servivce/page method or something similar, then you should consider checking Response.IsClientConnected before sending the response. Also, if the response is likely to take a long time or a lot of server-side processing is required, you should check this periodically until the response.end if called. See the following for details on this property:

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx

Alternatively, which I believe is most likely in your case, the error is being caused by something inside the framework. The following link may by of use:

http://blog.whitesites.com/fixing-The-remote-host-closed-the-connection-The-error-code-is-0x80070057__633882307305519259_blog.htm

The following stack-overflow post might also be of interest:

"The remote host closed the connection" in Response.OutputStream.Write

On a CSS hover event, can I change another div's styling?

This can not be done purely with css. This is a behaviour, which affects the styling of the page.

With jquery you can quickly implement the behavior from your question:

$(function() {
  $('#a').hover(function() {
    $('#b').css('background-color', 'yellow');
  }, function() {
    // on mouseout, reset the background colour
    $('#b').css('background-color', '');
  });
});

C Linking Error: undefined reference to 'main'

You are overwriting your object file runexp.o by running this command :

 gcc -o runexp.o scd.o data_proc.o -lm -fopenmp

In fact, the -o is for the output file. You need to run :

gcc -o runexp.out runexp.o scd.o data_proc.o -lm -fopenmp

runexp.out will be you binary file.

jquery .live('click') vs .click()

If you need simplify code then live is better in the most cases. If you need to get the best performance then delegate will always better than live. bind (click) vs delegate isn't so simple question (if you have a lot of similar items then delegate will be better).

Close Android Application

just call the finish() in the method you would like to end the activity in, for example when you use the onCreate() method, in the end of the method, just add finish() and you will see the activity ends as soon as it is created!

What does "all" stand for in a makefile?

The manual for GNU Make gives a clear definition for all in its list of standard targets.

If the author of the Makefile is following that convention then the target all should:

  1. Compile the entire program, but not build documentation.
  2. Be the the default target. As in running just make should do the same as make all.

To achieve 1 all is typically defined as a .PHONY target that depends on the executable(s) that form the entire program:

.PHONY : all
all : executable

To achieve 2 all should either be the first target defined in the make file or be assigned as the default goal:

.DEFAULT_GOAL := all

How to create a numpy array of all True or all False?

>>> a = numpy.full((2,4), True, dtype=bool)
>>> a[1][3]
True
>>> a
array([[ True,  True,  True,  True],
       [ True,  True,  True,  True]], dtype=bool)

numpy.full(Size, Scalar Value, Type). There is other arguments as well that can be passed, for documentation on that, check https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html

Changing file permission in Python

FYI here is a function to convert a permission string with 9 characters (e.g. 'rwsr-x-wt') to a mask that can be used with os.chmod().

def perm2mask(p):
        
    assert len(p) == 9, 'Bad permission length'
    assert all(p[k] in 'rw-' for k in [0,1,3,4,6,7]), 'Bad permission format (read-write)'
    assert all(p[k] in 'xs-' for k in [2,5]), 'Bad permission format (execute)'
    assert p[8] in 'xt-', 'Bad permission format (execute other)'
    
    m = 0
    
    if p[0] == 'r': m |= stat.S_IRUSR 
    if p[1] == 'w': m |= stat.S_IWUSR 
    if p[2] == 'x': m |= stat.S_IXUSR 
    if p[2] == 's': m |= stat.S_IXUSR | stat.S_ISUID 
    
    if p[3] == 'r': m |= stat.S_IRGRP 
    if p[4] == 'w': m |= stat.S_IWGRP 
    if p[5] == 'x': m |= stat.S_IXGRP 
    if p[5] == 's': m |= stat.S_IXGRP | stat.S_ISGID 
    
    if p[6] == 'r': m |= stat.S_IROTH 
    if p[7] == 'w': m |= stat.S_IWOTH 
    if p[8] == 'x': m |= stat.S_IXOTH 
    if p[8] == 't': m |= stat.S_IXOTH | stat.S_ISVTX
    
    return m

Note that setting SUID/SGID/SVTX bits will automatically set the corresponding execute bit. Without this, the resulting permission would be invalid (ST characters).

How to check if an object implements an interface?

For an instance

Character.Gorgon gor = new Character.Gorgon();

Then do

gor instanceof Monster

For a Class instance do

Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);

JavaScript array to CSV

ES6:

let csv = test_array.map(row=>row.join(',')).join('\n') 
//test_array being your 2D array

Adding value to input field with jQuery

$.each(obj, function(index, value) {
    $('#looking_for_job_titles').tagsinput('add', value);
    console.log(value);
});

Facebook share link - can you customize the message body text?

You can't do this using sharer.php, but you can do something similar using the Dialog API. http://developers.facebook.com/docs/reference/dialogs/

http://www.facebook.com/dialog/feed?  
app_id=123050457758183&  
link=http://developers.facebook.com/docs/reference/dialogs/&
picture=http://fbrell.com/f8.jpg&  
name=Facebook%20Dialogs&  
caption=Reference%20Documentation& 
description=Dialogs%20provide%20a%20simple,%20consistent%20interface%20for%20applications%20to%20interact%20with%20users.&
message=Facebook%20Dialogs%20are%20so%20easy!&
redirect_uri=http://www.example.com/response

Facebook dialog example

The catch is you must create a dummy Facebook application just to have an app_id. Note that your Facebook application doesn't have to do ANYTHING at all. Just be sure that it is properly configured, and you should be all set.

Adding an img element to a div with javascript

The following solution seems to be a much shorter version for that:

<div id="imageDiv"></div>

In Javascript:

document.getElementById('imageDiv').innerHTML = '<img width="100" height="100" src="images/hydrangeas.jpg">';

Error: "setFile(null,false) call failed" when using log4j

if it is window7(like mine), without administrative rights cannot write a file at C: drive

just give another folder in log4j.properties file

Set the name of the file

log4j.appender.FILE.File=C:\server\log.out you can see with notepad++

Keep CMD open after BAT file executes

Depending on how you are running the command, you can put /k after cmd to keep the window open.

cmd /k my_script.bat

Simply adding cmd /k to the end of your batch file will work too. Credit to Luigi D'Amico who posted about this in the comments below.

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}

javax.naming.NameNotFoundException

I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound

This means that nothing is bound to the jndi name greetJndi, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.

Is there any specific directory structure to deploy in JBoss?

The internal structure of the ejb-jar is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):

.
+-- greetBean.java
+-- greetHome.java
+-- greetRemote.java
+-- META-INF
    +-- ejb-jar.xml
    +-- jboss.xml

But as already mentioned, this tutorial is full of mistakes:

  • there is an extra character (<enterprise-beans>] <-- HERE) in the ejb-jar.xml (!)
  • a space is missing after PUBLIC in the ejb-jar.xml and jboss.xml (!!)
  • the jboss.xml is incorrect, it should contain a session element instead of entity (!!!)

Here is a "fixed" version of the ejb-jar.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <home>greetHome</home>
      <remote>greetRemote</remote>
      <ejb-class>greetBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
</ejb-jar>

And of the jboss.xml:

<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <jndi-name>greetJndi</jndi-name>
    </session>
  </enterprise-beans>
</jboss>

After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:

21:48:06,512 INFO  [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/}
21:48:06,534 INFO  [EjbDeployer] installing bean: ejb/#greetBean,uid19981448
21:48:06,534 INFO  [EjbDeployer]   with dependencies:
21:48:06,534 INFO  [EjbDeployer]   and supplies:
21:48:06,534 INFO  [EjbDeployer]    jndi:greetJndi
21:48:06,624 INFO  [EjbModule] Deploying greetBean
21:48:06,661 WARN  [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/
21:48:06,805 INFO  [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'

That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.

Subscript out of bounds - general definition and solution?

This came from standford's sna free tutorial and it states that ...

# Reachability can only be computed on one vertex at a time. To # get graph-wide statistics, change the value of "vertex" # manually or write a for loop. (Remember that, unlike R objects, # igraph objects are numbered from 0.)

ok, so when ever using igraph, the first roll/column is 0 other than 1, but matrix starts at 1, thus for any calculation under igraph, you would need x-1, shown at

this_node_reach <- subcomponent(g, (i - 1), mode = m)

but for the alter calculation, there is a typo here

alter = this_node_reach[j] + 1

delete +1 and it will work alright

Change jsp on button click

You have several options, I'll start from the easiest:

1- Change the input buttons to links, you can style them with css so they look like buttons:

<a href="CreateCourse.jsp">Creazione Nuovo Corso</a>

instead of

<input type="button" value="Creazione Nuovo Corso" name="CreateCourse" />

2- Use javascript to change the action of the form depending on the button you click:

<input type="button" value="Creazione Nuovo Corso" name="CreateCourse" 
onclick="document.forms[0].action = 'CreateCourse.jsp'; return true;" />

3- Use a servlet or JSP to handle the request and redirect or forward to the appropriate JSP page.

HTML image not showing in Gmail

Try to add title and alt properties to your image.... Gmail and some others blocks images without some attributes.. and it is also a logic to include your email to be read as spam.

Twitter bootstrap scrollable modal

The problem with @grenoult's CSS solution (which does work, mostly), is that it is fully responsive and on mobile when the keyboard pops up (i.e. when they click in an input in the modal dialog) the screen size changes and the modal dialog's size changes and it can hide the input they just clicked on so they can't see what they are typing.

The better solution for me was to use jquery as follows:

$(".modal-body").css({ "max-height" : $(window).height() - 212, "overflow-y" : "auto" });

It isn't responsive to changing the window size, but that doesn't happen that often anyway.

How to allow only numbers in textbox in mvc4 razor

Use a regular expression, e.g.

[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Count must be a natural number")]
public int Count { get; set; }

Remove space above and below <p> tag HTML

There are two ways:

The best way is to remove the <p> altogether. It is acting according to specification when it adds space.

Alternately, use CSS to style the <p>. Something like:

ul li p {
    padding: 0;
    margin: 0;
    display: inline;
}

Javascript to stop HTML5 video playback on modal window close

None of these worked for me using 4.1 video.js CDN. This code kills the video playing in a modal when the (.closemodal) is clicked. I had 3 videos. Someone else can refactor.


var myPlayer = videojs("my_video_1");
var myPlayer2 = videojs("my_video_2");
var myPlayer3 = videojs("my_video_3");
$(".closemodal").click(function(){
   myPlayer.pause();
myPlayer2.pause();
myPlayer3.pause();
});
});

as per their Api docs.

Convert a row of a data frame to vector

When you extract a single row from a data frame you get a one-row data frame. Convert it to a numeric vector:

as.numeric(df[1,])

As @Roland suggests, unlist(df[1,]) will convert the one-row data frame to a numeric vector without dropping the names. Therefore unname(unlist(df[1,])) is another, slightly more explicit way to get to the same result.

As @Josh comments below, if you have a not-completely-numeric (alphabetic, factor, mixed ...) data frame, you need as.character(df[1,]) instead.

Error: Jump to case label

C++11 standard on jumping over some initializations

JohannesD gave an explanation, now for the standards.

The C++11 N3337 standard draft 6.7 "Declaration statement" says:

3 It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps (87) from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).

87) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.

[ Example:

void f() {
   // ...
  goto lx;    // ill-formed: jump into scope of a
  // ...
ly:
  X a = 1;
  // ...
lx:
  goto ly;    // OK, jump implies destructor
              // call for a followed by construction
              // again immediately following label ly
}

— end example ]

As of GCC 5.2, the error message now says:

crosses initialization of

C

C allows it: c99 goto past initialization

The C99 N1256 standard draft Annex I "Common warnings" says:

2 A block with initialization of an object that has automatic storage duration is jumped into

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

Initially used only ViewDidLoad with tableView. On testing with loss of Wifi, by setting device to airplane mode, realized that the table did not refresh with return of Wifi. In fact, there appears to be no way to refresh tableView on the device even by hitting the home button with background mode set to YES in -Info.plist.

My solution:

-(void) viewWillAppear: (BOOL) animated { [self.tableView reloadData];}

Storing sex (gender) in database

I would go with Option 3 but multiple NON NULLABLE bit columns instead of one. IsMale (1=Yes / 0=No) IsFemale (1=Yes / 0=No)

if requried: IsUnknownGender (1=Yes / 0=No) and so on...

This makes for easy reading of the definitions, easy extensibility, easy programmability, no possibility of using values outside the domain and no requirement of a second lookup table+FK or CHECK constraints to lock down the values.

EDIT: Correction, you do need at least one constraint to ensure the set flags are valid.

How to list only files and not directories of a directory Bash?

You can also use ls with grep or egrep and put it in your profile as an alias:

ls -l | egrep -v '^d'
ls -l | grep -v '^d'

Chrome, Javascript, window.open in new tab

if you use window.open(url, '_blank') , it will be blocked(popup blocker) on Chrome,Firefox etc

try this,

$('#myButton').click(function () {
    var redirectWindow = window.open('http://google.com', '_blank');
    redirectWindow.location;
});

working js fiddle for this http://jsfiddle.net/safeeronline/70kdacL4/2/

working js fiddle for ajax window open http://jsfiddle.net/safeeronline/70kdacL4/1/

Forward host port to docker container

Your docker host exposes an adapter to all the containers. Assuming you are on recent ubuntu, you can run

ip addr

This will give you a list of network adapters, one of which will look something like

3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether 22:23:6b:28:6b:e0 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
inet6 fe80::a402:65ff:fe86:bba6/64 scope link
   valid_lft forever preferred_lft forever

You will need to tell rabbit/mongo to bind to that IP (172.17.42.1). After that, you should be able to open connections to 172.17.42.1 from within your containers.

Converting a sentence string to a string array of words in Java

Try using the following:

String str = "This is a simple sentence";
String[] strgs = str.split(" ");

That will create a substring at each index of the array of strings using the space as a split point.

How to enter in a Docker container already running with a new TTY

On Windows 10, I have docker installed. I am running Jnekins on a container and I encountered the same error message. Here is a step by step guide to resolve this issue:

Step 1: Open gitbash and run docker run -p 8080:8080 -p 50000:50000 jenkins.

Step 2: Open a new terminal.

Step 3: Do "docker ps" to get list of the running container. Copy the container id.

Step 4: Now if you do "docker exec -it {container id} sh" or "docker exec -it {container id} bash" you will get an error message similar to " the input device is not a TTY. If you are using mintty, try prefixing the command with 'winpty'"

Step 5: Run command " $winpty docker exec -it {container id} sh"

vola !! You are now inside the terminal.

What is a stack pointer used for in microprocessors?

Should you ever crave deeper understanding, I heartily recommend Patterson and Hennessy as an intro and Hennessy and Patterson as an intermediate to advanced text. They're pricey, but truly non-pareil; I just wish either or both were available when I got my Masters' degree and entered the workforce designing chips, systems, and parts of system software for them (but, alas!, that was WAY too long ago;-). Stack pointers are so crucial (and the distinction between a microprocessor and any other kind of CPU so utterly meaningful in this context... or, for that matter, in ANY other context, in the last few decades...!-) that I doubt anything but a couple of thorough from-the-ground-up refreshers can help!-)

Java random number with given length

Generate a random number (which is always between 0-1) and multiply by 1000000

Math.round(Math.random()*1000000);

Ajax request returns 200 OK, but an error event is fired instead of success

I reckon your aspx page doesn't return a JSON object. Your page should do something like this (page_load)

var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);

Response.Write(OutPut);

Also, try to change your AjaxFailed:

function AjaxFailed (XMLHttpRequest, textStatus) {

}

textStatus should give you the type of error you're getting.

MySQL GROUP BY two columns

First, let's make some test data:

create table client (client_id integer not null primary key auto_increment,
                     name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
                        client_id integer references client.id,
                        cash decimal(10,2),
                        stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
                                                       (1, 10.11, 23.22),
                                                       (2, 30.30, 40.40),
                                                       (2, 40.40, 50.50);

If you didn't need the portfolio ID, it would be easy:

select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id

+-----------+----------+--------------------+
| client_id | name     | max(cash + stocks) |
+-----------+----------+--------------------+
|         1 | John Doe |              33.33 | 
|         2 | Jane Doe |              90.90 | 
+-----------+----------+--------------------+

Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:

select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id

+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
|         1 |    33.33 | 
|         2 |    90.90 | 
+-----------+----------+

Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:

 select portfolio_id, cash + stocks from portfolio 
 join (select client_id, max(cash + stocks) as maxtotal 
       from portfolio
       group by client_id) as maxima
 using (client_id)
 where cash + stocks = maxtotal

+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
|            5 |         33.33 | 
|            6 |         33.33 | 
|            8 |         90.90 | 
+--------------+---------------+

Finally, we can join to the client table (as you did) in order to include the name of each client:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         1 | John Doe |            6 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

How to extract numbers from a string and get an array of ints?

I would suggest to check the ASCII values to extract numbers from a String Suppose you have an input String as myname12345 and if you want to just extract the numbers 12345 you can do so by first converting the String to Character Array then use the following pseudocode

    for(int i=0; i < CharacterArray.length; i++)
    {
        if( a[i] >=48 && a[i] <= 58)
            System.out.print(a[i]);
    }

once the numbers are extracted append them to an array

Hope this helps

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

Adding a column to an existing table in a Rails migration

Sometimes rails generate migration add_email_to_users email:string produces a migration like this

class AddEmailToUsers < ActiveRecord::Migration[5.0]
  def change
  end
end

In that case you have to manually an add_column to change:

class AddEmailToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :email, :string
  end
end

And then run rake db:migrate

Create an empty list in python with certain size

Here's my code for 2D list in python which would read no. of rows from the input :

empty = []
row = int(input())

for i in range(row):
    temp = list(map(int, input().split()))
    empty.append(temp)

for i in empty:
    for j in i:
        print(j, end=' ')
    print('')

How to check if a string contains text from an array of substrings in JavaScript?

substringsArray.every(substring=>yourBigString.indexOf(substring) === -1)

For full support ;)

How do I output the results of a HiveQL query to CSV?

I may be late to this one, but would help with the answer:

echo "COL_NAME1|COL_NAME2|COL_NAME3|COL_NAME4" > SAMPLE_Data.csv hive -e ' select distinct concat(COL_1, "|", COL_2, "|", COL_3, "|", COL_4) from table_Name where clause if required;' >> SAMPLE_Data.csv

onKeyPress Vs. onKeyUp and onKeyDown

A few practical facts that might be useful to decide which event to handle (run the script below and focus on the input box):

_x000D_
_x000D_
$('input').on('keyup keydown keypress',e=>console.log(e.type, e.keyCode, e.which, e.key))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input/>
_x000D_
_x000D_
_x000D_

Pressing:

  • non inserting/typing keys (e.g. Shift, Ctrl) will not trigger a keypress. Press Ctrl and release it:

    keydown 17 17 Control

    keyup 17 17 Control

  • keys from keyboards that apply characters transformations to other characters may lead to Dead and duplicate "keys" (e.g. ~, ´) on keydown. Press ´ and release it in order to display a double ´´:

    keydown 192 192 Dead

    keydown 192 192 ´´

    keypress 180 180 ´

    keypress 180 180 ´

    keyup 192 192 Dead

Additionally, non typing inputs (e.g. ranged <input type="range">) will still trigger all keyup, keydown and keypress events according to the pressed keys.

Execution time of C program

ANSI C only specifies second precision time functions. However, if you are running in a POSIX environment you can use the gettimeofday() function that provides microseconds resolution of time passed since the UNIX Epoch.

As a side note, I wouldn't recommend using clock() since it is badly implemented on many(if not all?) systems and not accurate, besides the fact that it only refers to how long your program has spent on the CPU and not the total lifetime of the program, which according to your question is what I assume you would like to measure.

How do I get and set Environment variables in C#?

I could be able to update the environment variable by using the following

string EnvPath = System.Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine) ?? string.Empty;
if (!string.IsNullOrEmpty(EnvPath) && !EnvPath .EndsWith(";"))
    EnvPath = EnvPath + ';';
EnvPath = EnvPath + @"C:\Test";
Environment.SetEnvironmentVariable("PATH", EnvPath , EnvironmentVariableTarget.Machine);

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

If you place the dollar sign before the letter, you will affect only the column, not the row. If you want to have it affect only a row, place the dollar before the number.

You may want to use =isblank() rather than =""

I'm also confused by your comment "no values throughout spreadsheet - just text" - text is a value.

One more hint - excel has a habit of rewriting rules - I don't know how many rules I've written only to discover that excel has changed the values in the "apply to" or formula entry fields.

If you could post an example, I'll revise the answer. Conditional formatting is very finicky.

Removing numbers from string

Not sure if your teacher allows you to use filters but...

filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h")

returns-

'aaasdffgh'

Much more efficient than looping...

Example:

for i in range(10):
  a.replace(str(i),'')

Return list from async/await method

Works for me:

List<Item> list = Task.Run(() => manager.GetList()).Result;

in this way it is not necessary to mark the method with async in the call.

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

The mail server on CentOS 6 and other IPv6 capable server platforms may be bound to IPv6 localhost (::1) instead of IPv4 localhost (127.0.0.1).

Typical symptoms:

[root@host /]# telnet 127.0.0.1 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused

[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100

[root@host /]# netstat -plant | grep 25
tcp        0      0 :::25                       :::*                        LISTEN      1082/exim           

If this happens, make sure that you don't have two entries for localhost in /etc/hosts with different IP addresses, like this (bad) example:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost.localdomain localhost localhost4.localdomain4 localhost4
::1       localhost localhost.localdomain localhost6 localhost6.localdomain6

To avoid confusion, make sure you only have one entry for localhost, preferably an IPv4 address, like this:

[root@host /]# cat /etc/hosts
127.0.0.1 localhost  localhost.localdomain   localhost4.localdomain4 localhost4
::1       localhost6 localhost6.localdomain6

How to list containers in Docker

To show only running containers use the given command:

docker ps

To show all containers use the given command:

docker ps -a

To show the latest created container (includes all states) use the given command:

docker ps -l

To show n last created containers (includes all states) use the given command:

docker ps -n=-1

To display total file sizes use the given command:

docker ps -s

The content presented above is from docker.com.

In the new version of Docker, commands are updated, and some management commands are added:

docker container ls

It is used to list all the running containers.

docker container ls -a

And then, if you want to clean them all,

docker rm $(docker ps -aq)

It is used to list all the containers created irrespective of its state.

And to stop all the Docker containers (force)

docker rm -f $(docker ps -a -q)  

Here the container is the management command.

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

enter image description here Had the same issue , I finally got it working after some trying. Here are the 8 html tags that I used on my web page to get the preview working :

In <head> tag:

<meta property="og:title" content="ABC Blabla 2020 Friday" />
<meta property="og:url" content="https://bla123.neocities.org/mp/friday.html" />
<meta property="og:description" content="Photo Album">
<meta property="og:image" itemprop="image" content="https://bla123.neocities.org/mp/images/thumbs/IMG_327.JPG"/>
<meta property="og:type" content="article" />
<meta property="og:locale" content="en_GB" />

In <body> tag:

<link itemprop="thumbnailUrl" href="https://bla123.neocities.org/mp/images/thumbs/IMG_327.JPG">

<span itemprop="thumbnail" itemscope itemtype="http://schema.org/ImageObject">
<link itemprop="url" href="https://bla123.neocities.org/mp/images/thumbs/IMG_327.JPG">
</span>

These 8 tags ( 6 in head , 2 in body) worked perfectly.

Tips:

1.Use the exact image location URL instead of directory format i.e. don't use images/OG_thumb.jpg

2.Case sensitive file extension: If the image extension name on your hosting provider is ".JPG" then do not use ".jpg" or ".jpeg' . I observed that based on hosting provider and browser combination error may or may not occur, so to be safe its easier to just match the case of file extension.

3.After doing above steps if the thumbnail preview is still not showing up in WhatsApp message then:

a. Force stop the mobile app ( I tried in Android) and try again

b.Use online tool to preview the OG tag eg I used : https://searchenginereports.net/open-graph-checker

c. In mobile browser paste direct link to the OG thumb and refresh the browser 4-5 times . eg https://bla123neocities.org/nmp/images/thumbs/IMG_327.JPG

Uses of content-disposition in an HTTP response header

Well, it seems that the Content-Disposition header was originally created for e-mail, not the web. (Link to relevant RFC.)

I'm guessing that web browsers may respond to

Response.AppendHeader("content-disposition", "inline; filename=" + fileName);

when saving, but I'm not sure.

Eclipse will not start and I haven't changed anything

Today, I had the same problem. My eclipse refused to start. When I double clicked on Eclipse icon I was able to see splashscreen for a second and then nothing happen. Tried most of the solutions here: removed lock file, renamed workspace, tried to start Eclipse with different clean parameters. I even put a new copy of Eclispe and tried to start with a new workspace. Nothing!

My logs were showing bunch of errors from yesterday when my workstation was rebooted at 17:45.

!ENTRY org.eclipse.ui.workbench 4 2 2014-12-17 17:45:12.178
!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.ui.workbench".
!STACK 0
java.lang.NullPointerException

In the end this very simple change (look below) saved my Eclipse together with my workspace!

SOLUTION:

I edited eclipse.ini and added following line:

-vm
C:\Program Files\Java\jdk1.6.0_26\bin\javaw.exe

Eclipse has started again with all my projects inside! I hope this can help.

Why does ASP.NET webforms need the Runat="Server" attribute?

I usually don't like to guess, but I'm going to on this one...

If you remember Microsoft's .NET marketing hype back in the day (2001?), it was hard to tell what .NET even was. Was it a server? a programming platform? a language? something new entirely? Given the ads, it was ambiguously anything you wanted it to be - it just solved any problem you might have.

So, my guess is there was a hidden grand vision that ASP.NET code could run anywhere - server side OR client side, in a copy of Internet Explorer tied to the .NET runtime. runat="server" is just a vestigial remnant, left behind because it's client-side equivalent never made it to production.

Remember those weird ads?

Related: Article from The Register with some .NET history.

How does one create an InputStream from a String?

Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:

InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );

Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.

How do I access my webcam in Python?

gstreamer can handle webcam input. If I remeber well, there are python bindings for it!

How do I format a String in an email so Outlook will print the line breaks?

For Outlook 2010 and later versions, use \t\n rather than using \r\n.

Why does PEP-8 specify a maximum line length of 79 characters?

I am a programmer who has to deal with a lot of code on a daily basis. Open source and what has been developed in house.

As a programmer, I find it useful to have many source files open at once, and often organise my desktop on my (widescreen) monitor so that two source files are side by side. I might be programming in both, or just reading one and programming in the other.

I find it dissatisfying and frustrating when one of those source files is >120 characters in width, because it means I can't comfortably fit a line of code on a line of screen. It upsets formatting to line wrap.

I say '120' because that's the level to which I would get annoyed at code being wider than. After that many characters, you should be splitting across lines for readability, let alone coding standards.

I write code with 80 columns in mind. This is just so that when I do leak over that boundary, it's not such a bad thing.

How do I grant myself admin access to a local SQL Server instance?

I adopted a SQL 2012 database where I was not a sysadmin but was an administrator on the machine. I used SSMS with "Run as Administrator", added my NT account as a SQL login and set the server role to sysadmin. No problem.

SQL Server : converting varchar to INT

I would try triming the number to see what you get:

select len(rtrim(ltrim(userid))) from audit

if that return the correct value then just do:

select convert(int, rtrim(ltrim(userid))) from audit

if that doesn't return the correct value then I would do a replace to remove the empty space:

 select convert(int, replace(userid, char(0), '')) from audit

Best way to do a PHP switch with multiple values per case?

Some other ideas not mentioned yet:

switch(true){ 
  case in_array($p, array('home', '')): 
    $current_home = 'current'; break;

  case preg_match('/^users\.(online|location|featured|new|browse|search|staff)$/', $p):
    $current_users = 'current'; break;

  case 'forum' == $p:
    $current_forum = 'current'; break; 
}

Someone will probably complain about readability issues with #2, but I would have no problem inheriting code like that.

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

Dynamically:

editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_NUM) });

Via xml:

<EditText
    android:maxLength="@integer/max_edittext_length"

Simple way to calculate median with MySQL

Taken from: http://mdb-blog.blogspot.com/2015/06/mysql-find-median-nth-element-without.html

I would suggest another way, without join, but working with strings

i did not checked it with tables with large data, but small/medium tables it works just fine.

The good thing here, that it works also by GROUPING so it can return the median for several items.

here is test code for test table:

DROP TABLE test.test_median
CREATE TABLE test.test_median AS
SELECT 'book' AS grp, 4 AS val UNION ALL
SELECT 'book', 7 UNION ALL
SELECT 'book', 2 UNION ALL
SELECT 'book', 2 UNION ALL
SELECT 'book', 9 UNION ALL
SELECT 'book', 8 UNION ALL
SELECT 'book', 3 UNION ALL

SELECT 'note', 11 UNION ALL

SELECT 'bike', 22 UNION ALL
SELECT 'bike', 26 

and the code for finding the median for each group:

SELECT grp,
         SUBSTRING_INDEX( SUBSTRING_INDEX( GROUP_CONCAT(val ORDER BY val), ',', COUNT(*)/2 ), ',', -1) as the_median,
         GROUP_CONCAT(val ORDER BY val) as all_vals_for_debug
FROM test.test_median
GROUP BY grp

Output:

grp | the_median| all_vals_for_debug
bike| 22        | 22,26
book| 4         | 2,2,3,4,7,8,9
note| 11        | 11