Programs & Examples On #Pixel perfect

Bootstrap: How do I identify the Bootstrap version?

The easiest would be to locate the bootstrap file (bootstrap.css OR bootstrap.min.css) and read through the docblock, you'll see something like this

Bootstrap v3.3.6 (http://getbootstrap.com)

Git error: "Please make sure you have the correct access rights and the repository exists"

Very common mistake was done by me. I copied using clip command xclip -sel clip < ~/.ssh/id_rsa.pub, but during pasting into github key input box, I removed last newline using backspace, which actually changed the public key.

So, always copy & paste ssh public key as it is without removing last newline.

Catching FULL exception message

You can add:

-ErrorVariable errvar

And then look in $errvar.

1067 error on attempt to start MySQL

I had the same error and it was caused by non standard characters in the log files path. In order to fix that I found my.ini config file (in my case C:\ProgramData\MySQL\MySQL Server 5.6\my.ini) and modified keys slow_query_log_file and log-error. After that I managed to start MySQL service succesfully.

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

public partial class recommended_books : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.RecommendedBook",
            c => new
                {
                    RecommendedBookID = c.Int(nullable: false, identity: true),
                    CourseID = c.Int(nullable: false),
                    DepartmentID = c.Int(nullable: false),
                    Title = c.String(),
                    Author = c.String(),
                    PublicationDate = c.DateTime(nullable: false),
                })
            .PrimaryKey(t => t.RecommendedBookID)
            .ForeignKey("dbo.Course", t => t.CourseID, cascadeDelete: false) // was true on migration
            .ForeignKey("dbo.Department", t => t.DepartmentID, cascadeDelete: false) // was true on migration
            .Index(t => t.CourseID)
            .Index(t => t.DepartmentID);

    }

    public override void Down()
    {
        DropForeignKey("dbo.RecommendedBook", "DepartmentID", "dbo.Department");
        DropForeignKey("dbo.RecommendedBook", "CourseID", "dbo.Course");
        DropIndex("dbo.RecommendedBook", new[] { "DepartmentID" });
        DropIndex("dbo.RecommendedBook", new[] { "CourseID" });
        DropTable("dbo.RecommendedBook");
    }
}

When your migration fails you are given a couple of options: 'Introducing FOREIGN KEY constraint 'FK_dbo.RecommendedBook_dbo.Department_DepartmentID' on table 'RecommendedBook' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.'

Here is an example of using the 'modify other FOREIGN KEY constraints' by setting 'cascadeDelete' to false in the migration file and then run 'update-database'.

How do I convert Long to byte[] and back in java

If you are looking for a fast unrolled version, this should do the trick, assuming a byte array called "b" with a length of 8:

byte[] -> long

long l = ((long) b[7] << 56)
       | ((long) b[6] & 0xff) << 48
       | ((long) b[5] & 0xff) << 40
       | ((long) b[4] & 0xff) << 32
       | ((long) b[3] & 0xff) << 24
       | ((long) b[2] & 0xff) << 16
       | ((long) b[1] & 0xff) << 8
       | ((long) b[0] & 0xff);

long -> byte[] as an exact counterpart to the above

byte[] b = new byte[] {
       (byte) lng,
       (byte) (lng >> 8),
       (byte) (lng >> 16),
       (byte) (lng >> 24),
       (byte) (lng >> 32),
       (byte) (lng >> 40),
       (byte) (lng >> 48),
       (byte) (lng >> 56)};

Search a whole table in mySQL for a string

If you are just looking for some text and don't need a result set for programming purposes, you could install HeidiSQL for free (I'm using v9.2.0.4947).

Right click any database or table and select "Find text on server".

All the matches are shown in a separate tab for each table - very nice.

Frighteningly useful and saved me hours. Forget messing about with lengthy queries!!

How can I right-align text in a DataGridView column?

DataGridViewColumn column0 = dataGridViewGroup.Columns[0];
DataGridViewColumn column1 = dataGridViewGroup.Columns[1];
column1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
column1.Width = 120;

Opening Chrome From Command Line

if you want to open incognito window, put the command below:

start chrome /incognito

How to find elements by class

Use class_= If you want to find element(s) without stating the HTML tag.

For single element:

soup.find(class_='my-class-name')

For multiple elements:

soup.find_all(class_='my-class-name')

Using two values for one switch case statement

JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.

Now you can:

  • directly assign variable from switch expression,
  • use new form of switch label (case L ->):

    The code to the right of a "case L ->" switch label is restricted to be an expression, a block, or (for convenience) a throw statement.

  • use multiple constants per case, separated by commas,
  • and also there are no more value breaks:

    To yield a value from a switch expression, the break with value statement is dropped in favor of a yield statement.

So the demo from one of the answers might look like this:

public class SwitchExpression {

  public static void main(String[] args) {
      int month = 9;
      int year = 2018;
      int numDays = switch (month) {
        case 1, 3, 5, 7, 8, 10, 12 -> 31;
        case 4, 6, 9, 11 -> 30;
        case 2 -> {
          if (java.time.Year.of(year).isLeap()) {
            System.out.println("Wow! It's leap year!");
            yield 29;
          } else {
            yield 28;
          }
        }
        default -> {
          System.out.println("Invalid month.");
          yield 0;
        }
      };
      System.out.println("Number of Days = " + numDays);
  }
}

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

Just 2 things I think make it ALWAYS preferable to use a # Temp Table rather then a CTE are:

  1. You can not put a primary key on a CTE so the data being accessed by the CTE will have to traverse each one of the indexes in the CTE's tables rather then just accessing the PK or Index on the temp table.

  2. Because you can not add constraints, indexes and primary keys to a CTE they are more prone to bugs creeping in and bad data.


-onedaywhen yesterday

Here is an example where #table constraints can prevent bad data which is not the case in CTE's

DECLARE @BadData TABLE ( 
                       ThisID int
                     , ThatID int );
INSERT INTO @BadData
       ( ThisID
       , ThatID
       ) 
VALUES
       ( 1, 1 ),
       ( 1, 2 ),
       ( 2, 2 ),
       ( 1, 1 );

IF OBJECT_ID('tempdb..#This') IS NOT NULL
    DROP TABLE #This;
CREATE TABLE #This ( 
             ThisID int NOT NULL
           , ThatID int NOT NULL
                        UNIQUE(ThisID, ThatID) );
INSERT INTO #This
SELECT * FROM @BadData;
WITH This_CTE
     AS (SELECT *
           FROM @BadData)
     SELECT *
       FROM This_CTE;

How to print a certain line of a file with PowerShell?

Just for fun, here some test:

#Added this for @Graimer's request ;) (not same computer, but one with HD little more #performant...)

measure-command { Get-Content ita\ita.txt -TotalCount 260000 | Select-Object -Last 1 }

Days              : 0
Hours             : 0

Minutes           : 0
Seconds           : 28
Milliseconds      : 893
Ticks             : 288932649
TotalDays         : 0,000334412788194444
TotalHours        : 0,00802590691666667
TotalMinutes      : 0,481554415
TotalSeconds      : 28,8932649
TotalMilliseconds : 28893,2649


> measure-command { (gc "c:\ps\ita\ita.txt")[260000] }


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 9
Milliseconds      : 257
Ticks             : 92572893
TotalDays         : 0,000107144552083333
TotalHours        : 0,00257146925
TotalMinutes      : 0,154288155
TotalSeconds      : 9,2572893
TotalMilliseconds : 9257,2893


> measure-command { ([System.IO.File]::ReadAllLines("c:\ps\ita\ita.txt"))[260000] }


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 234
Ticks             : 2348059
TotalDays         : 2,71766087962963E-06
TotalHours        : 6,52238611111111E-05
TotalMinutes      : 0,00391343166666667
TotalSeconds      : 0,2348059
TotalMilliseconds : 234,8059



> measure-command {get-content .\ita\ita.txt | select -index 260000}


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 36
Milliseconds      : 591
Ticks             : 365912596
TotalDays         : 0,000423509949074074
TotalHours        : 0,0101642387777778
TotalMinutes      : 0,609854326666667
TotalSeconds      : 36,5912596
TotalMilliseconds : 36591,2596

the winner is : ([System.IO.File]::ReadAllLines( path ))[index]

How can I get table names from an MS Access Database?

Schema information which is designed to be very close to that of the SQL-92 INFORMATION_SCHEMA may be obtained for the Jet/ACE engine (which is what I assume you mean by 'access') via the OLE DB providers.

See:

OpenSchema Method (ADO)

Supported Schema Rowsets

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

String dt = Date.Now.ToString("yyyy-MM-dd");

Now you got this for dt, 2010-09-09

Regular expression - starting and ending with a character string

Example: ajshdjashdjashdlasdlhdlSTARTasdasdsdaasdENDaknsdklansdlknaldknaaklsdn

1) START\w*END return: STARTasdasdsdaasdEND - will give you words between START and END

2) START\d*END return: START12121212END - will give you numbers between START and END

3) START\d*_\d*END return: START1212_1212END - will give you numbers between START and END having _

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Be aware to use constant HTTPS or HTTP for all requests. I had the same error msg: "No 'Access-Control-Allow-Origin' header is present on the requested resource."

Common elements in two lists

You can use set intersection operations with your ArrayList objects.

Something like this:

List<Integer> l1 = new ArrayList<Integer>();

l1.add(1);
l1.add(2);
l1.add(3);

List<Integer> l2= new ArrayList<Integer>();
l2.add(4);
l2.add(2);
l2.add(3);

System.out.println("l1 == "+l1);
System.out.println("l2 == "+l2);

List<Integer> l3 = new ArrayList<Integer>(l2);
l3.retainAll(l1);

    System.out.println("l3 == "+l3);

Now, l3 should have only common elements between l1 and l2.

CONSOLE OUTPUT
l1 == [1, 2, 3]
l2 == [4, 2, 3]
l3 == [2, 3]

How to Select Top 100 rows in Oracle?

Try this:

   SELECT *
FROM (SELECT * FROM (
    SELECT 
      id, 
      client_id, 
      create_time,
      ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn 
    FROM order
  ) 
  WHERE rn=1
  ORDER BY create_time desc) alias_name
WHERE rownum <= 100
ORDER BY rownum;

Or TOP:

SELECT TOP 2 * FROM Customers; //But not supported in Oracle

NOTE: I suppose that your internal query is fine. Please share your output of this.

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Make sure you started the server:

mysql.server start

Then connect with root user:

mysql -uroot

How do you hide the Address bar in Google Chrome for Chrome Apps?

Instructions as of Dec 2018:

  1. Visit the site you want in Chrome
  2. From menu select "More tools" > "Create shortcut..."
  3. From apps (can visit chrome://apps/), right click site then enable "Open as window"

Now when you open the shortcut it will open in a window without toolbar.

ImportError: No module named PIL

pip(3) uninstall Pillow
pip(3) uninstall PIL
pip(3) install Pillow

Apache and IIS side by side (both listening to port 80) on windows2003

For people with only one IP address and multiple sites on one server, you can configure IIS to listen on a port other than 80, e.g 8080 by setting the TCP port in the properties of each of its sites (including the default one).

In Apache, enable mod_proxy and mod_proxy_http, then add a catch-all VirtualHost (after all others) so that requests Apache isn't explicitly handling get "forwarded" on to IIS.

<VirtualHost *:80>
    ServerName foo.bar
    ServerAlias *
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8080/
</VirtualHost>

Now you can have Apache serve some sites and IIS serve others, with no visible difference to the user.

Edit: your IIS sites must not include their port number in any URLs within their responses, including headers.

Can Twitter Bootstrap alerts fade in as well as out?

The thing I use is this:

In your template an alert area

<div id="alert-area"></div>

Then an jQuery function for showing an alert

function newAlert (type, message) {
    $("#alert-area").append($("<div class='alert-message " + type + " fade in' data-alert><p> " + message + " </p></div>"));
    $(".alert-message").delay(2000).fadeOut("slow", function () { $(this).remove(); });
}
newAlert('success', 'Oh yeah!');

How to use Spring Boot with MySQL database and JPA?

I created a project like you did. The structure looks like this

project structure

The Classes are just copy pasted from yours.

I changed the application.properties to this:

spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

But I think your problem is in your pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>

<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Check these files for differences. Hope this helps

Update 1: I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL

List of Python format characters

Here you go, Python documentation on old string formatting. tutorial -> 7.1.1. Old String Formatting -> "More information can be found in the [link] section".

Note that you should start using the new string formatting when possible.

Importing Excel into a DataTable Quickly

Caling .Value2 is an expensive operation because it's a COM-interop call. I would instead read the entire range into an array and then loop through the array:

object[,] data = Range.Value2;

// Create new Column in DataTable
for (int cCnt = 1; cCnt <= Range.Columns.Count; cCnt++)
{
    textBox3.Text = cCnt.ToString();

    var Column = new DataColumn();
    Column.DataType = System.Type.GetType("System.String");
    Column.ColumnName = cCnt.ToString();
    DT.Columns.Add(Column);

    // Create row for Data Table
    for (int rCnt = 1; rCnt <= Range.Rows.Count; rCnt++)
    {
        textBox2.Text = rCnt.ToString();

        string CellVal = String.Empty;
        try
        {
            cellVal = (string)(data[rCnt, cCnt]);
        }
        catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
        {
            ConvertVal = (double)(data[rCnt, cCnt]);
            cellVal = ConvertVal.ToString();
        }

        DataRow Row;

        // Add to the DataTable
        if (cCnt == 1)
        {

            Row = DT.NewRow();
            Row[cCnt.ToString()] = cellVal;
            DT.Rows.Add(Row);
        }
        else
        {

            Row = DT.Rows[rCnt + 1];
            Row[cCnt.ToString()] = cellVal;

        }
    }
} 

Convert named list to vector with values only

purrr::flatten_*() is also a good option. the flatten_* functions add thin sanity checks and ensure type safety.

myList <- list('A'=1, 'B'=2, 'C'=3)

purrr::flatten_dbl(myList)
## [1] 1 2 3

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

How to Automatically Close Alerts using Twitter Bootstrap

With delay and fade :

setTimeout(function(){
    $(".alert").each(function(index){
        $(this).delay(200*index).fadeTo(1500,0).slideUp(500,function(){
            $(this).remove();
        });
    });
},2000);

Font size relative to the user's screen resolution?

This worked for me :

body {

  font-size: calc([minimum size] + ([maximum size] - [minimum size]) * ((100vw - [minimum 
viewport width]) / ([maximum viewport width] - [minimum viewport width])));

}

Explained in detail here: https://css-tricks.com/books/volume-i/scale-typography-screen-size/

What does java.lang.Thread.interrupt() do?

Thread.interrupt() sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait() may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)

Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. If the target thread does not poll the interrupted status the interrupt is effectively ignored.

