Programs & Examples On #Readability

Readability is a subjective parameter used to measure an aspect of code quality. It is based on the assumption that code should be easily comprehensible by humans, both in its form and in its meaning.

How to find good looking font color if background color is known?

Similar to @Aaron Digulla's suggestion except that I would suggest a graphics design tool, select the base color, in your case the background color, then adjust the Hue, Saturation and Value. Using this you can create color swatches very easily. Paint.Net is free and I use it all the time for this and also the pay-for-tools will also do this.

Simple way to copy or clone a DataRow?

You can use ImportRow method to copy Row from DataTable to DataTable with the same schema:

var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);

Update:

With your new Edit, I believe:

var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];

will work

Android Studio: Can't start Git

For the one using mac who installed Xcode7, you have to start Xcode and accept the license agreement for the android studio error to go away.

How do I add a newline to a windows-forms TextBox?

Have you tried something like:

textbox.text = "text" & system.environment.newline & "some more text"

How many concurrent requests does a single Flask process receive?

Flask will process one request per thread at the same time. If you have 2 processes with 4 threads each, that's 8 concurrent requests.

Flask doesn't spawn or manage threads or processes. That's the responsability of the WSGI gateway (eg. gunicorn).

Disable mouse scroll wheel zoom on embedded Google Maps

I extended @nathanielperales solution.

Below the behavior description:

  • click the map to enable scroll
  • when mouse leaves the map, disable scroll

Below the javascript code:

// Disable scroll zooming and bind back the click event
var onMapMouseleaveHandler = function (event) {
  var that = $(this);

  that.on('click', onMapClickHandler);
  that.off('mouseleave', onMapMouseleaveHandler);
  that.find('iframe').css("pointer-events", "none");
}

var onMapClickHandler = function (event) {
  var that = $(this);

  // Disable the click handler until the user leaves the map area
  that.off('click', onMapClickHandler);

  // Enable scrolling zoom
  that.find('iframe').css("pointer-events", "auto");

  // Handle the mouse leave event
  that.on('mouseleave', onMapMouseleaveHandler);
}

// Enable map zooming with mouse scroll when the user clicks the map
$('.maps.embed-container').on('click', onMapClickHandler);

And here is an jsFiddle example.

Stack, Static, and Heap in C++

What if your program does not know upfront how much memory to allocate (hence you cannot use stack variables). Say linked lists, the lists can grow without knowing upfront what is its size. So allocating on a heap makes sense for a linked list when you are not aware of how many elements would be inserted into it.

How do I delete multiple rows in Entity Framework (without foreach)

EF 6.1

public void DeleteWhere<TEntity>(Expression<Func<TEntity, bool>> predicate = null) 
where TEntity : class
{
    var dbSet = context.Set<TEntity>();
    if (predicate != null)
        dbSet.RemoveRange(dbSet.Where(predicate));
    else
        dbSet.RemoveRange(dbSet);

    context.SaveChanges();
} 

Usage:

// Delete where condition is met.
DeleteWhere<MyEntity>(d => d.Name == "Something");

Or:

// delete all from entity
DeleteWhere<MyEntity>();

Difference between left join and right join in SQL Server

select * from Table1 left join Table2 on Table1.id = Table2.id

In the first query Left join compares left-sided table table1 to right-sided table table2.

In Which all the properties of table1 will be shown, whereas in table2 only those properties will be shown in which condition get true.

select * from Table2 right join Table1 on Table1.id = Table2.id

In the first query Right join compares right-sided table table1 to left-sided table table2.

In Which all the properties of table1 will be shown, whereas in table2 only those properties will be shown in which condition get true.

Both queries will give the same result because the order of table declaration in query are different like you are declaring table1 and table2 in left and right respectively in first left join query, and also declaring table1 and table2 in right and left respectively in second right join query.

This is the reason why you are getting the same result in both queries. So if you want different result then execute this two queries respectively,

select * from Table1 left join Table2 on Table1.id = Table2.id

select * from Table1 right join Table2 on Table1.id = Table2.id

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

enter image description here

Follow the above image to edit rows from 200 to 100,000 Rows

Creating a mock HttpServletRequest out of a url string?

Here it is how to use MockHttpServletRequest:

// given
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServerName("www.example.com");
request.setRequestURI("/foo");
request.setQueryString("param1=value1&param");

// when
String url = request.getRequestURL() + '?' + request.getQueryString(); // assuming there is always queryString.

// then
assertThat(url, is("http://www.example.com:80/foo?param1=value1&param"));

What can I use for good quality code coverage for C#/.NET?

I am not sure what the difference is with the retail NCover, but there is also an NCover project on SourceForge that is of course open source and free.

Authorize attribute in ASP.NET MVC

Using Authorize attribute seems more convenient and feels more 'MVC way'. As for technical advantages there are some.

One scenario that comes to my mind is when you're using output caching in your app. Authorize attribute handles that well.

Another would be extensibility. The Authorize attribute is just basic out of the box filter, but you can override its methods and do some pre-authorize actions like logging etc. I'm not sure how you would do that through configuration.

How to compile or convert sass / scss to css with node-sass (no Ruby)?

The installation of these tools may vary on different OS.

Under Windows, node-sass currently supports VS2015 by default, if you only have VS2013 in your box and meet any error while running the command, you can define the version of VS by adding: --msvs_version=2013. This is noted on the node-sass npm page.

So, the safe command line that works on Windows with VS2013 is: npm install --msvs_version=2013 gulp node-sass gulp-sass

Accessing a local website from another computer inside the local network in IIS 7

Control Panel >> Windows Firewall

Advanced settings >> Inbound Rules >> World Wide Web Services - Enable it All or (Domain, Private, Public) as needed.

Python: access class property from string

x = getattr(self, source) will work just perfectly if source names ANY attribute of self, including the other_data in your example.

How to add headers to OkHttp request interceptor?

Finally, I added the headers this way:

@Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        Request newRequest;

        newRequest = request.newBuilder()
                .addHeader(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
                .addHeader(HeadersContract.HEADER_X_CLIENT_ID, CLIENT_ID)
                .build();
        return chain.proceed(newRequest);
    }

What is the function of FormulaR1C1?

FormulaR1C1 has the same behavior as Formula, only using R1C1 style annotation, instead of A1 annotation. In A1 annotation you would use:

Worksheets("Sheet1").Range("A5").Formula = "=A4+A10"

In R1C1 you would use:

Worksheets("Sheet1").Range("A5").FormulaR1C1 = "=R4C1+R10C1"

It doesn't act upon row 1 column 1, it acts upon the targeted cell or range. Column 1 is the same as column A, so R4C1 is the same as A4, R5C2 is B5, and so forth.

The command does not change names, the targeted cell changes. For your R2C3 (also known as C2) example :

Worksheets("Sheet1").Range("C2").FormulaR1C1 = "=your formula here"

How to change Oracle default data pump directory to import dumpfile?

With the directory parameter:

impdp system/password@$ORACLE_SID schemas=USER_SCHEMA directory=MY_DIR \
  dumpfile=mydumpfile.dmp logfile=impdpmydumpfile.log

The default directory is DATA_PUMP_DIR, which is presumably set to /u01/app/oracle/admin/mydatabase/dpdump on your system.

To use a different directory you (or your DBA) will have to create a new directory object in the database, which points to the Oracle-visible operating system directory you put the file into, and assign privileges to the user doing the import.

Convert Object to JSON string

jQuery does only make some regexp checking before calling the native browser method window.JSON.parse(). If that is not available, it uses eval() or more exactly new Function() to create a Javascript object.

The opposite of JSON.parse() is JSON.stringify() which serializes a Javascript object into a string. jQuery does not have functionality of its own for that, you have to use the browser built-in version or json2.js from http://www.json.org

JSON.stringify() is available in all major browsers, but to be compatible with older browsers you still need that fallback.

What is the difference between "is None" and "== None"

The answer is explained here.

To quote:

A class is free to implement comparison any way it chooses, and it can choose to make comparison against None mean something (which actually makes sense; if someone told you to implement the None object from scratch, how else would you get it to compare True against itself?).

Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None as a general rule.

how to find my angular version in my project?

define VERSION variable and import version into it.

import { VERSION } from '@angular/core';

Now you can use VERSION variable in your code to print version For example,

console.log(VERSION.full); 

What is the difference between private and protected members of C++ classes?

  • Private: It is an access specifier. By default the instance (member) variables or the methods of a class in c++/java are private. During inheritance, the code and the data are always inherited but is not accessible outside the class. We can declare our data members as private so that no one can make direct changes to our member variables and we can provide public getters and setters in order to change our private members. And this concept is always applied in the business rule.

  • Protected: It is also an access specifier. In C++, the protected members are accessible within the class and to the inherited class but not outside the class. In Java, the protected members are accessible within the class, to the inherited class as well as to all the classes within the same package.

Combining CSS Pseudo-elements, ":after" the ":last-child"

Adding another answer to this question because I needed precisely what @derek was asking for and I'd already gotten a bit further before seeing the answers here. Specifically, I needed CSS that could also account for the case with exactly two list items, where the comma is NOT desired. As an example, some authorship bylines I wanted to produce would look like the following:

One author: By Adam Smith.

Two authors: By Adam Smith and Jane Doe.

Three authors: By Adam Smith, Jane Doe, and Frank Underwood.

The solutions already given here work for one author and for 3 or more authors, but neglect to account for the two author case—where the "Oxford Comma" style (also known as "Harvard Comma" style in some parts) doesn't apply - ie, there should be no comma before the conjunction.

After an afternoon of tinkering, I had come up with the following:

<html>
 <head>
  <style type="text/css">
    .byline-list {
      list-style: none;
      padding: 0;
      margin: 0;
    }
    .byline-list > li {
      display: inline;
      padding: 0;
      margin: 0;
    }
    .byline-list > li::before {
      content: ", ";
    }
    .byline-list > li:last-child::before {
      content: ", and ";
    }
    .byline-list > li:first-child + li:last-child::before {
      content: " and ";
    }
    .byline-list > li:first-child::before {
      content: "By ";
    }
    .byline-list > li:last-child::after {
      content: ".";
    }
  </style>
 </head>
 <body>
  <ul class="byline-list">
   <li>Adam Smith</li>
  </ul>
  <ul class="byline-list">
   <li>Adam Smith</li><li>Jane Doe</li>
  </ul>
  <ul class="byline-list">
   <li>Adam Smith</li><li>Jane Doe</li><li>Frank Underwood</li>
  </ul>
 </body>
</html>

It displays the bylines as I've got them above.

In the end, I also had to get rid of any whitespace between li elements, in order to get around an annoyance: the inline-block property would otherwise leave a space before each comma. There's probably an alternative decent hack for it but that isn't the subject of this question so I'll leave that for someone else to answer.

Fiddle here: http://jsfiddle.net/5REP2/

CodeIgniter 404 Page Not Found, but why?

  1. Change your controller name first letter to uppercase.
  2. Change your url same as your controller name.

e.g:

Your controller name is YourController

Your url must be:

http://example.com/index.php/YourController/method

Not be:

http://example.com/index.php/yourcontroller/method

Is there a way to use SVG as content in a pseudo element :before or :after

Making use of CSS sprites and data uri gives extra interesting benefits like fast loading and less requests AND we get IE8 support by using image/base64:

Codepen sample using SVG

HTML

<div class="div1"></div>
<div class="div2"></div>

CSS

.div1:after, .div2:after {
  content: '';
  display: block;
  height: 80px;
  width: 80px;
  background-image: url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20height%3D%2280%22%20width%3D%22160%22%3E%0D%0A%20%20%3Ccircle%20cx%3D%2240%22%20cy%3D%2240%22%20r%3D%2238%22%20stroke%3D%22black%22%20stroke-width%3D%221%22%20fill%3D%22red%22%20%2F%3E%0D%0A%20%20%3Ccircle%20cx%3D%22120%22%20cy%3D%2240%22%20r%3D%2238%22%20stroke%3D%22black%22%20stroke-width%3D%221%22%20fill%3D%22blue%22%20%2F%3E%0D%0A%3C%2Fsvg%3E);
}
.div2:after {
  background-position: -80px 0;
}

For IE8, change to this:

  background-image: url(data:image/png;base64,data......);

PostgreSQL: insert from another table

Just supply literal values in the SELECT:

INSERT INTO TABLE1 (id, col_1, col_2, col_3)
SELECT id, 'data1', 'data2', 'data3'
FROM TABLE2
WHERE col_a = 'something';

