Programs & Examples On #Self documenting code

Deleting all records in a database table

if you want to completely empty the database and not just delete a model or models attached to it you can do:

rake db:purge

you can also do it on the test database

rake db:test:purge

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

Printing out a number in assembly language?

You might have some luck calling the Win32 API's MessageBoxA, although whether Win16 supports that particular method is for someone else to answer.

how to loop through each row of dataFrame in pyspark

Using list comprehensions in python, you can collect an entire column of values into a list using just two lines:

df = sqlContext.sql("show tables in default")
tableList = [x["tableName"] for x in df.rdd.collect()]

In the above example, we return a list of tables in database 'default', but the same can be adapted by replacing the query used in sql().

Or more abbreviated:

tableList = [x["tableName"] for x in sqlContext.sql("show tables in default").rdd.collect()]

And for your example of three columns, we can create a list of dictionaries, and then iterate through them in a for loop.

sql_text = "select name, age, city from user"
tupleList = [{name:x["name"], age:x["age"], city:x["city"]} 
             for x in sqlContext.sql(sql_text).rdd.collect()]
for row in tupleList:
    print("{} is a {} year old from {}".format(
        row["name"],
        row["age"],
        row["city"]))

How do I remove the file suffix and path portion from a path string in Bash?

Beware of the suggested perl solution: it removes anything after the first dot.

$ echo some.file.with.dots | perl -pe 's/\..*$//;s{^.*/}{}'
some

If you want to do it with perl, this works:

$ echo some.file.with.dots | perl -pe 's/(.*)\..*$/$1/;s{^.*/}{}'
some.file.with

But if you are using Bash, the solutions with y=${x%.*} (or basename "$x" .ext if you know the extension) are much simpler.

check if a key exists in a bucket in s3 using boto3

You can use S3Fs, which is essentially a wrapper around boto3 that exposes typical file-system style operations:

import s3fs
s3 = s3fs.S3FileSystem()
s3.exists('myfile.txt')

Git command to show which specific files are ignored by .gitignore