Polling occurs via the Thread.interrupted() method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.

EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.

  • Object.wait(), Thread.sleep(), and Thread.join()
  • Most java.util.concurrent structures
  • Java NIO (but not java.io) and it does NOT use InterruptedException, instead using ClosedByInterruptException.

EDIT (from @thomas-pornin's answer to exactly same question for completeness)

Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to Thread.stop() that is more like shooting the thread with an assault rifle.

What does the red exclamation point icon in Eclipse mean?

There can be several reasons. Most of the times it may be some of the below reasons ,

  1. You have deleted some of the .jar files from your /lib folder
  2. You have added new .jar files
  3. you have added new .jar files which may be conflict with others

So what to do is we have to resolve those missing / updating / newly_added jar files.

  1. right click on the project and go to properties
  2. Select Java Build Path
  3. go to the Libraries tab
  4. Remove the jar file references which you have removed already. There will be a red mark near them so you can identify them easily.
  5. Add the references to the newly added .jar files by using Add JARs
  6. Refresh the project

This will solve the problem if it's because one of the above reasons.

Fixed digits after decimal with f-strings

a = 10.1234

print(f"{a:0.2f}")

in 0.2f:

  • 0 is telling python to put no limit on the total number of digits to display
  • .2 is saying that we want to take only 2 digits after decimal (the result will be same as a round() function)
  • f is telling that it's a float number. If you forget f then it will just print 1 less digit after the decimal. In this case, it will be only 1 digit after the decimal.

A detailed video on f-string for numbers https://youtu.be/RtKUsUTY6to?t=606

How to pause a YouTube player when hiding the iframe?

This approach requires jQuery. First, select your iframe:

var yourIframe = $('iframe#yourId');
//yourId or something to select your iframe.

Now you select button play/pause of this iframe and click it

$('button.ytp-play-button.ytp-button', yourIframe).click();

I hope it will help you.

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

I forgot to select the column (or set/map the property to a column value):

IQueryable<SampleTable> queryable = from t in dbcontext.SampleTable
                                    where ...
                                    select new DataModel { Name = t.Name };

Calling queryable.OrderBy("Id") will throw exception, even though DataModel has property Id defined.

The correct query is:

IQueryable<SampleTable> queryable = from t in dbcontext.SampleTable
                                    where ...
                                    select new DataModel { Name = t.Name, Id = t.Id };

Adding an external directory to Tomcat classpath

What I suggest you do is add a META-INF directory with a MANIFEST.MF file in .war file.

Please note that according to servlet spec, it must be a .war file and not .war directory for the META-INF/MANIFEST.MF to be read by container.

Edit the MANIFEST.MF Class-Path property to C:\app_config\java_app:

See Using JAR Files: The Basics (Understanding the Manifest)

Enjoy.

Search for string within text column in MySQL

When you are using the wordpress prepare line, the above solutions do not work. This is the solution I used:

   $Table_Name    = $wpdb->prefix.'tablename';
   $SearchField = '%'. $YourVariable . '%';   
   $sql_query     = $wpdb->prepare("SELECT * FROM $Table_Name WHERE ColumnName LIKE %s", $SearchField) ;
 $rows = $wpdb->get_results($sql_query, ARRAY_A);

What does string::npos mean in this code?

$21.4 - "static const size_type npos = -1;"

It is returned by string functions indicating error/not found etc.

Correct way to use StringBuilder in SQL

[[ There are some good answers here but I find that they still are lacking a bit of information. ]]

return (new StringBuilder("select id1, " + " id2 " + " from " + " table"))
     .toString();

So as you point out, the example you give is a simplistic but let's analyze it anyway. What happens here is the compiler actually does the + work here because "select id1, " + " id2 " + " from " + " table" are all constants. So this turns into:

return new StringBuilder("select id1,  id2  from  table").toString();

In this case, obviously, there is no point in using StringBuilder. You might as well do:

// the compiler combines these constant strings
return "select id1, " + " id2 " + " from " + " table";

However, even if you were appending any fields or other non-constants then the compiler would use an internal StringBuilder -- there's no need for you to define one:

// an internal StringBuilder is used here
return "select id1, " + fieldName + " from " + tableName;

Under the covers, this turns into code that is approximately equivalent to:

StringBuilder sb = new StringBuilder("select id1, ");
sb.append(fieldName).append(" from ").append(tableName);
return sb.toString();

Really the only time you need to use StringBuilder directly is when you have conditional code. For example, code that looks like the following is desperate for a StringBuilder:

// 1 StringBuilder used in this line
String query = "select id1, " + fieldName + " from " + tableName;
if (where != null) {
   // another StringBuilder used here
   query += ' ' + where;
}

The + in the first line uses one StringBuilder instance. Then the += uses another StringBuilder instance. It is more efficient to do:

// choose a good starting size to lower chances of reallocation
StringBuilder sb = new StringBuilder(64);
sb.append("select id1, ").append(fieldName).append(" from ").append(tableName);
// conditional code
if (where != null) {
   sb.append(' ').append(where);
}
return sb.toString();

Another time that I use a StringBuilder is when I'm building a string from a number of method calls. Then I can create methods that take a StringBuilder argument:

private void addWhere(StringBuilder sb) {
   if (where != null) {
      sb.append(' ').append(where);
   }
}

When you are using a StringBuilder, you should watch for any usage of + at the same time:

sb.append("select " + fieldName);

That + will cause another internal StringBuilder to be created. This should of course be:

sb.append("select ").append(fieldName);

Lastly, as @T.J.rowder points out, you should always make a guess at the size of the StringBuilder. This will save on the number of char[] objects created when growing the size of the internal buffer.

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

You get this exact same error when trying to connect to a MySQL database from MS-Access when the bit version (32 vs 64) of Access doesn't match

  1. the bit version of the ODBC Driver you are using
  2. the bit version of the ODBC Manager you used to set it up.

For those of you trying to connect MS-Access to MySQL on a 64 bit Windows system, I went through sheer torture trying to get it to work with both MS-Access 2010 and MS-Access 2013. Finally got it working, and here are the lessons I've learned along the way:

I bought a new Windows 7, 64 bit laptop, and I have an app which relies on MS-Access using MySQL tables.

  1. I installed the latest version of MySQL, 5.6, using the All In One package install. This allows you to install both the database and ODBC drivers all at once. That's nice, but the ODBC driver it installs seems to be the 64 bit one, so it will not work with 32 bit MS-Access. It also seems a little buggy - not for sure on that one. When you Add a new DSN in the ODBC Manager, this driver appears as "Microsoft ODBC For Oracle". I could not get this one to work. I had to install the 32 bit one, discussed below.

    • MySQL was working fine after the install. I restored my application MySQL database in the usual way. Now I want to connect to it using MS-Access.


  2. I had previously installed Office 2013, which I assumed was 64 bit. But upon checking the version (File, Account, About Access), I see that it is 32 bit. Both Access 2010 and 2013 are most commonly sold as 32-bit versions.

  3. My machine is a 64 bit machine. So by default, when you go to set up your DSN's for MS-Access, and go in the usual way into the ODBC Manager via Control Panel, Administrative Options, you get the 64 bit ODBC manager. You have no way of knowing that! You just can't tell. This is a huge gotcha!! It is impossible to set up a DSN from there and have it successfully connect to MS Access 32 bit. You will get the dreaded error:

    "the specified dsn contains an architecture mismatch..."

  4. You must download and install the 32 bit ODBC driver from MySQL. I used version 3.5.1

    http://dev.mysql.com/downloads/connector/odbc/3.51.html

  5. You must tell the ODBC Manager in Control Panel to take a hike and must instead explicitly invoke the 32 bit ODBC Manager with this command executed at the Start, Command prompt:

    c:\windows\sysWOW64\odbcad32.exe

    I created a shortcut to this on my desktop. From here, build your DSN with this manager. Important point: BUILD THEM AS SYSTEM DSNS, NOT USER DSNS! This tripped me up for awhile.

    By the way, the 64 bit version of the ODBC Manager can also be run explicitly as:

    c:\windows\system32\odbcad32.exe

  6. Once you've installed the 32-bit ODBC Driver from MySql, when you click Add in the ODBC Manager you will see 2 drivers listed. Choose "MySQL ODBC 5.2 ANSI Driver". I did not try the UNICODE driver.


That does it. Once you have defined your DSN's in the 32 bit ODBC manager, you can connect to MySQL in the usual way from within Access - External Data, ODBC Database, Link to the Database, select Machine Data Source, and the DSN you created to your MySQL database will be there.

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

What worked for me was setting aspnet:MaxHttpCollectionKeys to a high value on appSettings tag on the inetpub VirtualDirectories\443\web.config file:

<configuration>
    <appSettings>
        <add key="aspnet:MaxHttpCollectionKeys" value="100000" />
    </appSettings>
</configuration>

How often should you use git-gc?

I use git gc after I do a big checkout, and have a lot of new object. it can save space. E.g. if you checkout a big SVN project using git-svn, and do a git gc, you typically save a lot of space

Good tutorial for using HTML5 History API (Pushstate?)

For a great tutorial the Mozilla Developer Network page on this functionality is all you'll need: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

Unfortunately, the HTML5 History API is implemented differently in all the HTML5 browsers (making it inconsistent and buggy) and has no fallback for HTML4 browsers. Fortunately, History.js provides cross-compatibility for the HTML5 browsers (ensuring all the HTML5 browsers work as expected) and optionally provides a hash-fallback for HTML4 browsers (including maintained support for data, titles, pushState and replaceState functionality).

You can read more about History.js here: https://github.com/browserstate/history.js

For an article about Hashbangs VS Hashes VS HTML5 History API, see here: https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling

Java Timer vs ExecutorService?

Here's some more good practices around Timer use:

http://tech.puredanger.com/2008/09/22/timer-rules/

In general, I'd use Timer for quick and dirty stuff and Executor for more robust usage.

Creating virtual directories in IIS express

If you're using Visual Studio 2013 (may require Pro edition or higher), I was able to add a virtual directory to an IIS Express (file-based) website by right-clicking on the website in the Solution Explorer and clicking Add > New Virtual Directory. This added an entry to the applicationhost.config file as with the manual methods described here.

UITableViewCell, show delete button on swipe

For Swift, Just write this code

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            print("Delete Hit")
        }
}

For Objective C, Just write this code

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
       if (editingStyle == UITableViewCellEditingStyleDelete) {           
            NSLog(@"index: %@",indexPath.row);
           }
}

How to deselect all selected rows in a DataGridView control?

Thanks Cody heres the c# for ref:

if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            DataGridView.HitTestInfo hit = dgv_track.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.None)
            {
                dgv_track.ClearSelection();
                dgv_track.CurrentCell = null;
            }
        }

Android: Align button to bottom-right of screen using FrameLayout?

If you want to try with java code. Here you go -

    final LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, 
                                             LayoutParams.WRAP_CONTENT);
    yourView.setLayoutParams(params);
    params.gravity = Gravity.BOTTOM; // set gravity

Rotate label text in seaborn factorplot

Any seaborn plots suported by facetgrid won't work with (e.g. catplot)

g.set_xticklabels(rotation=30) 

however barplot, countplot, etc. will work as they are not supported by facetgrid. Below will work for them.

g.set_xticklabels(g.get_xticklabels(), rotation=30)

Also, in case you have 2 graphs overlayed on top of each other, try set_xticklabels on graph which supports it.

Java constant examples (Create a java file having only constants)

Neither one. Use final class for Constants declare them as public static final and static import all constants wherever necessary.

public final class Constants {

    private Constants() {
            // restrict instantiation
    }

    public static final double PI = 3.14159;
    public static final double PLANCK_CONSTANT = 6.62606896e-34;
}

Usage :

import static Constants.PLANCK_CONSTANT;
import static Constants.PI;//import static Constants.*;

public class Calculations {

        public double getReducedPlanckConstant() {
                return PLANCK_CONSTANT / (2 * PI);
        }
}

See wiki link : http://en.wikipedia.org/wiki/Constant_interface

Is it possible to apply CSS to half of a character?

You can also do it using SVG, if you wish:

_x000D_
_x000D_
var title = document.querySelector('h1'),_x000D_
    text = title.innerHTML,_x000D_
    svgTemplate = document.querySelector('svg'),_x000D_
    charStyle = svgTemplate.querySelector('#text');_x000D_
_x000D_
svgTemplate.style.display = 'block';_x000D_
_x000D_
var space = 0;_x000D_
_x000D_
for (var i = 0; i < text.length; i++) {_x000D_
  var x = charStyle.cloneNode();_x000D_
  x.textContent = text[i];_x000D_
  svgTemplate.appendChild(x);_x000D_
  x.setAttribute('x', space);_x000D_
  space += x.clientWidth || 15;_x000D_
}_x000D_
_x000D_
title.innerHTML = '';_x000D_
title.appendChild(svgTemplate);
_x000D_
<svg style="display: none; height: 100px; width: 100%" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">_x000D_
    <defs id="FooDefs">_x000D_
        <linearGradient id="MyGradient" x1="0%" y1="0%" x2="100%" y2="0%">_x000D_
            <stop offset="50%" stop-color="blue" />_x000D_
            <stop offset="50%" stop-color="red" />_x000D_
        </linearGradient>_x000D_
    </defs>_x000D_
    <text y="50%" id="text" style="font-size: 72px; fill: url(#MyGradient)"></text>_x000D_
</svg>_x000D_
_x000D_
<h1>This is not a solution X</h1>
_x000D_
_x000D_
_x000D_

http://codepen.io/nicbell/pen/jGcbq

remove space between paragraph and unordered list

p, ul{
     padding:0; 
     margin:0;
}

If that's not what your looking for you'll have to be more specific

Rails: How can I rename a database column in a Ruby on Rails migration?

If the column is already populated with data and live in production, I'd recommend a step by step approach, so as to avoid downtime in production while waiting for the migrations.

First I'd create a db migration to add columns with the new name(s) and populate them with the values from the old column name.

class AddCorrectColumnNames < ActiveRecord::Migration
  def up
    add_column :table, :correct_name_column_one, :string
    add_column :table, :correct_name_column_two, :string

    puts 'Updating correctly named columns'
    execute "UPDATE table_name SET correct_name_column_one = old_name_column_one, correct_name_column_two = old_name_column_two"
    end
  end

  def down
    remove_column :table, :correct_name_column_one
    remove_column :table, :correct_name_column_two
  end