A select list can contain any value expression:

But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

And a string literal is certainly a value expression.

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

Printing *s as triangles in Java?

Question:

      *
     ***
    *****

Answer:

    int i,a,j;
    i=5;
    while (i>=3)
    {
        a=1;
        while (a<=i)
        {

            System.out.print(" ");
            a++;
        }
        j=10;
        while (j/2>=i)
        {
            System.out.print("*");
            --j;
        }
        System.out.println("");
        i--;
    }   

Enjoy!!

What is an API key?

An API key is a unique value that is assigned to a user of this service when he's accepted as a user of the service.

The service maintains all the issued keys and checks them at each request.

By looking at the supplied key at the request, a service checks whether it is a valid key to decide on whether to grant access to a user or not.

How to overlay images

You might want to check out this tutorial: http://www.webdesignerwall.com/tutorials/css-decorative-gallery/

In it the writer uses an empty span element to add an overlaying image. You can use jQuery to inject said span elements, if you'd like to keep your code as clean as possible. An example is also given in the aforementioned article.

Hope this helps!

-Dave

jQuery text() and newlines

You can use html instead of text and replace each occurrence of \n with <br>. You will have to correctly escape your text though.

x = x.replace(/&/g, '&amp;')
     .replace(/>/g, '&gt;')
     .replace(/</g, '&lt;')
     .replace(/\n/g, '<br>');

Where to find Java JDK Source Code?

Sadly, as of this writing, DESPITE their own documentation readme, there is no src.zip in the JDK 7 or 8 install directories when you download the Windows version.

Note: perhaps this happens because many of us don't actually run the install .exe, but instead extract it. Many of us don't run the Java install (the full blown windows install) for security reasons....we just want the JDK put someplace out of the way where potential viruses cannot find it.

But their policy regarding the windows .exe (whatever it truly is) is indeed nuts, HOWEVER, the src.zip DOES exist in the linux install (a .tar.gz). There are multiple ways of extracting a .tar and a .gz, and I prefer the free "7Zip" utility.

  1. download the Linux 64 bit .tar.gz
  2. use 7zip to uncompress the .tar.gz to a .tar
  3. use 7zip to extract the .tar to the installation directory
  4. src.zip will be waiting for you in that installation directory.
  5. pull it out and place it where you like.

Oracle, this is really beyond stupid.

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

ResourceBundle doesn't load files? You need to get the files into a resource first. How about just loading into a FileInputStream then a PropertyResourceBundle

   FileInputStream fis = new FileInputStream("skyscrapper.properties");
   resourceBundle = new PropertyResourceBundle(fis);

Or if you need the locale specific code, something like this should work

File file = new File("skyscrapper.properties");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("skyscrapper", Locale.getDefault(), loader);

how to align text vertically center in android

In relative layout you need specify textview height:

android:layout_height="100dp"

Or specify lines attribute:

android:lines="3"

How to print Boolean flag in NSLog?

Apple's FixIt supplied %hhd, which correctly gave me the value of my BOOL.

How do you count the number of occurrences of a certain substring in a SQL varchar?

You can use the following stored procedure to fetch , values.

IF  EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[sp_parsedata]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[sp_parsedata]
GO
create procedure sp_parsedata
(@cid integer,@st varchar(1000))
as
  declare @coid integer
  declare @c integer
  declare @c1 integer
  select @c1=len(@st) - len(replace(@st, ',', ''))
  set @c=0
  delete from table1 where complainid=@cid;
  while (@c<=@c1)
    begin
      if (@c<@c1) 
        begin
          select @coid=cast(replace(left(@st,CHARINDEX(',',@st,1)),',','') as integer)
          select @st=SUBSTRING(@st,CHARINDEX(',',@st,1)+1,LEN(@st))
        end
      else
        begin
          select @coid=cast(@st as integer)
        end
      insert into table1(complainid,courtid) values(@cid,@coid)
      set @c=@c+1
    end

.trim() in JavaScript not working in IE

Unfortunately there is not cross browser JavaScript support for trim().

If you aren't using jQuery (which has a .trim() method) you can use the following methods to add trim support to strings:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

What parameters should I use in a Google Maps URL to go to a lat-lon?

If you need a name on your pin, you can also use:

http://maps.google.com/?q=MY%20LOCATION@lat,long

String concatenation: concat() vs "+" operator

I ran a similar test as @marcio but with the following loop instead:

String c = a;
for (long i = 0; i < 100000L; i++) {
    c = c.concat(b); // make sure javac cannot skip the loop
    // using c += b for the alternative
}

Just for good measure, I threw in StringBuilder.append() as well. Each test was run 10 times, with 100k reps for each run. Here are the results:

  • StringBuilder wins hands down. The clock time result was 0 for most the runs, and the longest took 16ms.
  • a += b takes about 40000ms (40s) for each run.
  • concat only requires 10000ms (10s) per run.

I haven't decompiled the class to see the internals or run it through profiler yet, but I suspect a += b spends much of the time creating new objects of StringBuilder and then converting them back to String.

Java socket API: How to tell if a connection has been closed?

Here you are another general solution for any data type.

int offset = 0;
byte[] buffer = new byte[8192];

try {
    do {
        int b = inputStream.read();

        if (b == -1)
           break;

        buffer[offset++] = (byte) b;

        //check offset with buffer length and reallocate array if needed
    } while (inputStream.available() > 0);
} catch (SocketException e) {
    //connection was lost
}

//process buffer

PHP CSV string to array

I have used following function to parse csv string to associative array

public function csvToArray($file) {
    $rows = array();
    $headers = array();
    if (file_exists($file) && is_readable($file)) {
        $handle = fopen($file, 'r');
        while (!feof($handle)) {
            $row = fgetcsv($handle, 10240, ',', '"');
            if (empty($headers))
                $headers = $row;
            else if (is_array($row)) {
                array_splice($row, count($headers));
                $rows[] = array_combine($headers, $row);
            }
        }
        fclose($handle);
    } else {
        throw new Exception($file . ' doesn`t exist or is not readable.');
    }
    return $rows;
}

if your csv file name is mycsv.csv then you call this function as:

$dataArray = csvToArray(mycsv.csv);

you can get this script also in http://www.scriptville.in/parse-csv-data-to-array/

moving changed files to another branch for check-in

If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally - changes to files are not tied to a particular branch until you commit them.

If you have already committed your changes:

  1. Type git log and remember the SHA of the commit you want to move.
  2. Check out the branch you want to move the commit to.
  3. Type git cherry-pick SHA substituting the SHA from above.
  4. Switch back to your original branch.
  5. Use git reset HEAD~1 to reset back before your wrong-branch commit.

cherry-pick takes a given commit and applies it to the currently checked-out head, thus allowing you to copy the commit over to a new branch.

jQuery add class .active on menu

No other "addClass" methods worked for me when adding a class to an 'a' element on menu except this one:

$(function () {
        var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");  
        $('a').each(function () {
                            if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
                $(this).addClass('active');
            }
        });
    });

This took me four hours to find it.

javascript window.location in new tab

We have to dynamically set the attribute target="_blank" and it will open it in new tab. document.getElementsByTagName("a")[0].setAttribute('target', '_blank')

document.getElementsByTagName("a")[0].click()

If you want to open in new window, get the href link and use window.open

var link = document.getElementsByTagName("a")[0].getAttribute("href");

window.open(url, "","height=500,width=500");

Don't provide the second parameter as _blank in the above.

class << self idiom in Ruby

Usually, instance methods are global methods. That means they are available in all instances of the class on which they were defined. In contrast, a singleton method is implemented on a single object.

Ruby stores methods in classes and all methods must be associated with a class. The object on which a singleton method is defined is not a class (it is an instance of a class). If only classes can store methods, how can an object store a singleton method? When a singleton method is created, Ruby automatically creates an anonymous class to store that method. These anonymous classes are called metaclasses, also known as singleton classes or eigenclasses. The singleton method is associated with the metaclass which, in turn, is associated with the object on which the singleton method was defined.

If multiple singleton methods are defined within a single object, they are all stored in the same metaclass.

class Zen
end

z1 = Zen.new
z2 = Zen.new

class << z1
  def say_hello
    puts "Hello!"
  end
end

z1.say_hello    # Output: Hello!
z2.say_hello    # Output: NoMethodError: undefined method `say_hello'…

In the above example, class << z1 changes the current self to point to the metaclass of the z1 object; then, it defines the say_hello method within the metaclass.

Classes are also objects (instances of the built-in class called Class). Class methods are nothing more than singleton methods associated with a class object.

class Zabuton
  class << self
    def stuff
      puts "Stuffing zabuton…"
    end
  end
end

All objects may have metaclasses. That means classes can also have metaclasses. In the above example, class << self modifies self so it points to the metaclass of the Zabuton class. When a method is defined without an explicit receiver (the class/object on which the method will be defined), it is implicitly defined within the current scope, that is, the current value of self. Hence, the stuff method is defined within the metaclass of the Zabuton class. The above example is just another way to define a class method. IMHO, it's better to use the def self.my_new_clas_method syntax to define class methods, as it makes the code easier to understand. The above example was included so we understand what's happening when we come across the class << self syntax.

Additional info can be found at this post about Ruby Classes.

How can I use different certificates on specific connections?

We copy the JRE's truststore and add our custom certificates to that truststore, then tell the application to use the custom truststore with a system property. This way we leave the default JRE truststore alone.

The downside is that when you update the JRE you don't get its new truststore automatically merged with your custom one.

You could maybe handle this scenario by having an installer or startup routine that verifies the truststore/jdk and checks for a mismatch or automatically updates the truststore. I don't know what happens if you update the truststore while the application is running.

This solution isn't 100% elegant or foolproof but it's simple, works, and requires no code.

How to enable relation view in phpmyadmin

Enabling Relation View in phpMyAdmin / MAMP

If you’re using MAMP for your database driven projects you’ll probably be using phpMyAdmin to administer your MySQL database if you’ve decided to go down that route. If you’re creating a database you might be wondering how to create relationships and foriegn keys for your tables.

Firstly you need to check that you have access to the Relation view. To do this open phpMyAdmin and select a database. You need to make sure your tables’ storage engine is set to use InnoDB. Click on a table within your database and choose the Operations tab. Make sure that the storage engine is set to use InnoDB and save your changes.

Now, go back to your table view and click the Structure tab. Depending on your version of phpMyAdmin you should see a link titled Relation view below the table structure. If you can see it you’re good to go. If you can’t you’ll need to follow the steps below to set phpMyAdmin to enable Relations view.

  1. Find /Applications/MAMP/bin/phpMyAdmin/scripts/create_tables.sql
  2. I left this file default but you can change the table name to anything you want. I left mine phpMyAdmin
  3. Open phpMyAdmin and go to the Import tab.
  4. Click the browse button and find the create_tables.sql file and then click Go.
  5. The tables required for Relation view will be added to the database you specified.
  6. Open /Applications/MAMP/bin/phpMyAdmin/config.inc.php
  7. Find the Server(s) configuration code block and replace/uncomment the following code and fill in the values. If you left everything default in the create_tables.sql file then you should just cut and paste the lines below.

    $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
    $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
    $cfg['Servers'][$i]['relation'] = 'pma_relation';
    $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
    $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
    $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
    $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
    $cfg['Servers'][$i]['history'] = 'pma_history';
    
  8. Save the file and restart MAMP and refresh your phpMyAdmin console.

  9. Go to your database and view one of your tables in Structure mode. You should now see the Relation view link.

Source: http://newvibes.com/blog/enabling-relation-view-in-phpmyadmin-mamp/

How to get the new value of an HTML input after a keypress has modified it?

There are two kinds of input value: field's property and field's html attribute.

If you use keyup event and field.value you shuld get current value of the field. It's not the case when you use field.getAttribute('value') which would return what's in the html attribute (value=""). The property represents what's been typed into the field and changes as you type, while attribute doesn't change automatically (you can change it using field.setAttribute method).

AssertionError: View function mapping is overwriting an existing endpoint function: main

Your view names need to be unique even if they are pointing to the same view method.

app.add_url_rule('/',
                 view_func=Main.as_view('main'),
                 methods = ['GET'])

app.add_url_rule('/<page>/',
                 view_func=Main.as_view('page'),
                 methods = ['GET'])

How to compare two dates?

Other answers using datetime and comparisons also work for time only, without a date.

For example, to check if right now it is more or less than 8:00 a.m., we can use:

import datetime

eight_am = datetime.time( 8,0,0 ) # Time, without a date

And later compare with:

datetime.datetime.now().time() > eight_am  

which will return True

AutoComplete TextBox Control

You could attach to the KeyDown event and then query the database for that portion of the text that the user has already entered. For example, if the user enters "T", search for things that start with "T". Then, when they enter the next letter, for example "e", search for things in the table that start with "Te".

The available items could be displayed in a "floating" ListBox, for example. You would need to place the ListBox just beneath the TextBox so that they can see the entries available, then remove the ListBox when they're done typing.

Plotting a 3d cube, a sphere and a vector in Matplotlib

It is a little complicated, but you can draw all the objects by the following code:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations


fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
    if np.sum(np.abs(s-e)) == r[1]-r[0]:
        ax.plot3D(*zip(s, e), color="b")

# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")

# draw a point
ax.scatter([0], [0], [0], color="g", s=100)

# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d


class Arrow3D(FancyArrowPatch):

    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)

a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
            lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()

output_figure

.Net picking wrong referenced assembly version

If you are experiencing this problem when testing and/or debugging the application from the Visual Studio environment (ASP.NET Development Server), it is necessary to delete all temporary files on the development website folder. To know where that folder is, look for the ASP.NET Development Server icon on the Windows tray icon (it should have a title like this: ASP.NET Development Server - Port ####), right click the icon and select Show Details; thn, the field Physical path will tell you what the temporary folder is, all items there should be deleted to solve the problem. Build and run again the website and the problem should be solved (again, solved for the Development Environment).

using href links inside <option> tag

The accepted solution looks good, but there is one case it cannot handle:

The "onchange" event will not be triggered when the same option is reselected. So, I came up with the following improvement:

HTML

<select id="sampleSelect" >
  <option value="Home.php">Home</option>
  <option value="Contact.php">Contact</option>
  <option value="Sitemap.php">Sitemap</option>
</select>

jQuery

$("select").click(function() {
  var open = $(this).data("isopen");
  if(open) {
    window.location.href = $(this).val()
  }
  //set isopen to opposite so next time when use clicked select box
  //it wont trigger this event
  $(this).data("isopen", !open);
});

How do I ZIP a file in C#, using no 3rd-party APIs?

How can I programatically (C#) ZIP a file (in Windows) without using any third party libraries?

If using the 4.5+ Framework, there is now the ZipArchive and ZipFile classes.

using (ZipArchive zip = ZipFile.Open("test.zip", ZipArchiveMode.Create))
{
    zip.CreateEntryFromFile(@"c:\something.txt", "data/path/something.txt");
}

You need to add references to:

  • System.IO.Compression
  • System.IO.Compression.FileSystem

For .NET Core targeting net46, you need to add dependencies for

  • System.IO.Compression
  • System.IO.Compression.ZipFile

Example project.json:

"dependencies": {
  "System.IO.Compression": "4.1.0",
  "System.IO.Compression.ZipFile": "4.0.1"
},

"frameworks": {
  "net46": {}
}

For .NET Core 2.0, just adding a simple using statement is all that is needed:

  • using System.IO.Compression;

SQL Not Like Statement not working

mattgcon,

Should work, do you get more rows if you run the same SQL with the "NOT LIKE" line commented out? If not, check the data. I know you mentioned in your question, but check that the actual SQL statement is using that clause. The other answers with NULL are also a good idea.

How to get row index number in R?

It not quite clear what exactly you are trying to do.

To reference a row in a data frame use df[row,]

To get the first position in a vector of something use match(item,vector), where the vector could be one of the columns of your data frame, eg df$cname if the column name is cname.

Edit:

To combine these you would write:

df[match(item,df$cname),]

Note that the match gives you the first item in the list, so if you are not looking for a unique reference number, you may want to consider something else.

Code to loop through all records in MS Access

Found a good code with comments explaining each statement. Code found at - accessallinone

Sub DAOLooping()
On Error GoTo ErrorHandler

Dim strSQL As String
Dim rs As DAO.Recordset

strSQL = "tblTeachers"
'For the purposes of this post, we are simply going to make 
'strSQL equal to tblTeachers.
'You could use a full SELECT statement such as:
'SELECT * FROM tblTeachers (this would produce the same result in fact).
'You could also add a Where clause to filter which records are returned:
'SELECT * FROM tblTeachers Where ZIPPostal = '98052'
' (this would return 5 records)

Set rs = CurrentDb.OpenRecordset(strSQL)
'This line of code instantiates the recordset object!!! 
'In English, this means that we have opened up a recordset 
'and can access its values using the rs variable.

With rs


    If Not .BOF And Not .EOF Then
    'We don’t know if the recordset has any records, 
    'so we use this line of code to check. If there are no records 
    'we won’t execute any code in the if..end if statement.    

        .MoveLast
        .MoveFirst
        'It is not necessary to move to the last record and then back 
        'to the first one but it is good practice to do so.

        While (Not .EOF)
        'With this code, we are using a while loop to loop 
        'through the records. If we reach the end of the recordset, .EOF 
        'will return true and we will exit the while loop.

            Debug.Print rs.Fields("teacherID") & " " & rs.Fields("FirstName")
            'prints info from fields to the immediate window

            .MoveNext
            'We need to ensure that we use .MoveNext, 
            'otherwise we will be stuck in a loop forever… 
            '(or at least until you press CTRL+Break)
        Wend

    End If

    .close
    'Make sure you close the recordset...
End With

ExitSub:
    Set rs = Nothing
    '..and set it to nothing
    Exit Sub
ErrorHandler:
    Resume ExitSub
End Sub

Recordsets have two important properties when looping through data, EOF (End-Of-File) and BOF (Beginning-Of-File). Recordsets are like tables and when you loop through one, you are literally moving from record to record in sequence. As you move through the records the EOF property is set to false but after you try and go past the last record, the EOF property becomes true. This works the same in reverse for the BOF property.

These properties let us know when we have reached the limits of a recordset.

How to print out more than 20 items (documents) in MongoDB's shell?

I suggest you to have a ~/.mongorc.js file so you do not have to set the default size everytime.

 # execute in your terminal
 touch ~/.mongorc.js
 echo 'DBQuery.shellBatchSize = 100;' > ~/.mongorc.js
 # add one more line to always prettyprint the ouput
 echo 'DBQuery.prototype._prettyShell = true; ' >> ~/.mongorc.js

To know more about what else you can do, I suggest you to look at this article: http://mo.github.io/2017/01/22/mongo-db-tips-and-tricks.html

Does Go have "if x in" construct similar to Python?

Another option is using a map as a set. You use just the keys and having the value be something like a boolean that's always true. Then you can easily check if the map contains the key or not. This is useful if you need the behavior of a set, where if you add a value multiple times it's only in the set once.

Here's a simple example where I add random numbers as keys to a map. If the same number is generated more than once it doesn't matter, it will only appear in the final map once. Then I use a simple if check to see if a key is in the map or not.

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    var MAX int = 10

    m := make(map[int]bool)

    for i := 0; i <= MAX; i++ {
        m[rand.Intn(MAX)] = true
    }

    for i := 0; i <= MAX; i++ {
        if _, ok := m[i]; ok {
            fmt.Printf("%v is in map\n", i)
        } else {
            fmt.Printf("%v is not in map\n", i)
        }
    }
}

Here it is on the go playground

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

Import Libraries in Eclipse?

Extract the jar, and put it somewhere in your Java project (usually under a "lib" subdirectory).

Right click the project, open its preferences, go for Java build path, and then the Libraries tab. You can add the library there with "add a jar".

If your jar is not open source, you may want to store it elsewhere and connect to it as an external jar.

Get current language in CultureInfo

Current system language is retrieved using :

  CultureInfo.InstalledUICulture

"Gets the CultureInfo that represents the culture installed with the operating system."

InstalledUICulture

To set it as default language for thread use :

   System.Globalization.CultureInfo.DefaultThreadCurrentCulture=CultureInfo.InstalledUICulture;

Import a file from a subdirectory?

Just an addition to these answers.

If you want to import all files from all subdirectories, you can add this to the root of your file.

import sys, os
sys.path.extend([f'./{name}' for name in os.listdir(".") if os.path.isdir(name)])

And then you can simply import files from the subdirectories just as if these files are inside the current directory.

Working example

If I have the following directory with subdirectories in my project...

.
+-- a.py
+-- b.py
+-- c.py
+-- subdirectory_a
¦   +-- d.py
¦   +-- e.py
+-- subdirectory_b
¦   +-- f.py
+-- subdirectory_c
¦   +-- g.py
+-- subdirectory_d
    +-- h.py

I can put the following code inside my a.py file

import sys, os
sys.path.extend([f'./{name}' for name in os.listdir(".") if os.path.isdir(name)])

# And then you can import files just as if these files are inside the current directory

import b
import c
import d
import e
import f
import g
import h

In other words, this code will abstract from which directory the file is coming from.

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

I have found a variety of runtimes including Visual Studio(VS) versions are available at http://scn.sap.com/docs/DOC-7824

Calculate time difference in Windows batch file

Based on previous answers, here are reusable "procedures" and a usage example for calculating the elapsed time:

@echo off
setlocal

set starttime=%TIME%
echo Start Time: %starttime%

REM ---------------------------------------------
REM --- PUT THE CODE YOU WANT TO MEASURE HERE ---
REM ---------------------------------------------

set endtime=%TIME%
echo End Time: %endtime%
call :elapsed_time %starttime% %endtime% duration
echo Duration: %duration%

endlocal
echo on & goto :eof

REM --- HELPER PROCEDURES ---

:time_to_centiseconds
:: %~1 - time
:: %~2 - centiseconds output variable
setlocal
set _time=%~1
for /F "tokens=1-4 delims=:.," %%a in ("%_time%") do (
   set /A "_result=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
endlocal & set %~2=%_result%
goto :eof

:centiseconds_to_time
:: %~1 - centiseconds
:: %~2 - time output variable
setlocal
set _centiseconds=%~1
rem now break the centiseconds down to hors, minutes, seconds and the remaining centiseconds
set /A _h=%_centiseconds% / 360000
set /A _m=(%_centiseconds% - %_h%*360000) / 6000
set /A _s=(%_centiseconds% - %_h%*360000 - %_m%*6000) / 100
set /A _hs=(%_centiseconds% - %_h%*360000 - %_m%*6000 - %_s%*100)
rem some formatting
if %_h% LSS 10 set _h=0%_h%
if %_m% LSS 10 set _m=0%_m%
if %_s% LSS 10 set _s=0%_s%
if %_hs% LSS 10 set _hs=0%_hs%
set _result=%_h%:%_m%:%_s%.%_hs%
endlocal & set %~2=%_result%
goto :eof

:elapsed_time
:: %~1 - time1 - start time
:: %~2 - time2 - end time
:: %~3 - elapsed time output
setlocal
set _time1=%~1
set _time2=%~2
call :time_to_centiseconds %_time1% _centi1
call :time_to_centiseconds %_time2% _centi2
set /A _duration=%_centi2%-%_centi1%
call :centiseconds_to_time %_duration% _result
endlocal & set %~3=%_result%
goto :eof

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

Linux: where are environment variables stored?

Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

There is a simple trick for this. After you constructed the frame with all it buttons do this:

frame.getRootPane().setDefaultButton(submitButton);

For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked.


And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:

@Override
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode()==KeyEvent.VK_ENTER){
        System.out.println("Hello");

        JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
    }

}

UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:

SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

I'm using n (Node version management)

You can install it in two ways

brew install n

or

npm install -g n

You can switch between different version of node and io. Here's an example from my current env when I call n without params:

$ n

  io/3.3.1
  node/0.12.7
  node/4.0.0
  node/5.0.0
? node/5.10.1 

SQL Server - Convert varchar to another collation (code page) to fix character encoding

I think SELECT CAST( CAST([field] AS VARBINARY(120)) AS varchar(120)) for your update

MySQL "Group By" and "Order By"

According to SQL standard you cannot use non-aggregate columns in select list. MySQL allows such usage (uless ONLY_FULL_GROUP_BY mode used) but result is not predictable.

ONLY_FULL_GROUP_BY

You should first select fromEmail, MIN(read), and then, with second query (or subquery) - Subject.

Spring MVC Controller redirect using URL parameters instead of in response