Here's how to print the complete list of files in the working tree which match patterns located anywhere in Git's multiple gitignore sources (if you're using GNU find):

$ cd {your project directory}
$ find . -path ./.git -prune -o -print \
| git check-ignore --no-index --stdin --verbose

It will check all the files in the current branch of the repository (unless you've deleted them locally).

And it identifies the particular gitignore source lines, as well.

Git continues to track changes in some files which match gitignore patterns, simply because those files were added already. Usefully, the above command displays those files, too.

Negative gitignore patterns are also matched. However, these are easily distinguishable in the listing, because they begin with !.

If you're using Windows, Git Bash includes GNU find (as revealed by find --version).

If the list is long (and you have rev), you can display them by extension (somewhat), too:

$ cd {your project directory}
$ find . -path ./.git -prune -o -print \
| git check-ignore --no-index --stdin --verbose \
| rev | sort | rev

For more details, see man find, man git-check-ignore, man rev, and man sort.

The point of this whole approach is that Git (the software) is changing rapidly and is highly complex. By contrast, GNU's find is extremely stable (at least, in its features used here). So, anyone who desires to be competitive by displaying their in-depth knowledge of Git will answer the question in a different way.

What's the best answer? This answer deliberately minimizes its reliance on Git knowledge, toward achieving the goal of stability and simplicity through modularity (information isolation), and is designed to last a long time.

CSS transition effect makes image blurry / moves image 1px, in Chrome?

Scaling to double and bringing down to half with zoom worked for me.

transform: scale(2);
zoom: 0.5;

Get current time in milliseconds using C++ and Boost

Try this: import headers as mentioned.. gives seconds and milliseconds only. If you need to explain the code read this link.

#include <windows.h>

#include <stdio.h>

void main()
{

    SYSTEMTIME st;
    SYSTEMTIME lt;

    GetSystemTime(&st);
   // GetLocalTime(&lt);

     printf("The system time is: %02d:%03d\n", st.wSecond, st.wMilliseconds);
   //  printf("The local time is: %02d:%03d\n", lt.wSecond, lt.wMilliseconds);

}

How to find the Target *.exe file of *.appref-ms

ClickOnce applications are stored under the user's profile at %LocalAppData%\Apps\2.0\.

From there, use the search function to find your application.

TypeError: Converting circular structure to JSON in nodejs

It's because you don't an async response For example:

app.get(`${api}/users`, async (req, res) => {
    const users = await User.find()
    res.send(users);
   })

Python float to int conversion

int converts by truncation, as has been mentioned by others. This can result in the answer being one different than expected. One way around this is to check if the result is 'close enough' to an integer and adjust accordingly, otherwise the usual conversion. This is assuming you don't get too much roundoff and calculation error, which is a separate issue. For example:

def toint(f):
    trunc = int(f)
    diff = f - trunc

    # trunc is one too low
    if abs(f - trunc - 1) < 0.00001:
        return trunc + 1
    # trunc is one too high
    if abs(f - trunc + 1) < 0.00001:
        return trunc - 1
    # trunc is the right value
    return trunc

This function will adjust for off-by-one errors for near integers. The mpmath library does something similar for floating point numbers that are close to integers.

Set colspan dynamically with jquery

I have adapted the script from Russ Cam (thank you, Russ Cam!) to my own needs: I needed to merge any columns that had the same value, not just empty cells.

This could be useful to someone else... Here is what I have come up with:

jQuery(document).ready(function() {

   jQuery('table.tblSimpleAgenda tr').each(function() {
    var tr = this;
    var counter = 0;
    var strLookupText = '';

    jQuery('td', tr).each(function(index, value) {
      var td = jQuery(this);

      if ((td.text() == strLookupText) || (td.text() == "")) {
        counter++;
        td.prev().attr('colSpan', '' + parseInt(counter + 1,10) + '').css({textAlign : 'center'});
        td.remove();
      }
      else {
        counter = 0;
      }

      // Sets the strLookupText variable to hold the current value. The next time in the loop the system will check the current value against the previous value.
      strLookupText = td.text();

    });

  });

});

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

You can use functions in pyspark.sql.functions: functions like year, month, etc

refer to here: https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame

from pyspark.sql.functions import *

newdf = elevDF.select(year(elevDF.date).alias('dt_year'), month(elevDF.date).alias('dt_month'), dayofmonth(elevDF.date).alias('dt_day'), dayofyear(elevDF.date).alias('dt_dayofy'), hour(elevDF.date).alias('dt_hour'), minute(elevDF.date).alias('dt_min'), weekofyear(elevDF.date).alias('dt_week_no'), unix_timestamp(elevDF.date).alias('dt_int'))

newdf.show()


+-------+--------+------+---------+-------+------+----------+----------+
|dt_year|dt_month|dt_day|dt_dayofy|dt_hour|dt_min|dt_week_no|    dt_int|
+-------+--------+------+---------+-------+------+----------+----------+
|   2015|       9|     6|      249|      0|     0|        36|1441497601|
|   2015|       9|     6|      249|      0|     0|        36|1441497601|
|   2015|       9|     6|      249|      0|     0|        36|1441497603|
|   2015|       9|     6|      249|      0|     1|        36|1441497694|
|   2015|       9|     6|      249|      0|    20|        36|1441498808|
|   2015|       9|     6|      249|      0|    20|        36|1441498811|
|   2015|       9|     6|      249|      0|    20|        36|1441498815|

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

How to get elements with multiple classes

Okay this code does exactly what you need:

HTML:

<div class="class1">nothing happens hear.</div>

<div class="class1 class2">This element will receive yout code.</div>

<div class="class1">nothing happens hear.</div>

JS:

function getElementMultipleClasses() {
    var x = document.getElementsByClassName("class1 class2");
    x[0].innerHTML = "This is the element you want";
}
getElementMultipleClasses();

Hope it helps! ;)

How to install wget in macOS?

For macOS Sierra, to build wget 1.18 from source with Xcode 8.2.

  1. Install Xcode

  2. Build OpenSSL

    Since Xcode doesn't come with OpenSSL lib, you need build by yourself. I found this: https://github.com/sqlcipher/openssl-xcode, follow instruction and build OpenSSL lib. Then, prepare your OpenSSL directory with "include" and "lib/libcrypto.a", "lib/libssl.a" in it.

    Let's say it is: "/Users/xxx/openssl-xcode/openssl", so there should be "/Users/xxx/openssl-xcode/openssl/include" for OpenSSL include and "/Users/xxx/openssl-xcode/openssl/lib" for "libcrypto.a" and "libssl.a".

  3. Build wget

    Go to wget directory, configure:

    ./configure --with-ssl=openssl --with-libssl-prefix=/Users/xxx/openssl-xcode/openssl
    

    wget should configure and found OpenSSL, then make:

    make
    

    wget made out. Install wget:

    make install
    

    Or just copy wget to where you want.

  4. Configure cert

    You may find wget cannot verify any https connection, because there is no CA certs for the OpenSSL you built. You need to run:

    New way:

    If you machine doesn't have "/usr/local/ssl/" dir, first make it.

    ln -s /etc/ssl/cert.pem /usr/local/ssl/cert.pem
    

    Old way:

    security find-certificate -a -p /Library/Keychains/System.keychain > cert.pem
    security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> cert.pem
    

    Then put cert.pem to: "/usr/local/ssl/cert.pem"

    DONE: It should be all right now.

How to call Stored Procedures with EntityFramework?

Based up the OP's original request to be able to called a stored proc like this...

using (Entities context = new Entities())
{
    context.MyStoreadProcedure(Parameters); 
}

Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....

using (testentities te = new testentities())
{
    //-------------------------------------------------------------
    // Simple stored proc
    //-------------------------------------------------------------
    var parms1 = new testone() { inparm = "abcd" };
    var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
    var r1 = results1.ToList<TestOneResultSet>();
}

... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...

[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
    [TestMethod]
    public void GetTenantForName_ReturnsOneRecord()
    {
        // ARRANGE
        const int expectedCount = 1;
        const string expectedName = "Me";

        // Build the paraemeters object
        var parameters = new GetTenantForTenantNameParameters
        {
            TenantName = expectedName
        };

        // get an instance of the stored procedure passing the parameters
        var procedure = new GetTenantForTenantNameProcedure(parameters);

        // Initialise the procedure name and schema from procedure attributes
        procedure.InitializeFromAttributes();

        // Add some tenants to context so we have something for the procedure to return!
        AddTenentsToContext(Context);

        // ACT
        // Get the results by calling the stored procedure from the context extention method 
        var results = Context.ExecuteStoredProcedure(procedure);

        // ASSERT
        Assert.AreEqual(expectedCount, results.Count);
    }
}

internal class GetTenantForTenantNameParameters
{
    [Name("TenantName")]
    [Size(100)]
    [ParameterDbType(SqlDbType.VarChar)]
    public string TenantName { get; set; }
}

[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
    : StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
    public GetTenantForTenantNameProcedure(
        GetTenantForTenantNameParameters parameters)
        : base(parameters)
    {
    }
}

If either of those two approaches are any good?

Extract month and year from a zoo::yearmon object

For large vectors:

y = as.POSIXlt(date1)$year + 1900    # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1        # x$mon : 0–11

In C#, what's the difference between \n and \r\n?

It's about how the operating system recognizes line ends.

  • Windows user \r\n
  • Mac user \r
  • Linux uses \n

Morale: if you are developing for Windows, stick to \r\n. Or even better, use C# string functions to deal with strings which already consider line endings (WriteLine, and such).

Android Studio gradle takes too long to build

I was facing the same problem for a long time but I solved it by adjusting the settings in gradle.

Step 1:In Module app add dependency in BuildScript

buildscript {
 dependencies {
         classpath 'com.android.tools.build:gradle:2.0.0-alpha9'
}
}

Step 2: Add dexOption and give the following heapSize

  dexOptions {
    incremental = true;
    preDexLibraries = false
    javaMaxHeapSize "4g"
}

Step 3: Add productFlavors

    productFlavors {
    dev {
        minSdkVersion 23
        applicationId = "com.Reading.home"
    }
    prod {
        minSdkVersion 15
        applicationId = "com.Reading.home" // you don't need it, but can be useful

    }
}

This should reduce your build time.

When to use <span> instead <p>?

Semantically speaking, a p is a paragraph tag and should be used to format a paragraph of text. A span is an inline formatting change that isn't handled semantically.

How to overlay density plots in R?

Whenever there are issues of mismatched axis limits, the right tool in base graphics is to use matplot. The key is to leverage the from and to arguments to density.default. It's a bit hackish, but fairly straightforward to roll yourself:

set.seed(102349)
x1 = rnorm(1000, mean = 5, sd = 3)
x2 = rnorm(5000, mean = 2, sd = 8)

xrng = range(x1, x2)

#force the x values at which density is
#  evaluated to be the same between 'density'
#  calls by specifying 'from' and 'to'
#  (and possibly 'n', if you'd like)
kde1 = density(x1, from = xrng[1L], to = xrng[2L])
kde2 = density(x2, from = xrng[1L], to = xrng[2L])

matplot(kde1$x, cbind(kde1$y, kde2$y))

A plot depicting the output of the call to matplot. Two curves are observed, one red, the other black; the black curve extends higher than the red, while the red curve is the "fatter".

Add bells and whistles as desired (matplot accepts all the standard plot/par arguments, e.g. lty, type, col, lwd, ...).

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

got the below error

PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm install vue npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! errno UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! request to https://registry.npmjs.org/vue failed, reason: unable to get local issuer certificate

npm ERR! A complete log of this run can be found in: npm ERR!
C:\Users\chpr\AppData\Roaming\npm-cache_logs\2020-07-29T03_22_40_225Z-debug.log PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm ERR!
C:\Users\chpr\AppData\Roaming\npm-cache_logs\2020-07-29T03_22_40_225Z-debug.log

Below command solved the issue:

npm config set strict-ssl false

Getting 404 Not Found error while trying to use ErrorDocument

The ErrorDocument directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot. In your case, this means that the actual path to the ErrorDocument is

ErrorDocument 404 /hellothere/error/404page.html

uncaught syntaxerror unexpected token U JSON

I experienced this error when I ran a find condition on a JSONArray within a for loop. The problem I faced was the result of one of the values in the for loop returning null. Hence, when I tried to access a property on that it failed.

So if you are doing anything within JSONArrays where you are not sure of the data source and its integrity I thinks its a good habit to deal with null and undefined exceptions in this case.

I fixed it by checking for null on the returned value of find on the JSONArray and handling exceptions appropriately.

Thought this might help.

SQL Bulk Insert with FIRSTROW parameter skips the following line

Maybe check that the header has the same line-ending as the actual data rows (as specified in ROWTERMINATOR)?

Update: from MSDN:

The FIRSTROW attribute is not intended to skip column headers. Skipping headers is not supported by the BULK INSERT statement. When skipping rows, the SQL Server Database Engine looks only at the field terminators, and does not validate the data in the fields of skipped rows.

How do I generate a list with a specified increment step?

You can use scalar multiplication to modify each element in your vector.

> r <- 0:10 
> r <- r * 2
> r 
 [1]  0  2  4  6  8 10 12 14 16 18 20

or

> r <- 0:10 * 2 
> r 
 [1]  0  2  4  6  8 10 12 14 16 18 20

Best algorithm for detecting cycles in a directed graph

Start with a DFS: a cycle exists if and only if a back-edge is discovered during DFS. This is proved as a result of white-path theorum.

Removing packages installed with go get

It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src and the package file under $GOPATH/pkg/<architecture>, for example: $GOPATH/pkg/windows_amd64.

Python Library Path

import sys
sys.path

Unix: How to delete files listed in a file

Use this:

while IFS= read -r file ; do rm -- "$file" ; done < delete.list

If you need glob expansion you can omit quoting $file:

IFS=""
while read -r file ; do rm -- $file ; done < delete.list

But be warned that file names can contain "problematic" content and I would use the unquoted version. Imagine this pattern in the file

*
*/*
*/*/*

This would delete quite a lot from the current directory! I would encourage you to prepare the delete list in a way that glob patterns aren't required anymore, and then use quoting like in my first example.

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

If you have an Order class, adding a property that references another class in your model, for instance Customer should be enough to let EF know there's a relationship in there:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    public virtual Customer Customer { get; set; }
}

You can always set the FK relation explicitly:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    [ForeignKey("Customer")]
    public string CustomerID { get; set; }
    public virtual Customer Customer { get; set; }
}

The ForeignKeyAttribute constructor takes a string as a parameter: if you place it on a foreign key property it represents the name of the associated navigation property. If you place it on the navigation property it represents the name of the associated foreign key.

What this means is, if you where to place the ForeignKeyAttribute on the Customer property, the attribute would take CustomerID in the constructor:

public string CustomerID { get; set; }
[ForeignKey("CustomerID")]
public virtual Customer Customer { get; set; }

EDIT based on Latest Code You get that error because of this line:

[ForeignKey("Parent")]
public Patient Patient { get; set; }

EF will look for a property called Parent to use it as the Foreign Key enforcer. You can do 2 things:

1) Remove the ForeignKeyAttribute and replace it with the RequiredAttribute to mark the relation as required:

[Required]
public virtual Patient Patient { get; set; }

Decorating a property with the RequiredAttribute also has a nice side effect: The relation in the database is created with ON DELETE CASCADE.

I would also recommend making the property virtual to enable Lazy Loading.

2) Create a property called Parent that will serve as a Foreign Key. In that case it probably makes more sense to call it for instance ParentID (you'll need to change the name in the ForeignKeyAttribute as well):

public int ParentID { get; set; }

In my experience in this case though it works better to have it the other way around:

[ForeignKey("Patient")]
public int ParentID { get; set; }

public virtual Patient Patient { get; set; }

Console.WriteLine and generic List

        List<int> a = new List<int>() { 1, 2, 3, 4, 5 };
        a.ForEach(p => Console.WriteLine(p));

edit: ahhh he beat me to it.

The server committed a protocol violation. Section=ResponseStatusLine ERROR

In my case the IIS did not have the necessary permissions to access the relevant ASPX path.

I gave the IIS user permissions to the relevant directory and all was well.

HTML form action and onsubmit issues

Try

onsubmit="return checkRegistration()"

Which @NotNull Java annotation should I use?

According to the Java 7 features list JSR-308 type annotations are deferred to Java 8. JSR-305 annotations are not even mentioned.

There is a bit of info on the state of JSR-305 in an appendix of the latest JSR-308 draft. This includes the observation that JSR-305 annotations seem to be abandoned. The JSR-305 page also shows it as "inactive".

In the mean time, the pragmatic answer is to use the annotation types that are supported by the most widely used tools ... and be prepared to change them if the situation changes.


In fact, JSR-308 does not define any annotation types/classes, and it looks like they think it is out of scope. (And they are right, given the existence of JSR-305).

However, if JSR-308 really looks like making it into Java 8, it wouldn't surprise me if interest in JSR-305 revived. AFAIK, the JSR-305 team hasn't formally abandoned their work. They have just been quiet for 2+ years.

It is interesting that Bill Pugh (the tech lead for JSR-305) is one of the guy behind FindBugs.

Why doesn't TFS get latest get the latest?

I had the same issue with Visual Studio 2012. No matter what I did, it didn't get the code from TFS source control.

In my case, the cause was mappings a folder + subfolder from the source control separately but to the same tree in my local HD.

The solution was removing the subfolder mapping using the "manage workspaces" window.

How to redirect in a servlet filter?

In Filter the response is of ServletResponse rather than HttpServletResponse. Hence do the cast to HttpServletResponse.

HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendRedirect("/login.jsp");

If using a context path:

httpResponse.sendRedirect(req.getContextPath() + "/login.jsp");

Also don't forget to call return; at the end.

postgres: upgrade a user to be a superuser?

$ su - postgres
$ psql
$ \du; for see the user on db
select the user that do you want be superuser and:
$ ALTER USER "user" with superuser;

How to open select file dialog via js?

_x000D_
_x000D_
function promptFile(contentType, multiple) {
  var input = document.createElement("input");
  input.type = "file";
  input.multiple = multiple;
  input.accept = contentType;
  return new Promise(function(resolve) {
    document.activeElement.onfocus = function() {
      document.activeElement.onfocus = null;
      setTimeout(resolve, 500);
    };
    input.onchange = function() {
      var files = Array.from(input.files);
      if (multiple)
        return resolve(files);
      resolve(files[0]);
    };
    input.click();
  });
}
function promptFilename() {
  promptFile().then(function(file) {
    document.querySelector("span").innerText = file && file.name || "no file selected";
  });
}
_x000D_
<button onclick="promptFilename()">Open</button>
<span></span>
_x000D_
_x000D_
_x000D_

Check if input is integer type in C

Just check is your number has any difference with float version of it, or not.

float num; 
scanf("%f",&num);

if(num != (int)num) {
    printf("it's not an integer");
    return;
}

Scroll to element on click in Angular 4

Another way to do it in Angular:

Markup:

<textarea #inputMessage></textarea>

Add ViewChild() property:

@ViewChild('inputMessage')
inputMessageRef: ElementRef;

Scroll anywhere you want inside of the component using scrollIntoView() function:

this.inputMessageRef.nativeElement.scrollIntoView();

intl extension: installing php_intl.dll

I resolved this issue by adding PHP directory to PATH variable. I just appended ;C:\xampp\php to Path variable in Windows Environment Variables.

ORA-01036: illegal variable name/number when running query through C#

Just for others getting this error and looking for info on it, it is also thrown if you happen to pass a binding parameter and then never use it. I couldn't really find that stated clearly anywhere but had to prove it through trial and error.

How get all values in a column using PHP?

Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.


This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php

$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row['names'];  
}
// now $storeArray will have all the names.

How do I test if a variable does not equal either of two values?

This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).

switch(test) {
    case A:
    case B:
        do other stuff;
        break;
    default:
        do stuff;
}

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Some special characters give this type of error, so use

$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";

How do you right-justify text in an HTML textbox?

Did you try setting the style:

input {
    text-align:right;
}

Just tested, this works fine (in FF3 at least):

<html>
    <head>
        <title>Blah</title>
        <style type="text/css">
        input { text-align:right; }
        </style>
    </head>
    <body>
        <input type="text" value="2">
    </body>
</html>

You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.

How to fix height of TR?

Try putting the height into one of the cells, like this:

<table class="tableContainer" cellspacing="10px">
 <tr>
  <td style="height:15px;">NHS Number</td>
  <td>&#160;</td>

Note however, that you won't be able to make the cell smaller than the content requires it to be. In that case you would have to make the text smaller first.

How to redirect siteA to siteB with A or CNAME records

These days, many site owners are using CDN services which pulls data from CDN server. If that's your case then you are left with two options:

  1. Create a subdomain and edit DNS by Adding a CNAME record

  2. Don't create a subdomain but only create a CNAME record pointing back to your temporary DNS URL.

This solution only implies to pulling code from CDN which will show that it's fetching data from cdn.sitename.com but practically its pulling from your CDN host.

What is external linkage and internal linkage?

I think Internal and External Linkage in C++ gives a clear and concise explanation:

A translation unit refers to an implementation (.c/.cpp) file and all header (.h/.hpp) files it includes. If an object or function inside such a translation unit has internal linkage, then that specific symbol is only visible to the linker within that translation unit. If an object or function has external linkage, the linker can also see it when processing other translation units. The static keyword, when used in the global namespace, forces a symbol to have internal linkage. The extern keyword results in a symbol having external linkage.

The compiler defaults the linkage of symbols such that:

Non-const global variables have external linkage by default
Const global variables have internal linkage by default
Functions have external linkage by default

cannot import name patterns

patterns module is not supported.. mine worked with this.

from django.conf.urls import *
from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    # ... your url patterns
]

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Instances of the String constructor have a .search() method which accepts a RegExp and returns the index of the first match.

To start the search from a particular position (faking the second parameter of .indexOf()) you can slice off the first i characters:

str.slice(i).search(/re/)

But this will get the index in the shorter string (after the first part was sliced off) so you'll want to then add the length of the chopped off part (i) to the returned index if it wasn't -1. This will give you the index in the original string:

function regexIndexOf(text, re, i) {
    var indexInSuffix = text.slice(i).search(re);
    return indexInSuffix < 0 ? indexInSuffix : indexInSuffix + i;
}

Shortcut for creating single item list in C#

Inspired by the other answers (and so I can pick it up whenever I need it!), but with naming/style aligned with F# (which has a standard singleton function per data structure*):

namespace System.Collections.Generic
{
    public static class List
    {
        public static List<T> Singleton<T>(T value) => new List<T>(1) { value };
    }
}

* except for ResizeArray itself of course, hence this question :)


In practice I actually name it Create to align with other helpers I define such as Tuple.Create, Lazy.Create[2], LazyTask.Create etc:

namespace System.Collections.Generic
{
    public static class List
    {
        public static List<T> Create<T>(T value) => new List<T>(1) { value };
    }
}

[2]

namespace System
{
    public static class Lazy
    {
        public static Lazy<T> Create<T>(Func<T> factory) => new Lazy<T>(factory);
    }
}

Sending data back to the Main Activity in Android

There are some ways of doing this. 1. by using the startActivityForResult() which is very well explained in the above answers.

  1. by creating the static variables in your "Utils" class or any other class of your own. For example i want to pass studentId from ActivityB to ActivityA.First my ActivityA is calling the ActivityB. Then inside ActivityB set the studentId (which is a static field in Utils.class). Like this Utils.STUDENT_ID="1234"; then while comming back to the ActivityA use the studentId which is stored in Utils.STUDENT_ID.

  2. by creating a getter and setter method in your Application Class.

like this:

public class MyApplication extends Application {

    private static MyApplication instance = null;
    private String studentId="";

    public static MyApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public void setStudentId(String studentID){
        this.studentId=studentID;
    }

    public String getStudentId(){
        return this.studentId;
    }
}

so you are done . just set the data inside when u are in ActivityB and after comming back to ActivityA , get the data.

Filter LogCat to get only the messages from My Application in Android?

ADT v15 for Eclipse let you specify an application name (which is actually the package value in your androidmanifest.xml).

I love being able to filter by app, but the new logcat has a bug with the autoscroll. When you scroll up a little to look at previous logs, it automatically scrolls back to the bottom in a couple seconds. It seems scrolling 1/2 way up the log does keep it from jumping back to the bottom, but that's often useless.

EDIT: I tried specifying an app filter from the command-line -- but no luck. If someone figures this out OR how to stop the autoscroll, please let me know.

Check if an array contains any element of another array in JavaScript

Here is an interesting case I thought I should share.

Let's say that you have an array of objects and an array of selected filters.

let arr = [
  { id: 'x', tags: ['foo'] },
  { id: 'y', tags: ['foo', 'bar'] },
  { id: 'z', tags: ['baz'] }
];

const filters = ['foo'];

To apply the selected filters to this structure we can

if (filters.length > 0)
  arr = arr.filter(obj =>
    obj.tags.some(tag => filters.includes(tag))
  );

// [
//   { id: 'x', tags: ['foo'] },
//   { id: 'y', tags: ['foo', 'bar'] }
// ]

Using OR & AND in COUNTIFS

i found i had to do something akin to

=(countifs (A1:A196,"yes", j1:j196, "agree") + (countifs (A1:A196,"no", j1:j196, "agree"))

Laravel - Eloquent or Fluent random row

tl;dr: It's nowadays implemented into Laravel, see "edit 3" below.


Sadly, as of today there are some caveats with the ->orderBy(DB::raw('RAND()')) proposed solution:

  • It isn't DB-agnostic. e.g. SQLite and PostgreSQL use RANDOM()
  • Even worse, this solution isn't applicable anymore since this change:

    $direction = strtolower($direction) == 'asc' ? 'asc' : 'desc';


edit: Now you can use the orderByRaw() method: ->orderByRaw('RAND()'). However this is still not DB-agnostic.

FWIW, CodeIgniter implements a special RANDOM sorting direction, which is replaced with the correct grammar when building query. Also it seems to be fairly easy to implement. Looks like we have a candidate for improving Laravel :)

update: here is the issue about this on GitHub, and my pending pull request.


edit 2: Let's cut the chase. Since Laravel 5.1.18 you can add macros to the query builder:

use Illuminate\Database\Query\Builder;

Builder::macro('orderByRandom', function () {

    $randomFunctions = [
        'mysql'  => 'RAND()',
        'pgsql'  => 'RANDOM()',
        'sqlite' => 'RANDOM()',
        'sqlsrv' => 'NEWID()',
    ];

    $driver = $this->getConnection()->getDriverName();

    return $this->orderByRaw($randomFunctions[$driver]);
});

Usage:

User::where('active', 1)->orderByRandom()->limit(10)->get();

DB::table('users')->where('active', 1)->orderByRandom()->limit(10)->get();


edit 3: Finally! Since Laravel 5.2.33 (changelog, PR #13642) you can use the native method inRandomOrder():

User::where('active', 1)->inRandomOrder()->limit(10)->get();

DB::table('users')->where('active', 1)->inRandomOrder()->limit(10)->get();

Cannot assign requested address - possible causes?

sysctl -w net.ipv4.tcp_timestamps=1
sysctl -w net.ipv4.tcp_tw_recycle=1

Does Android support near real time push notification?

The problem with GCM is that there is a lot of configuration involved in the process:

  • You have to add a lot of boilerplate to you Android app
  • You need to configure an external server to comunicate with the GCM server
  • You will have to write tests

If you like simple things (like me) you should try UrbanAirship. It is (IMHO) the easiest way to use GCM in your app without doing a lot of configuration. It also gives you a pretty GUI to test that your GCM messages are being delivered correctly.

  • You can find the docs and getting started guide here
  • You can find a sample application here

Note: I am not afiliated with UrbanAirship in any way

What is the hamburger menu icon called and the three vertical dots icon called?

According to Reddit, more options icon and kabob menu are popular names. I prefer the latter as it goes well with hamburger menu.

What is the use of the JavaScript 'bind' method?

bind allows-

  • set the value of "this" to an specific object. This becomes very helpful as sometimes this is not what is intended.
  • reuse methods
  • curry a function

For example, you have a function to deduct monthly club fees

function getMonthlyFee(fee){
  var remaining = this.total - fee;
  this.total = remaining;
  return this.name +' remaining balance:'+remaining;
}

Now you want to reuse this function for a different club member. Note that the monthly fee will vary from member to member.

Let's imagine Rachel has a balance of 500, and a monthly membership fee of 90.

var rachel = {name:'Rachel Green', total:500};

Now, create a function that can be used again and again to deduct the fee from her account every month

//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320

Now, the same getMonthlyFee function could be used for another member with a different membership fee. For Example, Ross Geller has a 250 balance and a monthly fee of 25

var ross = {name:'Ross Geller', total:250};
//bind
var getRossFee = getMonthlyFee.bind(ross, 25);
//deduct
getRossFee(); //Ross Geller remaining balance:225
getRossFee(); //Ross Geller remaining balance:200

Update style of a component onScroll in React.js

Here is another example using HOOKS fontAwesomeIcon and Kendo UI React
[![screenshot here][1]][1]

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';


const ScrollBackToTop = () => {
  const [show, handleShow] = useState(false);

  useEffect(() => {
    window.addEventListener('scroll', () => {
      if (window.scrollY > 1200) {
        handleShow(true);
      } else handleShow(false);
    });
    return () => {
      window.removeEventListener('scroll');
    };
  }, []);

  const backToTop = () => {
    window.scroll({ top: 0, behavior: 'smooth' });
  };

  return (
    <div>
      {show && (
      <div className="backToTop text-center">
        <button className="backToTop-btn k-button " onClick={() => backToTop()} >
          <div className="d-none d-xl-block mr-1">Top</div>
          <FontAwesomeIcon icon="chevron-up"/>
        </button>
      </div>
      )}
    </div>
  );
};

export default ScrollBackToTop;```


  [1]: https://i.stack.imgur.com/ZquHI.png

How can I copy a file from a remote server to using Putty in Windows?

One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.

What size should apple-touch-icon.png be for iPad and iPhone?

I think this question is about web icons. I've tried giving an icon at 512x512, and on the iPhone 4 simulator it looks great (in the preview) however, when added to the home-screen it's badly pixelated.

On the good side, if you use a larger icon on the iPad (still with my 512x512 test) it does seem to come out in better quality on the iPad. Hopefully the iPhone 4 rendering is a bug.

I've opened a bug about this on radar.

EDIT:

I'm currently using a 114x114 icon in hopes that it'll look good on the iPhone 4 when it is released. If the iPhone 4 still has a bug when it comes out, I'm going to optimize the icon for the iPad (crisp and no resize at 72x72), and then let it scale down for old iPhones.

Check whether a value is a number in JavaScript or jQuery

You've an number of options, depending on how you want to play it:

isNaN(val)

Returns true if val is not a number, false if it is. In your case, this is probably what you need.

isFinite(val)

Returns true if val, when cast to a String, is a number and it is not equal to +/- Infinity

/^\d+$/.test(val)

Returns true if val, when cast to a String, has only digits (probably not what you need).

Today's Date in Perl in MM/DD/YYYY format

Formating numbers with leading zero is done easily with "sprintf", a built-in function in perl (documentation with: perldoc perlfunc)

use strict;
use warnings;
use Date::Calc qw();
my ($y, $m, $d) = Date::Calc::Today();
my $ddmmyyyy = sprintf '%02d.%02d.%d', $d, $m, $y;
print $ddmmyyyy . "\n";

This gives you:

14.05.2014

Eclipse returns error message "Java was started but returned exit code = 1"

I received this error out of the blue. Eclipse stopped working even though I made no config changes and did not install any new jdk's.

Here was my eclipse.ini file :

--clean
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vm
C:/Program Files (x86)/Java/jre7/bin/javaw.exe
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms40m
-Xmx1024m

To get Eclipse to start successfully I removed

    -vmargs
    -Dosgi.requiredJavaVersion=1.6
    -vm 
C:/Program Files (x86)/Java/jre7/bin/javaw.exe

So here is my updated file :

--clean
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20130807-1835
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-Xms40m
-Xmx1024m

I have no idea why removing osgi.requiredJavaVersion=1.6 fixed this as my jvm version is 1.6. From the doc http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html

osgi.requiredJavaVersion
The minimum java version that is required to launch Eclipse. The default value is "1.4.1".

I think my java version was set correctly. Anyway Eclipse starts and runs for me now......

How to grey out a button?

The most easy solution is to set color filter to the background image of a button as I saw here

You can do as follow:

if ('need to set button disable')
    button.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
else
    button.getBackground().setColorFilter(null);

Hope I helped someone...

Convert .class to .java

Invoking javap to read the bytecode

The javap command takes class-names without the .class extension. Try

javap -c ClassName

Converting .class files back to .java files

javap will however not give you the implementations of the methods in java-syntax. It will at most give it to you in JVM bytecode format.

To actually decompile (i.e., do the reverse of javac) you will have to use proper decompiler. See for instance the following related question:

Maximum call stack size exceeded error

The issue in my case is because I have children route with same path with the parent :

const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    children: [
      { path: '', redirectTo: 'home', pathMatch: 'prefix' },
      { path: 'home', loadChildren: './home.module#HomeModule' },
    ]
  }
];

So I had to remove the line of the children route

const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    children: [
      { path: 'home', loadChildren: './home.module#HomeModule' },
    ]
  }
];

document.getElementById replacement in angular4 / typescript?

Try this:

TypeScript file code:

(<HTMLInputElement>document.getElementById("name")).value

HTML code:

 <input id="name" type="text" #name /> 

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

From my own question:

start /b myProgram.exe params...

works if you start the program from an existing DOS session.

If not, call a vb script

wscript.exe invis.vbs myProgram.exe %*

The Windows Script Host Run() method takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

Here is invis.vbs:

set args = WScript.Arguments
num = args.Count

if num = 0 then
    WScript.Echo "Usage: [CScript | WScript] invis.vbs aScript.bat <some script arguments>"
    WScript.Quit 1
end if

sargs = ""
if num > 1 then
    sargs = " "
    for k = 1 to num - 1
        anArg = args.Item(k)
        sargs = sargs & anArg & " "
    next
end if

Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False

PHP: Get key from array?

Use the array_search function.

Example from php.net

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;

How to convert seconds to time format?

1 day = 86400000 milliseconds.

DecodeTime(milliseconds/86400000,hr,min,sec,msec)

Ups! I was thinking in delphi, there must be something similar in all languages.

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

In case you want to search for all the issues updated after 9am previous day until today at 9AM, please try: updated >= startOfDay(-15h) and updated <= startOfDay(9h). (explanation: 9AM - 24h/day = -15h)

You can also use updated >= startOfDay(-900m) . where 900m = 15h*60m

Reference: https://confluence.atlassian.com/display/JIRA/Advanced+Searching

How can I post data as form data instead of a request payload?

The continued confusion surrounding this issue inspired me to write a blog post about it. The solution I propose in this post is better than your current top rated solution because it does not restrict you to parametrizing your data object for $http service calls; i.e. with my solution you can simply continue to pass actual data objects to $http.post(), etc. and still achieve the desired result.

Also, the top rated answer relies on the inclusion of full jQuery in the page for the $.param() function, whereas my solution is jQuery agnostic, pure AngularJS ready.

http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

Hope this helps.

Get random integer in range (x, y]?

Just add one to the result. That turns [0, 10) into (0,10] (for integers). [0, 10) is just a more confusing way to say [0, 9], and (0,10] is [1,10] (for integers).

SQL Server Creating a temp table for this query

If you want to create a temp table after check exist table.You can use the following code

DROP TABLE IF EXISTS tempdb.dbo.#temptable
CREATE TABLE #temptable
  (
   SiteName             NVARCHAR(50),
   BillingMonth         varchar(10),
   Consumption          INT,
  )

After creating the temporary table, you can insert data into this table as a regular table:

INSERT INTO #temptable
SELECT COLUMN1,...
FROM
(...)

or

INSERT INTO #temptable
VALUES (value1, value2, value3, ...);

The SELECT statement is used to select data from a temp table.

SELECT * FROM #temptable

you can manually remove the temporary table by using the DROP TABLE statement:

DROP TABLE #temptable;

Using client certificate in Curl command

TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.

If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.

As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/chainedcert.pem;  # server certificate
    ssl_certificate_key /path/to/key;          # server key

    ssl_client_certificate /path/to/ca.pem;    # client CA
    ssl_verify_client on;
    proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;

    location / {
        proxy_pass http://localhost:3000;
    }
}

Getting Hour and Minute in PHP

Try this:

$hourMin = date('H:i');

This will be 24-hour time with an hour that is always two digits. For all options, see the PHP docs for date().

Eclipse: stop code from running (java)

Open the Console view, locate the console for your running app and hit the Big Red Button.

Alternatively if you open the Debug perspective you will see all running apps in (by default) the top left. You can select the one that's causing you grief and once again hit the Big Red Button.enter image description here

Removing elements by class name?

In pure vanilla Javascript, without jQuery or ES6, you could do:

const elements = document.getElementsByClassName("my-class");

while (elements.length > 0) elements[0].remove();

How to convert R Markdown to PDF?

Only two steps:

  1. Install the latest release "pandoc" from here:

    https://github.com/jgm/pandoc/releases

  2. Call the function pandoc in the library(knitr)

    library(knitr)
    pandoc('input.md', format = 'latex')
    

Thus, you can convert your "input.md" into "input.pdf".

Why am I getting error CS0246: The type or namespace name could not be found?

most of the problems cause by .NET Framework. So just go to project properties and change .Net version same as your reference dll.

Done!!!

Hope it's help :)

SQL Sum Multiple rows into one

You should group by the field you want the SUM apply to, and not include in SELECT any field other than multiple rows values, like COUNT, SUM, AVE, etc, because if you include Bill field like in this case, only the first value in the set of rows will be displayed, being almost meaningless and confusing.

This will return the sum of bills per account number:

SELECT SUM(Bill) FROM Table1 GROUP BY AccountNumber

You could add more clauses like WHERE, ORDER BY etc as needed.

Changing background color of selected item in recyclerview

I got it like this

public void onClick(View v){
        v.findViewById(R.id.textView).setBackgroundColor(R.drawable.selector_row);
 }

Thanks

What is the volatile keyword useful for?

volatile only guarantees that all threads, even themselves, are incrementing. For example: a counter sees the same face of the variable at the same time. It is not used instead of synchronized or atomic or other stuff, it completely makes the reads synchronized. Please do not compare it with other java keywords. As the example shows below volatile variable operations are also atomic they fail or succeed at once.

package io.netty.example.telnet;

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

public class Main {

    public static volatile  int a = 0;
    public static void main(String args[]) throws InterruptedException{

        List<Thread> list = new  ArrayList<Thread>();
        for(int i = 0 ; i<11 ;i++){
            list.add(new Pojo());
        }

        for (Thread thread : list) {
            thread.start();
        }

        Thread.sleep(20000);
        System.out.println(a);
    }
}
class Pojo extends Thread{
    int a = 10001;
    public void run() {
        while(a-->0){
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Main.a++;
            System.out.println("a = "+Main.a);
        }
    }
}

Even you put volatile or not results will always differ. But if you use AtomicInteger as below results will be always same. This is same with synchronized also.

    package io.netty.example.telnet;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.atomic.AtomicInteger;

    public class Main {

        public static volatile  AtomicInteger a = new AtomicInteger(0);
        public static void main(String args[]) throws InterruptedException{

            List<Thread> list = new  ArrayList<Thread>();
            for(int i = 0 ; i<11 ;i++){
                list.add(new Pojo());
            }

            for (Thread thread : list) {
                thread.start();
            }

            Thread.sleep(20000);
            System.out.println(a.get());

        }
    }
    class Pojo extends Thread{
        int a = 10001;
        public void run() {
            while(a-->0){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Main.a.incrementAndGet();
                System.out.println("a = "+Main.a);
            }
        }
    }

How to read a CSV file from a URL with Python?

Using pandas it is very simple to read a csv file directly from a url

import pandas as pd
data = pd.read_csv('https://example.com/passkey=wedsmdjsjmdd')

This will read your data in tabular format, which will be very easy to process

Change Orientation of Bluestack : portrait/landscape mode

This works for me for BlueStacks 4:

  • Install "Rotation Control" app enter image description here
  • Enable it to appear onto taskbar; optionally with system start enter image description here
  • Whenever you want to rotate the screen, just pull down the task bar, and give it a go enter image description here

How can I change the thickness of my <hr> tag

I would recommend setting the HR itself to be 0px high and use its border to be visible instead. I have noticed that when you zoom in and out (ctrl + mouse wheel) the thickness of HR itself changes, while when you set the border it always stays the same:

hr {
    height: 0px;
    border: none;
    border-top: 1px solid black;
}

What does the regex \S mean in JavaScript?

\s matches whitespace (spaces, tabs and new lines). \S is negated \s.

How can I sort an ArrayList of Strings in Java?

Collections.sort(teamsName.subList(1, teamsName.size()));

The code above will reflect the actual sublist of your original list sorted.

Calculating Time Difference

from time import time

start_time = time()
...

end_time = time()
seconds_elapsed = end_time - start_time

hours, rest = divmod(seconds_elapsed, 3600)
minutes, seconds = divmod(rest, 60)

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

You also need to change the DataSource of the connection string. KELVIN-PC is the name of your local machine and the sql server is running on the default instance.

If you are sure the the server is running as the default instance, you can always use . in the DataSource, eg.

connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"

otherwise, you need to specify the name of the instance of the server,

connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"

CSS hide scroll bar if not needed

.selected-elementClass{
    overflow-y:auto;
}

How to amend older Git commit?

I've used another way for a few times. In fact, it is a manual git rebase -i and it is useful when you want to rearrange several commits including squashing or splitting some of them. The main advantage is that you don't have to decide about every commit's destiny at a single moment. You'll also have all Git features available during the process unlike during a rebase. For example, you can display the log of both original and rewritten history at any time, or even do another rebase!

I'll refer to the commits in the following way, so it's readable easily:

C # good commit after a bad one
B # bad commit
A # good commit before a bad one

Your history in the beginning looks like this:

x - A - B - C
|           |
|           master
|
origin/master

We'll recreate it to this way:

x - A - B*- C'
|           |
|           master
|
origin/master

Procedure

git checkout B       # get working-tree to the state of commit B
git reset --soft A   # tell Git that we are working before commit B
git checkout -b rewrite-history   # switch to a new branch for alternative history

Improve your old commit using git add (git add -i, git stash etc.) now. You can even split your old commit into two or more.

git commit           # recreate commit B (result = B*)
git cherry-pick C    # copy C to our new branch (result = C')

Intermediate result:

x - A - B - C 
|    \      |
|     \     master
|      \
|       B*- C'
|           |
|           rewrite-history
|
origin/master

Let's finish:

git checkout master
git reset --hard rewrite-history  # make this branch master

Or using just one command:

git branch -f master  # make this place the new tip of the master branch

That's it, you can push your progress now.

The last task is to delete the temporary branch:

git branch -d rewrite-history

How can I print out all possible letter combinations a given phone number can represent?

In numeric keyboards, texts and numbers are placed on the same key. For example 2 has “ABC” if we wanted to write anything starting with ‘A’ we need to type key 2 once. If we wanted to type ‘B’, press key 2 twice and thrice for typing ‘C’. below is picture of such keypad.

keypad http://d2o58evtke57tz.cloudfront.net/wp-content/uploads/phoneKeyboard.png

Given a keypad as shown in diagram, and a n digit number, list all words which are possible by pressing these numbers.

For example if input number is 234, possible words which can be formed are (Alphabetical order): adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfi

Let’s do some calculations first. How many words are possible with seven digits with each digit representing n letters? For first digit we have at most four choices, and for each choice for first letter, we have at most four choices for second digit and so on. So it’s simple maths it will be O(4^n). Since keys 0 and 1 don’t have any corresponding alphabet and many characters have 3 characters, 4^n would be the upper bound of number of words and not the minimum words.

Now let’s do some examples.

For number above 234. Do you see any pattern? Yes, we notice that the last character always either G,H or I and whenever it resets its value from I to G, the digit at the left of it gets changed. Similarly whenever the second last alphabet resets its value, the third last alphabet gets changes and so on. First character resets only once when we have generated all words. This can be looked from other end also. That is to say whenever character at position i changes, character at position i+1 goes through all possible characters and it creates ripple effect till we reach at end. Since 0 and 1 don’t have any characters associated with them. we should break as there will no iteration for these digits.

Let’s take the second approach as it will be easy to implement it using recursion. We go till the end and come back one by one. Perfect condition for recursion. let’s search for base case. When we reach at the last character, we print the word with all possible characters for last digit and return. Simple base case.When we reach at the last character, we print the word with all possible characters for last digit and return. Simple base case.

Following is C implementation of recursive approach to print all possible word corresponding to a n digit input number. Note that input number is represented as an array to simplify the code.

#include <stdio.h>
#include <string.h>

// hashTable[i] stores all characters that correspond to digit i in phone
const char hashTable[10][5] = {"", "", "abc", "def", "ghi", "jkl",
                           "mno", "pqrs", "tuv", "wxyz"};

// A recursive function to print all possible words that can be obtained
// by input number[] of size n.  The output words are one by one stored
// in output[]
void  printWordsUtil(int number[], int curr_digit, char output[], int n)
{
    // Base case, if current output word is prepared
int i;
if (curr_digit == n)
{
    printf("%s ", output);
    return ;
}

// Try all 3 possible characters for current digir in number[]
// and recur for remaining digits
for (i=0; i<strlen(hashTable[number[curr_digit]]); i++)
{
    output[curr_digit] = hashTable[number[curr_digit]][i];
    printWordsUtil(number, curr_digit+1, output, n);
    if (number[curr_digit] == 0 || number[curr_digit] == 1)
        return;
}
}

// A wrapper over printWordsUtil().  It creates an output array and
// calls printWordsUtil()
void printWords(int number[], int n)
{
char result[n+1];
result[n] ='\0';
printWordsUtil(number, 0, result, n);
}

//Driver program
int main(void)
{
int number[] = {2, 3, 4};
int n = sizeof(number)/sizeof(number[0]);
printWords(number, n);
return 0;
}

Output:

adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfi

Time Complexity:

Time complexity of above code is O(4^n) where n is number of digits in input number.

References:

http://www.flipkart.com/programming-interviews-exposed-secrets-landing-your-next-job-3rd/p/itmdxghumef3sdjn?pid=9788126539116&affid=sandeepgfg

Finding square root without using sqrt function?

Here is a very simple but unsafe approach to find the square-root of a number. Unsafe because it only works by natural numbers, where you know that the base respectively the exponent are natural numbers. I had to use it for a task where i was neither allowed to use the #include<cmath> -library, nor i was allowed to use pointers.

potency = base ^ exponent

// FUNCTION: square-root
int sqrt(int x)
{
    int quotient = 0;
    int i = 0;

    bool resultfound = false;
    while (resultfound == false) {
        if (i*i == x) {
          quotient = i;
          resultfound = true;
        }
        i++;
    }
    return quotient;
}

PHP Warning: Unknown: failed to open stream

Go to folder htdocs

cd htdocs

Execute

chmod -R 755 sites

No need to sudo !

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

Convert all first letter to upper case, rest lower for each word

string s = "THIS IS MY TEXT RIGHT NOW";

s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

Practical uses of different data structures

Found the list in a similar question, previously on StackOverflow:

Hash Table - used for fast data lookup - symbol table for compilers, database indexing, caches,Unique data representation.

Trie - dictionary, such as one found on a mobile telephone for autocompletion and spell-checking.

Suffix tree - fast full text searches used in most word processors.

Stack - undo\redo operation in word processors, Expression evaluation and syntax parsing, many virtual machines like JVM are stack oriented.

Queues - Transport and operations research where various entities are stored and held to be processed later ie the queue performs the function of a buffer.

Priority queues - process scheduling in the kernel

Trees - Parsers, Filesystem

Radix tree - IP routing table

BSP tree - 3D computer graphics

Graphs - Connections/relations in social networking sites, Routing ,networks of communication, data organization etc.

Heap - Dynamic memory allocation in lisp

This is the answer originally posted by RV Pradeep

Some other, less useful links:

Applications are only listed for some data structures

Not application focused, by good summary and relevant

COUNT / GROUP BY with active record?

I believe you'll want something like this:

 $this->db->select('user_id, COUNT(user_id) as total');
 $this->db->group_by('user_id'); 
 $this->db->order_by('total', 'desc'); 
 $this->db->get('tablename', 10);

This will produce a result like

|  USER_ID |  TOTAL  |
|    12    |    3    |
|    15    |    2    |
|    18    |    1    |

UPDATE: As some pointed out in the comments the original query was summing the user_ids rather than counting them. I've updated the active record query to correct this.

error LNK2005, already defined?

Assuming you want 'k' to be a different value in different .cpp files (hence declaring it twice), try changing both files to

namespace {
    int k;
}

This guarantees that the name 'k' uniquely identifies 'k' across translation units. The old version static int k; is deprecated.

If you want them to point to the same value, change one to extern int k;.

How do you close/hide the Android soft keyboard using Java?

Actually, always Android authority is giving new updates but they are not handling their old drawbacks which all Android developers face in their development this should be handled by Android authority by default, on changing focus from EditText should hide/show soft input keyboard option. But sorry about that, they are not managing. Ok, leave it.

Below are the solutions to show/hide/toggle a keyboard option in Activity or Fragment.

Show keyboard for the view:

/**
 * open soft keyboard.
 *
 * @param context
 * @param view
 */
public static void showKeyBoard(Context context, View view) {
    try {
        InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.showSoftInput(view, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Show keyboard with Activity context:

/**
 * open soft keyboard.
 *
 * @param mActivity context
 */
public static void showKeyBoard(Activity mActivity) {
    try {
        View view = mActivity.getCurrentFocus();
        if (view != null) {
            InputMethodManager keyboard = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            keyboard.showSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.SHOW_FORCED);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Show keyboard with Fragment context:

/**
 * open soft keyboard.
 *
 * @param mFragment context
 */
public static void showKeyBoard(Fragment mFragment) {
    try {
        if (mFragment == null || mFragment.getActivity() == null) {
            return;
        }
        View view = mFragment.getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager keyboard = (InputMethodManager) mFragment.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            keyboard.showSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.SHOW_FORCED);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Hide keyboard for the view:

/**
 * close soft keyboard.
 *
 * @param context
 * @param view
 */
public static void hideKeyBoard(Context context, View view) {
    try {
        InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.hideSoftInputFromWindow(view.getWindowToken(), 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Hide keyboard with Activity context:

/**
 * close opened soft keyboard.
 *
 * @param mActivity context
 */
public static void hideSoftKeyboard(Activity mActivity) {
    try {
        View view = mActivity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Hide keyboard with Fragment context:

/**
 * close opened soft keyboard.
 *
 * @param mFragment context
 */
public static void hideSoftKeyboard(Fragment mFragment) {
    try {
        if (mFragment == null || mFragment.getActivity() == null) {
            return;
        }
        View view = mFragment.getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) mFragment.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Toggle Keyboard:

/**
 * toggle soft keyboard.
 *
 * @param context
 */
public static void toggleSoftKeyboard(Context context) {
    try {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Play audio with Python

It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.

import wave
import io
from AppKit import NSSound


wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())

wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())

seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()

wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])

wave_shell.close()

wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()

TypeScript: Interfaces vs Types

In addition to the brilliant answers already provided, there are noticeable differences when it comes to extending types vs interfaces. I recently run into a couple of cases where an interface can't do the job:

  1. Cannot extend a union type using an interface
  2. Cannot extend generic interface

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

In your state, home is initialized as an array homes: []

In your return, there is an attempt to render home (which is an array). <p>Stuff: {homes}</p>

Cannot be done this way --- If you want to render it, you need to render an array into each single item. For example: using map()

Ex: {home.map(item=>item)}

JFrame Maximize window

I ended up using this code:

public void setMaximized(boolean maximized){
    if(maximized){
        DisplayMode mode = this.getGraphicsConfiguration().getDevice().getDisplayMode();
        Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(this.getGraphicsConfiguration());
        this.setMaximizedBounds(new Rectangle(
                mode.getWidth() - insets.right - insets.left, 
                mode.getHeight() - insets.top - insets.bottom
        ));
        this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
    }else{
        this.setExtendedState(JFrame.NORMAL);
    }
}

This options worked the best of all the options, including multiple monitor support. The only flaw this has is that the taskbar offset is used on all monitors is some configurations.

jQuery Scroll To bottom of the page

Using 'document.body.clientHeight' you can get the seen height of the body elements

$('html, body').animate({
    scrollTop: $("#particularDivision").offset().top - document.body.clientHeight + $("#particularDivision").height()
}, 1000);

this scrolls at the id 'particularDivision'

Default interface methods are only supported starting with Android N

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'


android {
compileSdkVersion 30
buildToolsVersion "30.0.0"

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

defaultConfig {
    applicationId "com.example.architecture"
    minSdkVersion 16
    targetSdkVersion 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
 buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
   }
}
dependencies {

implementation 'androidx.room:room-runtime:2.2.5'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
annotationProcessor 'androidx.room:room-compiler:2.2.5'
def lifecycle_version = "2.2.0"
def arch_version = "2.1.0"

implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
implementation "androidx.cardview:cardview:1.0.0"
}

Add the configuration in your app module's build.gradle

android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Jackson how to transform JsonNode to ArrayNode without casting?

I would assume at the end of the day you want to consume the data in the ArrayNode by iterating it. For that:

Iterator<JsonNode> iterator = datasets.withArray("datasets").elements();
while (iterator.hasNext()) 
        System.out.print(iterator.next().toString() + " "); 

or if you're into streams and lambda functions:

import com.google.common.collect.Streams;
Streams.stream(datasets.withArray("datasets").elements())
    .forEach( item -> System.out.print(item.toString()) )

How to list the size of each file and directory and sort by descending size in Bash?

Another simple solution.

$ for entry in $(ls); do du -s "$entry"; done | sort -n

the result will look like

2900    tmp
6781    boot
8428    bin
24932   lib64
34436   sbin
90084   var
106676  etc
125216  lib
3313136 usr
4828700 opt

changing "du -s" to "du -sh" will show human readable size, but we won't be able to sort in this method.

SELECT last id, without INSERT

You could descendingly order the tabele by id and limit the number of results to one:

SELECT id FROM tablename ORDER BY id DESC LIMIT 1

BUT: ORDER BY rearranges the entire table for this request. So if you have a lot of data and you need to repeat this operation several times, I would not recommend this solution.

Very Simple, Very Smooth, JavaScript Marquee

hiya simple demo from recommendations in above comments: http://jsfiddle.net/FWWEn/

with pause functionality on mouseover: http://jsfiddle.net/zrW5q/

hope this helps, have a nice one, cheers!

html

<h1>Hello World!</h1>
<h2>I'll marquee twice</h2>
<h3>I go fast!</h3>
<h4>Left to right</h4>
<h5>I'll defer that question</h5>?

Jquery code

 (function($) {
        $.fn.textWidth = function(){
             var calc = '<span style="display:none">' + $(this).text() + '</span>';
             $('body').append(calc);
             var width = $('body').find('span:last').width();
             $('body').find('span:last').remove();
            return width;
        };

        $.fn.marquee = function(args) {
            var that = $(this);
            var textWidth = that.textWidth(),
                offset = that.width(),
                width = offset,
                css = {
                    'text-indent' : that.css('text-indent'),
                    'overflow' : that.css('overflow'),
                    'white-space' : that.css('white-space')
                },
                marqueeCss = {
                    'text-indent' : width,
                    'overflow' : 'hidden',
                    'white-space' : 'nowrap'
                },
                args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args),
                i = 0,
                stop = textWidth*-1,
                dfd = $.Deferred();

            function go() {
                if(!that.length) return dfd.reject();
                if(width == stop) {
                    i++;
                    if(i == args.count) {
                        that.css(css);
                        return dfd.resolve();
                    }
                    if(args.leftToRight) {
                        width = textWidth*-1;
                    } else {
                        width = offset;
                    }
                }
                that.css('text-indent', width + 'px');
                if(args.leftToRight) {
                    width++;
                } else {
                    width--;
                }
                setTimeout(go, args.speed);
            };
            if(args.leftToRight) {
                width = textWidth*-1;
                width++;
                stop = offset;
            } else {
                width--;            
            }
            that.css(marqueeCss);
            go();
            return dfd.promise();
        };
    })(jQuery);

$('h1').marquee();
$('h2').marquee({ count: 2 });
$('h3').marquee({ speed: 5 });
$('h4').marquee({ leftToRight: true });
$('h5').marquee({ count: 1, speed: 2 }).done(function() { $('h5').css('color', '#f00'); })?

ClientScript.RegisterClientScriptBlock?

Hai sridhar, I found an answer for your prob

ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);

change false to true

or try this

ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);

Visually managing MongoDB documents and collections

The real answer is ... No.

So far as I have found there is no reasonable or publicly available Windows MonogoDB client which is really very sad since MongoDB is pretty sweet.

I've thought about throwing together a simple app with WPF on Codeplex ... but I haven't been super motivated.

What would features would you be interested in having? Maybe you can inspire me or others?

For example, do you just want to view DBs / collections & perhaps simple edits (so you don't have to use the shell) or do you require something more complex?

Efficient way to add spaces between characters in a string

A very pythonic and practical way to do it is by using the string join() method:

str.join(iterable)

The official Python documentations says:

Return a string which is the concatenation of the strings in iterable... The separator between elements is the string providing this method.

How to use it?

Remember: this is a string method.

This method will be applied to the str above, which reflects the string that will be used as separator of the items in the iterable.

Let's have some practical example!

iterable = "BINGO"
separator = " " # A whitespace character.
                # The string to which the method will be applied
separator.join(iterable)
> 'B I N G O'

In practice you would do it like this:

iterable = "BINGO"    
" ".join(iterable)
> 'B I N G O'

But remember that the argument is an iterable, like a string, list, tuple. Although the method returns a string.

iterable = ['B', 'I', 'N', 'G', 'O']    
" ".join(iterable)
> 'B I N G O'

What happens if you use a hyphen as a string instead?

iterable = ['B', 'I', 'N', 'G', 'O']    
"-".join(iterable)
> 'B-I-N-G-O'

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

How can I hide/show a div when a button is clicked?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show and hide div with JavaScript</title>
<script>

    var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
    var show_button = 'Show', hide_button = 'Hide';
    function showhide() {
        var div = document.getElementById( "hide_show" );
        var showhide = document.getElementById( "showhide" );
        if ( div.style.display !== "none" ) {
            div.style.display = "none";
            button = show_button;
            showhide.innerHTML = button_beg + button + button_end;
        } else {
            div.style.display = "block";
            button = hide_button;
            showhide.innerHTML = button_beg + button + button_end;
        }
    }
    function setup_button( status ) {
        if ( status == 'show' ) {
            button = hide_button;
        } else {
            button = show_button;
        }
        var showhide = document.getElementById( "showhide" );
        showhide.innerHTML = button_beg + button + button_end;
    }
    window.onload = function () {
        setup_button( 'hide' );
        showhide(); // if setup_button is set to 'show' comment this line
    }
</script>
</head>
<body>
    <div id="showhide"></div>
    <div id="hide_show">
        <p>This div will be show and hide on button click</p>
    </div>
</body>
</html>

Sticky Header after scrolling down

Here is a JS fiddle http://jsfiddle.net/ke9kW/1/

As the others say, set the header to fixed, and start it with display: none

then jQuery

$(window).scroll(function () {
  if ( $(this).scrollTop() > 200 && !$('header').hasClass('open') ) {
    $('header').addClass('open');
    $('header').slideDown();
   } else if ( $(this).scrollTop() <= 200 ) {
    $('header').removeClass('open');
    $('header').slideUp();
  }
});

where 200 is the height in pixels you'd like it to move down at. The addition of the open class is to allow us to run an elseif instead of just else, so some of the code doesn't unnecessarily run on every scrollevent, save a lil bit of memory

How do I disable the security certificate check in Python requests

To add to Blender's answer, you can disable SSL certificate validation for all requests using Session.verify = False

import requests

session = requests.Session()
session.verify = False
session.post(url='https://example.com', data={'bar':'baz'})

Note that urllib3, (which Requests uses), strongly discourages making unverified HTTPS requests and will raise an InsecureRequestWarning.

Java: Difference between the setPreferredSize() and setSize() methods in components

IIRC ...

setSize sets the size of the component.

setPreferredSize sets the preferred size. The Layoutmanager will try to arrange that much space for your component.

It depends on whether you're using a layout manager or not ...

Concatenate String in String Objective-c

simple one:

[[@"first" stringByAppendingString:@"second"] stringByAppendingString:@"third"];

if you have many STRINGS to Concatenate, you should use NSMutableString for better performance

how to get the attribute value of an xml node using java

use

document.getElementsByTagName(" * ");

to get all XML elements from within an XML file, this does however return repeating attributes

example:

NodeList list = doc.getElementsByTagName("*");


System.out.println("XML Elements: ");

        for (int i=0; i<list.getLength(); i++) {

            Element element = (Element)list.item(i);
            System.out.println(element.getNodeName());
        }

Can't use System.Windows.Forms

You have to add the reference of the namespace : System.Windows.Forms to your project, because for some reason it is not already added, so you can add New Reference from Visual Studio menu.

Right click on "Reference" ? "Add New Reference" ? "System.Windows.Forms"

PLS-00103: Encountered the symbol "CREATE"

At line 5 there is a / missing.

There is a good answer on the differences between ; and / here.

Basically, when running a CREATE block via script, you need to use / to let SQLPlus know when the block ends, since a PL/SQL block can contain many instances of ;.

Initialise numpy array of unknown length

For posterity, I think this is quicker:

a = np.array([np.array(list()) for _ in y])

You might even be able to pass in a generator (i.e. [] -> ()), in which case the inner list is never fully stored in memory.


Responding to comment below:

>>> import numpy as np
>>> y = range(10)
>>> a = np.array([np.array(list) for _ in y])
>>> a
array([array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object)], dtype=object)

Referring to a Column Alias in a WHERE Clause

For me, the simplest way to use ALIAS in WHERE class is to create a subquery and select from it instead.

Example:

WITH Q1 AS (
    SELECT LENGTH(name) AS name_length,
    id,
    name
    FROM any_table
)

SELECT id, name, name_length form Q1 where name_length > 0

Cheers, Kel

Send push to Android by C# using FCM (Firebase Cloud Messaging)

Try to send a json object. Replace this:

tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";    
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
        Console.WriteLine(postData);
        Byte[] byteArray = Encoding.UTF8.GetBytes(postData);

For this:

tRequest.ContentType = "application/json"; 
    var data = new
        {
            to = deviceId,
            notification = new
            {
                body = "This is the message",
                title = "This is the title",
                icon = "myicon"
            }
        };

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(data);

        Byte[] byteArray = Encoding.UTF8.GetBytes(json);

Add and remove multiple classes in jQuery

Add multiple classes:

$("p").addClass("class1 class2 class3");

or in cascade:

$("p").addClass("class1").addClass("class2").addClass("class3");

Very similar also to remove more classes:

$("p").removeClass("class1 class2 class3");

or in cascade:

$("p").removeClass("class1").removeClass("class2").removeClass("class3");

how to change any data type into a string in python

str is meant to produce a string representation of the object's data. If you're writing your own class and you want str to work for you, add:

def __str__(self):
    return "Some descriptive string"

print str(myObj) will call myObj.__str__().

repr is a similar method, which generally produces information on the class info. For most core library object, repr produces the class name (and sometime some class information) between angle brackets. repr will be used, for example, by just typing your object into your interactions pane, without using print or anything else.

You can define the behavior of repr for your own objects just like you can define the behavior of str:

def __repr__(self):
    return "Some descriptive string"

>>> myObj in your interactions pane, or repr(myObj), will result in myObj.__repr__()

Polling the keyboard (detect a keypress) in python

From the comments:

import msvcrt # built-in module

def kbfunc():
    return ord(msvcrt.getch()) if msvcrt.kbhit() else 0

Thanks for the help. I ended up writing a C DLL called PyKeyboardAccess.dll and accessing the crt conio functions, exporting this routine:

#include <conio.h>

int kb_inkey () {
   int rc;
   int key;

   key = _kbhit();

   if (key == 0) {
      rc = 0;
   } else {
      rc = _getch();
   }

   return rc;
}

And I access it in python using the ctypes module (built into python 2.5):

import ctypes
import time

#
# first, load the DLL
#


try:
    kblib = ctypes.CDLL("PyKeyboardAccess.dll")
except:
    raise ("Error Loading PyKeyboardAccess.dll")


#
# now, find our function
#

try:
    kbfunc = kblib.kb_inkey
except:
    raise ("Could not find the kb_inkey function in the dll!")


#
# Ok, now let's demo the capability
#

while 1:
    x = kbfunc()

    if x != 0:
        print "Got key: %d" % x
    else:
        time.sleep(.01)

how to put image in center of html page?

Hey now you can give to body background image

and set the background-position:center center;

as like this

body{
background:url('../img/some.jpg') no-repeat center center;
min-height:100%;
}

Selenium and xPath - locating a link by containing text

I think the problem is here:

[contains(text()='Some text')]

To break this down,

  1. The [] are a conditional that operates on each individual node in that node set -- each span node in your case. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  2. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  3. contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order.

You should try to change this to

[text()[contains(.,'Some text')]]

  1. The outer [] are a conditional that operates on each individual node in that node set text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.

  2. The inner [] are a conditional that operates on each node in that node set.

  3. contains is a function that operates on a string. Here it is passed an individual text node (.).

javascript functions to show and hide divs

You need the link inside to be clickable, meaning it needs a href with some content, and also, close() is a built-in function of window, so you need to change the name of the function to avoid a conflict.

<div id="upbutton"><a href="#" onclick="close2()">click to close</a></div>

Also if you want a real "button" instead of a link, you should use <input type="button"/> or <button/>.

how to select first N rows from a table in T-SQL?

You can also use rowcount, but TOP is probably better and cleaner, hence the upvote for Mehrdad

SET ROWCOUNT 10
SELECT * FROM dbo.Orders
WHERE EmployeeID = 5
ORDER BY OrderDate

SET ROWCOUNT 0

How do I make a PHP form that submits to self?

The proper way would be to use $_SERVER["PHP_SELF"] (in conjunction with htmlspecialchars to avoid possible exploits). You can also just skip the action= part empty, which is not W3C valid, but currently works in most (all?) browsers - the default is to submit to self if it's empty.

Here is an example form that takes a name and email, and then displays the values you have entered upon submit:

<?php if (!empty($_POST)): ?>
    Welcome, <?php echo htmlspecialchars($_POST["name"]); ?>!<br>
    Your email is <?php echo htmlspecialchars($_POST["email"]); ?>.<br>
<?php else: ?>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        Name: <input type="text" name="name"><br>
        Email: <input type="text" name="email"><br>
        <input type="submit">
    </form>
<?php endif; ?>

Fastest check if row exists in PostgreSQL

I would like to propose another thought to specifically address your sentence: "So I want to check if a single row from the batch exists in the table because then I know they all were inserted."

You are making things efficient by inserting in "batches" but then doing existence checks one record at a time? This seems counter intuitive to me. So when you say "inserts are always done in batches" I take it you mean you are inserting multiple records with one insert statement. You need to realize that Postgres is ACID compliant. If you are inserting multiple records (a batch of data) with one insert statement, there is no need to check if some were inserted or not. The statement either passes or it will fail. All records will be inserted or none.

On the other hand, if your C# code is simply doing a "set" separate insert statements, for example, in a loop, and in your mind, this is a "batch" .. then you should not in fact describe it as "inserts are always done in batches". The fact that you expect that part of what you call a "batch", may actually not be inserted, and hence feel the need for a check, strongly suggests this is the case, in which case you have a more fundamental problem. You need change your paradigm to actually insert multiple records with one insert, and forego checking if the individual records made it.

Consider this example:

CREATE TABLE temp_test (
    id SERIAL PRIMARY KEY,
    sometext TEXT,
    userid INT,
    somethingtomakeitfail INT unique
)
-- insert a batch of 3 rows
;;
INSERT INTO temp_test (sometext, userid, somethingtomakeitfail) VALUES
('foo', 1, 1),
('bar', 2, 2),
('baz', 3, 3)
;;
-- inspect the data of what we inserted
SELECT * FROM temp_test
;;
-- this entire statement will fail .. no need to check which one made it
INSERT INTO temp_test (sometext, userid, somethingtomakeitfail) VALUES
('foo', 2, 4),
('bar', 2, 5),
('baz', 3, 3)  -- <<--(deliberately simulate a failure)
;;
-- check it ... everything is the same from the last successful insert ..
-- no need to check which records from the 2nd insert may have made it in
SELECT * FROM temp_test

This is in fact the paradigm for any ACID compliant DB .. not just Postgresql. In other words you are better off if you fix your "batch" concept and avoid having to do any row by row checks in the first place.

Linq with group by having count

Like this:

from c in db.Company
group c by c.Name into grp
where grp.Count() > 1
select grp.Key

Or, using the method syntax:

Company
    .GroupBy(c => c.Name)
    .Where(grp => grp.Count() > 1)
    .Select(grp => grp.Key);

How to use Comparator in Java to sort

Do not waste time implementing Sorting Algorithm by your own. Instead; use

Collections.sort() to sort data.

Reference list item by index within Django template?

A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

such as get my_list[x] in templates:

in template

{% load index %}
{{ my_list|index:x }}

templatetags/index.py

from django import template
register = template.Library()

@register.filter
def index(indexable, i):
    return indexable[i]

if my_list = [['a','b','c'], ['d','e','f']], you can use {{ my_list|index:x|index:y }} in template to get my_list[x][y]

It works fine with "for"

{{ my_list|index:forloop.counter0 }}

Tested and works well ^_^

How to use "not" in xpath?

not() is a function in xpath (as opposed to an operator), so

//a[not(contains(@id, 'xx'))]

How to sort List<Integer>?

You are using Lists, concrete ArrayList. ArrayList also implements Collection interface. Collection interface has sort method which is used to sort the elements present in the specified list of Collection in ascending order. This will be the quickest and possibly the best way for your case.

Sorting a list in ascending order can be performed as default operation on this way:

Collections.sort(list);

Sorting a list in descending order can be performed on this way:

Collections.reverse(list);

According to these facts, your solution has to be written like this:

public class tes 
{
    public static void main(String args[])
    {
        List<Integer> lList = new ArrayList<Integer>();
        lList.add(4);
        lList.add(1);
        lList.add(7);
        lList.add(2);
        lList.add(9);
        lList.add(1);
        lList.add(5);

        Collections.sort(lList);
        for(int i=0; i<lList.size();i++ )
        {
            System.out.println(lList.get(i));
        }
     }
}

More about Collections you can read here.

How do I find which application is using up my port?

It may be possible that there is no other application running. It is possible that the socket wasn't cleanly shutdown from a previous session in which case you may have to wait for a while before the TIME_WAIT expires on that socket. Unfortunately, you won't be able to use the port till that socket expires. If you can start your server after waiting for a while (a few minutes) then the problem is not due to some other application running on port 8080.

Editor does not contain a main type in Eclipse

Just change "String[] args" to "String args[]".

How to use NULL or empty string in SQL

You can simply do this:

SELECT *
FROM   yourTable
WHERE  yourColumn IS NULL OR yourColumn = ''

How to access the services from RESTful API in my angularjs page?

Option 1: $http service

AngularJS provides the $http service that does exactly what you want: Sending AJAX requests to web services and receiving data from them, using JSON (which is perfectly for talking to REST services).

To give an example (taken from the AngularJS documentation and slightly adapted):

$http({ method: 'GET', url: '/foo' }).
  success(function (data, status, headers, config) {
    // ...
  }).
  error(function (data, status, headers, config) {
    // ...
  });

Option 2: $resource service

Please note that there is also another service in AngularJS, the $resource service which provides access to REST services in a more high-level fashion (example again taken from AngularJS documentation):

var Users = $resource('/user/:userId', { userId: '@id' });
var user = Users.get({ userId: 123 }, function () {
  user.abc = true;
  user.$save();
});

Option 3: Restangular

Moreover, there are also third-party solutions, such as Restangular. See its documentation on how to use it. Basically, it's way more declarative and abstracts more of the details away from you.

Bitwise operation and usage

There may be a better way to find where an array element is between two values, but as this example shows, the & works here, whereas and does not.

import numpy as np
a=np.array([1.2, 2.3, 3.4])
np.where((a>2) and (a<3))      
#Result: Value Error
np.where((a>2) & (a<3))
#Result: (array([1]),)

Get unique values from a list in python

My solution to check contents for uniqueness but preserve the original order:

def getUnique(self):
    notunique = self.readLines()
    unique = []
    for line in notunique: # Loop over content
        append = True # Will be set to false if line matches existing line
        for existing in unique:
            if line == existing: # Line exists ? do not append and go to the next line
                append = False
                break # Already know file is unique, break loop
        if append: unique.append(line) # Line not found? add to list
    return unique

Edit: Probably can be more efficient by using dictionary keys to check for existence instead of doing a whole file loop for each line, I wouldn't use my solution for large sets.

How to create a custom exception type in Java?

You have to define your exception elsewhere as a new class

public class YourCustomException extends Exception{

//Required inherited methods here
}

Then you can throw and catch YourCustomException as much as you'd like.

wkhtmltopdf: cannot connect to X server

  1. Download file from this link
  2. Extract it and move executable file(/wkhtmltox/bin/wkhtmltopdf) to /usr/bin/
  3. Rename it to wkhtmltopdf if current name is not wkhtmltopdf. So that now you have an executable at /usr/bin/wkhtmltopdf
  4. Set permissions: sudo chmod a+x /usr/bin/wkhtmltopdf
  5. Install required support packages. sudo apt-get install openssl build-essential xorg libssl-dev
  6. Now, check with wkhtmltopdf http://www.google.com test.pdf hint: detail information from this link

Error in eval(expr, envir, enclos) : object not found

I think I got what I was looking for..

data.train <- read.table("Assign2.WineComplete.csv",sep=",",header=T)
fit <- rpart(quality ~ ., method="class",data=data.train)
plot(fit)
text(fit, use.n=TRUE)
summary(fit)

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

System.Timers.Timer vs System.Threading.Timer

Information from Microsoft about this (see Remarks on MSDN):

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
  • System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

It is interesting to mention that System.Timers.Timer was deprecated with .NET Core 1.0, but was implemented again in .NET Core 2.0 (/ .NET Standard 2.0). The goal with .NET Standard 2.0 was that it should be as easy as possible to switch from the .NET Framework which is probably the reason it came back.

When it was deprecated, the .NET Portability Analyzer Visual Studio Add-In recommended to use System.Threading.Timer instead.

Looks like that Microsoft favors System.Threading.Timer before System.Timers.Timer.

EDIT NOTE 2018-11-15: I hand to change my answer since the old information about .NET Core 1.0 was not valid anymore.

Convert regular Python string to raw string

s = "hel\nlo"
raws = '%r'%s #coversion to raw string
#print(raws) will print 'hel\nlo' with single quotes.
print(raws[1:-1]) # will print hel\nlo without single quotes.
#raws[1:-1] string slicing is performed

Conversion failed when converting date and/or time from character string in SQL SERVER 2008

DECLARE @FromDate DATETIME

SET @FromDate =  'Jan 10 2016 12:00AM'

DECLARE @ToDate DATETIME
SET @ToDate = 'Jan 10 2017 12:00AM'

DECLARE @Dynamic_Qry nvarchar(Max) =''

SET @Dynamic_Qry='SELECT

(CONVERT(DATETIME,(SELECT 
     CASE WHEN (  ''IssueDate''   =''IssueDate'') THEN 
               EMP_DOCUMENT.ISSUE_DATE 
          WHEN (''IssueDate'' =''ExpiryDate'' ) THEN       
               EMP_DOCUMENT.EXPIRY_DATE ELSE EMP_DOCUMENT.APPROVED_ON END   
          CHEKDATE ), 101)  

)FROM CR.EMP_DOCUMENT  as EMP_DOCUMENT WHERE 1=1 

AND  (
      CONVERT(DATETIME,(SELECT 
        CASE WHEN (  ''IssueDate''   =''IssueDate'') THEN
                 EMP_DOCUMENT.ISSUE_DATE 
             WHEN (''IssueDate'' =''ExpiryDate'' ) THEN EMP_DOCUMENT.EXPIRY_DATE 
             ELSE EMP_DOCUMENT.APPROVED_ON END 
             CHEKDATE ), 101)  
) BETWEEN  '''+ CONVERT(CHAR(10), @FromDate, 126) +'''  AND '''+CONVERT(CHAR(10),  @ToDate , 126
)
+'''  
'

print @Dynamic_Qry

EXEC(@Dynamic_Qry) 

How do I make a stored procedure in MS Access?

If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:

 PARAMETERS SomeParam Text(10);
 SELECT Field FROM Table
 WHERE OtherField=SomeParam

You can also say:

CREATE PROCEDURE ProcedureName
   (Parameter1 datatype, Parameter2 datatype) AS
   SQLStatement

From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs

Note that the procedure contains only one statement.

rbind error: "names do not match previous names"

easy enough to use the unname() function:

data.frame <- unname(data.frame)

How to use "raise" keyword in Python

You can use it to raise errors as part of error-checking:

if (a < b):
    raise ValueError()

Or handle some errors, and then pass them on as part of error-handling:

try:
    f = open('file.txt', 'r')
except IOError:
    # do some processing here
    # and then pass the error on
    raise

Why should I use core.autocrlf=true in Git?

The only specific reasons to set autocrlf to true are:

  • avoid git status showing all your files as modified because of the automatic EOL conversion done when cloning a Unix-based EOL Git repo to a Windows one (see issue 83 for instance)
  • and your coding tools somehow depends on a native EOL style being present in your file:

Unless you can see specific treatment which must deal with native EOL, you are better off leaving autocrlf to false (git config --global core.autocrlf false).

Note that this config would be a local one (because config isn't pushed from repo to repo)

If you want the same config for all users cloning that repo, check out "What's the best CRLF handling strategy with git?", using the text attribute in the .gitattributes file.

Example:

*.vcproj    text eol=crlf
*.sh        text eol=lf

Note: starting git 2.8 (March 2016), merge markers will no longer introduce mixed line ending (LF) in a CRLF file.
See "Make Git use CRLF on its “<<<<<<< HEAD” merge lines"

How to style icon color, size, and shadow of Font Awesome Icons

Credit: Can I change the color of Font Awesome's icon color?

(this answer builds on that answer)

(for the bookmark icon, for example:)

inyour.css file:

.icon-bookmark.icon-white {
    color: white;
}

inyour.html file:

<div class="icon-bookmark icon-white"></div>

Checkout one file from Subversion

I'd just browse it and export the single file. If you have HTTP access, just use the web browser to find the file and grab it.

If you need to get it back in after editing it, that might be slightly more tedious, but I'm sure there might be an svn import function...

Getting all names in an enum as a String[]

You can put enum values to list of strings and convert to array:

    List<String> stateList = new ArrayList<>();

            for (State state: State.values()) {
                stateList.add(state.toString());
            }

    String[] stateArray = new String[stateList.size()];
    stateArray = stateList.toArray(stateArray);

link button property to open in new tab?

 <asp:LinkButton ID="LinkButton1" runat="server" target="_blank">LinkButton</asp:LinkButton>

Use target="_blank" because It creates anchor markup. the following HTML is generated for above code

<a id="ctl00_ContentPlaceHolder1_LinkButton1" target="_blank" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$LinkButton1','')">LinkButton</a>

How to set a radio button in Android

btnDisplay.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

            // get selected radio button from radioGroup
        int selectedId = radioSexGroup.getCheckedRadioButtonId();

        // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);

        Toast.makeText(MyAndroidAppActivity.this,
            radioSexButton.getText(), Toast.LENGTH_SHORT).show();

    }

});

Get path to execution directory of Windows Forms application

Application.Current results in an appdomain http://msdn.microsoft.com/en-us/library/system.appdomain_members.aspx

Also this should give you the location of the assembly

AppDomain.CurrentDomain.BaseDirectory

I seem to recall there being multiple ways of getting the location of the application. but this one worked for me in the past atleast (it's been a while since i've done winforms programming :/)

CSS Background Opacity

This is because the inner div has 100% of the opacity of the div it is nested in (which has 40% opacity).

In order to circumvent it, there are a few things you could do.

You could create two separate divs like so:

<div id="background"></div>
<div id="bContent"></div>

Set your desired CSS opacity and other properties for the background and use the z-index property (z-index) to style and position the bContent div. With this you can place the div overtope of the background div without having it's opacity mucked with.


Another option is to RGBa. This will allow you to nest your divs and still achieve div specific opacity.


The last option is to simply make a semi transparent .png image of the color you want in your desired image editor of choice, set the background-image property to the URL of the image and then you won't have to worry about mucking about with the CSS and losing the capability and organization of a nested div structure.

How to make multiple divs display in one line but still retain width?

You can use display:inline-block.

This property allows a DOM element to have all the attributes of a block element, but keeping it inline. There's some drawbacks, but most of the time it's good enough. Why it's good and why it may not work for you.

EDIT: The only modern browser that has some problems with it is IE7. See Quirksmode.org

AngularJS : The correct way of binding to a service properties

I would rather keep my watchers a less as possible. My reason is based on my experiences and one might argue it theoretically.
The issue with using watchers is that you can use any property on scope to call any of the methods in any component or service you like.
In a real world project, pretty soon you'll end up with a non-tracable (better said hard to trace) chain of methods being called and values being changed which specially makes the on-boarding process tragic.

How do I create a user account for basic authentication?

It looks to me like Windows 8 and IIS 7 no longer provides any UI to create a user name and password for basic authentication that is NOT a windows local user account. It is clearly a superior approach to create an IIS-only user/password authentication pair, but it is not clear and easy how it is done.

Command line tools exist for this purpose. Some people create a Windows account and then remove the Log on Locally User Privilege.

Eclipse: Set maximum line length for auto formatting?

Preferences -> Java -> Code Style -> Formatter / "Edit..."

Tabs: "Line wrapping" , "Comments"

Field: "Maximum line width"

Set both to make comments have the same length too. You might need to create a new profile if you don't have one already.

What do the result codes in SVN mean?

I usually use svn through a gui, either my IDE or a client. Because of that, I can never remember the codes when I do have to resort to the command line.

I find this cheat sheet a great help: Subversion Cheat Sheet

casting int to char using C++ style casting

You should use static_cast<char>(i) to cast the integer i to char.

reinterpret_cast should almost never be used, unless you want to cast one type into a fundamentally different type.

Also reinterpret_cast is machine dependent so safely using it requires complete understanding of the types as well as how the compiler implements the cast.

For more information about C++ casting see:

How to display the current time and date in C#

If you want to do it in XAML,

xmlns:sys="clr-namespace:System;assembly=mscorlib"
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}}"

With some formatting,

<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now},
                  StringFormat='{}{0:dd-MMM-yyyy hh:mm:ss}'}"

How to perform a for-each loop over all the files under a specified path?

Use command substitution instead of quotes to execute find instead of passing the command as a string:

for line in $(find . -iname '*.txt'); do 
     echo $line
     ls -l $line; 
done

Convert hexadecimal string (hex) to a binary string

With all zeroes:

static String hexToBin(String s) {
    String preBin = new BigInteger(s, 16).toString(2);
    Integer length = preBin.length();
    if (length < 8) {
        for (int i = 0; i < 8 - length; i++) {
            preBin = "0" + preBin;
        }
    }
    return preBin;
}

LINQ to read XML

A couple of plain old foreach loops provides a clean solution:

foreach (XElement level1Element in XElement.Load("data.xml").Elements("level1"))
{
    result.AppendLine(level1Element.Attribute("name").Value);

    foreach (XElement level2Element in level1Element.Elements("level2"))
    {
        result.AppendLine("  " + level2Element.Attribute("name").Value);
    }
}

java.nio.file.Path for a classpath resource

It turns out you can do this, with the help of the built-in Zip File System provider. However, passing a resource URI directly to Paths.get won't work; instead, one must first create a zip filesystem for the jar URI without the entry name, then refer to the entry in that filesystem:

static Path resourceToPath(URL resource)
throws IOException,
       URISyntaxException {

    Objects.requireNonNull(resource, "Resource URL cannot be null");
    URI uri = resource.toURI();

    String scheme = uri.getScheme();
    if (scheme.equals("file")) {
        return Paths.get(uri);
    }

    if (!scheme.equals("jar")) {
        throw new IllegalArgumentException("Cannot convert to Path: " + uri);
    }

    String s = uri.toString();
    int separator = s.indexOf("!/");
    String entryName = s.substring(separator + 2);
    URI fileURI = URI.create(s.substring(0, separator));

    FileSystem fs = FileSystems.newFileSystem(fileURI,
        Collections.<String, Object>emptyMap());
    return fs.getPath(entryName);
}

Update:

It’s been rightly pointed out that the above code contains a resource leak, since the code opens a new FileSystem object but never closes it. The best approach is to pass a Consumer-like worker object, much like how Holger’s answer does it. Open the ZipFS FileSystem just long enough for the worker to do whatever it needs to do with the Path (as long as the worker doesn’t try to store the Path object for later use), then close the FileSystem.

How do I convert a string to a double in Python?

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).

docker unauthorized: authentication required - upon push with successful login

You'll need to log in to Docker.

Step 1: log in to docker hub

Based on @KaraPirinc's comment, in Docker version 17 in order to log in:

docker login -u username --password-stdin

Then enter your password when asked.

Step 2: create a repository in the docker hub.

Let's say "mysqlserver:sql".

docker push <user username>/mysqlserver:sql

Disable browser's back button

IF you need to softly suppress the delete and backspace keys in your Web app, so that when they are editing / deleting items the page does not get redirected unexpectedly, you can use this code:

window.addEventListener('keydown', function(e) {
  var key = e.keyCode || e.which;
  if (key == 8 /*BACKSPACE*/ || key == 46/*DELETE*/) {
    var len=window.location.href.length;
    if(window.location.href[len-1]!='#') window.location.href += "#";
  }
},false);

C# "must declare a body because it is not marked abstract, extern, or partial"

You need to provide a body for the get; portion as well as the set; portion of the property.

I suspect you want this to be:

private int _hour; // backing field
private int Hour
    {
        get { return _hour; }
        set
        {
            //make sure hour is positive
            if (value < MIN_HOUR)
            {
                _hour = 0;
                MessageBox.Show("Hour value " + value.ToString() + " cannot be negative. Reset to " + MIN_HOUR.ToString(),
                "Invalid Hour", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                //take the modulus to ensure always less than 24 hours
                //works even if the value is already within range, or value equal to 24
                _hour = value % MAX_HOUR;
            }
        }
    }

That being said, I'd also consider making this code simpler. It's probably is better to use exceptions rather than a MessageBox inside of your property setter for invalid input, as it won't tie you to a specific UI framework.

If that is inappropriate, I would recommend converting this to a method instead of using a property setter. This is especially true since properties have an implicit expectation of being "lightweight"- and displaying a MessageBox to the user really violates that expectation.

No matching bean of type ... found for dependency

I had the same issue but in my case, implemented class was accidently become 'abstract' as a result autowiring was failing.

How to convert NSDate into unix timestamp iphone sdk?

As per @kexik's suggestion using the UNIX time function as below :

  time_t result = time(NULL);
  NSLog([NSString stringWithFormat:@"The current Unix epoch time is %d",(int)result]);

.As per my experience - don't use timeIntervalSince1970 , it gives epoch timestamp - number of seconds you are behind GMT.

There used to be a bug with [[NSDate date]timeIntervalSince1970] , it used to add/subtract time based on the timezone of the phone but it seems to be resolved now.

How to use <DllImport> in VB.NET?

You can also try this

Private Declare Function GetWindowText Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal lpString As StringBuilder, ByVal cch As Integer) As Integer

I always use Declare Function instead of DllImport... Its more simply, its shorter and does the same

Php, wait 5 seconds before executing an action

before starting your actions, use

 sleep(5);

Best way to combine two or more byte arrays in C#

Many of the answers seem to me to be ignoring the stated requirements:

  • The result should be a byte array
  • It should be as efficient as possible

These two together rule out a LINQ sequence of bytes - anything with yield is going to make it impossible to get the final size without iterating through the whole sequence.

If those aren't the real requirements of course, LINQ could be a perfectly good solution (or the IList<T> implementation). However, I'll assume that Superdumbell knows what he wants.

(EDIT: I've just had another thought. There's a big semantic difference between making a copy of the arrays and reading them lazily. Consider what happens if you change the data in one of the "source" arrays after calling the Combine (or whatever) method but before using the result - with lazy evaluation, that change will be visible. With an immediate copy, it won't. Different situations will call for different behaviour - just something to be aware of.)

Here are my proposed methods - which are very similar to those contained in some of the other answers, certainly :)

public static byte[] Combine(byte[] first, byte[] second)
{
    byte[] ret = new byte[first.Length + second.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    return ret;
}

public static byte[] Combine(byte[] first, byte[] second, byte[] third)
{
    byte[] ret = new byte[first.Length + second.Length + third.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    Buffer.BlockCopy(third, 0, ret, first.Length + second.Length,
                     third.Length);
    return ret;
}

public static byte[] Combine(params byte[][] arrays)
{
    byte[] ret = new byte[arrays.Sum(x => x.Length)];
    int offset = 0;
    foreach (byte[] data in arrays)
    {
        Buffer.BlockCopy(data, 0, ret, offset, data.Length);
        offset += data.Length;
    }
    return ret;
}

Of course the "params" version requires creating an array of the byte arrays first, which introduces extra inefficiency.

SQL Server date format yyyymmdd

DECLARE @v DATE= '3/15/2013'

SELECT CONVERT(VARCHAR(10), @v, 112)

you can convert any date format or date time format to YYYYMMDD with no delimiters

How to change the status bar color in Android?

Well, Izhar solution was OK but, personally, I am trying to avoid from code that looks as this:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//Do what you need for this SDK
};

As well, I don't like to duplicate code either. In your answer I have to add such line of code in all Activities:

setStatusBarColor(findViewById(R.id.statusBarBackground),getResources().getColor(android.R.color.white));

So, I took Izhar solution and used XML to get the same result: Create a layout for the StatusBar status_bar.xml

<View xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="@dimen/statusBarHeight"
     android:background="@color/primaryColorDark"
     android:elevation="@dimen/statusBarElevation">

Notice the height and elevation attributes, these will be set in values, values-v19, values-v21 further down.

Add this layout to your activities layout using include, main_activity.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/Black" >

<include layout="@layout/status_bar"/>
<include android:id="@+id/app_bar" layout="@layout/app_bar"/>
//The rest of your layout       
</RelativeLayout>

For the Toolbar, add top margin attribute:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="@color/primaryColor"
app:theme="@style/MyCustomToolBarTheme"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
android:elevation="@dimen/toolbarElevation"
android:layout_marginTop="@dimen/appBarTopMargin"
android:textDirection="ltr"
android:layoutDirection="ltr">

In your appTheme style-v19.xml and styles-v21.xml, add the windowTranslucent attr:

styles-v19.xml, v21:

<resources>
<item name="android:windowTranslucentStatus">true</item>
</resources>

And finally, on your dimens, dimens-v19, dimens-v21, add the values for the Toolbar topMargin, and the height of the statusBarHeight: dimens.xml for less than KitKat:

<resources>
<dimen name="toolbarElevation">4dp</dimen>
<dimen name="appBarTopMargin">0dp</dimen>
<dimen name="statusBarHeight">0dp</dimen>
</resources>

The status bar height is always 24dp dimens-v19.xml for KitKat and above:

<resources>
<dimen name="statusBarHeight">24dp</dimen>
<dimen name="appBarTopMargin">24dp</dimen>
</resources>

dimens-v21.xml for Lolipop, just add the elevation if needed:

<resources>
<dimen name="statusBarElevation">4dp</dimen>
</resources>

This is the result for Jellybean KitKat and Lollipop:

enter image description here

How to loop over grouped Pandas dataframe?

Here is an example of iterating over a pd.DataFrame grouped by the column atable. For this sample, "create" statements for an SQL database are generated within the for loop:

import pandas as pd

df1 = pd.DataFrame({
    'atable':     ['Users', 'Users', 'Domains', 'Domains', 'Locks'],
    'column':     ['col_1', 'col_2', 'col_a', 'col_b', 'col'],
    'column_type':['varchar', 'varchar', 'int', 'varchar', 'varchar'],
    'is_null':    ['No', 'No', 'Yes', 'No', 'Yes'],
})

df1_grouped = df1.groupby('atable')

# iterate over each group
for group_name, df_group in df1_grouped:
    print('\nCREATE TABLE {}('.format(group_name))

    for row_index, row in df_group.iterrows():
        col = row['column']
        column_type = row['column_type']
        is_null = 'NOT NULL' if row['is_null'] == 'NO' else ''
        print('\t{} {} {},'.format(col, column_type, is_null))

    print(");")

Free easy way to draw graphs and charts in C++?

Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.

How can I detect if a selector returns null?

The selector returns an array of jQuery objects. If no matching elements are found, it returns an empty array. You can check the .length of the collection returned by the selector or check whether the first array element is 'undefined'.

You can use any the following examples inside an IF statement and they all produce the same result. True, if the selector found a matching element, false otherwise.

$('#notAnElement').length > 0
$('#notAnElement').get(0) !== undefined
$('#notAnElement')[0] !== undefined