end

Then I'd commit just that change, and push the change into production.

git commit -m 'adding columns with correct name'

Then once the commit has been pushed into production, I'd run.

Production $ bundle exec rake db:migrate

Then I'd update all of the views/controllers that referenced the old column name to the new column name. Run through my test suite, and commit just those changes. (After making sure it was working locally and passing all tests first!)

git commit -m 'using correct column name instead of old stinky bad column name'

Then I'd push that commit to production.

At this point you can remove the original column without worrying about any sort of downtime associated with the migration itself.

class RemoveBadColumnNames < ActiveRecord::Migration
  def up
    remove_column :table, :old_name_column_one
    remove_column :table, :old_name_column_two
  end

  def down
    add_column :table, :old_name_column_one, :string
    add_column :table, :old_name_column_two, :string
  end
end

Then push this latest migration to production and run bundle exec rake db:migrate in the background.

I realize this is a bit more involved of a process, but I'd rather do this than have issues with my production migration.

Properly close mongoose's connection once you're done

You will get an error if you try to close/disconnect outside of the method. The best solution is to close the connection in both callbacks in the method. The dummy code is here.

const newTodo = new Todo({text:'cook dinner'});

newTodo.save().then((docs) => {
  console.log('todo saved',docs);
  mongoose.connection.close();
},(e) => {
  console.log('unable to save');
});

java.net.ConnectException :connection timed out: connect?

Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a. C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name. Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.

How to query MongoDB with "like"?

If you want 'Like' search in mongo then you should go with $regex by using this query will be

db.product.find({name:{$regex:/m/i}})

for more you can read the documentation as well. https://docs.mongodb.com/manual/reference/operator/query/regex/

Increasing nesting function calls limit

Personally I would suggest this is an error as opposed to a setting that needs adjusting. In my code it was because I had a class that had the same name as a library within one of my controllers and it seemed to trip it up.

Output errors and see where this is being triggered.

Remove the first character of a string

deleting a char:

def del_char(string, indexes):

    'deletes all the indexes from the string and returns the new one'

    return ''.join((char for idx, char in enumerate(string) if idx not in indexes))

it deletes all the chars that are in indexes; you can use it in your case with del_char(your_string, [0])

How to get EditText value and display it on screen through TextView?

yesButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        eiteText=(EditText)findViewById(R.id.nameET);
        String result=eiteText.getText().toString();
        Log.d("TAG",result);
    }
});

Counting repeated characters in a string in Python

import collections

d = collections.defaultdict(int)
for c in thestring:
    d[c] += 1

A collections.defaultdict is like a dict (subclasses it, actually), but when an entry is sought and not found, instead of reporting it doesn't have it, it makes it and inserts it by calling the supplied 0-argument callable. Most popular are defaultdict(int), for counting (or, equivalently, to make a multiset AKA bag data structure), and defaultdict(list), which does away forever with the need to use .setdefault(akey, []).append(avalue) and similar awkward idioms.

So once you've done this d is a dict-like container mapping every character to the number of times it appears, and you can emit it any way you like, of course. For example, most-popular character first:

for c in sorted(d, key=d.get, reverse=True):
  print '%s %6d' % (c, d[c])

Styling Google Maps InfoWindow

Google wrote some code to assist with this. Here are some examples: Example using InfoBubble, Styled markers and Info Window Custom (using OverlayView).

The code in the links above take different routes to achieve similar results. The gist of it is that it is not easy to style InfoWindows directly, and it might be easier to use the additional InfoBubble class instead of InfoWindow, or to override GOverlay. Another option would be to modify the elements of the InfoWindow using javascript (or jQuery), like later ATOzTOA suggested.

Possibly the simplest of these examples is using InfoBubble instead of InfoWindow. InfoBubble is available by importing this file (which you should host yourself): http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/src/infobubble.js

InfoBubble's Github project page.

InfoBubble is very stylable, compared to InfoWindow:

 infoBubble = new InfoBubble({
      map: map,
      content: '<div class="mylabel">The label</div>',
      position: new google.maps.LatLng(-32.0, 149.0),
      shadowStyle: 1,
      padding: 0,
      backgroundColor: 'rgb(57,57,57)',
      borderRadius: 5,
      arrowSize: 10,
      borderWidth: 1,
      borderColor: '#2c2c2c',
      disableAutoPan: true,
      hideCloseButton: true,
      arrowPosition: 30,
      backgroundClassName: 'transparent',
      arrowStyle: 2
});

infoBubble.open();

You can also call it with a given map and marker to open on:

infoBubble.open(map, marker);

As another example, the Info Window Custom example extends the GOverlay class from the Google Maps API and uses this as a base for creating a more flexible info window. It first creates the class:

/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Map} map The map on which to display this InfoBox.
 * @param {Object} opts Passes configuration options - content,
 *   offsetVertical, offsetHorizontal, className, height, width
 */
function InfoBox(opts) {
  google.maps.OverlayView.call(this);
  this.latlng_ = opts.latlng;
  this.map_ = opts.map;
  this.offsetVertical_ = -195;
  this.offsetHorizontal_ = 0;
  this.height_ = 165;
  this.width_ = 266;

  var me = this;
  this.boundsChangedListener_ =
    google.maps.event.addListener(this.map_, "bounds_changed", function() {
      return me.panMap.apply(me);
    });

  // Once the properties of this OverlayView are initialized, set its map so
  // that we can display it.  This will trigger calls to panes_changed and
  // draw.
  this.setMap(this.map_);
}

after which it proceeds to override GOverlay:

InfoBox.prototype = new google.maps.OverlayView();

You should then override the methods you need: createElement, draw, remove and panMap. It gets rather involved, but in theory you are just drawing a div on the map yourself now, instead of using a normal Info Window.

how to delete default values in text field using selenium?

For page object model -

 @FindBy(xpath="//foo")
   public WebElement textBox;

now in your function

 public void clearExistingText(String newText){
    textBox.clear();
    textBox.sendKeys(newText);
  }

for general selenium architecture -

driver.findElement(By.xpath("//yourxpath")).clear();
driver.findElement(By.xpath("//yourxpath")).sendKeys("newText");

Parse JSON String to JSON Object in C#.NET

use new JavaScriptSerializer().Deserialize<object>(jsonString)

You need System.Web.Extensions dll and import the following namespace.

Namespace: System.Web.Script.Serialization

for more info MSDN

This action could not be completed. Try Again (-22421)

(As of May 23, 2018)

Step 1

Open Xcode --> Product tab --> Archive --> export and save to desktop

Step 2

Open Xcode --> Xcode tab --> Open Developer Tool --> Application Loader >> double-click Deliver YourApp and select the recently exported .ipa file from your desktop

Solved the issue every time =)

What is the difference between properties and attributes in HTML?

well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html

but currently attr and prop are not so different and there are almost the same

but they prefer prop for some things

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)

What is a monad?

But, You could have invented Monads!

sigfpe says:

But all of these introduce monads as something esoteric in need of explanation. But what I want to argue is that they aren't esoteric at all. In fact, faced with various problems in functional programming you would have been led, inexorably, to certain solutions, all of which are examples of monads. In fact, I hope to get you to invent them now if you haven't already. It's then a small step to notice that all of these solutions are in fact the same solution in disguise. And after reading this, you might be in a better position to understand other documents on monads because you'll recognise everything you see as something you've already invented.

Many of the problems that monads try to solve are related to the issue of side effects. So we'll start with them. (Note that monads let you do more than handle side-effects, in particular many types of container object can be viewed as monads. Some of the introductions to monads find it hard to reconcile these two different uses of monads and concentrate on just one or the other.)

In an imperative programming language such as C++, functions behave nothing like the functions of mathematics. For example, suppose we have a C++ function that takes a single floating point argument and returns a floating point result. Superficially it might seem a little like a mathematical function mapping reals to reals, but a C++ function can do more than just return a number that depends on its arguments. It can read and write the values of global variables as well as writing output to the screen and receiving input from the user. In a pure functional language, however, a function can only read what is supplied to it in its arguments and the only way it can have an effect on the world is through the values it returns.

Using getline() in C++

i think you are not pausing the program before it ended so the output you are putting after getting the inpus is not seeing on the screen right?

do:

getchar();

before the end of the program

Laravel requires the Mcrypt PHP extension

This solved it for me on my Linux Mint local enviroment https://askubuntu.com/questions/350942/cannot-get-mcrypt-for-php5

I needed to make a symlink to my /etc/php5/conf.d/mcrypt.ini file in the following folders /etc/php5/apache2/conf.d/mcrypt.ini and /etc/php5/cli/conf.d/mcrypt.ini

Set width of dropdown element in HTML select dropdown options

HTML:

<select class="shortenedSelect">
    <option value="0" disabled>Please select an item</option>
    <option value="1">Item text goes in here but it is way too long to fit inside a select option that has a fixed width adding more</option>
</select>

CSS:

.shortenedSelect {
    max-width: 350px;
}

Javascript:

// Shorten select option text if it stretches beyond max-width of select element
$.each($('.shortenedSelect option'), function(key, optionElement) {
    var curText = $(optionElement).text();
    $(this).attr('title', curText);

    // Tip: parseInt('350px', 10) removes the 'px' by forcing parseInt to use a base ten numbering system.
    var lengthToShortenTo = Math.round(parseInt($(this).parent('select').css('max-width'), 10) / 7.3);

    if (curText.length > lengthToShortenTo) {
        $(this).text('... ' + curText.substring((curText.length - lengthToShortenTo), curText.length));
    }
});

// Show full name in tooltip after choosing an option
$('.shortenedSelect').change(function() {
    $(this).attr('title', ($(this).find('option:eq('+$(this).get(0).selectedIndex +')').attr('title')));
});

Works perfectly. I had the same issue myself. Check out this JSFiddle http://jsfiddle.net/jNWS6/426/

How do you plot bar charts in gnuplot?

Simple bar graph:

bar graph

set boxwidth 0.5
set style fill solid
plot "data.dat" using 1:3:xtic(2) with boxes

data.dat:

0 label       100
1 label2      450
2 "bar label" 75

If you want to style your bars differently, you can do something like:

multi color bar graph

set style line 1 lc rgb "red"
set style line 2 lc rgb "blue"

set style fill solid
set boxwidth 0.5

plot "data.dat" every ::0::0 using 1:3:xtic(2) with boxes ls 1, \
     "data.dat" every ::1::2 using 1:3:xtic(2) with boxes ls 2

If you want to do multiple bars for each entry:

data.dat:

0     5
0.5   6


1.5   3
2     7


3     8
3.5   1

gnuplot:

set xtics ("label" 0.25, "label2" 1.75, "bar label" 3.25,)

set boxwidth 0.5
set style fill solid

plot 'data.dat' every 2    using 1:2 with boxes ls 1,\
     'data.dat' every 2::1 using 1:2 with boxes ls 2

barchart_multi

If you want to be tricky and use some neat gnuplot tricks:

Gnuplot has psuedo-columns that can be used as the index to color:

plot 'data.dat' using 1:2:0 with boxes lc variable

barchart_multi2

Further you can use a function to pick the colors you want:

mycolor(x) = ((x*11244898) + 2851770)
plot 'data.dat' using 1:2:(mycolor($0)) with boxes lc rgb variable

barchart_multi3

Note: you will have to add a couple other basic commands to get the same effect as the sample images.

Edit and replay XHR chrome/firefox etc?

There are a few ways to do this, as mentioned above, but in my experience the best way to manipulate an XHR request and resend is to use chrome dev tools to copy the request as cURL request (right click on the request in the network tab) and to simply import into the Postman app (giant import button in the top left).

Calculating Page Load Time In JavaScript

Why so complicated? When you can do:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;

If you need more times check out the window.performance object:

console.log(window.performance);

Will show you the timing object:

connectEnd                 Time when server connection is finished.
connectStart               Time just before server connection begins.
domComplete                Time just before document readiness completes.
domContentLoadedEventEnd   Time after DOMContentLoaded event completes.
domContentLoadedEventStart Time just before DOMContentLoaded starts.
domInteractive             Time just before readiness set to interactive.
domLoading                 Time just before readiness set to loading.
domainLookupEnd            Time after domain name lookup.
domainLookupStart          Time just before domain name lookup.
fetchStart                 Time when the resource starts being fetched.
loadEventEnd               Time when the load event is complete.
loadEventStart             Time just before the load event is fired.
navigationStart            Time after the previous document begins unload.
redirectCount              Number of redirects since the last non-redirect.
redirectEnd                Time after last redirect response ends.
redirectStart              Time of fetch that initiated a redirect.
requestStart               Time just before a server request.
responseEnd                Time after the end of a response or connection.
responseStart              Time just before the start of a response.
timing                     Reference to a performance timing object.
navigation                 Reference to performance navigation object.
performance                Reference to performance object for a window.
type                       Type of the last non-redirect navigation event.
unloadEventEnd             Time after the previous document is unloaded.
unloadEventStart           Time just before the unload event is fired.

Browser Support

More Info

change html text from link with jquery

try this in javascript

 document.getElementById("22IdMObileFull").text ="itsClicked"

Missing XML comment for publicly visible type or member

In your solution, once you check the option to generate XML Document file, it start checking your public members, for having the XMLDoc, if they don't, you'll receive a warning per each element. if you don't really want to release your DLL, and also you don't need documentations then, go to your solution, build section, and turn it off, else if you need it, so fill them, and if there are unimportant properties and fields, just surpass them with pre-compiler instruction #pragma warning disable 1591 you can also restore the warning : #pragma warning restore 1591

pragma usage: any where in code before the place you get compiler warning for... (for file, put it in header, and you do not need to enable it again, for single class wrap around a class, or for method wrap around a method, or ... you do not either need to wrap it around, you can call it and restore it casually (start in begin of file, and end inside a method)), write this code:

#pragma warning disable 1591 and in case you need to restore it, use: #pragma warning restore 1591

Here an example:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using RealEstate.Entity.Models.Base;

namespace RealEstate.Models.Base
{
    public class CityVM
    {

#pragma warning disable 1591

        [Required]
        public string Id { get; set; }

        [Required]
        public string Name { get; set; }

        public List<LanguageBasedName> LanguageBasedNames { get; set; }

        [Required]
        public string CountryId { get; set; }

#pragma warning restore 1591