@RequestMapping(path="/apps/add", method=RequestMethod.POST)
public String addApps(String appUrl, Model model, final RedirectAttributes redirectAttrs) {
    if (!validate(appUrl)) {
       redirectAttrs.addFlashAttribute("error", "Validation failed");
    }
    return "redirect:/apps/add"
} 

@RequestMapping(path="/apps/add", method=RequestMethod.GET)
public String addAppss(Model model) {
    String error = model.asMap().get("error");
}

Server certificate verification failed: issuer is not trusted

If you are using svn with Jenkins on a Windows Server, you must accept https certificate using the same Jenkins's Windows service user.
So , if your Jenkins service runs as "MYSERVER\Administrator", you must use this command before all others, only one time of course :

runas /user:MYSERVER\Administrator "svn --username user --password password list https://myserver/svn/REPO "

svn asks you to accept the certificate and stores it in the right path.

After this you'll be able to use svn in jenkins job directly in a Windows batch command step.

How do I calculate a trendline for a graph?

Here's a working example in golang. I searched around and found this page and converted this over to what I needed. Hope someone else can find it useful.

// https://classroom.synonym.com/calculate-trendline-2709.html
package main

import (
    "fmt"
    "math"
)

func main() {

    graph := [][]float64{
        {1, 3},
        {2, 5},
        {3, 6.5},
    }

    n := len(graph)

    // get the slope
    var a float64
    var b float64
    var bx float64
    var by float64
    var c float64
    var d float64
    var slope float64

    for _, point := range graph {

        a += point[0] * point[1]
        bx += point[0]
        by += point[1]
        c += math.Pow(point[0], 2)
        d += point[0]

    }

    a *= float64(n)           // 97.5
    b = bx * by               // 87
    c *= float64(n)           // 42
    d = math.Pow(d, 2)        // 36
    slope = (a - b) / (c - d) // 1.75

    // calculating the y-intercept (b) of the Trendline
    var e float64
    var f float64

    e = by                            // 14.5
    f = slope * bx                    // 10.5
    intercept := (e - f) / float64(n) // (14.5 - 10.5) / 3 = 1.3

    // output
    fmt.Println(slope)
    fmt.Println(intercept)

}

Creating files in C++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string filename = "/tmp/filename.txt";

int main() {
  std::ofstream o(filename.c_str());

  o << "Hello, World\n" << std::endl;

  return 0;
}

This is what I had to do in order to use a variable for the filename instead of a regular string.

How to instantiate, initialize and populate an array in TypeScript?

If you really want to have named parameters plus have your objects be instances of your class, you can do the following:

class bar {
    constructor (options?: {length: number; height: number;}) {
        if (options) {
            this.length = options.length;
            this.height = options.height;
        }
    }
    length: number;
    height: number;
}

class foo {
    bars: bar[] = new Array();
}

var ham = new foo();
ham.bars = [
    new bar({length: 4, height: 2}),
    new bar({length: 1, height: 3})
];

Also here's the related item on typescript issue tracker.

What is Dispatcher Servlet in Spring?

In Spring MVC, all incoming requests go through a single servlet. This servlet - DispatcherServlet - is the front controller. Front controller is a typical design pattern in the web applications development. In this case, a single servlet receives all requests and transfers them to all other components of the application.

The task of the DispatcherServlet is to send request to the specific Spring MVC controller.

Usually we have a lot of controllers and DispatcherServlet refers to one of the following mappers in order to determine the target controller:

If no configuration is performed, the DispatcherServlet uses BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping by default.

When the target controller is identified, the DispatcherServlet sends request to it. The controller performs some work according to the request (or delegate it to the other objects), and returns back to the DispatcherServlet with the Model and the name of the View.

The name of the View is only a logical name. This logical name is then used to search for the actual View (to avoid coupling with the controller and specific View). Then DispatcherServlet refers to the ViewResolver and maps the logical name of the View to the specific implementation of the View.

Some possible Implementations of the ViewResolver are:

When the DispatcherServlet determines the view that will display the results it will be rendered as the response.

Finally, the DispatcherServlet returns the Response object back to the client.

How to redirect a url in NGINX

First make sure you have installed Nginx with the HTTP rewrite module. To install this we need to have pcre-library

How to install pcre library

If the above mentioned are done or if you already have them, then just add the below code in your nginx server block

  if ($host !~* ^www\.) {
    rewrite ^(.*)$ http://www.$host$1 permanent;
  }

To remove www from every request you can use

  if ($host = 'www.your_domain.com' ) {
   rewrite  ^/(.*)$  http://your_domain.com/$1  permanent;
  }

so your server block will look like

  server {
            listen       80;
            server_name  test.com;
            if ($host !~* ^www\.) {
                    rewrite ^(.*)$ http://www.$host$1 permanent;
            }
            client_max_body_size   10M;
            client_body_buffer_size   128k;

            root       /home/test/test/public;
            passenger_enabled on;
            rails_env production;

            error_page   500 502 503 504  /50x.html;
            location = /50x.html {
                    root   html;
            }
    }

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

When you open the file you want to write to, open it with a specific encoding that can handle all the characters.

with open('filename', 'w', encoding='utf-8') as f:
    print(r['body'], file=f)

How do I set log4j level on the command line?

In my pretty standard setup I've been seeing the following work well when passed in as VM Option (commandline before class in Java, or VM Option in an IDE):

-Droot.log.level=TRACE

How do I check my gcc C++ compiler version for my Eclipse?

Just type

gcc --version

in any terminal near you.. ;-)

How to cancel a pull request on github?

Super EASY way to close a Pull Request - LATEST!

  1. Navigate to the Original Repository where the pull request has been submitted to.
  2. Select the Pull requests tab
  3. Select your pull request that you wish to remove. This will open it up.
  4. Towards the bottom, just enter a valid comment for closure and press Close Pull Request button

enter image description here

How to add jQuery in JS file

If document.write('<\script ...') isn't working, try document.createElement('script')...

Other than that, you should be worried about the type of website you're making - do you really think its a good idea to include .js files from .js files?

Bind class toggle to window scroll event

What about performance?

  1. Always debounce events to reduce calculations
  2. Use scope.applyAsync to reduce overall digest cycles count
function debounce(func, wait) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        var later = function () {
            timeout = null;
            func.apply(context, args);
        };

        if (!timeout) func.apply(context, args);
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

angular.module('app.layout')
  .directive('classScroll', function ($window) {    
    return {
        restrict: 'A',
        link: function (scope, element) {    
            function toggle() {
                angular.element(element)
                  .toggleClass('class-scroll--scrolled', 
                    window.pageYOffset > 0);
                scope.$applyAsync();
            }    
            angular.element($window)
              .on('scroll', debounce(toggle, 50));

            toggle();
        }
    };
});

3. If you don't need to trigger watchers/digests at all then use compile

.directive('classScroll', function ($window, utils) {
    return {
        restrict: 'A',
        compile: function (element, attributes) {
            function toggle() {
                angular.element(element)
                  .toggleClass(attributes.classScroll,
                    window.pageYOffset > 0);
            }

            angular.element($window)
              .on('scroll', utils.debounce(toggle, 50));
            toggle();
        }
    };
  });

And you can use it like <header class-scroll="header--scrolled">

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

How to use vim in the terminal?

Run vim from the terminal. For the basics, you're advised to run the command vimtutor.

# On your terminal command line:
$ vim

If you have a specific file to edit, pass it as an argument.

$ vim yourfile.cpp

Likewise, launch the tutorial

$ vimtutor

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Add "EntityFramework.SqlServer.dll" into your bin folder. Problem will get resolved.

node.js vs. meteor.js what's the difference?

A loose analogy is, "Meteor is to Node as Rails is to Ruby." It's a large, opinionated framework that uses Node on the server. Node itself is just a low-level framework providing functions for sending and receiving HTTP requests and performing other I/O.

Meteor is radically ambitious: By default, every page it serves is actually a Handlebars template that's kept in sync with the server. Try the Leaderboard example: You create a template that simply says "List the names and scores," and every time any client changes a name or score, the page updates with the new data—not just for that client, but for everyone viewing the page.

Another difference: While Node itself is stable and widely used in production, Meteor is in a "preview" state. There are serious bugs, and certain things that don't fit with Meteor's data-centric conceptual model (such as animations) are very hard to do.

If you love playing with new technologies, give Meteor a spin. If you want a more traditional, stable web framework built on Node, take a look at Express.

Algorithm to randomly generate an aesthetically-pleasing color palette

I'd strongly recommend using a CG HSVtoRGB shader function, they are awesome... it gives you natural color control like a painter instead of control like a crt monitor, which you arent presumably!

This is a way to make 1 float value. i.e. Grey, into 1000 ds of combinations of color and brightness and saturation etc:

int rand = a global color randomizer that you can control by script/ by a crossfader etc.
float h = perlin(grey,23.3*rand)
float s = perlin(grey,54,4*rand)
float v = perlin(grey,12.6*rand)

Return float4 HSVtoRGB(h,s,v);

result is AWESOME COLOR RANDOMIZATION! it's not natural but it uses natural color gradients and it looks organic and controlleably irridescent / pastel parameters.

For perlin, you can use this function, it is a fast zig zag version of perlin.

function  zig ( xx : float ): float{    //lfo nz -1,1
    xx= xx+32;
    var x0 = Mathf.Floor(xx);
    var x1 = x0+1;
    var v0 = (Mathf.Sin (x0*.014686)*31718.927)%1;
    var v1 = (Mathf.Sin  (x1*.014686)*31718.927)%1;
    return Mathf.Lerp( v0 , v1 , (xx)%1 )*2-1;
}

Creating a URL in the controller .NET MVC

If you need the full url (for instance to send by email) consider using one of the following built-in methods:

With this you create the route to use to build the url:

Url.RouteUrl("OpinionByCompany", new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}), HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)

Here the url is built after the route engine determine the correct one:

Url.Action("Detail","Opinion",new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}),HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)

In both methods, the last 2 parameters specifies the protocol and hostname.

Regards.

How can I use nohup to run process as a background process in linux?

In general, I use nohup CMD & to run a nohup background process. However, when the command is in a form that nohup won't accept then I run it through bash -c "...".

For example:

nohup bash -c "(time ./script arg1 arg2 > script.out) &> time_n_err.out" &

stdout from the script gets written to script.out, while stderr and the output of time goes into time_n_err.out.

So, in your case:

nohup bash -c "(time bash executeScript 1 input fileOutput > scrOutput) &> timeUse.txt" &

What is the correct syntax of ng-include?

try this

<div ng-app="myApp" ng-controller="customersCtrl"> 
  <div ng-include="'myTable.htm'"></div>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("customers.php").then(function (response) {
        $scope.names = response.data.records;
    });
});
</script>

Rails: How can I set default values in ActiveRecord?

I ran into problems with after_initialize giving ActiveModel::MissingAttributeError errors when doing complex finds:

eg:

@bottles = Bottle.includes(:supplier, :substance).where(search).order("suppliers.name ASC").paginate(:page => page_no)

"search" in the .where is hash of conditions

So I ended up doing it by overriding initialize in this way:

def initialize
  super
  default_values
end

private
 def default_values
     self.date_received ||= Date.current
 end

The super call is necessary to make sure the object initializing correctly from ActiveRecord::Base before doing my customize code, ie: default_values

Conversion from List<T> to array T[]

You can simply use ToArray() extension method

Example:

Person p1 = new Person() { Name = "Person 1", Age = 27 };
Person p2 = new Person() { Name = "Person 2", Age = 31 };

List<Person> people = new List<Person> { p1, p2 };

var array = people.ToArray();

According to Docs

The elements are copied using Array.Copy(), which is an O(n) operation, where n is Count.

Python exit commands - why so many and when should each be used?

sys.exit is the canonical way to exit.

Internally sys.exit just raises SystemExit. However, calling sys.exitis more idiomatic than raising SystemExit directly.

os.exit is a low-level system call that exits directly without calling any cleanup handlers.

quit and exit exist only to provide an easy way out of the Python prompt. This is for new users or users who accidentally entered the Python prompt, and don't want to know the right syntax. They are likely to try typing exit or quit. While this will not exit the interpreter, it at least issues a message that tells them a way out:

>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()
$

This is essentially just a hack that utilizes the fact that the interpreter prints the __repr__ of any expression that you enter at the prompt.

Grant execute permission for a user on all stored procedures in database?

This is a solution that means that as you add new stored procedures to the schema, users can execute them without having to call grant execute on the new stored procedure:

IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'asp_net')
DROP USER asp_net
GO