        /// <summary>
        /// Some countries do not have neither a State, nor a Province
        /// </summary>
        public string StateOrProvinceId { get; set; }
    }
}

Note that pragma directive start at the begin of line

Is there a standardized method to swap two variables in Python?

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

Python docs: Evaluation order

That means the following for the expression a,b = b,a :

  • The right-hand side b,a is evaluated, that is to say, a tuple of two elements is created in the memory. The two elements are the objects designated by the identifiers b and a, that were existing before the instruction is encountered during the execution of the program.
  • Just after the creation of this tuple, no assignment of this tuple object has still been made, but it doesn't matter, Python internally knows where it is.
  • Then, the left-hand side is evaluated, that is to say, the tuple is assigned to the left-hand side.
  • As the left-hand side is composed of two identifiers, the tuple is unpacked in order that the first identifier a be assigned to the first element of the tuple (which is the object that was formerly b before the swap because it had name b)
    and the second identifier b is assigned to the second element of the tuple (which is the object that was formerly a before the swap because its identifiers was a)

This mechanism has effectively swapped the objects assigned to the identifiers a and b

So, to answer your question: YES, it's the standard way to swap two identifiers on two objects.
By the way, the objects are not variables, they are objects.

How to check all versions of python installed on osx and centos

Use,

yum list installed
command to find the packages you installed.

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

Please find below another way to make the same thing.

This procedure also takes in a schema name as a parameter in case you need it to access your table.

CREATE PROCEDURE Export_Data_NBA
@TableName nchar(50),
@TableSchema nvarchar(50) = ''

AS
DECLARE @TableToBeExported as nvarchar(50);

DECLARE @OUTPUT TABLE (col1 nvarchar(max));
DECLARE @colnamestable VARCHAR(max);
select @colnamestable = COALESCE(@colnamestable, '') +COLUMN_NAME+ ','
from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName
order BY ORDINAL_POSITION

SELECT @colnamestable = LEFT(@colnamestable,DATALENGTH(@colnamestable)-1)

INSERT INTO @OUTPUT
select @colnamestable

DECLARE @selectstatement VARCHAR(max);
select @selectstatement = COALESCE(@selectstatement, '') + 'Convert(nvarchar(100),'+COLUMN_NAME+')+'',''+'
from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName
order BY ORDINAL_POSITION

SELECT @selectstatement = LEFT(@selectstatement,DATALENGTH(@selectstatement)-1)

DECLARE @sqlstatment as nvarchar(max);

SET @TableToBeExported = @TableSchema+'.'+@TableToBeExported

SELECT @sqlstatment = N'Select '+@selectstatement+N' from '+@TableToBeExported

INSERT INTO @OUTPUT
exec sp_executesql @stmt = @sqlstatment

SELECT * from @OUTPUT

django MultiValueDictKeyError error, how do I deal with it

Choose what is best for you:

1

is_private = request.POST.get('is_private', False);

If is_private key is present in request.POST the is_private variable will be equal to it, if not, then it will be equal to False.

2

if 'is_private' in request.POST:
    is_private = request.POST['is_private']
else:
    is_private = False

3

from django.utils.datastructures import MultiValueDictKeyError
try:
    is_private = request.POST['is_private']
except MultiValueDictKeyError:
    is_private = False

convert string to specific datetime format?

This another helpful code:

"2011-05-19 10:30:14".to_datetime.strftime('%a %b %d %H:%M:%S %Z %Y')

How do I merge changes to a single file, rather than merging commits?

The following command will (1) compare the file of the correct branch, to master (2) interactively ask you which modifications to apply.

git checkout --patch master

Display exact matches only with grep

^ marks the beginning of the line and $ marks the end of the line. This will return exact matches of "OK" only:

(This also works with double quotes if that's your preference.)

grep '^OK$'

If there are other characters before the OK / NOTOK (like the job name), you can exclude the "NOT" prefix by allowing any characters .* and then excluding "NOT" [^NOT] just before the "OK":

grep '^.*[^NOT]OK$'

How to check if a date is greater than another in Java?

You can use Date.before() or Date.after() or Date.equals() for date comparison.

Taken from here:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDiff {

    public static void main( String[] args )
    {
        compareDates("2017-01-13 00:00:00", "2017-01-14 00:00:00");// output will be Date1 is before Date2
        compareDates("2017-01-13 00:00:00", "2017-01-12 00:00:00");//output will be Date1 is after Date2
        compareDates("2017-01-13 00:00:00", "2017-01-13 10:20:30");//output will be Date1 is before Date2 because date2 is ahead of date 1 by 10:20:30 hours
        compareDates("2017-01-13 00:00:00", "2017-01-13 00:00:00");//output will be Date1 is equal Date2 because both date and time are equal
    }

    public static void compareDates(String d1,String d2)
    {
        try{
            // If you already have date objects then skip 1

            //1
            // Create 2 dates starts
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(d2);

            System.out.println("Date1"+sdf.format(date1));
            System.out.println("Date2"+sdf.format(date2));System.out.println();

            // Create 2 dates ends
            //1

            // Date object is having 3 methods namely after,before and equals for comparing
            // after() will return true if and only if date1 is after date 2
            if(date1.after(date2)){
                System.out.println("Date1 is after Date2");
            }
            // before() will return true if and only if date1 is before date2
            if(date1.before(date2)){
                System.out.println("Date1 is before Date2");
            }

            //equals() returns true if both the dates are equal
            if(date1.equals(date2)){
                System.out.println("Date1 is equal Date2");
            }

            System.out.println();
        }
        catch(ParseException ex){
            ex.printStackTrace();
        }
    }

    public static void compareDates(Date date1,Date date2)
    {
        // if you already have date objects then skip 1
        //1

        //1

        //date object is having 3 methods namely after,before and equals for comparing
        //after() will return true if and only if date1 is after date 2
        if(date1.after(date2)){
            System.out.println("Date1 is after Date2");
        }

        //before() will return true if and only if date1 is before date2
        if(date1.before(date2)){
            System.out.println("Date1 is before Date2");
        }

        //equals() returns true if both the dates are equal
        if(date1.equals(date2)){
            System.out.println("Date1 is equal Date2");
        }

        System.out.println();
    }
}

How can I alter a primary key constraint using SQL syntax?

Yes. The only way would be to drop the constraint with an Alter table then recreate it.

ALTER TABLE <Table_Name>
DROP CONSTRAINT <constraint_name>

ALTER TABLE <Table_Name>
ADD CONSTRAINT <constraint_name> PRIMARY KEY (<Column1>,<Column2>)

fs.writeFile in a promise, asynchronous-synchronous stuff

As of 2019...

...the correct answer is to use async/await with the native fs promises module included in node. Upgrade to Node.js 10 or 11 (already supported by major cloud providers) and do this:

const fs = require('fs').promises;

// This must run inside a function marked `async`:
const file = await fs.readFile('filename.txt', 'utf8');
await fs.writeFile('filename.txt', 'test');

Do not use third-party packages and do not write your own wrappers, that's not necessary anymore.

No longer experimental

Before Node 11.14.0, you would still get a warning that this feature is experimental, but it works just fine and it's the way to go in the future. Since 11.14.0, the feature is no longer experimental and is production-ready.

What if I prefer import instead of require?

It works, too - but only in Node.js versions where this feature is not marked as experimental.

import { promises as fs } from 'fs';

(async () => {
    await fs.writeFile('./test.txt', 'test', 'utf8');
})();

image processing to improve tesseract OCR accuracy

As a rule of thumb, I usually apply the following image pre-processing techniques using OpenCV library:

  1. Rescaling the image (it's recommended if you’re working with images that have a DPI of less than 300 dpi):

    img = cv2.resize(img, None, fx=1.2, fy=1.2, interpolation=cv2.INTER_CUBIC)
    
  2. Converting image to grayscale:

    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
  3. Applying dilation and erosion to remove the noise (you may play with the kernel size depending on your data set):

    kernel = np.ones((1, 1), np.uint8)
    img = cv2.dilate(img, kernel, iterations=1)
    img = cv2.erode(img, kernel, iterations=1)
    
  4. Applying blur, which can be done by using one of the following lines (each of which has its pros and cons, however, median blur and bilateral filter usually perform better than gaussian blur.):

    cv2.threshold(cv2.GaussianBlur(img, (5, 5), 0), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    
    cv2.threshold(cv2.bilateralFilter(img, 5, 75, 75), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    
    cv2.threshold(cv2.medianBlur(img, 3), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    
    cv2.adaptiveThreshold(cv2.GaussianBlur(img, (5, 5), 0), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
    
    cv2.adaptiveThreshold(cv2.bilateralFilter(img, 9, 75, 75), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
    
    cv2.adaptiveThreshold(cv2.medianBlur(img, 3), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
    

I've recently written a pretty simple guide to Tesseract but it should enable you to write your first OCR script and clear up some hurdles that I experienced when things were less clear than I would have liked in the documentation.

In case you'd like to check them out, here I'm sharing the links with you:

How to map a composite key with JPA and Hibernate?

Another option is to map is as a Map of composite elements in the ConfPath table.

This mapping would benefit from an index on (ConfPathID,levelStation) though.

public class ConfPath {
    private Map<Long,Time> timeForLevelStation = new HashMap<Long,Time>();

    public Time getTime(long levelStation) {
        return timeForLevelStation.get(levelStation);
    }

    public void putTime(long levelStation, Time newValue) {
        timeForLevelStation.put(levelStation, newValue);
    }
}

public class Time {
    String src;
    String dst;
    long distance;
    long price;

    public long getDistance() {
        return distance;
    }

    public void setDistance(long distance) {
        this.distance = distance;
    }

    public String getDst() {
        return dst;
    }

    public void setDst(String dst) {
        this.dst = dst;
    }

    public long getPrice() {
        return price;
    }

    public void setPrice(long price) {
        this.price = price;
    }

    public String getSrc() {
        return src;
    }

    public void setSrc(String src) {
        this.src = src;
    }
}

Mapping:

<class name="ConfPath" table="ConfPath">
    <id column="ID" name="id">
        <generator class="native"/>
    </id>
    <map cascade="all-delete-orphan" name="values" table="example"
            lazy="extra">
        <key column="ConfPathID"/>
        <map-key type="long" column="levelStation"/>
        <composite-element class="Time">
            <property name="src" column="src" type="string" length="100"/>
            <property name="dst" column="dst" type="string" length="100"/>
            <property name="distance" column="distance"/>
            <property name="price" column="price"/>
        </composite-element>
    </map>
</class>

How to disable "prevent this page from creating additional dialogs"?

I know everybody is ethically against this, but I understand there are reasons of practical joking where this is desired. I think Chrome took a solid stance on this by enforcing a mandatory one second separation time between alert messages. This gives the visitor just enough time to close the page or refresh if they're stuck on an annoying prank site.

So to answer your question, it's all a matter of timing. If you alert more than once per second, Chrome will create that checkbox. Here's a simple example of a workaround:

var countdown = 99;
function annoy(){
    if(countdown>0){
        alert(countdown+" bottles of beer on the wall, "+countdown+" bottles of beer! Take one down, pass it around, "+(countdown-1)+" bottles of beer on the wall!");
        countdown--;

        // Time must always be 1000 milliseconds, 999 or less causes the checkbox to appear
        setTimeout(function(){
            annoy();
        }, 1000);
    }
}

// Don't alert right away or Chrome will catch you
setTimeout(function(){
    annoy();
}, 1000);

Query error with ambiguous column name in SQL

This happens because there are fields with the same name in more than one table, in the query, because of the joins, so you should reference the fields differently, giving names (aliases) to the tables.

How to stop a PowerShell script on the first error?

You should be able to accomplish this by using the statement $ErrorActionPreference = "Stop" at the beginning of your scripts.

The default setting of $ErrorActionPreference is Continue, which is why you are seeing your scripts keep going after errors occur.

How to use a different version of python during NPM install?

set python to python2.7 before running npm install

Linux:

export PYTHON=python2.7

Windows:

set PYTHON=python2.7

Moment JS start and end of given month

Try the following code:

const moment=require('moment');
console.log("startDate=>",moment().startOf('month').format("YYYY-DD-MM"));
console.log("endDate=>",moment().endOf('month').format("YYYY-DD-MM"));

Open new Terminal Tab from command line (Mac OS X)

Update: This answer gained popularity based on the shell function posted below, which still works as of OSX 10.10 (with the exception of the -g option).
However, a more fully featured, more robust, tested script version is now available at the npm registry as CLI ttab, which also supports iTerm2:

  • If you have Node.js installed, simply run:

    npm install -g ttab
    

    (depending on how you installed Node.js, you may have to prepend sudo).

  • Otherwise, follow these instructions.

  • Once installed, run ttab -h for concise usage information, or man ttab to view the manual.


Building on the accepted answer, below is a bash convenience function for opening a new tab in the current Terminal window and optionally executing a command (as a bonus, there's a variant function for creating a new window instead).

If a command is specified, its first token will be used as the new tab's title.

Sample invocations:

    # Get command-line help.
newtab -h
    # Simpy open new tab.
newtab
    # Open new tab and execute command (quoted parameters are supported).
newtab ls -l "$Home/Library/Application Support"
    # Open a new tab with a given working directory and execute a command;
    # Double-quote the command passed to `eval` and use backslash-escaping inside.
newtab eval "cd ~/Library/Application\ Support; ls"
    # Open new tab, execute commands, close tab.
newtab eval "ls \$HOME/Library/Application\ Support; echo Press a key to exit.; read -s -n 1; exit"
    # Open new tab and execute script.
newtab /path/to/someScript
    # Open new tab, execute script, close tab.
newtab exec /path/to/someScript
    # Open new tab and execute script, but don't activate the new tab.
newtab -G /path/to/someScript

CAVEAT: When you run newtab (or newwin) from a script, the script's initial working folder will be the working folder in the new tab/window, even if you change the working folder inside the script before invoking newtab/newwin - pass eval with a cd command as a workaround (see example above).

Source code (paste into your bash profile, for instance):

# Opens a new tab in the current Terminal window and optionally executes a command.
# When invoked via a function named 'newwin', opens a new Terminal *window* instead.
function newtab {

    # If this function was invoked directly by a function named 'newwin', we open a new *window* instead
    # of a new tab in the existing window.
    local funcName=$FUNCNAME
    local targetType='tab'
    local targetDesc='new tab in the active Terminal window'
    local makeTab=1
    case "${FUNCNAME[1]}" in
        newwin)
            makeTab=0
            funcName=${FUNCNAME[1]}
            targetType='window'
            targetDesc='new Terminal window'
            ;;
    esac

    # Command-line help.
    if [[ "$1" == '--help' || "$1" == '-h' ]]; then
        cat <<EOF
Synopsis:
    $funcName [-g|-G] [command [param1 ...]]

Description:
    Opens a $targetDesc and optionally executes a command.

    The new $targetType will run a login shell (i.e., load the user's shell profile) and inherit
    the working folder from this shell (the active Terminal tab).
    IMPORTANT: In scripts, \`$funcName\` *statically* inherits the working folder from the
    *invoking Terminal tab* at the time of script *invocation*, even if you change the
    working folder *inside* the script before invoking \`$funcName\`.

    -g (back*g*round) causes Terminal not to activate, but within Terminal, the new tab/window
      will become the active element.
    -G causes Terminal not to activate *and* the active element within Terminal not to change;
      i.e., the previously active window and tab stay active.

    NOTE: With -g or -G specified, for technical reasons, Terminal will still activate *briefly* when
    you create a new tab (creating a new window is not affected).

    When a command is specified, its first token will become the new ${targetType}'s title.
    Quoted parameters are handled properly.

    To specify multiple commands, use 'eval' followed by a single, *double*-quoted string
    in which the commands are separated by ';' Do NOT use backslash-escaped double quotes inside
    this string; rather, use backslash-escaping as needed.
    Use 'exit' as the last command to automatically close the tab when the command
    terminates; precede it with 'read -s -n 1' to wait for a keystroke first.

    Alternatively, pass a script name or path; prefix with 'exec' to automatically
    close the $targetType when the script terminates.

Examples:
    $funcName ls -l "\$Home/Library/Application Support"
    $funcName eval "ls \\\$HOME/Library/Application\ Support; echo Press a key to exit.; read -s -n 1; exit"
    $funcName /path/to/someScript
    $funcName exec /path/to/someScript
EOF
        return 0
    fi

    # Option-parameters loop.
    inBackground=0
    while (( $# )); do
        case "$1" in
            -g)
                inBackground=1
                ;;
            -G)
                inBackground=2
                ;;
            --) # Explicit end-of-options marker.
                shift   # Move to next param and proceed with data-parameter analysis below.
                break
                ;;
            -*) # An unrecognized switch.
                echo "$FUNCNAME: PARAMETER ERROR: Unrecognized option: '$1'. To force interpretation as non-option, precede with '--'. Use -h or --h for help." 1>&2 && return 2
                ;;
            *)  # 1st argument reached; proceed with argument-parameter analysis below.
                break
                ;;
        esac
        shift
    done

    # All remaining parameters, if any, make up the command to execute in the new tab/window.

    local CMD_PREFIX='tell application "Terminal" to do script'

        # Command for opening a new Terminal window (with a single, new tab).
    local CMD_NEWWIN=$CMD_PREFIX    # Curiously, simply executing 'do script' with no further arguments opens a new *window*.
        # Commands for opening a new tab in the current Terminal window.
        # Sadly, there is no direct way to open a new tab in an existing window, so we must activate Terminal first, then send a keyboard shortcut.
    local CMD_ACTIVATE='tell application "Terminal" to activate'
    local CMD_NEWTAB='tell application "System Events" to keystroke "t" using {command down}'
        # For use with -g: commands for saving and restoring the previous application
    local CMD_SAVE_ACTIVE_APPNAME='tell application "System Events" to set prevAppName to displayed name of first process whose frontmost is true'
    local CMD_REACTIVATE_PREV_APP='activate application prevAppName'
        # For use with -G: commands for saving and restoring the previous state within Terminal
    local CMD_SAVE_ACTIVE_WIN='tell application "Terminal" to set prevWin to front window'
    local CMD_REACTIVATE_PREV_WIN='set frontmost of prevWin to true'
    local CMD_SAVE_ACTIVE_TAB='tell application "Terminal" to set prevTab to (selected tab of front window)'
    local CMD_REACTIVATE_PREV_TAB='tell application "Terminal" to set selected of prevTab to true'

    if (( $# )); then # Command specified; open a new tab or window, then execute command.
            # Use the command's first token as the tab title.
        local tabTitle=$1
        case "$tabTitle" in
            exec|eval) # Use following token instead, if the 1st one is 'eval' or 'exec'.
                tabTitle=$(echo "$2" | awk '{ print $1 }') 
                ;;
            cd) # Use last path component of following token instead, if the 1st one is 'cd'
                tabTitle=$(basename "$2")
                ;;
        esac
        local CMD_SETTITLE="tell application \"Terminal\" to set custom title of front window to \"$tabTitle\""
            # The tricky part is to quote the command tokens properly when passing them to AppleScript:
            # Step 1: Quote all parameters (as needed) using printf '%q' - this will perform backslash-escaping.
        local quotedArgs=$(printf '%q ' "$@")
            # Step 2: Escape all backslashes again (by doubling them), because AppleScript expects that.
        local cmd="$CMD_PREFIX \"${quotedArgs//\\/\\\\}\""
            # Open new tab or window, execute command, and assign tab title.
            # '>/dev/null' suppresses AppleScript's output when it creates a new tab.
        if (( makeTab )); then
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active tab after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_SAVE_ACTIVE_TAB" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$cmd in front window" -e "$CMD_SETTITLE" -e "$CMD_REACTIVATE_PREV_APP" -e "$CMD_REACTIVATE_PREV_TAB" >/dev/null
                else
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$cmd in front window" -e "$CMD_SETTITLE" -e "$CMD_REACTIVATE_PREV_APP" >/dev/null
                fi
            else
                osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$cmd in front window" -e "$CMD_SETTITLE" >/dev/null
            fi
        else # make *window*
            # Note: $CMD_NEWWIN is not needed, as $cmd implicitly creates a new window.
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active window after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_WIN" -e "$cmd" -e "$CMD_SETTITLE" -e "$CMD_REACTIVATE_PREV_WIN" >/dev/null
                else
                    osascript -e "$cmd" -e "$CMD_SETTITLE" >/dev/null
                fi
            else
                    # Note: Even though we do not strictly need to activate Terminal first, we do it, as assigning the custom title to the 'front window' would otherwise sometimes target the wrong window.
                osascript -e "$CMD_ACTIVATE" -e "$cmd" -e "$CMD_SETTITLE" >/dev/null
            fi
        fi        
    else    # No command specified; simply open a new tab or window.
        if (( makeTab )); then
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active tab after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_SAVE_ACTIVE_TAB" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$CMD_REACTIVATE_PREV_APP" -e "$CMD_REACTIVATE_PREV_TAB" >/dev/null
                else
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$CMD_REACTIVATE_PREV_APP" >/dev/null
                fi
            else
                osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" >/dev/null
            fi
        else # make *window*
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active window after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_WIN" -e "$CMD_NEWWIN" -e "$CMD_REACTIVATE_PREV_WIN" >/dev/null
                else
                    osascript -e "$CMD_NEWWIN" >/dev/null
                fi
            else
                    # Note: Even though we do not strictly need to activate Terminal first, we do it so as to better visualize what is happening (the new window will appear stacked on top of an existing one).
                osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWWIN" >/dev/null
            fi
        fi
    fi

}

# Opens a new Terminal window and optionally executes a command.
function newwin {
    newtab "$@" # Simply pass through to 'newtab', which will examine the call stack to see how it was invoked.
}

What is the best way to manage a user's session in React?

I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.

You should use either cookies or localStorage for persisting a user's session data. You can also use a closure as a wrapper around your cookie or localStorage data.

Here is a simple example of a UserProfile closure that will hold the user's name.

var UserProfile = (function() {
  var full_name = "";

  var getName = function() {
    return full_name;    // Or pull this from cookie/localStorage
  };

  var setName = function(name) {
    full_name = name;     
    // Also set this in cookie/localStorage
  };

  return {
    getName: getName,
    setName: setName
  }

})();

export default UserProfile;

When a user logs in, you can populate this object with user name, email address etc.

import UserProfile from './UserProfile';

UserProfile.setName("Some Guy");

Then you can get this data from any component in your app when needed.

import UserProfile from './UserProfile';

UserProfile.getName();

Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.

How to set UICollectionViewCell Width and Height programmatically

Swift 5, Programmatic UICollectionView setting Cell width and height

// MARK: MyViewController

final class MyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    private lazy var collectionViewLayout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        let spacing: CGFloat = 1
        let numOfColumns: CGFloat = 3
        let itemSize: CGFloat = (UIScreen.main.bounds.width - (numOfColumns - spacing) - 2) / 3
        layout.itemSize = CGSize(width: itemSize, height: itemSize)
        layout.minimumInteritemSpacing = spacing
        layout.minimumLineSpacing = spacing
        layout.sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
        return layout
    }()
    
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: collectionViewLayout)
        collectionView.backgroundColor = .white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        return collectionView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureCollectionView()
    }
    
    private func configureCollectionView() {
        view.addSubview(collectionView)
        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            collectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            collectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
        ])
        collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: "PhotoCell")
    }
    
    // MARK: UICollectionViewDataSource

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
        cell.backgroundColor = .red
        return cell
    }
    
}

// MARK: PhotoCell

final class PhotoCell: UICollectionViewCell {
    
    lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.layer.masksToBounds = true
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init?(coder:) not implemented")
    }
    
    func setupViews() {
        addSubview(imageView)
        NSLayoutConstraint.activate([
            topAnchor.constraint(equalTo: topAnchor),
            bottomAnchor.constraint(equalTo: bottomAnchor),
            leadingAnchor.constraint(equalTo: leadingAnchor),
            trailingAnchor.constraint(equalTo: trailingAnchor)
        ])
    }
    
}

What is N-Tier architecture?

Wikipedia:

In software engineering, multi-tier architecture (often referred to as n-tier architecture) is a client-server architecture in which, the presentation, the application processing and the data management are logically separate processes. For example, an application that uses middleware to service data requests between a user and a database employs multi-tier architecture. The most widespread use of "multi-tier architecture" refers to three-tier architecture.

It's debatable what counts as "tiers," but in my opinion it needs to at least cross the process boundary. Or else it's called layers. But, it does not need to be in physically different machines. Although I don't recommend it, you can host logical tier and database on the same box.

alt text

Edit: One implication is that presentation tier and the logic tier (sometimes called Business Logic Layer) needs to cross machine boundaries "across the wire" sometimes over unreliable, slow, and/or insecure network. This is very different from simple Desktop application where the data lives on the same machine as files or Web Application where you can hit the database directly.

For n-tier programming, you need to package up the data in some sort of transportable form called "dataset" and fly them over the wire. .NET's DataSet class or Web Services protocol like SOAP are few of such attempts to fly objects over the wire.

How to break out or exit a method in Java?

Use the return keyword to exit from a method.

public void someMethod() {
    //... a bunch of code ...
    if (someCondition()) {
        return;
    }
    //... otherwise do the following...
}

Pls note: We may use break statements which are used to break/exit only from a loop, and not the entire program.

To exit from program: System.exit() Method:
System.exit has status code, which tells about the termination, such as:
exit(0) : Indicates successful termination.
exit(1) or exit(-1) or any non-zero value – indicates unsuccessful termination.

Android notification is not showing

The code won't work without an icon. So, add the setSmallIcon call to the builder chain like this for it to work:

.setSmallIcon(R.drawable.icon)

Android Oreo (8.0) and above

Android 8 introduced a new requirement of setting the channelId property by using a NotificationChannel.

private NotificationManager mNotificationManager;

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);

NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Today's Bible Verse");
bigText.setSummaryText("Text in detail");

mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);

mNotificationManager =
    (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

// === Removed some obsoletes
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
    String channelId = "Your_channel_id";
    NotificationChannel channel = new NotificationChannel(
                                        channelId,
                                        "Channel human readable title",
                                        NotificationManager.IMPORTANCE_HIGH);
   mNotificationManager.createNotificationChannel(channel);
  mBuilder.setChannelId(channelId);
}

mNotificationManager.notify(0, mBuilder.build());

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

You can use toStringAsFixed in order to display the limited digits after decimal points. toStringAsFixed returns a decimal-point string-representation. toStringAsFixed accepts an argument called fraction Digits which is how many digits after decimal we want to display. Here is how to use it.

double pi = 3.1415926;
const val = pi.toStringAsFixed(2); // 3.14

What is the easiest way to install BLAS and LAPACK for scipy?

Always for Ubuntu/Debian, chjortlund's answer it's very good but not perfect, since this way you get an unoptimized BLAS library. You have simply to do:

sudo apt install libatlas-base-dev

and voila'!

Source

Div 100% height works on Firefox but not in IE

I'm not sure what problem you are solving, but when I have two side by side containers that need to be the same height, I run a little javascript on page load that finds the maximum height of the two and explicitly sets the other to the same height. It seems to me that height: 100% might just mean "make it the size needed to fully contain the content" when what you really want is "make both the size of the largest content."

Note: you'll need to resize them again if anything happens on the page to change their height -- like a validation summary being made visible or a collapsible menu opening.

Npm Error - No matching version found for

try

npm install --force
npm install --legacy-peer-deps

C++ template constructor

template<class...>struct types{using type=types;};
template<class T>struct tag{using type=T;};
template<class Tag>using type_t=typename Tag::type;

the above helpers let you work with types as values.

class A {
  template<class T>
  A( tag<T> );
};

the tag<T> type is a variable with no state besides the type it caries. You can use this to pass a pure-type value into a template function and have the type be deduced by the template function:

auto a = A(tag<int>{});

You can pass in more than one type:

class A {
  template<class T, class U, class V>
  A( types<T,U,V> );
};
auto a = A(types<int,double,std::string>{});

Write lines of text to a file in R

I suggest:

writeLines(c("Hello","World"), "output.txt")

It is shorter and more direct than the current accepted answer. It is not necessary to do:

fileConn<-file("output.txt")
# writeLines command using fileConn connection
close(fileConn)

Because the documentation for writeLines() says:

If the con is a character string, the function calls file to obtain a file connection which is opened for the duration of the function call.

# default settings for writeLines(): sep = "\n", useBytes = FALSE
# so: sep = "" would join all together e.g.

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

Set your PRIMARY KEY as AUTO_INCREMENT.

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

Difference between style = "position:absolute" and style = "position:relative"

Relative:

  1. An element with position: relative; is positioned relative to its normal position.

  2. If you add no positioning attributes (top, left, bottom or right) on a relative element it will have no effect on it's positioning at all. It will behave exactly as a position: static element.

  3. But if you do add some other positioning attribute, say, top: 10px;, it will shift its position 10 pixels down from where it would normally be.

  4. An element with this type of positioning gets affected by other elements and it itself also affects others.

Absolute:

  1. An element with position: absolute; allows you to place any element exactly where you want it to be. You use the positioning attributes top, left, bottom. and right to set the location.

  2. It is placed relative to the nearest non-static ancestor. If there is no such container, it is placed relative to the page itself.

  3. It gets removed from the normal flow of elements on the page.

  4. An element with this type of positioning is not affected by other elements and also it doesn't affect flow of other elements.

See this self-explanatory example for better clarity. https://codepen.io/nyctophiliac/pen/BJMqjX

SQL NVARCHAR and VARCHAR Limits

The accepted answer helped me but I got tripped up while doing concatenation of varchars involving case statements. I know the OP's question does not involve case statements but I thought this would be helpful to post here for others like me who ended up here while struggling to build long dynamic SQL statements involving case statements.

When using case statements with string concatenation the rules mentioned in the accepted answer apply to each section of the case statement independently.

declare @l_sql varchar(max) = ''

set @l_sql = @l_sql +
case when 1=1 then
    --without this correction the result is truncated
    --CONVERT(VARCHAR(MAX), '')
 +REPLICATE('1', 8000)
 +REPLICATE('1', 8000)
end

print len(@l_sql)

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

  • You can also use the file extension to check for the filetype.
  • More simpler way would be to do something as given below inside add :

    add : function (e,data){
       var extension = data.originalFiles[0].name.substr( 
       (data.originalFiles[0].name.lastIndexOf('.') +1) );
                switch(extension){
                    case 'csv':
                    case 'xls':
                    case 'xlsx':
                        data.url = <Your URL>; 
                        data.submit();
                    break;
                    default:
                        alert("File type not accepted");
                    break;
                }
      }
    

How do you extract classes' source code from a dll file?

I used Refractor to recover my script/code from dll file.

Properly escape a double quote in CSV

If a value contains a comma, a newline character or a double quote, then the string must be enclosed in double quotes. E.g: "Newline char in this field \n".

You can use below online tool to escape "" and , operators. https://www.freeformatter.com/csv-escape.html#ad-output

How to set the image from drawable dynamically in android?

getDrawable() is deprecated. now you can use

imageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.msg_status_client_read)) 

Storing a Key Value Array into a compact JSON string

To me, this is the most "natural" way to structure such data in JSON, provided that all of the keys are strings.

{
    "keyvaluelist": {
        "slide0001.html": "Looking Ahead",
        "slide0008.html": "Forecast",
        "slide0021.html": "Summary"
    },
    "otherdata": {
        "one": "1",
        "two": "2",
        "three": "3"
    },
    "anotherthing": "thing1",
    "onelastthing": "thing2"
}

I read this as

a JSON object with four elements
    element 1 is a map of key/value pairs named "keyvaluelist",
    element 2 is a map of key/value pairs named "otherdata",
    element 3 is a string named "anotherthing",
    element 4 is a string named "onelastthing"

The first element or second element could alternatively be described as objects themselves, of course, with three elements each.

Command to find information about CPUs on a UNIX machine

There is no standard Unix command, AFAIK. I haven't used Sun OS, but on Linux, you can use this:

cat /proc/cpuinfo

Sorry that it is Linux, not Sun OS. There is probably something similar though for Sun OS.

How to download Visual Studio Community Edition 2015 (not 2017)

The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203

Is quitting an application frowned upon?

There is a (relatively) simple design which will allow you to get around the "exit" conundrum. Make your app have a "base" state (activity) which is just a blank screen. On the first onCreate of the activity, you can launch another activity that your app's main functionality is in. The "exit" can then be accomplished by finish()ing this second activity and going back to the base of just a blank screen. The OS can keep this blank screen in memory for as long as it wants...

In essence, because you cannot exit out to OS, you simply transform into a self-created nothingness.

Fitting a Normal distribution to 1D data

To see both the normal distribution and your actual data you should plot your data as a histogram, then draw the probability density function over this. See the example on https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.normal.html for exactly how to do this.

Convert nested Python dict to object?

Building off my answer to "python: How to add property to a class dynamically?":

class data(object):
    def __init__(self,*args,**argd):
        self.__dict__.update(dict(*args,**argd))

def makedata(d):
    d2 = {}
    for n in d:
        d2[n] = trydata(d[n])
    return data(d2)

def trydata(o):
    if isinstance(o,dict):
        return makedata(o)
    elif isinstance(o,list):
        return [trydata(i) for i in o]
    else:
        return o

You call makedata on the dictionary you want converted, or maybe trydata depending on what you expect as input, and it spits out a data object.

Notes:

  • You can add elifs to trydata if you need more functionality.
  • Obviously this won't work if you want x.a = {} or similar.
  • If you want a readonly version, use the class data from the original answer.

Image convert to Base64

Function convert image to base64 using jquery (you can convert to vanila js). Hope it help to you!

Usage: input is your nameId input has file image

<input type="file" id="asd"/>
<button onclick="proccessData()">Submit</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

async function converImageToBase64(inputId) {
  let image = $('#'+inputId)[0]['files']

  if (image && image[0]) {
    const reader = new FileReader();

    return new Promise(resolve => {
      reader.onload = ev => {
        resolve(ev.target.result)
      }
      reader.readAsDataURL(image[0])
    })
  }
}

async function proccessData() {
  const image = await converImageToBase64('asd')
  console.log(image)
}

</script>

Example: converImageToBase64('yourFileInputId')

https://codepen.io/mariohandsome/pen/yLadmVb

How are people unit testing with Entity Framework 6, should you bother?

I would not unit test code I don't own. What are you testing here, that the MSFT compiler works?

That said, to make this code testable, you almost HAVE to make your data access layer separate from your business logic code. What I do is take all of my EF stuff and put it in a (or multiple) DAO or DAL class which also has a corresponding interface. Then I write my service which will have the DAO or DAL object injected in as a dependency (constructor injection preferably) referenced as the interface. Now the part that needs to be tested (your code) can easily be tested by mocking out the DAO interface and injecting that into your service instance inside your unit test.

//this is testable just inject a mock of IProductDAO during unit testing
public class ProductService : IProductService
{
    private IProductDAO _productDAO;

    public ProductService(IProductDAO productDAO)
    {
        _productDAO = productDAO;
    }

    public List<Product> GetAllProducts()
    {
        return _productDAO.GetAll();
    }

    ...
}

I would consider live Data Access Layers to be part of integration testing, not unit testing. I have seen guys run verifications on how many trips to the database hibernate makes before, but they were on a project that involved billions of records in their datastore and those extra trips really mattered.

proper name for python * operator?

For a colloquial name there is "splatting".

For arguments (list type) you use single * and for keyword arguments (dictionary type) you use double **.

Both * and ** is sometimes referred to as "splatting".

See for reference of this name being used: https://stackoverflow.com/a/47875892/14305096

How to submit a form on enter when the textarea has focus?

Why do you want a textarea to submit when you hit enter?

A "text" input will submit by default when you press enter. It is a single line input.

<input type="text" value="...">

A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.

<textarea name="area"></textarea>

You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.

Extracting first n columns of a numpy matrix

I know this is quite an old question -

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

How to change Format of a Cell to Text using VBA

To answer your direct question, it is:

Range("A1").NumberFormat = "@"

Or

Cells(1,1).NumberFormat = "@"

However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.

Change the value in app.config file dynamically

It works, just look at the bin/Debug folder, you are probably looking at app.config file inside project.

Add numpy array as column to Pandas data frame

import numpy as np
import pandas as pd
import scipy.sparse as sparse

df = pd.DataFrame(np.arange(1,10).reshape(3,3))
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['newcol'] = arr.toarray().tolist()
print(df)

yields

   0  1  2     newcol
0  1  2  3  [0, 1, 0]
1  4  5  6  [0, 0, 1]
2  7  8  9  [1, 0, 0]

Adding gif image in an ImageView in android

import android.app.Activity;
import android.util.Log;
import android.widget.ImageView;

/**
 * Created by atiq.mumtaz on 25.04.2016.
 */
public class GifImage_Player extends Thread
{
    Activity activity;
    ImageView image_view;
    boolean is_running=false;
    int pause_time;
    int[] drawables;

    public GifImage_Player(Activity activity,ImageView img_view,int[] drawable)
    {
        this.activity=activity;
        this.image_view=img_view;
        this.is_running=true;
        pause_time=25;
        this.drawables=drawable;
    }

    public void set_pause_time(int interval)
    {
        this.pause_time=interval;
    }
    public void stop_playing()
    {
        this.is_running=false;
    }

    public void run()
    {
        Log.d("Gif Player","Gif Player Stopped");

        int pointer=0;
        while (this.is_running)
        {
           if(drawables.length>0)
           {
             if((drawables.length-1)==pointer)
             {
                 pointer=0;
             }


               try
               {
                   activity.runOnUiThread(new Run(pointer));
                   Thread.sleep(pause_time);
               }
               catch (Exception e)
               {
                   Log.d("GifPlayer","Exception: "+e.getMessage());
                   is_running=false;
               }
               pointer++;
           }
        }
        Log.d("Gif Player","Gif Player Stopped");
    }

    class Run implements Runnable
    {
        int pointer;
        public Run(int pointer)
        {
            this.pointer=pointer;
        }
        public void run()
       {
           image_view.setImageResource(drawables[pointer]);
       }
    }
}

/////////////////////////////Usage///////////////////////////////////////




  int[] int_array=new int[]{R.drawable.tmp_0,R.drawable.tmp_1,R.drawable.tmp_2,R.drawable.tmp_3
               ,R.drawable.tmp_4,R.drawable.tmp_5,R.drawable.tmp_6,R.drawable.tmp_7,R.drawable.tmp_8,R.drawable.tmp_9,
                    R.drawable.tmp_10,R.drawable.tmp_11,R.drawable.tmp_12,R.drawable.tmp_13,R.drawable.tmp_14,R.drawable.tmp_15,
                    R.drawable.tmp_16,R.drawable.tmp_17,R.drawable.tmp_18,R.drawable.tmp_19,R.drawable.tmp_20,R.drawable.tmp_21,R.drawable.tmp_22,R.drawable.tmp_23};

GifImage_Player gif_player;             
gif_player=new GifImage_Player(this,(ImageView)findViewById(R.id.mygif),int_array);
            gif_player.start();

Refresh a page using PHP

Adding this meta tag in PHP might help:

echo '<META HTTP-EQUIV="Refresh" Content="0; URL=' . $location . '">';

Difference between Divide and Conquer Algo and Dynamic Programming

Divide and Conquer

  • In this problem is solved in following three steps: 1. Divide - Dividing into number of sub-problems 2. Conquer - Conquering by solving sub-problems recursively 3. Combine - Combining sub-problem solutions to get original problem's solution
  • Recursive approach
  • Top Down technique
  • Example: Merge Sort

Dynamic Programming

  • In this the problem is solved in following steps: 1. Defining structure of optimal solution 2. Defines value of optimal solutions repeatedly. 3. Obtaining values of optimal solution in bottom-up fashion 4. Getting final optimal solution from obtained values
  • Non-Recursive
  • Bottom Up Technique
  • Example: Strassen's Matrix Multiplication

What is the use of the %n format specifier in C?

Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

#include <stdio.h>

int main()
{
  int val;

  printf("blah %n blah\n", &val);

  printf("val = %d\n", val);

  return 0;

}

The previous code prints:

blah  blah
val = 5

High-precision clock in Python

def start(self):
    sec_arg = 10.0
    cptr = 0
    time_start = time.time()
    time_init = time.time()
    while True:
        cptr += 1
        time_start = time.time()
        time.sleep(((time_init + (sec_arg * cptr)) - time_start ))

        # AND YOUR CODE .......
        t00 = threading.Thread(name='thread_request', target=self.send_request, args=([]))
        t00.start()

What is the idiomatic Go equivalent of C's ternary operator?

As pointed out (and hopefully unsurprisingly), using if+else is indeed the idiomatic way to do conditionals in Go.

In addition to the full blown var+if+else block of code, though, this spelling is also used often:

index := val
if val <= 0 {
    index = -val
}

and if you have a block of code that is repetitive enough, such as the equivalent of int value = a <= b ? a : b, you can create a function to hold it:

func min(a, b int) int {
    if a <= b {
        return a
    }
    return b
}

...

value := min(a, b)

The compiler will inline such simple functions, so it's fast, more clear, and shorter.

What is the difference between a database and a data warehouse?

Example: A house is worth $100,000, and it is appreciating at $1000 per year.

To keep track of the current house value, you would use a database as the value would change every year.

Three years later, you would be able to see the value of the house which is $103,000.

To keep track of the historical house value, you would use a data warehouse as the value of the house should be

$100,000 on year 0, 
$101,000 on year 1, 
$102,000 on year 2, 
$103,000 on year 3. 

X11/Xlib.h not found in Ubuntu

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

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

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

How do you Change a Package's Log Level using Log4j?

set the system property log4j.debug=true. Then you can determine where your configuration is running amuck.

Convert a Python list with strings all to lowercase or uppercase

>>> map(str.lower,["A","B","C"])
['a', 'b', 'c']

Exit a while loop in VBS/VBA

VBScript's While loops don't support early exit. Use the Do loop for that:

num = 0
do while (num < 10)
  if (status = "Fail") then exit do
  num = num + 1
loop

How do I grab an INI value within a shell script?

The answer of "Karen Gabrielyan" among another answers was the best but in some environments we dont have awk, like typical busybox, i changed the answer by below code.

trim()
{
    local trimmed="$1"

    # Strip leading space.
    trimmed="${trimmed## }"
    # Strip trailing space.
    trimmed="${trimmed%% }"

    echo "$trimmed"
}


  function parseIniFile() { #accepts the name of the file to parse as argument ($1)
        #declare syntax below (-gA) only works with bash 4.2 and higher
        unset g_iniProperties
        declare -gA g_iniProperties
        currentSection=""
        while read -r line
        do
            if [[ $line = [*  ]] ; then
                if [[ $line = [* ]] ; then 
                    currentSection=$(echo $line | sed -e 's/\r//g' | tr -d "[]")  
                fi
            else
                if [[ $line = *=*  ]] ; then
                    cleanLine=$(echo $line | sed -e 's/\r//g')
                    key=$(trim $currentSection.$(echo $cleanLine | cut -d'=' -f1'))
                    value=$(trim $(echo $cleanLine | cut -d'=' -f2))
                    g_iniProperties[$key]=$value
                fi
            fi;
        done < $1
    }

Multiple conditions in ngClass - Angular 4

<section [ngClass]="{'class1': expression1, 'class2': expression2, 
'class3': expression3}">

Don't forget to add single quotes around class names.

Changing java platform on which netbeans runs

on Fedora it is currently impossible to set a new jdk-HOME to some sdk. They designed it such that it will always break. Try --jdkhome [whatever] but in all likelihood it will break and show some cryptic nonsensical error message as usual.

What does the question mark and the colon (?: ternary operator) mean in objective-c?

It's the ternary or conditional operator. It's basic form is:

condition ? valueIfTrue : valueIfFalse

Where the values will only be evaluated if they are chosen.

HTML5 Video Autoplay not working correctly

Try autoplay="autoplay" instead of the "true" value. That's the documented way to enable autoplay. That sounds weirdly redundant, I know.

Does "git fetch --tags" include "git fetch"?

The general problem here is that git fetch will fetch +refs/heads/*:refs/remotes/$remote/*. If any of these commits have tags, those tags will also be fetched. However if there are tags not reachable by any branch on the remote, they will not be fetched.

The --tags option switches the refspec to +refs/tags/*:refs/tags/*. You could ask git fetch to grab both. I'm pretty sure to just do a git fetch && git fetch -t you'd use the following command:

git fetch origin "+refs/heads/*:refs/remotes/origin/*" "+refs/tags/*:refs/tags/*"

And if you wanted to make this the default for this repo, you can add a second refspec to the default fetch:

git config --local --add remote.origin.fetch "+refs/tags/*:refs/tags/*"

This will add a second fetch = line in the .git/config for this remote.


I spent a while looking for the way to handle this for a project. This is what I came up with.

git fetch -fup origin "+refs/*:refs/*"

In my case I wanted these features

  • Grab all heads and tags from the remote so use refspec refs/*:refs/*
  • Overwrite local branches and tags with non-fast-forward + before the refspec
  • Overwrite currently checked out branch if needed -u
  • Delete branches and tags not present in remote -p
  • And force to be sure -f

sorting integers in order lowest to highest java

For sorting narrow range of integers try Counting sort, which has a complexity of O(range + n), where n is number of items to be sorted. If you'd like to sort something not discrete use optimal n*log(n) algorithms (quicksort, heapsort, mergesort). Merge sort is also used in a method already mentioned by other responses Arrays.sort. There is no simple way how to recommend some algorithm or function call, because there are dozens of special cases, where you would use some sort, but not the other.

So please specify the exact purpose of your application (to learn something (well - start with the insertion sort or bubble sort), effectivity for integers (use counting sort), effectivity and reusability for structures (use n*log(n) algorithms), or zou just want it to be somehow sorted - use Arrays.sort :-)). If you'd like to sort string representations of integers, than u might be interrested in radix sort....

How to upload folders on GitHub

You can also use the command line, Change directory where your folder is located then type the following :

     git init
     git add <folder1> <folder2> <etc.>
     git commit -m "Your message about the commit"
     git remote add origin https://github.com/yourUsername/yourRepository.git
     git push -u origin master
     git push origin master  

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

Please confirm that your firewall is allowing outbound traffic and that you are not being blocked by antivirus software.

I received the same issue and the culprit was antivirus software.

Java : Convert formatted xml file to one line string

// 1. Read xml from file to StringBuilder (StringBuffer)
// 2. call s = stringBuffer.toString()
// 3. remove all "\n" and "\t": 
s.replaceAll("\n",""); 
s.replaceAll("\t","");

edited:

I made a small mistake, it is better to use StringBuilder in your case (I suppose you don't need thread-safe StringBuffer)

Delete all data rows from an Excel table (apart from the first)

The codes above wouldn't work in Excel 2010 My code bellow allows you to go through number of sheets you would like then select tables and delete rows

Sub DeleteTableRows()
Dim table As ListObject
Dim SelectedCell As Range
Dim TableName As String
Dim ActiveTable As ListObject

'select ammount of sheets want to this to run
For i = 1 To 3
    Sheets(i).Select
    Range("A1").Select
    Set SelectedCell = ActiveCell
    Selection.AutoFilter

    'Determine if ActiveCell is inside a Table
    On Error GoTo NoTableSelected
    TableName = SelectedCell.ListObject.Name
    Set ActiveTable = ActiveSheet.ListObjects(TableName)
    On Error GoTo 0

    'Clear first Row
    ActiveTable.DataBodyRange.Rows(1).ClearContents
    'Delete all the other rows `IF `they exist
    On Error Resume Next
    ActiveTable.DataBodyRange.Offset(1, 0).Resize(ActiveTable.DataBodyRange.Rows.Count - 1, _
    ActiveTable.DataBodyRange.Columns.Count).Rows.Delete
    Selection.AutoFilter
    On Error GoTo 0
Next i
Exit Sub
'Error Handling
NoTableSelected:
  MsgBox "There is no Table currently selected!", vbCritical

End Sub

Uninstalling an MSI file from the command line without using msiexec

Also remember that an uninstall can be initiated using the WMIC command:

wmic product get name --> This will list the names of all installed apps

wmic product where name='myappsname' call uninstall --> this will uninstall the app.

Resize image proportionally with MaxHeight and MaxWidth constraints

Like this?

public static void Test()
{
    using (var image = Image.FromFile(@"c:\logo.png"))
    using (var newImage = ScaleImage(image, 300, 400))
    {
        newImage.Save(@"c:\test.png", ImageFormat.Png);
    }
}

public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);

    using (var graphics = Graphics.FromImage(newImage))
        graphics.DrawImage(image, 0, 0, newWidth, newHeight);

    return newImage;
}

Edit seaborn legend

Took me a while to read through the above. This was the answer for me:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=False
)

plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)

Reference this for more arguments: matplotlib.pyplot.legend

enter image description here

What does the variable $this mean in PHP?

The best way to learn about the $this variable in PHP is to try it against the interpreter in various contexts:

print isset($this);              //true,   $this exists
print gettype($this);            //Object, $this is an object 
print is_array($this);           //false,  $this isn't an array
print get_object_vars($this);    //true,   $this's variables are an array
print is_object($this);          //true,   $this is still an object
print get_class($this);          //YourProject\YourFile\YourClass
print get_parent_class($this);   //YourBundle\YourStuff\YourParentClass
print gettype($this->container); //object
print_r($this);                  //delicious data dump of $this
print $this->yourvariable        //access $this variable with ->

So the $this pseudo-variable has the Current Object's method's and properties. Such a thing is useful because it lets you access all member variables and member methods inside the class. For example:

Class Dog{
    public $my_member_variable;                             //member variable

    function normal_method_inside_Dog() {                   //member method

        //Assign data to member variable from inside the member method
        $this->my_member_variable = "whatever";

        //Get data from member variable from inside the member method.
        print $this->my_member_variable;
    }
}

$this is reference to a PHP Object that was created by the interpreter for you, that contains an array of variables.

If you call $this inside a normal method in a normal class, $this returns the Object (the class) to which that method belongs.

It's possible for $this to be undefined if the context has no parent Object.

php.net has a big page talking about PHP object oriented programming and how $this behaves depending on context. https://www.php.net/manual/en/language.oop5.basic.php

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

There's no "simple command" to do that. You can write a function, or take your choice of several that are available online in various code repositories. I use this:

function get-loggedonuser ($computername){

#mjolinor 3/17/10

$regexa = '.+Domain="(.+)",Name="(.+)"$'
$regexd = '.+LogonId="(\d+)"$'

$logontype = @{
"0"="Local System"
"2"="Interactive" #(Local logon)
"3"="Network" # (Remote logon)
"4"="Batch" # (Scheduled task)
"5"="Service" # (Service account logon)
"7"="Unlock" #(Screen saver)
"8"="NetworkCleartext" # (Cleartext network logon)
"9"="NewCredentials" #(RunAs using alternate credentials)
"10"="RemoteInteractive" #(RDP\TS\RemoteAssistance)
"11"="CachedInteractive" #(Local w\cached credentials)
}

$logon_sessions = @(gwmi win32_logonsession -ComputerName $computername)
$logon_users = @(gwmi win32_loggedonuser -ComputerName $computername)

$session_user = @{}

$logon_users |% {
$_.antecedent -match $regexa > $nul
$username = $matches[1] + "\" + $matches[2]
$_.dependent -match $regexd > $nul
$session = $matches[1]
$session_user[$session] += $username
}


$logon_sessions |%{
$starttime = [management.managementdatetimeconverter]::todatetime($_.starttime)

$loggedonuser = New-Object -TypeName psobject
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Session" -Value $_.logonid
$loggedonuser | Add-Member -MemberType NoteProperty -Name "User" -Value $session_user[$_.logonid]
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Type" -Value $logontype[$_.logontype.tostring()]
$loggedonuser | Add-Member -MemberType NoteProperty -Name "Auth" -Value $_.authenticationpackage
$loggedonuser | Add-Member -MemberType NoteProperty -Name "StartTime" -Value $starttime

$loggedonuser
}

}

How to permanently add a private key with ssh-add on Ubuntu?

I tried @Aaron's solution and it didn't quite work for me, because it would re-add my keys every time I opened a new tab in my terminal. So I modified it a bit(note that most of my keys are also password-protected so I can't just send the output to /dev/null):

added_keys=`ssh-add -l`

if [ ! $(echo $added_keys | grep -o -e my_key) ]; then
    ssh-add "$HOME/.ssh/my_key"
fi

What this does is that it checks the output of ssh-add -l(which lists all keys that have been added) for a specific key and if it doesn't find it, then it adds it with ssh-add.

Now the first time I open my terminal I'm asked for the passwords for my private keys and I'm not asked again until I reboot(or logout - I haven't checked) my computer.

Since I have a bunch of keys I store the output of ssh-add -l in a variable to improve performance(at least I guess it improves performance :) )

PS: I'm on linux and this code went to my ~/.bashrc file - if you are on Mac OS X, then I assume you should add it to .zshrc or .profile

EDIT: As pointed out by @Aaron in the comments, the .zshrc file is used from the zsh shell - so if you're not using that(if you're not sure, then most likely, you're using bash instead), this code should go to your .bashrc file.

Find maximum value of a column and return the corresponding row values using Pandas

I'd recommend using nlargest for better performance and shorter code. import pandas

df[col_name].value_counts().nlargest(n=1)

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Same-origin policy

You can't access an <iframe> with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.

Origin is considered different if at least one of the following parts of the address isn't maintained:

protocol://hostname:port/...

Protocol, hostname and port must be the same of your domain if you want to access a frame.

NOTE: Internet Explorer is known to not strictly follow this rule, see here for details.

Examples

Here's what would happen trying to access the following URLs from http://www.example.com/home/index.html

URL                                             RESULT 
http://www.example.com/home/other.html       -> Success 
http://www.example.com/dir/inner/another.php -> Success 
http://www.example.com:80                    -> Success (default port for HTTP) 
http://www.example.com:2251                  -> Failure: different port 
http://data.example.com/dir/other.html       -> Failure: different hostname 
https://www.example.com/home/index.html:80   -> Failure: different protocol
ftp://www.example.com:21                     -> Failure: different protocol & port 
https://google.com/search?q=james+bond       -> Failure: different protocol, port & hostname 

Workaround

Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, if you own both the pages, you can work around this problem using window.postMessage and its relative message event to send messages between the two pages, like this:

  • In your main page:

    const frame = document.getElementById('your-frame-id');
    frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');
    

    The second argument to postMessage() can be '*' to indicate no preference about the origin of the destination. A target origin should always be provided when possible, to avoid disclosing the data you send to any other site.

  • In your <iframe> (contained in the main page):

    window.addEventListener('message', event => {
        // IMPORTANT: check the origin of the data! 
        if (event.origin.startsWith('http://your-first-site.com')) { 
            // The data was sent from your site.
            // Data sent with postMessage is stored in event.data:
            console.log(event.data); 
        } else {
            // The data was NOT sent from your site! 
            // Be careful! Do not use it. This else branch is
            // here just for clarity, you usually shouldn't need it.
            return; 
        } 
    }); 
    

This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.

Disabling same-origin policy in your browser

There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should NEVER be done if you do not know exactly what you are doing (e.g. development purposes).

Only using @JsonIgnore during serialization, but not deserialization

Exactly how to do this depends on the version of Jackson that you're using. This changed around version 1.9, before that, you could do this by adding @JsonIgnore to the getter.

Which you've tried:

Add @JsonIgnore on the getter method only

Do this, and also add a specific @JsonProperty annotation for your JSON "password" field name to the setter method for the password on your object.

More recent versions of Jackson have added READ_ONLY and WRITE_ONLY annotation arguments for JsonProperty. So you could also do something like:

@JsonProperty(access = Access.WRITE_ONLY)
private String password;

Docs can be found here.

How to identify server IP address in PHP

If you are using PHP version 5.3 or higher you can do the following:

$host= gethostname();
$ip = gethostbyname($host);

This works well when you are running a stand-alone script, not running through the web server.

How can I pass a parameter to a t-sql script?

Two options save vijay.sql

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

and then run as sqlplus -s username/password @vijay.sql '20100101'

If statements for Checkboxes

I suggest

if (checkbox.IsChecked == true)
{
    //do something
}

Hope it's helpful ^^

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

trigger('submit') does not work.beacuse onSubmit method does not get fired. the following code works for me, call onSubmit method when using this code :

$("form").find(':submit').click();

Drawable image on a canvas

Drawable d = ContextCompat.getDrawable(context, R.drawable.***)
d.setBounds(left, top, right, bottom);
d.draw(canvas);

Useful example of a shutdown hook in Java?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

implement time delay in c

For short delays (say, some microseconds) on Linux OS, you can use "usleep":

// C Program to perform short delays
#include <unistd.h>
#include <stdio.h>

int main(){
    printf("Hello!\n");
    usleep(1000000); // For a 1-second delay
    printf("Bye!\n);
    return 0;

How to delete specific rows and columns from a matrix in a smarter way?

> S = matrix(c(1,2,3,4,5,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,5,4,3,2,1),ncol = 5,byrow = TRUE);S
[,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    2    1    2    3    4
[3,]    3    2    1    2    3
[4,]    4    3    2    1    2
[5,]    5    4    3    2    1
> S<-S[,-2]
> S
[,1] [,2] [,3] [,4]
[1,]    1    3    4    5
[2,]    2    2    3    4
[3,]    3    1    2    3
[4,]    4    2    1    2
[5,]    5    3    2    1

Just use the command S <- S[,-2] to remove the second column. Similarly to delete a row, for example, to delete the second row use S <- S[-2,].

Adding :default => true to boolean in existing Rails column

change_column :things, :price_1, :integer, default: 123, null: false

Seems to be best way to add a default to an existing column that doesn't have null: false already.

Otherwise:

change_column :things, :price_1, :integer, default: 123

Some research I did on this:

https://gist.github.com/Dorian/417b9a0e1a4e09a558c39345d50c8c3b

How can I know if a branch has been already merged into master?

Here is a little one-liner that will let you know if your current branch incorporates or is out of data from a remote origin/master branch:

$ git fetch && git branch -r --merged | grep -q origin/master && echo Incorporates origin/master || echo Out of date from origin/master

I came across this question when working on a feature branch and frequently wanting to make sure that I have the most recent work incorporated into my own separate working branch.

To generalize this test I have added the following alias to my ~/.gitconfig:

[alias]
   current = !git branch -r --merged | grep -q $1 && echo Incorporates $1 || echo Out of date from $1 && :

Then I can call:

$ git current origin/master

to check if I am current.

How to flush output after each `echo` call?

I'm late to the discussion but I read that many people are saying appending flush(); at the end of each code looks dirty, and they are right.

Best solution is to disable deflate, gzip and all buffering from Apache, intermediate handlers and PHP. Then in your php.ini you should have:

            output_buffering = Off
            zlib.output_compression = Off
            implicit_flush = Off

Temporary solution is to have this in your php.ini IF you can solve your problem with flush(); but you think it is dirty and ugly to put it everywhere.

implicit_flush = On

If you only put it above in your php.ini, you don't need to put flush(); in your code anymore.

How to Correctly Use Lists in R?

Just to address the last part of your question, since that really points out the difference between a list and vector in R:

Why do these two expressions not return the same result?

x = list(1, 2, 3, 4); x2 = list(1:4)

A list can contain any other class as each element. So you can have a list where the first element is a character vector, the second is a data frame, etc. In this case, you have created two different lists. x has four vectors, each of length 1. x2 has 1 vector of length 4:

> length(x[[1]])
[1] 1
> length(x2[[1]])
[1] 4

So these are completely different lists.

R lists are very much like a hash map data structure in that each index value can be associated with any object. Here's a simple example of a list that contains 3 different classes (including a function):

> complicated.list <- list("a"=1:4, "b"=1:3, "c"=matrix(1:4, nrow=2), "d"=search)
> lapply(complicated.list, class)
$a
[1] "integer"
$b
[1] "integer"
$c
[1] "matrix"
$d
[1] "function"

Given that the last element is the search function, I can call it like so:

> complicated.list[["d"]]()
[1] ".GlobalEnv" ...

As a final comment on this: it should be noted that a data.frame is really a list (from the data.frame documentation):

A data frame is a list of variables of the same number of rows with unique row names, given class ‘"data.frame"’

That's why columns in a data.frame can have different data types, while columns in a matrix cannot. As an example, here I try to create a matrix with numbers and characters:

> a <- 1:4
> class(a)
[1] "integer"
> b <- c("a","b","c","d")
> d <- cbind(a, b)
> d
 a   b  
[1,] "1" "a"
[2,] "2" "b"
[3,] "3" "c"
[4,] "4" "d"
> class(d[,1])
[1] "character"

Note how I cannot change the data type in the first column to numeric because the second column has characters:

> d[,1] <- as.numeric(d[,1])
> class(d[,1])
[1] "character"

Counting unique / distinct values by group in a data frame

A data.table approach

library(data.table)
DT <- data.table(myvec)

DT[, .(number_of_distinct_orders = length(unique(order_no))), by = name]

data.table v >= 1.9.5 has a built in uniqueN function now

DT[, .(number_of_distinct_orders = uniqueN(order_no)), by = name]

How to use SearchView in Toolbar Android

If you want to add it directly in the toolbar.

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

    <android.support.v7.widget.Toolbar
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:iconifiedByDefault="false"
            android:queryHint="Search"
            android:layout_centerHorizontal="true" />

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

How can I pretty-print JSON in a shell script?

bat is a cat clone with syntax highlighting:

Example:

echo '{"bignum":1e1000}' | bat -p -l json

-p will output without headers, and -l will explicitly specify the language.

It has colouring and formatting for JSON and does not have the problems noted in this comment: How can I pretty-print JSON in a shell script?

how to include js file in php?

I have never been a fan of closing blocks of PHP to output content to the browser, I prefer to have my output captured so if at some point within my logic I decide I want to change my output (after output has already been sent) I can just delete the current buffer.

But as Pekka said, the main reason you are having issues with your javascript inclusion is because your using href to specify the location of the js file where as you should be using src.

If you have a functions file with your functions inside then add something like:

function js_link($src)
{
    if(file_exists("my/html/root/" . $src))
    {
        //we know it will exists within the HTTP Context
        return sprintf("<script type=\"text/javascript\" src=\"%s\"></script>",$src);
    }
    return "<!-- Unable to load " . $src . "-->";
}

The n in your code without the need for closing your blocks with ?> you can just use:

echo js_link("jquery/1.6/main.js");

How can I use an array of function pointers?

The above answers may help you but you may also want to know how to use array of function pointers.

void fun1()
{

}

void fun2()
{

}

void fun3()
{

}

void (*func_ptr[3])() = {fun1, fun2, fun3};

main()
{
    int option;


    printf("\nEnter function number you want");
    printf("\nYou should not enter other than 0 , 1, 2"); /* because we have only 3 functions */
    scanf("%d",&option);

    if((option>=0)&&(option<=2))
    { 
        (*func_ptr[option])();
    }

    return 0;
}

You can only assign the addresses of functions with the same return type and same argument types and no of arguments to a single function pointer array.

You can also pass arguments like below if all the above functions are having the same number of arguments of same type.

  (*func_ptr[option])(argu1);

Note: here in the array the numbering of the function pointers will be starting from 0 same as in general arrays. So in above example fun1 can be called if option=0, fun2 can be called if option=1 and fun3 can be called if option=2.

Android Imagebutton change Image OnClick

It is very simple

public void onClick(View v) {

        imgButton.setImageResource(R.drawable.ic_launcher);

    }

Using set Background image resource will chanage the background of the button

Copy Data from a table in one Database to another separate database

Don't forget to insert SET IDENTITY_INSERT MobileApplication1 ON to the top, else you will get an error. This is for SQL Server

SET IDENTITY_INSERT MOB.MobileApplication1 ON
INSERT INTO [SERVER1].DB.MOB.MobileApplication1 m
      (m.MobileApplicationDetailId,
       m.MobilePlatformId)
SELECT ma.MobileApplicationId,
       ma.MobilePlatformId 
FROM [SERVER2].DB.MOB.MobileApplication2 ma

When should a class be Comparable and/or Comparator?

Difference between Comparator and Comparable interfaces

Comparable is used to compare itself by using with another object.

Comparator is used to compare two datatypes are objects.

How to convert a string to lower or upper case in Ruby

Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase:

"hello James!".downcase    #=> "hello james!"

Similarly, upcase capitalizes every letter and capitalize capitalizes the first letter of the string but lowercases the rest:

"hello James!".upcase      #=> "HELLO JAMES!"
"hello James!".capitalize  #=> "Hello james!"
"hello James!".titleize    #=> "Hello James!"

If you want to modify a string in place, you can add an exclamation point to any of those methods:

string = "hello James!"
string.downcase!
string   #=> "hello james!"

Refer to the documentation for String for more information.

How to hide command output in Bash

Use this.

{
  /your/first/command
  /your/second/command
} &> /dev/null

Explanation

To eliminate output from commands, you have two options:

  • Close the output descriptor file, which keeps it from accepting any more input. That looks like this:

    your_command "Is anybody listening?" >&-
    

    Usually, output goes either to file descriptor 1 (stdout) or 2 (stderr). If you close a file descriptor, you'll have to do so for every numbered descriptor, as &> (below) is a special BASH syntax incompatible with >&-:

    /your/first/command >&- 2>&-
    

    Be careful to note the order: >&- closes stdout, which is what you want to do; &>- redirects stdout and stderr to a file named - (hyphen), which is not what what you want to do. It'll look the same at first, but the latter creates a stray file in your working directory. It's easy to remember: >&2 redirects stdout to descriptor 2 (stderr), >&3 redirects stdout to descriptor 3, and >&- redirects stdout to a dead end (i.e. it closes stdout).

    Also beware that some commands may not handle a closed file descriptor particularly well ("write error: Bad file descriptor"), which is why the better solution may be to...

  • Redirect output to /dev/null, which accepts all output and does nothing with it. It looks like this:

    your_command "Hello?" > /dev/null
    

    For output redirection to a file, you can direct both stdout and stderr to the same place very concisely, but only in bash:

    /your/first/command &> /dev/null
    

Finally, to do the same for a number of commands at once, surround the whole thing in curly braces. Bash treats this as a group of commands, aggregating the output file descriptors so you can redirect all at once. If you're familiar instead with subshells using ( command1; command2; ) syntax, you'll find the braces behave almost exactly the same way, except that unless you involve them in a pipe the braces will not create a subshell and thus will allow you to set variables inside.

{
  /your/first/command
  /your/second/command
} &> /dev/null

See the bash manual on redirections for more details, options, and syntax.

Developing for Android in Eclipse: R.java not regenerating

You can try one more thing.

Go to C:\Program Files (x86)\Android\android-sdk\tools>, run adb kill-server and then adb start-server. This worked for me, and I do not know the reason :-).

Android webview slow

I think the following works best:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

Android 19 has Chromium engine for WebView. I guess it works better with hardware acceleration.

What do we mean by Byte array?

I assume you know what a byte is. A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

Just as bytes can encode different types and ranges of data (numbers from 0 to 255, numbers from -128 to 127, single characters using ASCII e.g. 'a' or '%', CPU op-codes), each byte in a byte array may be any of these things, or contribute to some multi-byte values such as numbers with larger range (e.g. 16-bit unsigned int from 0..65535), international character sets, textual strings ("hello"), or part/all of a compiled computer programs.

The crucial thing about a byte array is that it gives indexed (fast), precise, raw access to each 8-bit value being stored in that part of memory, and you can operate on those bytes to control every single bit. The bad thing is the computer just treats every entry as an independent 8-bit number - which may be what your program is dealing with, or you may prefer some powerful data-type such as a string that keeps track of its own length and grows as necessary, or a floating point number that lets you store say 3.14 without thinking about the bit-wise representation. As a data type, it is inefficient to insert or remove data near the start of a long array, as all the subsequent elements need to be shuffled to make or fill the gap created/required.

MySQL - Trigger for updating same table after insert

This is how I update a row in the same table on insert

activationCode and email are rows in the table USER. On insert I don't specify a value for activationCode, it will be created on the fly by MySQL.

Change username with your MySQL username and db_name with your db name.

CREATE DEFINER=`username`@`localhost` 
       TRIGGER `db_name`.`user_BEFORE_INSERT` 
       BEFORE INSERT ON `user` 
       FOR EACH ROW
         BEGIN
            SET new.activationCode = MD5(new.email);
         END

How to restrict UITextField to take only numbers in Swift?

Swift 3

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField==yourTextFieldOutlet {
                if(CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: yourTextFieldOutlet.text!))){
//if numbers only, then your code here
                }
                else{
                showAlert(title: "Error",message: "Enter Number only",type: "failure")
                }
            }
    return true
    }

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

C++, What does the colon after a constructor mean?

It means that len is not set using the default constructor. while the demo class is being constructed. For instance:

class Demo{
    int foo;
public:
    Demo(){ foo = 1;}
};

Would first place a value in foo before setting it to 1. It's slightly faster and more efficient.

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

How to fix broken paste clipboard in VNC on Windows

You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.

How to retrieve absolute path given relative

You could use bash string substitution for any relative path $line:

line=$(echo ${line/#..\//`cd ..; pwd`\/})
line=$(echo ${line/#.\//`pwd`\/})
echo $line

The basic front-of-string substitution follows the formula
${string/#substring/replacement}
which is discussed well here: https://www.tldp.org/LDP/abs/html/string-manipulation.html

The \ character negates the / when we want it to be part of the string that we find/replace.

Android: Flush DNS

copied from: https://android.stackexchange.com/questions/12962/flush-clear-dns-cache

Addresses are cached for 600 seconds (10 minutes) by default. Failed lookups are cached for 10 seconds. From everything I've seen, there's nothing built in to flush the cache. This is apparently a reported bug http://code.google.com/p/android/issues/detail?id=7904 in Android because of the way it stores DNS cache. Clearing the browser cache doesn't touch the DNS, the "hard reset" clears it.

What does the "undefined reference to varName" in C mean?

You're getting a linker error, so your extern is working (the compiler compiled a.c without a problem), but when it went to link the object files together at the end it couldn't resolve your extern -- void doSomething(int); wasn't actually found anywhere. Did you mess up the extern? Make sure there's actually a doSomething defined in b.c that takes an int and returns void, and make sure you remembered to include b.c in your file list (i.e. you're doing something like gcc a.c b.c, not just gcc a.c)

Fastest way to convert a dict's keys & values from `unicode` to `str`?

Just use print(*(dict.keys()))

The * can be used for unpacking containers e.g. lists. For more info on * check this SO answer.

How to set the background image of a html 5 canvas to .png image

You can use this plugin, but for printing purpose i have added some code like <button onclick="window.print();">Print</button> and for saving image <button onclick="savePhoto();">Save Picture</button>

     function savePhoto() {
     var canvas = document.getElementById("canvas");
     var img    = canvas.toDataURL("image/png");
     window.location = img;}

checkout this plugin http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app

How to remove last n characters from every element in the R vector

The same may be achieved with the stringi package:

library('stringi')
char_array <- c("foo_bar","bar_foo","apple","beer")
a <- data.frame("data"=char_array, "data2"=1:4)
(a$data <- stri_sub(a$data, 1, -4)) # from the first to the last but 4th char
## [1] "foo_" "bar_" "ap"   "b" 

Add custom message to thrown exception while maintaining stack trace in Java

There is an Exception constructor that takes also the cause argument: Exception(String message, Throwable t).

You can use it to propagate the stacktrace:

try{
    //...
}catch(Exception E){
    if(!transNbr.equals("")){
        throw new Exception("transaction: " + transNbr, E); 
    }
    //...
}