IF  EXISTS (SELECT * FROM sys.database_principals 
WHERE name = N'db_execproc' AND type = 'R')
DROP ROLE [db_execproc]
GO

--Create a database role....
CREATE ROLE [db_execproc] AUTHORIZATION [dbo]
GO

--...with EXECUTE permission at the schema level...
GRANT EXECUTE ON SCHEMA::dbo TO db_execproc;
GO

--http://www.patrickkeisler.com/2012/10/grant-execute-permission-on-all-stored.html
--Any stored procedures that are created in the dbo schema can be 
--executed by users who are members of the db_execproc database role

--...add a user e.g. for the NETWORK SERVICE login that asp.net uses
CREATE USER asp_net 
FOR LOGIN [NT AUTHORITY\NETWORK SERVICE] 
WITH DEFAULT_SCHEMA=[dbo]
GO

--...and add them to the roles you need
EXEC sp_addrolemember N'db_execproc', 'asp_net';
EXEC sp_addrolemember N'db_datareader', 'asp_net';
EXEC sp_addrolemember N'db_datawriter', 'asp_net';
GO

Reference: Grant Execute Permission on All Stored Procedures

Use of min and max functions in C++

std::min and std::max are templates. So, they can be used on a variety of types that provide the less than operator, including floats, doubles, long doubles. So, if you wanted to write generic C++ code you'd do something like this:

template<typename T>
T const& max3(T const& a, T const& b, T const& c)
{
   using std::max;
   return max(max(a,b),c); // non-qualified max allows ADL
}

As for performance, I don't think fmin and fmax differ from their C++ counterparts.

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

It depends where you put this initialisation.

If the array is static as in

char array[100] = {0};

int main(void)
{
...
}

then it is the compiler that reserves the 100 0 bytes in the data segement of the program. In this case you could have omitted the initialiser.

If your array is auto, then it is another story.

int foo(void)
{
char array[100] = {0};
...
}

In this case at every call of the function foo you will have a hidden memset.

The code above is equivalent to

int foo(void)
{ 
char array[100];

memset(array, 0, sizeof(array));
....
}

and if you omit the initializer your array will contain random data (the data of the stack).

If your local array is declared static like in

int foo(void)
{ 
static char array[100] = {0};
...
}

then it is technically the same case as the first one.

How to get your Netbeans project into Eclipse

In Eclipse:

File>Import>General>Existing projects in Workspace

Browse until get the netbeans project folder > Finish

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

Does Ubuntu use SELinux? Check to see if it's enabled and enforcing. /var/log/audit/audit.log may be helpul (if that's where Ubuntu sticks it -- that's the RHEL/Fedora location).

Could not find a version that satisfies the requirement tensorflow

For installing Tensorflow in Windows using Command Prompt or Terminal, write the following command:

pip install tensorflow

CSS Calc Viewport Units Workaround?

Before I answer this, I'd like to point out that Chrome and IE 10+ actually supports calc with viewport units.

FIDDLE (In IE10+)

Solution (for other browsers): box-sizing

1) Start of by setting your height as 100vh.

2) With box-sizing set to border-box - add a padding-top of 75vw. This means that the padding will be part f the inner height.

3) Just offset the extra padding-top with a negative margin-top

FIDDLE

div
{
    /*height: calc(100vh - 75vw);*/
    height: 100vh;
    margin-top: -75vw;
    padding-top: 75vw;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    background: pink;
}

How to execute cmd commands via Java

If you want to run several commands in the cmd shell then you can construct a single command like this:

  rt.exec("cmd /c start cmd.exe /K \"cd c:/ && dir\"");

This page explains more.

In Java, how do I get the difference in seconds between 2 dates?

It is not recommended to use java.util.Date or System.currentTimeMillis() to measure elapsed times. These dates are not guaranteed to be monotonic and will changes occur when the system clock is modified (eg when corrected from server). In probability this will happen rarely, but why not code a better solution rather than worrying about possibly negative or very large changes?

Instead I would recommend using System.nanoTime().

long t1 = System.nanoTime();
long t2 = System.nanoTime();

long elapsedTimeInSeconds = (t2 - t1) / 1000000000;

EDIT

For more information about monoticity see the answer to a related question I asked, where possible nanoTime uses a monotonic clock. I have tested but only using Windows XP, Java 1.6 and modifying the clock whereby nanoTime was monotonic and currentTimeMillis wasn't.

Also from Java's Real time doc's:

Q: 50. Is the time returned via the real-time clock of better resolution than that returned by System.nanoTime()?

The real-time clock and System.nanoTime() are both based on the same system call and thus the same clock.

With Java RTS, all time-based APIs (for example, Timers, Periodic Threads, Deadline Monitoring, and so forth) are based on the high-resolution timer. And, together with real-time priorities, they can ensure that the appropriate code will be executed at the right time for real-time constraints. In contrast, ordinary Java SE APIs offer just a few methods capable of handling high-resolution times, with no guarantee of execution at a given time. Using System.nanoTime() between various points in the code to perform elapsed time measurements should always be accurate.

Remote Connections Mysql Ubuntu

You are using ubuntu 12 (quite old one)

First, Open the /etc/mysql/mysql.conf.d/mysqld.cnf file (/etc/mysql/my.cnf in Ubuntu 14.04 and earlier versions

Under the [mysqld] Locate the Line, bind-address = 127.0.0.1 And change it to, bind-address = 0.0.0.0 or comment it

Then, Restart the Ubuntu MysQL Server systemctl restart mysql.service

Now Ubuntu Server will allow remote access to the MySQL Server, But still you need to configure MySQL users to allow access from any host.

User must be 'username'@'%' with all the required grants

To make sure that, MySQL server listens on all interfaces, run the netstat command as follows.

netstat -tulnp | grep mysql

Hope this works !

what is the use of $this->uri->segment(3) in codeigniter pagination

By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure: $product_id = $this->uri->segment(3, 0);

It helps avoid having to write code like this:

[if ($this->uri->segment(3) === FALSE)
{
    $product_id = 0;
}
else
{
    $product_id = $this->uri->segment(3);
}]

The shortest possible output from git log containing author and date

I use these two .gitconfig settings:

[log]
  date = relative
[format]
  pretty = format:%h %Cblue%ad%Creset %ae %Cgreen%s%Creset

%ad is the author date, which can be overidden by --date or the option specified in the [log] stanza in .gitconfig. I like the relative date because it gives an immediate feeling of when stuff was comitted. Output looks like this:

6c3e1a2 2 hours ago [email protected] lsof is a dependency now.
0754f18 11 hours ago [email protected] Properly unmount, so detaching works.
336a3ac 13 hours ago [email protected] Show ami registration command if auto register fails
be2ad45 17 hours ago [email protected] Fixes #6. Sao Paolo region is included as well.
5aed68e 17 hours ago [email protected] Shorten while loops

This is all of course in color, so it is easy to distinguish the various parts of a log line. Also it is the default when typing git log because of the [format] section.

2014 UPDATE: Since git now supports padding I have a nice amendment to the version above:

pretty = format:%C(yellow)%h %Cblue%>(12)%ad %Cgreen%<(7)%aN%Cred%d %Creset%s

This right aligns the relative dates and left aligns committer names, meaning you get a column-like look that is easy on the eyes.

Screenshot

  ss#1

2016 UPDATE: Since GPG commit signing is becoming a thing, I thought I'd update this post with a version that includes signature verification (in the screenshot it's the magenta letter right after the commit). A short explanation of the flag:

%G?: show "G" for a good (valid) signature, "B" for a bad signature, "U" for a good signature with unknown validity and "N" for no signature

Other changes include:

  • colors are now removed if the output is to something other than the tty (which is useful for grepping etc.)
  • git log -g now contains the reflog selector.
  • Save 2 parens on refnames and put them at the end (to preserve column alignment)
  • Truncate relative dates if they are too long (e.g. 3 years, 4..)
  • Truncate commiter names (might be a little short for some ppl, just change the %<(7,trunc) or check out the git .mailmap feature to shorten commiter names)

Here's the config:

pretty = format:%C(auto,yellow)%h%C(auto,magenta)% G? %C(auto,blue)%>(12,trunc)%ad %C(auto,green)%<(7,trunc)%aN%C(auto,reset)%s%C(auto,red)% gD% D

All in all column alignment is now preserved a lot better at the expense of some (hopefully) useless characters. Feel free to edit if you have any improvements, I'd love to make the message color depend on whether a commit is signed, but it doesn't seem like that is possible atm.

Screenshot

Screenshot of git log

Does document.body.innerHTML = "" clear the web page?

Using document.body.innerHTML = ''; does work! Just saying, if using HTML (DOM or on function) you can use
document.writeln(''); but only onClick or onDoubleClick :)

How to include "zero" / "0" results in COUNT aggregate?

The problem with a LEFT JOIN is that if there are no appointments, it will still return one row with a null, which when aggregated by COUNT will become 1, and it will appear that the person has one appointment when actually they have none. I think this will give the correct results:

SELECT person.person_id,
(SELECT COUNT(*) FROM appointment WHERE person.person_id = appointment.person_id) AS 'Appointments'
FROM person;

Execute Insert command and return inserted Id in Sql

using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) " +
    "VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
{
    cmd.Parameters.AddWithValue("@na", Mem_NA);
    cmd.Parameters.AddWithValue("@occ", Mem_Occ);
    con.Open();

    int modified = cmd.ExecuteNonQuery();

    if (con.State == System.Data.ConnectionState.Open) con.Close();
        return modified;
}

SCOPE_IDENTITY : Returns the last identity value inserted into an identity column in the same scope. for more details http://technet.microsoft.com/en-us/library/ms190315.aspx

How to scanf only integer and repeat reading if the user enters non-numeric characters?

#include <stdio.h>
main()
{
    char str[100];
    int num;
    while(1) {
        printf("Enter a number: ");
        scanf("%[^0-9]%d",str,&num);
        printf("You entered the number %d\n",num);
    }
    return 0;
}

%[^0-9] in scanf() gobbles up all that is not between 0 and 9. Basically it cleans the input stream of non-digits and puts it in str. Well, the length of non-digit sequence is limited to 100. The following %d selects only integers in the input stream and places it in num.

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.

Drawing an image from a data URL to a canvas

Just to add to the other answers: In case you don't like the onload callback approach, you can "promisify" it like so:

let url = "data:image/gif;base64,R0lGODl...";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// now do something with img

Splitting strings using a delimiter in python

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

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

Postgresql: password authentication failed for user "postgres"

I had faced similar issue. While accessing any database I was getting below prompt after updating password "password authentication failed for user “postgres”" in PGAdmin


Solution:

  1. Shut down postgres server
  2. Re-run pgadmin
  3. pgadmin will ask for password.
  4. Please enter current password of mentioned user

Hope it will resolve your issue

enter image description here

How do I get the current date in Cocoa

You need to do something along the lines of the following:

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
NSLog(@"%d", [components hour]);

And so on.

No matching bean of type ... found for dependency

In my case it was the wrong dependecy for CrudRepository. My IDE added also follwing:

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
        <version>1.11.2.RELEASE</version>
    </dependency>

But I just needed:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>RELEASE</version>
    </dependency>

I removed the first one and everything was fine.

remove None value from a list without removing the 0 value

For Python 2.7 (See Raymond's answer, for Python 3 equivalent):

Wanting to know whether something "is not None" is so common in python (and other OO languages), that in my Common.py (which I import to each module with "from Common import *"), I include these lines:

def exists(it):
    return (it is not None)

Then to remove None elements from a list, simply do:

filter(exists, L)

I find this easier to read, than the corresponding list comprehension (which Raymond shows, as his Python 2 version).

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

Begin, Rescue and Ensure in Ruby?

Yes, ensure ENSURES it is run every time, so you don't need the file.close in the begin block.

By the way, a good way to test is to do:

begin
  # Raise an error here
  raise "Error!!"
rescue
  #handle the error here
ensure
  p "=========inside ensure block"
end

You can test to see if "=========inside ensure block" will be printed out when there is an exception. Then you can comment out the statement that raises the error and see if the ensure statement is executed by seeing if anything gets printed out.

How to export SQL Server database to MySQL?

As mentioned above, if your data contains tab characters, commas, or newlines in your data then it's going to be very hard to export and import it with CSV. Values will overflow out of the fields and you will get errors. This problem is even worse if any of your long fields contain multi-line text with newline characters in them.

My method in these cases is to use the BCP command-line utility to export the data from SQL server, then use LOAD DATA INFILE .. INTO TABLE command in MySQL to read the data file back in. BCP is one of the oldest SQL Server command line utilities (dating back to the birth of SQL server - v6.5) but it is still around and still one of the easiest and most reliable ways to get data out.

To use this technique you need to create each destination table with the same or equivalent schema in MySQL. I do that by right clicking the Database in SQL enterprise manager, then Tasks->Generate Scripts... and create a SQL script for all the tables. You must then convert the script to MySQL compatible SQL by hand (definitely the worst part of the job) and finally run the CREATE TABLE commands on the MySQL database so you have matching tables to the SQL server versions column-wise, empty and ready for data.

Then, export the data from the MS-SQL side as follows.

bcp DatabaseName..TableName out TableName.dat -q -c -T -S ServerName -r \0 -t !\t!

(If you're using SQL Server Express, use a -S value like so: -S "ComputerName\SQLExpress")

That will create a file named TableName.dat, with fields delimited by ![tab]! and rows delimited by \0 NUL characters.

Now copy the .dat files into /tmp on the MySQL server and load on the MySQL side like so:

LOAD DATA INFILE '/tmp/TableName.dat' INTO TABLE TableName FIELDS TERMINATED BY '!\t!' LINES TERMINATED BY '\0';

Don't forget that the tables (TableName in this example) must be created already on the MySQL side.

This procedure is painfully manual when it comes to converting the SQL schema over, however it works for even the most difficult of data and because it uses flat files you never need to persuade SQL Server to talk to MySQL, or vice versa.

Renaming branches remotely in Git

If you really just want to rename branches remotely, without renaming any local branches at the same time, you can do this with a single command:

git push <remote> <remote>/<old_name>:refs/heads/<new_name> :<old_name>

I wrote this script (git-rename-remote-branch) which provides a handy shortcut to do the above easily.

As a bash function:

git-rename-remote-branch(){
  if [ $# -ne 3 ]; then
    echo "Rationale : Rename a branch on the server without checking it out."
    echo "Usage     : ${FUNCNAME[0]} <remote> <old name> <new name>"
    echo "Example   : ${FUNCNAME[0]} origin master release"
    return 1 
  fi

  git push $1 $1/$2\:refs/heads/$3 :$2
}

To integrate @ksrb's comment: What this basically does is two pushes in a single command, first git push <remote> <remote>/<old_name>:refs/heads/<new_name> to push a new remote branch based on the old remote tracking branch and then git push <remote> :<old_name> to delete the old remote branch.

How to write Unicode characters to the console?

Console.OutputEncoding Property

https://docs.microsoft.com/en-us/dotnet/api/system.console.outputencoding

Note that successfully displaying Unicode characters to the console requires the following:

  • The console must use a TrueType font, such as Lucida Console or Consolas, to display characters.

Chrome DevTools Devices does not detect device when plugged in

On a Galaxy S7 and Windows 10 laptop, all I had to do whilst connected to the computer was change the USB connection mode to "Audio Source" (Phone Settings > Developer Options > USB Configuration).

This then immediately came up with the on-device prompt to allow the RSA key fingerprint. Then the dev tools on computer recognised my device.

Why this works I do not know, however it is by far the simplest of solutions, and without the need for installing unnecessary software.

I have also had some luck changing it to "MTP (Media Transfer Protocol)" mode too, but only on occasion.

Edit:

The MTP option no longer works for me.

In addition to Audio Source, setting the connection mode to MIDI also works. It is alot easier to change the connection mode by accessing it straight from the device's notification bar - Tap the "Transferring media files via USB" or the equivalent notification.

Using MIDI is probably the easiest of the two since it doesn't require going into several setting screens to access it.

Is it possible to send an array with the Postman Chrome extension?

This also works for lists within the object:

Id:37
IdParent:26
Name:Poplet
Values[0].Id:1349
Values[0].Name:SomeName
Values[1].Id:1350
Values[1].Name:AnotherName

the equivalent JSON would be:

{
    "Id": 37,
    "IdParent": 26,
    "Name": "Poplet",
    "Values": [
        {
            "Id": 1349,
            "Name": "SomeName"
        },
        {
            "Id": 1350,
            "Name": "AnotherName"
        }
    ]
}

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

You may need to change the Appication Pool setting "Enable 32bit Applications" to TRUE in IIS7 if you have at least 1 32bit dll\exe in your project.

How to format a number as percentage in R?

Here's my solution for defining a new function (mostly so I can play around with Curry and Compose :-) ):

library(roxygen)
printpct <- Compose(function(x) x*100, Curry(sprintf,fmt="%1.2f%%"))

Object of class mysqli_result could not be converted to string in

Before using the $result variable, you should use $row = mysqli_fetch_array($result) or mysqli_fetch_assoc() functions.

Like this:

$row = mysqli_fetch_array($result);

and use the $row array as you need.

JQuery get data from JSON array

try this

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

How to leave/exit/deactivate a Python virtualenv

You can use virtualenvwrapper in order to ease the way you work with virtualenv.

Installing virtualenvwrapper:

pip install virtualenvwrapper

If you are using a standard shell, open your ~/.bashrc or ~/.zshrc if you use Oh My Zsh. Add these two lines:

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

To activate an existing virtualenv, use command workon:

$ workon myenv
(myenv)$

In order to deactivate your virtualenv:

(myenv)$ deactivate

Here is my tutorial, step by step on how to install virtualenv and virtualenvwrapper.

Simple PHP calculator

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Calculator</title>
    </head>
    <body>
    HTML Code is here:

         <form method="post">
            <input type="text" name="numb1">
            <input type="text" name="numb2">
            <select name="operator" id="">
               <option>None</option>
               <option>Add</option>
               <option>Subtract</option>
               <option>Multiply</option>
               <option>Divide</option>
               <option>Square</option>
            </select>
            <button type="submit" name="submit" value="submit">Calculate</button>
         </form>

    PHP Code:

        <?php 

            if (isset($_POST['submit'])) {
                $result1 = $_POST['numb1'];
                $result2 = $_POST['numb2'];
                $operator = $_POST['operator'];
                switch ($operator) {
                    case 'None':
                        echo "You need to select any operator";
                        break;
                    case 'Add':
                        echo $result1 + $result2;
                        break;
                    case 'Subtract':
                        echo $result1 - $result2;
                        break;
                    case 'Multiply':
                        echo $result1 * $result2;
                        break;
                    case 'Divide':
                        echo $result1 / $result2;
                        break;
                    case 'Square':
                        echo $result1 ** $result2;
                        break;
                }
            }


         ?>
        enter code here

    </body>
    </html>

Docker: Multiple Dockerfiles in project

Author Note

This answer is out of date. Fig not longer exists and has been replaced by Docker compose. Accepted answers cannot be deleted ....

Docker Compose supports the building of project hierachy. So it's now easy to support a Dockerfile in each sub directory.

+-- docker-compose.yml
+-- project1
¦   +-- Dockerfile
+-- project2
    +-- Dockerfile

Original answer

I just create a directory containing a Dockerfile for each component. Example:

When building the containers just give the directory name and Docker will select the correct Dockerfile.

How to Convert JSON object to Custom C# object?

JSON.Net is your best bet but, depending on the shape of the objects and whether there are circular dependencies, you could use JavaScriptSerializer or DataContractSerializer.

Java: Converting String to and from ByteBuffer and associated problems

Unless things have changed, you're better off with

public static ByteBuffer str_to_bb(String msg, Charset charset){
    return ByteBuffer.wrap(msg.getBytes(charset));
}

public static String bb_to_str(ByteBuffer buffer, Charset charset){
    byte[] bytes;
    if(buffer.hasArray()) {
        bytes = buffer.array();
    } else {
        bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
    }
    return new String(bytes, charset);
}

Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How do I get git to default to ssh and not https for new repositories

Set up a repository's origin branch to be SSH

The GitHub repository setup page is just a suggested list of commands (and GitHub now suggests using the HTTPS protocol). Unless you have administrative access to GitHub's site, I don't know of any way to change their suggested commands.

If you'd rather use the SSH protocol, simply add a remote branch like so (i.e. use this command in place of GitHub's suggested command). To modify an existing branch, see the next section.

$ git remote add origin [email protected]:nikhilbhardwaj/abc.git

Modify a pre-existing repository

As you already know, to switch a pre-existing repository to use SSH instead of HTTPS, you can change the remote url within your .git/config file.

[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    -url = https://github.com/nikhilbhardwaj/abc.git
    +url = [email protected]:nikhilbhardwaj/abc.git

A shortcut is to use the set-url command:

$ git remote set-url origin [email protected]:nikhilbhardwaj/abc.git

More information about the SSH-HTTPS switch

Can I add an image to an ASP.NET button?

.my_btn{ 
  font-family:Arial; 
  font-size:10pt; 
  font-weight:normal; 
  height:30px; 
  line-height:30px; 
  width:98px; 
  border:0px;
  background-image:url('../Images/menu_image.png'); 
  cursor:pointer;
}

<asp:Button ID="clickme" runat="server" Text="Click" CssClass="my_btn" />

How to convert a string with comma-delimited items to a list in Python?

I usually use:

l = [ word.strip() for word in text.split(',') ]

the strip remove spaces around words.

How to get the full URL of a Drupal page?

This method all is old method, in drupal 7 we can get it very simple

    current_path()

and another function with tiny difference

request_path()

Deleting rows with Python in a CSV file

You should have if row[2] != "0". Otherwise it's not checking to see if the string value is equal to 0.

Flatten an irregular list of lists

Generator using recursion and duck typing (updated for Python 3):

def flatten(L):
    for item in L:
        try:
            yield from flatten(item)
        except TypeError:
            yield item

list(flatten([[[1, 2, 3], [4, 5]], 6]))
>>>[1, 2, 3, 4, 5, 6]

How to deploy correctly when using Composer's develop / production switch?

I think is better automate the process:

Add the composer.lock file in your git repository, make sure you use composer.phar install --no-dev when you release, but in you dev machine you could use any composer command without concerns, this will no go to production, the production will base its dependencies in the lock file.

On the server you checkout this specific version or label, and run all the tests before replace the app, if the tests pass you continue the deployment.

If the test depend on dev dependencies, as composer do not have a test scope dependency, a not much elegant solution could be run the test with the dev dependencies (composer.phar install), remove the vendor library, run composer.phar install --no-dev again, this will use cached dependencies so is faster. But that is a hack if you know the concept of scopes in other build tools

Automate this and forget the rest, go drink a beer :-)

PS.: As in the @Sven comment bellow, is not a good idea not checkout the composer.lock file, because this will make composer install work as composer update.

You could do that automation with http://deployer.org/ it is a simple tool.

Find an element in a list of tuples

Read up on List Comprehensions

[ (x,y) for x, y in a if x  == 1 ]

Also read up up generator functions and the yield statement.

def filter_value( someList, value ):
    for x, y in someList:
        if x == value :
            yield x,y

result= list( filter_value( a, 1 ) )

Is there a foreach loop in Go?

I have jus implement this library:https://github.com/jose78/go-collection. This is an example about how to use the Foreach loop:

package main

import (
    "fmt"

    col "github.com/jose78/go-collection/collections"
)

type user struct {
    name string
    age  int
    id   int
}

func main() {
    newList := col.ListType{user{"Alvaro", 6, 1}, user{"Sofia", 3, 2}}
    newList = append(newList, user{"Mon", 0, 3})

    newList.Foreach(simpleLoop)
    
    if err := newList.Foreach(simpleLoopWithError); err != nil{
        fmt.Printf("This error >>> %v <<< was produced", err )  
    }
}

var simpleLoop col.FnForeachList = func(mapper interface{}, index int) {
    fmt.Printf("%d.- item:%v\n", index, mapper)
}


var simpleLoopWithError col.FnForeachList = func(mapper interface{}, index int) {
    if index > 1{
        panic(fmt.Sprintf("Error produced with index == %d\n", index))
    }
    fmt.Printf("%d.- item:%v\n", index, mapper)
}

The result of this execution should be:

0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
2.- item:{Mon 0 3}
0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
Recovered in f Error produced with index == 2

ERROR: Error produced with index == 2
This error >>> Error produced with index == 2
 <<< was produced

Try this code in playGrounD

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

The answer is misleading because it attempts to fix a problem that is not a problem. You actually CAN have a WHERE CLAUSE in each segment of a UNION. You cannot have an ORDER BY except in the last segment. Therefore, this should work...

select top 2 t1.ID, t1.ReceivedDate
from Table t1
where t1.Type = 'TYPE_1'
-----remove this-- order by ReceivedDate desc
union
select top 2 t2.ID,  t2.ReceivedDate --- add second column
  from Table t2
 where t2.Type = 'TYPE_2'
order by ReceivedDate desc

What are CN, OU, DC in an LDAP search?

At least with Active Directory, I have been able to search by DistinguishedName by doing an LDAP query in this format (assuming that such a record exists with this distinguishedName):

"(distinguishedName=CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com)"

How can I send a file document to the printer and have it print?

You can use the DevExpress PdfDocumentProcessor.Print(PdfPrinterSettings) Method.

public void Print(string pdfFilePath)
{
      if (!File.Exists(pdfFilePath))
          throw new FileNotFoundException("No such file exists!", pdfFilePath);

      // Create a Pdf Document Processor instance and load a PDF into it.
      PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor();
      documentProcessor.LoadDocument(pdfFilePath);

      if (documentProcessor != null)
      {
          PrinterSettings settings = new PrinterSettings();

          //var paperSizes = settings.PaperSizes.Cast<PaperSize>().ToList();
          //PaperSize sizeCustom = paperSizes.FirstOrDefault<PaperSize>(size => size.Kind == PaperKind.Custom); // finding paper size

          settings.DefaultPageSettings.PaperSize = new PaperSize("Label", 400, 600);

          // Print pdf
          documentProcessor.Print(settings);
      }
}

OS X Bash, 'watch' command

Here's a slightly changed version of this answer that:

  • checks for valid args
  • shows a date and duration title at the top
  • moves the "duration" argument to be the 1st argument, so complex commands can be easily passed as the remaining arguments.

To use it:

  • Save this to ~/bin/watch
  • execute chmod 700 ~/bin/watch in a terminal to make it executable.
  • try it by running watch 1 echo "hi there"

~/bin/watch

#!/bin/bash

function show_help()
{
  echo ""
  echo "usage: watch [sleep duration in seconds] [command]"
  echo ""
  echo "e.g. To cat a file every second, run the following"
  echo ""
  echo "     watch 1 cat /tmp/it.txt" 
  exit;
}

function show_help_if_required()
{
  if [ "$1" == "help" ]
  then
      show_help
  fi
  if [ -z "$1" ]
    then
      show_help
  fi
}

function require_numeric_value()
{
  REG_EX='^[0-9]+$'
  if ! [[ $1 =~ $REG_EX ]] ; then
    show_help
  fi
}

show_help_if_required $1
require_numeric_value $1

DURATION=$1
shift

while :; do 
  clear
  echo "Updating every $DURATION seconds. Last updated $(date)"
  bash -c "$*"
  sleep $DURATION
done

phpMyAdmin says no privilege to create database, despite logged in as root user

It appears to be a transient issue and fixed itself afterwards. Thanks for everyone's attention.

delete vs delete[] operators in C++

delete is used for one single pointer and delete[] is used for deleting an array through a pointer. This might help you to understand better.

chrome undo the action of "prevent this page from creating additional dialogs"

There seems to be a process that suppresses all console.log messages if there are too many alerts in a JS script. That's a problem if you are trying to debug a script. I've been running a script on Chrome and Brave and all of a sudden console.log messages were stopped. Yet with Firefox all the console.log messages still appear... same exact script. The problem is not checking or unchecking the warnings, errors, and debug messages.

I'm at a loss for this... is it Windows blocking "a site"? I tried clearing the cache resetting all settings in Chrome, yet the problem still remains. I suppose I could try reinstalling both browsers.

offsetTop vs. jQuery.offset().top

It is possible that the offset could be a non-integer, using em as the measurement unit, relative font-sizes in %.

I also theorise that the offset might not be a whole number when the zoom isn't 100% but that depends how the browser handles scaling.

How to swap two variables in JavaScript

var a = 5;
var b = 10;

b = [a, a = b][0];
//or
b = [a, a = b];
b = b[0];

//or
b = [a, b];
a = b[1];
b = b[0];


alert("a=" + a + ',' + "b=" + b);

remove or comment the 2 //or's and run with the one set of code

http://jsfiddle.net/USdv8/57/

FIFO class in Java

You're looking for any class that implements the Queue interface, excluding PriorityQueue and PriorityBlockingQueue, which do not use a FIFO algorithm.

Probably a LinkedList using add (adds one to the end) and removeFirst (removes one from the front and returns it) is the easiest one to use.

For example, here's a program that uses a LinkedList to queue and retrieve the digits of PI:

import java.util.LinkedList;

class Test {
    public static void main(String args[]) {
        char arr[] = {3,1,4,1,5,9,2,6,5,3,5,8,9};
        LinkedList<Integer> fifo = new LinkedList<Integer>();

        for (int i = 0; i < arr.length; i++)
            fifo.add (new Integer (arr[i]));

        System.out.print (fifo.removeFirst() + ".");
        while (! fifo.isEmpty())
            System.out.print (fifo.removeFirst());
        System.out.println();
    }
} 

Alternatively, if you know you only want to treat it as a queue (without the extra features of a linked list), you can just use the Queue interface itself:

import java.util.LinkedList;
import java.util.Queue;

class Test {
    public static void main(String args[]) {
        char arr[] = {3,1,4,1,5,9,2,6,5,3,5,8,9};
        Queue<Integer> fifo = new LinkedList<Integer>();

        for (int i = 0; i < arr.length; i++)
            fifo.add (new Integer (arr[i]));

        System.out.print (fifo.remove() + ".");
        while (! fifo.isEmpty())
            System.out.print (fifo.remove());
        System.out.println();
    }
}

This has the advantage of allowing you to replace the underlying concrete class with any class that provides the Queue interface, without having to change the code too much.

The basic changes are to change the type of fifo to a Queue and to use remove() instead of removeFirst(), the latter being unavailable for the Queue interface.

Calling isEmpty() is still okay since that belongs to the Collection interface of which Queue is a derivative.

Find size of object instance in bytes in c#

For value types, you can use Marshal.SizeOf. Of course, it returns the number of bytes required to marshal the structure in unmanaged memory, which is not necessarily what the CLR uses.

git stash apply version

To view your recent work and what branch it happened on run

git stash list

then select the stash to apply and use only number:

git stash apply n

Where n (in the above sample) is that number corresponding to the Work In Progress.

Apache - MySQL Service detected with wrong path. / Ports already in use

Set XAMPP controlpanel to run under Administrator priviledges.

In Win 7 1. First make sure XAMPP control panel is not running 2. SHIFT+right click on XAMPP Control Panel 3. Click on properties 4. In properties select tab 'Compatibility' 5. On bottom of the tab under 'Privilege level' check the box "Run this program as an administrator" 6. Click OK

this worked for me

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

OS specific instructions in CMAKE: How to?

In General

You can detect and specify variables for several operating systems like that:

Detect Microsoft Windows

if(WIN32)
    # for Windows operating system in general
endif()

Or:

if(MSVC OR MSYS OR MINGW)
    # for detecting Windows compilers
endif()

Detect Apple MacOS

if(APPLE)
    # for MacOS X or iOS, watchOS, tvOS (since 3.10.3)
endif()

Detect Unix and Linux

if(UNIX AND NOT APPLE)
    # for Linux, BSD, Solaris, Minix
endif()

Your specific linker issue

To solve your issue with the Windows-specific wsock32 library, just remove it from other systems, like that:

if(WIN32)
    target_link_libraries(${PROJECT_NAME} bioutils wsock32)
else
    target_link_libraries(${PROJECT_NAME} bioutils)
endif()

How to get RegistrationID using GCM in android

In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.

In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.

Jenkins Host key verification failed

Try

ssh-keygen -R hostname

-R hostname Removes all keys belonging to hostname from a known_hosts file. This option is useful to delete hashed hosts

Comparing boxed Long values 127 and 128

Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.

This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127, whichever is bigger.(We can set top level value upto which Integer values should get cached by using java.lang.Integer.IntegerCache.high).

 For example:
    If we set java.lang.Integer.IntegerCache.high=500;
    then values from -128 to 500 will get cached and 

    Integer a=498;
    Integer b=499;
    System.out.println(a==b)

    Output will be "true".

Float and Double objects never gets cached.

Character will get cache from 0 to 127

You are comparing two objects. so == operator will check equality of object references. There are following ways to do it.

1) type cast both objects into primitive values and compare

    (long)val3 == (long)val4

2) read value of object and compare

    val3.longValue() == val4.longValue()

3) Use equals() method on object comparison.

    val3.equals(val4);  

Returning multiple objects in an R function

One way to handle this is to put the information as an attribute on the primary one. I must stress, I really think this is the appropriate thing to do only when the two pieces of information are related such that one has information about the other.

For example, I sometimes stash the name of "crucial variables" or variables that have been significantly modified by storing a list of variable names as an attribute on the data frame:

attr(my.DF, 'Modified.Variables') <- DVs.For.Analysis$Names.of.Modified.Vars
return(my.DF)

This allows me to store a list of variable names with the data frame itself.

Error CS1705: "which has a higher version than referenced assembly"

One possible cause is that the second assembly is installed in GAC while the first assembly, with a higher version number, is added to the References of the project. To verify this, double click the assembly in the project references, and check if there is another assembly with the same name in the Object Browser.

If that is the case, use the gacutil.exe utility to uninstall the second assembly from the GAC. For example, if these are 64-bit assemblies:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\x64\gacutil.exe -u <assembly_name>

Is there a vr (vertical rule) in html?

You can use css for simulate a vertical line, and use the class on the div

.vhLine {
  border-left: thick solid #000000;
}

Getting unique values in Excel by using formulas only

You can also do it this way.

Create the following named ranges:

nList = the list of original values
nRow = ROW(nList)-ROW(OFFSET(nList,0,0,1,1))+1
nUnique = IF(COUNTIF(OFFSET(nList,nRow,0),nList)=0,COUNTIF(nList, "<"&nList),"")

With these 3 named ranges you can generate the ordered list of unique values with the formula below. It will be sorted in ascending order.

IFERROR(INDEX(nList,MATCH(SMALL(nUnique,ROW()-?),nUnique,0)),"")

You will need to substitute the row number of the cell just above the first element of your unique ordered list for the '?' character.

eg. If your unique ordered list begins in cell B5 then the formula will be:

IFERROR(INDEX(nList,MATCH(SMALL(nUnique,ROW()-4),nUnique,0)),"")

How to change the project in GCP using CLI commands

For what its worth if you have a more than a handful of projects, which I do, use:

gcloud init

This will list all your projects and give you the option to change current project settings, add a new project configuration or switch:

Pick configuration to use:
 [1] Re-initialize this configuration [esqimo-preprod] with new settings
 [2] Create a new configuration
 [3] Switch to and re-initialize existing configuration: [default]
 [4] Switch to and re-initialize existing configuration: [project 1]
 [5] Switch to and re-initialize existing configuration: [project 2]
Please enter your numeric choice:

It will always ask you to login and display options for different google accounts that you may have.

Given that I manage multiple organisations and projects this approach lets' me to simply switch between them.

Why would you use String.Equals over ==?

I've just been banging my head against a wall trying to solve a bug because I read this page and concluded there was no meaningful difference when in practice there is so I'll post this link here in case anyone else finds they get different results out of == and equals.

Object == equality fails, but .Equals succeeds. Does this make sense?

string a = "x";
string b = new String(new []{'x'});

Console.WriteLine("x == x " + (a == b));//True
Console.WriteLine("object x == x " + ((object)a == (object)b));//False
Console.WriteLine("x equals x " + (a.Equals(b)));//True
Console.WriteLine("object x equals x " + (((object)a).Equals((object)b)));//True

How do I show the schema of a table in a MySQL database?

SHOW CREATE TABLE yourTable;

or

SHOW COLUMNS FROM yourTable;

Convert String to Carbon

Try this

$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;

Best way to convert an ArrayList to a string

Would the following be any good:

List<String> streamValues = new ArrayList<>();
Arrays.deepToString(streamValues.toArray()));   

Leave out quotes when copying from cell

Possible problem in relation to answer from "user3616725":
Im on Windows 8.1 and there seems to be a problem with the linked VBA code from accepted answer from "user3616725":

Sub CopyCellContents()
 ' !!! IMPORTANT !!!:
 ' CREATE A REFERENCE IN THE VBE TO "Microsft Forms 2.0 Library" OR "Microsft Forms 2.0 Object Library"
 ' DO THIS BY (IN VBA EDITOR) CLICKING TOOLS -> REFERENCES & THEN TICKING "Microsoft Forms 2.0 Library" OR "Microsft Forms 2.0 Object Library"
 Dim objData As New DataObject
 Dim strTemp As String
 strTemp = ActiveCell.Value
 objData.SetText (strTemp)
 objData.PutInClipboard
End Sub

Details:
Running above code and pasting clipboard into a cell in Excel I get two symbols composed of squares with a question mark inside, like this: ??. Pasting into Notepad doesn't even show anything.

Solution:
After searching for quite some time I found another VBA script from user "Nepumuk" which makes use of the Windows API. Here's his code that finally worked for me:

Option Explicit

Private Declare Function OpenClipboard Lib "user32.dll" ( _
    ByVal hwnd As Long) As Long
Private Declare Function CloseClipboard Lib "user32.dll" () As Long
Private Declare Function EmptyClipboard Lib "user32.dll" () As Long
Private Declare Function SetClipboardData Lib "user32.dll" ( _
    ByVal wFormat As Long, _
    ByVal hMem As Long) As Long
Private Declare Function GlobalAlloc Lib "kernel32.dll" ( _
    ByVal wFlags As Long, _
    ByVal dwBytes As Long) As Long
Private Declare Function GlobalLock Lib "kernel32.dll" ( _
    ByVal hMem As Long) As Long
Private Declare Function GlobalUnlock Lib "kernel32.dll" ( _
    ByVal hMem As Long) As Long
Private Declare Function GlobalFree Lib "kernel32.dll" ( _
    ByVal hMem As Long) As Long
Private Declare Function lstrcpy Lib "kernel32.dll" ( _
    ByVal lpStr1 As Any, _
    ByVal lpStr2 As Any) As Long

Private Const CF_TEXT As Long = 1&

Private Const GMEM_MOVEABLE As Long = 2

Public Sub Beispiel()
    Call StringToClipboard("Hallo ...")
End Sub

Private Sub StringToClipboard(strText As String)
    Dim lngIdentifier As Long, lngPointer As Long
    lngIdentifier = GlobalAlloc(GMEM_MOVEABLE, Len(strText) + 1)
    lngPointer = GlobalLock(lngIdentifier)
    Call lstrcpy(ByVal lngPointer, strText)
    Call GlobalUnlock(lngIdentifier)
    Call OpenClipboard(0&)
    Call EmptyClipboard
    Call SetClipboardData(CF_TEXT, lngIdentifier)
    Call CloseClipboard
    Call GlobalFree(lngIdentifier)
End Sub

To use it the same way like the first VBA code from above, change the Sub "Beispiel()" from:

Public Sub Beispiel()
    Call StringToClipboard("Hallo ...")
End Sub

To:

Sub CopyCellContents()
    Call StringToClipboard(ActiveCell.Value)
End Sub

And run it via Excel macro menu like suggested from "user3616725" from accepted answer:

Back in Excel, go Tools>Macro>Macros and select the macro called "CopyCellContents" and then choose Options from the dialog. Here you can assign the macro to a shortcut key (eg like Ctrl+c for normal copy) - I used Ctrl+q.

Then, when you want to copy a single cell over to Notepad/wherever, just do Ctrl+q (or whatever you chose) and then do a Ctrl+v or Edit>Paste in your chosen destination.


Edit (21st of November in 2015):
@ comment from "dotctor":
No, this seriously is no new question! In my opinion it is a good addition for the accepted answer as my answer addresses problems that you can face when using the code from the accepted answer. If I would have more reputation, I would have created a comment.
@ comment from "Teepeemm":
Yes, you are right, answers beginning with title "Problem:" are misleading. Changed to: "Possible problem in relation to answer from "user3616725":". As a comment I certainly would have written much more compact.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

How to store JSON object in SQLite database

An alternative could be to use the new JSON extension for SQLite. I've only just come across this myself: https://www.sqlite.org/json1.html This would allow you to perform a certain level of querying the stored JSON. If you used VARCHAR or TEXT to store a JSON string you would have no ability to query it. This is a great article showing its usage (in python) http://charlesleifer.com/blog/using-the-sqlite-json1-and-fts5-extensions-with-python/

How do you render primitives as wireframes in OpenGL?

use this function: void glPolygonMode( GLenum face, GLenum mode);

face : Specifies the polygons that mode applies to. can be GL_FRONT for front side of the polygone and GL_BACK for his back and GL_FRONT_AND_BACK for both.

mode : Three modes are defined and can be specified in mode:

GL_POINT :Polygon vertices that are marked as the start of a boundary edge are drawn as points.

GL_LINE : Boundary edges of the polygon are drawn as line segments. (your target)

GL_FILL : The interior of the polygon is filled.

P.S : glPolygonMode controls the interpretation of polygons for rasterization in the graphics pipeline.

for more information look at the OpenGL reference pages in khronos group : https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glPolygonMode.xhtml

ImportError: No module named 'bottle' - PyCharm

In the case where you are able to import the module when using the CLI interpreter but not in PyCharm, make sure your project interpreter in PyCharm is set to an actual interpreter (eg. /usr/bin/python2.7) and not venv (~/PycharmProject/venv/...)

How to read a text file in project's root directory?

You can have it embedded (build action set to Resource) as well, this is how to retrieve it from there:

private static UnmanagedMemoryStream GetResourceStream(string resName)
{
    var assembly = Assembly.GetExecutingAssembly();
    var strResources = assembly.GetName().Name + ".g.resources";
    var rStream = assembly.GetManifestResourceStream(strResources);
    var resourceReader = new ResourceReader(rStream);
    var items = resourceReader.OfType<DictionaryEntry>();
    var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
    return (UnmanagedMemoryStream)stream;
}

private void Button1_Click(object sender, RoutedEventArgs e)
{
    string resName = "Test.txt";
    var file = GetResourceStream(resName);
    using (var reader = new StreamReader(file))
    {
        var line = reader.ReadLine();
        MessageBox.Show(line);
    }
}

(Some code taken from this answer by Charles)

openssl s_client using a proxy

You can use proxytunnel:

proxytunnel -p yourproxy:8080 -d www.google.com:443 -a 7000

and then you can do this:

openssl s_client -connect localhost:7000 -showcerts

Hope this can help you!

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

How do I handle newlines in JSON?

JSON.stringify

JSON.stringify(`{ 
  a:"a"
}`)

would convert the above string to

"{ \n      a:\"a\"\n    }"

as mentioned here

json stringify

This function adds double quotes at the beginning and end of the input string and escapes special JSON characters. In particular, a newline is replaced by the \n character, a tab is replaced by the \t character, a backslash is replaced by two backslashes \, and a backslash is placed before each quotation mark.

fetch in git doesn't get all branches

To make it more specific Create a tracking branch, which means you are now tracking a remote branch.

git branch --track branch remote-branch
git branch --track exp remotes/origin/experimental

After which you can

git branch   # to see the remote tracking branch "exp" created .

Then to work on that branch do

git checkout branchname
git checkout exp

After you have made changes to the branch. You can git fetch and git merge with your remote tracking branch to merge your changes and push to the remote branch as below.

git fetch origin
git merge origin/experimental  
git push origin/experimental

Hope it helps and gives you an idea, how this works.

How do I increase the scrollback buffer in a running screen session?

WARNING: setting this value too high may cause your system to experience a significant hiccup. The higher the value you set, the more virtual memory is allocated to the screen process when initiating the screen session. I set my ~/.screenrc to "defscrollback 123456789" and when I initiated a screen, my entire system froze up for a good 10 minutes before coming back to the point that I was able to kill the screen process (which was consuming 16.6GB of VIRT mem by then).

Correct way to integrate jQuery plugins in AngularJS

i have alreay 2 situations where directives and services/factories didnt play well.

the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

i even tried to make a directive with a controller and an isolated-scope

only when i moved everything to a controller and it worked like magic.

example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

get next and previous day with PHP

strtotime('-1 day', strtotime($date))

This returns the number of difference in seconds of the given date and the $date.so you are getting wrong result .

Suppose $date is todays date and -1 day means it returns -86400 as the difference and the when you try using date you will get 1969-12-31 Unix timestamp start date.

How to "add existing frameworks" in Xcode 4?

The frameworks directory is as follow in my computer: /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/System/Library/Frameworks

not the directory

/Developer/SDKs/MacOSXversion.sdk/System/Library/Frameworks

Check for column name in a SqlDataReader object

Here is a working sample for Jasmin's idea:

var cols = r.GetSchemaTable().Rows.Cast<DataRow>().Select
    (row => row["ColumnName"] as string).ToList(); 

if (cols.Contains("the column name"))
{

}

How to use phpexcel to read data and insert into database?

Using the PHPExcel library to read an Excel file and transfer the data into a database

//  Include PHPExcel_IOFactory
include 'PHPExcel/IOFactory.php';

$inputFileName = './sampleData/example1.xls';

//  Read your Excel workbook
try {
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
    die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}

//  Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0); 
$highestRow = $sheet->getHighestRow(); 
$highestColumn = $sheet->getHighestColumn();

//  Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){ 
    //  Read a row of data into an array
    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                                    NULL,
                                    TRUE,
                                    FALSE);
    //  Insert row data array into your database of choice here
}

Anything more becomes very dependent on your database, and how you want the data structured in it

Writing file to web server - ASP.NET

protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
    using (StreamWriter w = new StreamWriter(Server.MapPath("~/data.txt"), true))
    {
        w.WriteLine(TextBox1.Text); // Write the text
    }
}

Django - what is the difference between render(), render_to_response() and direct_to_template()?

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render

render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app])

render() is a brand spanking new shortcut for render_to_response in 1.3 that will automatically use RequestContext that I will most definitely be using from now on.


2020 EDIT: It should be noted that render_to_response() was removed in Django 3.0

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response

render_to_response(template[, dictionary][, context_instance][, mimetype])¶

render_to_response is your standard render function used in the tutorials and such. To use RequestContext you'd have to specify context_instance=RequestContext(request)


https://docs.djangoproject.com/en/1.8/ref/generic-views/#django-views-generic-simple-direct-to-template

direct_to_template is a generic view that I use in my views (as opposed to in my urls) because like the new render() function, it automatically uses RequestContext and all its context_processors.

But direct_to_template should be avoided as function based generic views are deprecated. Either use render or an actual class, see https://docs.djangoproject.com/en/1.3/topics/generic-views-migration/

I'm happy I haven't typed RequestContext in a long, long time.

How to end a session in ExpressJS

req.session.destroy(); 

The above did not work for me so I did this.

req.session.cookie.expires = new Date().getTime();

By setting the expiration of the cookie to the current time, the session expired on its own.

Bootstrap 4 datapicker.js not included

You can use this and then you can add just a class form from bootstrap. (does not matter which version)

<div class="form-group">
 <label >Begin voorverkoop periode</label>
 <input type="date" name="bday" max="3000-12-31" 
        min="1000-01-01" class="form-control">
</div>
<div class="form-group">
 <label >Einde voorverkoop periode</label>
 <input type="date" name="bday" min="1000-01-01"
        max="3000-12-31" class="form-control">
</div>

How do I load a file from resource folder?

Try Flowing codes on Spring project

ClassPathResource resource = new ClassPathResource("fileName");
InputStream inputStream = resource.getInputStream();

Or on non spring project

 ClassLoader classLoader = getClass().getClassLoader();
 File file = new File(classLoader.getResource("fileName").getFile());
 InputStream inputStream = new FileInputStream(file);

Connect Android Studio with SVN

Go to File->Settings->Version Control->Subversion enter the path for your SVN executable in the General tab under Subversion configuration directory. Also, you can download a latest SVN client such as VisualSVN and point the path to the executable as mentioned above. That will most likely solve your problem.

Select all text inside EditText when it gets focus

SelectAllOnFocus works the first time the EditText gets focus, but if you want to select the text every time the user clicks on it, you need to call editText.clearFocus() in between times.

For example, if your app has one EditText and one button, clicking the button after changing the EditText leaves the focus in the EditText. Then the user has to use the cursor handle and the backspace key to delete what's in the EditText before they can enter a new value. So call editText.clearFocus() in the Button's onClick method.

How to get the selected radio button’s value?

    var value = $('input:radio[name="radiogroupname"]:checked').val();