Programs & Examples On #Kindle

Kindle eBook Reader

New warnings in iOS 9: "all bitcode will be dropped"

In my case for avoiding that problem:

  1. Be sure that you are dealing with Xcode 7, NOT lower versions. In lower version this flag does not exist.

  2. Setup: Project>Build Settings>All>Build Options>Enable Bitcode = NO

enter image description here

Spring Boot - Cannot determine embedded database driver class for database type NONE

If you really need "spring-boot-starter-data-jpa" as your project dependency and at the same time you don't want to allow your app to access any database, you can simply exclude auto-configuration classes

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

Google Spreadsheet, Count IF contains a string

You should use

=COUNTIF(A2:A51, "*iPad*")/COUNTA(A2:A51)

Additionally, if you wanted to count more than one element, like iPads OR Kindles, you would use

=SUM(COUNTIF(A2:A51, {"*iPad*", "*kindle*"}))/COUNTA(A2:A51)

in the numerator.

Insert variable into Header Location PHP

We can also use this with the $_GET method

$employee_id = 'EMP-1234';

header('Location: employee.php?id='.$employee_id);

Mobile Redirect using htaccess

I tested bits and pieces of the following, but not the complete rule set in its entirety, so if you run into trouble with it let me know and I'll dig around a bit more. However, assuming I got everything correct, you could try something like the following:

RewriteEngine On

# Check if this is the noredirect query string
RewriteCond %{QUERY_STRING} (^|&)noredirect=true(&|$)
# Set a cookie, and skip the next rule
RewriteRule ^ - [CO=mredir:0:%{HTTP_HOST},S]

# Check if this looks like a mobile device
# (You could add another [OR] to the second one and add in what you
#  had to check, but I believe most mobile devices should send at
#  least one of these headers)
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP:Profile}       !^$
# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST}          !^m\.
# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP:Cookie}        !\smredir=0(;|$)
# Now redirect to the mobile site
RewriteRule ^ http://m.example.org%{REQUEST_URI} [R,L]

ImportError: No module named 'django.core.urlresolvers'

To solve this either you down-grade the Django to any version lesser than 2.0. pip install Django==1.11.29.

How do I get a python program to do nothing?

The pass command is what you are looking for. Use pass for any construct that you want to "ignore". Your example uses a conditional expression but you can do the same for almost anything.

For your specific use case, perhaps you'd want to test the opposite condition and only perform an action if the condition is false:

if num2 != num5:
    make_some_changes()

This will be the same as this:

if num2 == num5:
    pass
else:
    make_some_changes()

That way you won't even have to use pass and you'll also be closer to adhering to the "Flatter is better than nested" convention in PEP20.


You can read more about the pass statement in the documentation:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

if condition:
    pass
try:
    make_some_changes()
except Exception:
    pass # do nothing
class Foo():
    pass # an empty class definition
def bar():
    pass # an empty function definition

Convert date time string to epoch in Bash

get_curr_date () {
    # get unix time
    DATE=$(date +%s)
    echo "DATE_CURR : "$DATE
}

conv_utime_hread () {
    # convert unix time to human readable format
    DATE_HREAD=$(date -d @$DATE +%Y%m%d_%H%M%S)
    echo "DATE_HREAD          : "$DATE_HREAD
}

How can I use goto in Javascript?

There is a way this can be done, but it needs to be planned carefully. Take for example the following QBASIC program:

1 A = 1; B = 10;
10 print "A = ",A;
20 IF (A < B) THEN A = A + 1; GOTO 10
30 PRINT "That's the end."

Then create your JavaScript to initialize all variables first, followed by making an initial function call to start the ball rolling (we execute this initial function call at the end), and set up functions for every set of lines that you know will be executed in the one unit.

Follow this with the initial function call...

var a, b;
function fa(){
    a = 1;
    b = 10;
    fb();
}
function fb(){
    document.write("a = "+ a + "<br>");
    fc();
}
function fc(){
    if(a<b){
        a++;
        fb();
        return;
    }
    else
    {
    document.write("That's the end.<br>");
    }
}
fa();

The result in this instance is:

a = 1
a = 2
a = 3
a = 4
a = 5
a = 6
a = 7
a = 8
a = 9
a = 10
That's the end.

How can I get the file name from request.FILES?

file = request.FILES['filename']
file.name           # Gives name
file.content_type   # Gives Content type text/html etc
file.size           # Gives file's size in byte
file.read()         # Reads file

Inserting records into a MySQL table using Java

There is a mistake in your insert statement chage it to below and try : String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

How to visualize an XML schema?

We use Liquid XML Studio, it provides a intuitive editable representation of an XSD schema. It also shows the annotations inline, which we find very useful and the split code/gfx view is invaluable when writting or editing an XSD.

Liquid XML Studio XSD Editor

Perform an action in every sub-directory using Bash

find . -type d -print0 | xargs -0 -n 1 my_command

How can I convert a stack trace to a string?

Kotlin

Extending the Throwable class will give you the String property error.stackTraceString:

val Throwable.stackTraceString: String
  get() {
    val sw = StringWriter()
    val pw = PrintWriter(sw)
    this.printStackTrace(pw)
    return sw.toString()
  }

jQuery select box validation

simplify the whole thing a bit, fix some issues with commas which will blow up some browsers:

  $(document).ready(function () {
       $("#register").validate({
           debug: true,
           rules: {
               year: {
                   required: function () {
                       return ($("#year option:selected").val() == "0");
                   }
               }
           },
           messages: {
               year: "Year Required"
           }
       });
   });

Jumping to an assumption, should your select not have this attribute validate="required:true"?

Joda DateTime to Timestamp conversion

It is a common misconception that time (a measurable 4th dimension) is different over the world. Timestamp as a moment in time is unique. Date however is influenced how we "see" time but actually it is "time of day".

An example: two people look at the clock at the same moment. The timestamp is the same, right? But one of them is in London and sees 12:00 noon (GMT, timezone offset is 0), and the other is in Belgrade and sees 14:00 (CET, Central Europe, daylight saving now, offset is +2).

Their perception is different but the moment is the same.

You can find more details in this answer.

UPDATE

OK, it's not a duplicate of this question but it is pointless since you are confusing the terms "Timestamp = moment in time (objective)" and "Date[Time] = time of day (subjective)".

Let's look at your original question code broken down like this:

// Get the "original" value from database.
Timestamp momentFromDB = rs.getTimestamp("anytimestampcolumn");

// Turn it into a Joda DateTime with time zone.
DateTime dt = new DateTime(momentFromDB, DateTimeZone.forID("anytimezone"));

// And then turn it back into a timestamp but "with time zone".
Timestamp ts = new Timestamp(dt.getMillis());

I haven't run this code but I am certain it will print true and the same number of milliseconds each time:

System.out.println("momentFromDB == dt : " + (momentFromDB.getTime() == dt.getTimeInMillis());
System.out.println("momentFromDB == ts : " + (momentFromDB.getTime() == ts.getTime()));
System.out.println("dt == ts : " + (dt.getTimeInMillis() == ts.getTime()));

System.out.println("momentFromDB [ms] : " + momentFromDB.getTime());
System.out.println("ts [ms] : " + ts.getTime());
System.out.println("dt [ms] : " + dt.getTimeInMillis());

But as you said yourself printing them out as strings will result in "different" time because DateTime applies the time zone. That's why "time" is stored and transferred as Timestamp objects (which basically wraps a long) and displayed or entered as Date[Time].

In your own answer you are artificially adding an offset and creating a "wrong" time. If you use that timestamp to create another DateTime and print it out it will be offset twice.

// Turn it back into a Joda DateTime with time zone.
DateTime dt = new DateTime(ts, DateTimeZone.forID("anytimezone"));

P.S. If you have the time go through the very complex Joda Time source code to see how it holds the time (millis) and how it prints it.

JUnit Test as proof

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.junit.Before;
import org.junit.Test;


public class WorldTimeTest {
    private static final int MILLIS_IN_HOUR = 1000 * 60 * 60;
    private static final String ISO_FORMAT_NO_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSS";
    private static final String ISO_FORMAT_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    private TimeZone londonTimeZone;
    private TimeZone newYorkTimeZone;
    private TimeZone sydneyTimeZone;
    private long nowInMillis;
    private Date now;

    public static SimpleDateFormat createDateFormat(String pattern, TimeZone timeZone) throws Exception {
        SimpleDateFormat result = new SimpleDateFormat(pattern);
        // Must explicitly set the time zone with "setCalendar()".
        result.setCalendar(Calendar.getInstance(timeZone));
        return result;
    }

    public static SimpleDateFormat createDateFormat(String pattern) throws Exception {
        return createDateFormat(pattern, TimeZone.getDefault());
    }

    public static SimpleDateFormat createDateFormat() throws Exception {
        return createDateFormat(ISO_FORMAT_WITH_TZ, TimeZone.getDefault());
    }

    public void printSystemInfo() throws Exception {
        final String[] propertyNames = {
                "java.runtime.name", "java.runtime.version", "java.vm.name", "java.vm.version",
                "os.name", "os.version", "os.arch",
                "user.language", "user.country", "user.script", "user.variant",
                "user.language.format", "user.country.format", "user.script.format",
                "user.timezone" };

        System.out.println();
        System.out.println("System Information:");
        for (String name : propertyNames) {
            if (name == null || name.length() == 0) {
                continue;
            }
            String value = System.getProperty(name);
            if (value != null && value.length() > 0) {
                System.out.println("  " + name + " = " + value);
            }
        }

        final TimeZone defaultTZ = TimeZone.getDefault();
        final int defaultOffset = defaultTZ.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final int userOffset = TimeZone.getTimeZone(System
                .getProperty("user.timezone")).getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final Locale defaultLocale = Locale.getDefault();

        System.out.println("  default.timezone-offset (hours) = " + userOffset);
        System.out.println("  default.timezone = " + defaultTZ.getDisplayName());
        System.out.println("  default.timezone.id = " + defaultTZ.getID());
        System.out.println("  default.timezone-offset (hours) = " + defaultOffset);
        System.out.println("  default.locale = "
                + defaultLocale.getLanguage() + "_" + defaultLocale.getCountry()
                + " (" + defaultLocale.getDisplayLanguage()
                + "," + defaultLocale.getDisplayCountry() + ")");
        System.out.println("  now = " + nowInMillis + " [ms] or "
                + createDateFormat().format(now));
        System.out.println();
    }

    @Before
    public void setUp() throws Exception {
        // Remember this moment.
        now = new Date();
        nowInMillis = now.getTime(); // == System.currentTimeMillis();

        // Print out some system information.
        printSystemInfo();

        // "Europe/London" time zone is DST aware, we'll use fixed offset.
        londonTimeZone = TimeZone.getTimeZone("GMT");
        // The same applies to "America/New York" time zone ...
        newYorkTimeZone = TimeZone.getTimeZone("GMT-5");
        // ... and for the "Australia/Sydney" time zone.
        sydneyTimeZone = TimeZone.getTimeZone("GMT+10");
    }

    @Test
    public void testDateFormatting() throws Exception {
        int londonOffset = londonTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR; // in hours
        Calendar londonCalendar = Calendar.getInstance(londonTimeZone);
        londonCalendar.setTime(now);

        int newYorkOffset = newYorkTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar newYorkCalendar = Calendar.getInstance(newYorkTimeZone);
        newYorkCalendar.setTime(now);

        int sydneyOffset = sydneyTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar sydneyCalendar = Calendar.getInstance(sydneyTimeZone);
        sydneyCalendar.setTime(now);

        // Check each time zone offset.
        assertThat(londonOffset, equalTo(0));
        assertThat(newYorkOffset, equalTo(-5));
        assertThat(sydneyOffset, equalTo(10));

        // Check that calendars are not equals (due to time zone difference).
        assertThat(londonCalendar, not(equalTo(newYorkCalendar)));
        assertThat(londonCalendar, not(equalTo(sydneyCalendar)));

        // Check if they all point to the same moment in time, in milliseconds.
        assertThat(londonCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(newYorkCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(sydneyCalendar.getTimeInMillis(), equalTo(nowInMillis));

        // Check if they all point to the same moment in time, as Date.
        assertThat(londonCalendar.getTime(), equalTo(now));
        assertThat(newYorkCalendar.getTime(), equalTo(now));
        assertThat(sydneyCalendar.getTime(), equalTo(now));

        // Check if hours are all different (skip local time because
        // this test could be executed in those exact time zones).
        assertThat(newYorkCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
        assertThat(sydneyCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));


        // Display London time in multiple forms.
        SimpleDateFormat dfLondonNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        SimpleDateFormat dfLondonWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        System.out.println("London (" + londonTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + londonOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfLondonNoTZ.format(londonCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfLondonWithTZ.format(londonCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + londonCalendar.getTime() + " / " + londonCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(londonCalendar.getTime())
                + " / " + createDateFormat().format(londonCalendar.getTime()));


        // Display New York time in multiple forms.
        SimpleDateFormat dfNewYorkNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        SimpleDateFormat dfNewYorkWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        System.out.println("New York (" + newYorkTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + newYorkOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfNewYorkNoTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfNewYorkWithTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + newYorkCalendar.getTime() + " / " + newYorkCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(newYorkCalendar.getTime())
                + " / " + createDateFormat().format(newYorkCalendar.getTime()));


        // Display Sydney time in multiple forms.
        SimpleDateFormat dfSydneyNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
        SimpleDateFormat dfSydneyWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
        System.out.println("Sydney (" + sydneyTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + sydneyOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfSydneyNoTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfSydneyWithTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + sydneyCalendar.getTime() + " / " + sydneyCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(sydneyCalendar.getTime())
                + " / " + createDateFormat().format(sydneyCalendar.getTime()));
    }

    @Test
    public void testDateParsing() throws Exception {
        // Create date parsers that look for time zone information in a date-time string.
        final SimpleDateFormat londonFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);

        // Create date parsers that ignore time zone information in a date-time string.
        final SimpleDateFormat londonFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);

        // We are looking for the moment this millenium started, the famous Y2K,
        // when at midnight everyone welcomed the New Year 2000, i.e. 2000-01-01 00:00:00.
        // Which of these is the right one?
        // a) "2000-01-01T00:00:00.000-00:00"
        // b) "2000-01-01T00:00:00.000-05:00"
        // c) "2000-01-01T00:00:00.000+10:00"
        // None of them? All of them?
        // For those who guessed it - yes, it is a trick question because we didn't specify
        // the "where" part, or what kind of time (local/global) we are looking for.
        // The first (a) is the local Y2K moment in London, which is at the same time global.
        // The second (b) is the local Y2K moment in New York, but London is already celebrating for 5 hours.
        // The third (c) is the local Y2K moment in Sydney, and they started celebrating 15 hours before New York did.
        // The point here is that each answer is correct because everyone thinks of that moment in terms of "celebration at midnight".
        // The key word here is "midnight"! That moment is actually a "time of day" moment illustrating our perception of time based on the movement of our Sun.

        // These are global Y2K moments, i.e. the same moment all over the world, UTC/GMT midnight.
        final String MIDNIGHT_GLOBAL = "2000-01-01T00:00:00.000-00:00";
        final Date milleniumInLondon = londonFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInNewYork = newYorkFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInSydney = sydneyFormatTZ.parse(MIDNIGHT_GLOBAL);

        // Check if they all point to the same moment in time.
        // And that parser ignores its own configured time zone and uses the information from the date-time string.
        assertThat(milleniumInNewYork, equalTo(milleniumInLondon));
        assertThat(milleniumInSydney, equalTo(milleniumInLondon));


        // These are all local Y2K moments, a.k.a. midnight at each location on Earth, with time zone information.
        final String MIDNIGHT_LONDON = "2000-01-01T00:00:00.000-00:00";
        final String MIDNIGHT_NEW_YORK = "2000-01-01T00:00:00.000-05:00";
        final String MIDNIGHT_SYDNEY = "2000-01-01T00:00:00.000+10:00";
        final Date midnightInLondonTZ = londonFormatLocal.parse(MIDNIGHT_LONDON);
        final Date midnightInNewYorkTZ = newYorkFormatLocal.parse(MIDNIGHT_NEW_YORK);
        final Date midnightInSydneyTZ = sydneyFormatLocal.parse(MIDNIGHT_SYDNEY);

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYorkTZ, not(equalTo(midnightInLondonTZ)));
        assertThat(midnightInSydneyTZ, not(equalTo(midnightInLondonTZ)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondonTZ.getTime() - midnightInNewYorkTZ.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondonTZ.getTime() - midnightInSydneyTZ.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // These are also local Y2K moments, just withouth the time zone information.
        final String MIDNIGHT_ANYWHERE = "2000-01-01T00:00:00.000";
        final Date midnightInLondon = londonFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInNewYork = newYorkFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInSydney = sydneyFormatLocal.parse(MIDNIGHT_ANYWHERE);

        // Check if these are the same as the local moments with time zone information.
        assertThat(midnightInLondon, equalTo(midnightInLondonTZ));
        assertThat(midnightInNewYork, equalTo(midnightInNewYorkTZ));
        assertThat(midnightInSydney, equalTo(midnightInSydneyTZ));

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYork, not(equalTo(midnightInLondon)));
        assertThat(midnightInSydney, not(equalTo(midnightInLondon)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondon.getTime() - midnightInNewYork.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondon.getTime() - midnightInSydney.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // Final check - if Y2K moment is in London ..
        final String Y2K_LONDON = "2000-01-01T00:00:00.000Z";
        // .. New York local time would be still 5 hours in 1999 ..
        final String Y2K_NEW_YORK = "1999-12-31T19:00:00.000-05:00";
        // .. and Sydney local time would be 10 hours in 2000.
        final String Y2K_SYDNEY = "2000-01-01T10:00:00.000+10:00";

        final String londonTime = londonFormatTZ.format(milleniumInLondon);
        final String newYorkTime = newYorkFormatTZ.format(milleniumInLondon);
        final String sydneyTime = sydneyFormatTZ.format(milleniumInLondon);

        // WHat do you think, will the test pass?
        assertThat(londonTime, equalTo(Y2K_LONDON));
        assertThat(newYorkTime, equalTo(Y2K_NEW_YORK));
        assertThat(sydneyTime, equalTo(Y2K_SYDNEY));
    }
}

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

How to backup a local Git repository?

[Just leaving this here for my own reference.]

My bundle script called git-backup looks like this

#!/usr/bin/env ruby
if __FILE__ == $0
        bundle_name = ARGV[0] if (ARGV[0])
        bundle_name = `pwd`.split('/').last.chomp if bundle_name.nil? 
        bundle_name += ".git.bundle"
        puts "Backing up to bundle #{bundle_name}"
        `git bundle create /data/Dropbox/backup/git-repos/#{bundle_name} --all`
end

Sometimes I use git backup and sometimes I use git backup different-name which gives me most of the possibilities I need.

How do you stop MySQL on a Mac OS install?

For me the following solution worked Unable to stop MySQL on OS X 10.10

To stop the auto start I used:

sudo launchctl unload -w /Library/LaunchDaemons/com.mysql.mysql.plist

And to kill the service I used:

sudo pkill mysqld

Incorrect integer value: '' for column 'id' at row 1

Try to edit your my.cf and comment the original sql_mode and add sql_mode = "".

vi /etc/mysql/my.cnf

sql_mode = ""

save and quit...

service mysql restart

Why is Java's SimpleDateFormat not thread-safe?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner.

From the JavaDoc,

But Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

To make the SimpleDateFormat class thread-safe, look at the following approaches :

  • Create a new SimpleDateFormat instance each time you need to use one. Although this is thread safe, it is the slowest possible approach.
  • Use synchronization. This is a bad idea because you should never choke-point your threads on a server.
  • Use a ThreadLocal. This is the fastest approach of the 3 (see http://www.javacodegeeks.com/2010/07/java-best-practices-dateformat-in.html).

Popup Message boxes

A couple of "enhancements" I use for debugging, especially when running projects (ie not in debug mode).

  1. Default the message-box title to the name of the calling method. This is handy for stopping a thread at a given point, but must be cleaned-up before release.
  2. Automatically copy the caller-name and message to the clipboard, because you can't search an image!

    package forumposts;
    
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.StringSelection;
    import javax.swing.JOptionPane;
    
    public final class MsgBox
    {
        public static void info(String message) {
            info(message, theNameOfTheMethodThatCalledMe());
        }
        public static void info(String message, String caller) {
            show(message, caller, JOptionPane.INFORMATION_MESSAGE);
        }
    
        static void error(String message) {
            error(message, theNameOfTheMethodThatCalledMe());
        }
        public static void error(String message, String caller) {
            show(message, caller, JOptionPane.ERROR_MESSAGE);
        }
    
        public static void show(String message, String title, int iconId) {
            setClipboard(title+":"+NEW_LINE+message);
            JOptionPane.showMessageDialog(null, message, title, iconId);
        }
        private static final String NEW_LINE = System.lineSeparator();
    
        public static String theNameOfTheMethodThatCalledMe() {
            return Thread.currentThread().getStackTrace()[3].getMethodName();
        }
    
        public static void setClipboard(String message) {
            CLIPBOARD.setContents(new StringSelection(message), null);
            // nb: we don't respond to the "your content was splattered"
            //     event, so it's OK to pass a null owner.
        }
        private static final Toolkit AWT_TOOLKIT = Toolkit.getDefaultToolkit();
        private static final Clipboard CLIPBOARD = AWT_TOOLKIT.getSystemClipboard();
    
    }
    

The full class also has debug and warning methods, but I cut them for brevity and you get the main points anyway. You can use a public static boolean isDebugEnabled to suppress debug messages. If done properly the optimizer will (almost) remove these method calls from your production code. See: http://c2.com/cgi/wiki?ConditionalCompilationInJava

Cheers. Keith.

Reliable method to get machine's MAC address in C#

Really hate to dig up this old post but I feel the question deserves another answer specific to windows 8-10.

Using NetworkInformation from the Windows.Networking.Connectivity namespace, you can get the Id of the network adapter windows is using. Then you can get the interface MAC Address from the previously mentioned GetAllNetworkInterfaces().

This will not work in Windows Store Apps as NetworkInterface in System.Net.NetworkInformation does not expose GetAllNetworkInterfaces.

string GetMacAddress()
{
    var connectionProfile = NetworkInformation.GetInternetConnectionProfile();
    if (connectionProfile == null) return "";

    var inUseId = connectionProfile.NetworkAdapter.NetworkAdapterId.ToString("B").ToUpperInvariant();
    if(string.IsNullOrWhiteSpace(inUseId)) return "";

    var mac = NetworkInterface.GetAllNetworkInterfaces()
        .Where(n => inUseId == n.Id)
        .Select(n => n.GetPhysicalAddress().GetAddressBytes().Select(b=>b.ToString("X2")))
        .Select(macBytes => string.Join(" ", macBytes))
        .FirstOrDefault();

    return mac;
}

Set the absolute position of a view

My code for Xamarin, I am using FrameLayout for this purpose and following is my code:

               List<object> content = new List<object>();

        object aWebView = new {ContentType="web",Width="300", Height = "300",X="10",Y="30",ContentUrl="http://www.google.com" };
        content.Add(aWebView);
        object aWebView2 = new { ContentType = "image", Width = "300", Height = "300", X = "20", Y = "40", ContentUrl = "https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4" };
        content.Add(aWebView2);
        FrameLayout myLayout = (FrameLayout)FindViewById(Resource.Id.frameLayout1);
        foreach (object item in content)
        {

            string contentType = item.GetType().GetProperty("ContentType").GetValue(item, null).ToString();
            FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(Convert.ToInt32(item.GetType().GetProperty("Width").GetValue(item, null).ToString()), Convert.ToInt32(item.GetType().GetProperty("Height").GetValue(item, null).ToString()));
            param.LeftMargin = Convert.ToInt32(item.GetType().GetProperty("X").GetValue(item, null).ToString());
            param.TopMargin = Convert.ToInt32(item.GetType().GetProperty("Y").GetValue(item, null).ToString());

            switch (contentType) {
                case "web":{
                        WebView webview = new WebView(this);

                        //webview.hei;
                        myLayout.AddView(webview, param);
                        webview.SetWebViewClient(new WebViewClient());
                        webview.LoadUrl(item.GetType().GetProperty("ContentUrl").GetValue(item, null).ToString());

                        break;
                    }
                case "image":
                    {
                        ImageView imageview = new ImageView(this);

                        //webview.hei;
                        myLayout.AddView(imageview, param);
                        var imageBitmap =  GetImageBitmapFromUrl("https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4");
                        imageview.SetImageBitmap(imageBitmap);


                        break;
                    }

            }

        }

It was useful for me because I needed the property of view to overlap each other on basis of their appearance, e.g the views get stacked one above other.

alert() not working in Chrome

put this line at the end of the body. May be the DOM is not ready yet at the moment this line is read by compiler.

<script type="text/javascript" src="script.js"></script>"

Counting duplicates in Excel

I don't know if it's entirely possible to do your ideal pattern. But I found a way to do your first way: CountIF

+-------+-------------------+
|   A   |         B         |
+-------+-------------------+
| GL15  | =COUNTIF(A:A, A1) |
+-------+-------------------+
| GL15  | =COUNTIF(A:A, A2) |
+-------+-------------------+
| GL15  | =COUNTIF(A:A, A3) |
+-------+-------------------+
| GL16  | =COUNTIF(A:A, A4) |
+-------+-------------------+
| GL17  | =COUNTIF(A:A, A5) |
+-------+-------------------+
| GL17  | =COUNTIF(A:A, A6) |
+-------+-------------------+

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

In the SQL Server Management Studio, to find out details of the active transaction, execute following command

DBCC opentran()

You will get the detail of the active transaction, then from the SPID of the active transaction, get the detail about the SPID using following commands

exec sp_who2 <SPID>
exec sp_lock <SPID>

For example, if SPID is 69 then execute the command as

exec sp_who2 69
exec sp_lock 69

Now , you can kill that process using the following command

KILL 69

I hope this helps :)

Stopping fixed position scrolling at a certain point?

A possible CSS ONLY solution can be achived with position: sticky;

The browser support is actually really good: https://caniuse.com/#search=position%3A%20sticky

here is an example: https://jsfiddle.net/0vcoa43L/7/

Moving Average Pandas

The rolling mean returns a Series you only have to add it as a new column of your DataFrame (MA) as described below.

For information, the rolling_mean function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas documentation.

Warning Prior to version 0.18.0, pd.rolling_*, pd.expanding_*, and pd.ewm* were module level functions and are now deprecated. These are replaced by using the Rolling, Expanding and EWM. objects and a corresponding method call.

df['MA'] = df.rolling(window=5).mean()

print(df)
#             Value    MA
# Date                   
# 1989-01-02   6.11   NaN
# 1989-01-03   6.08   NaN
# 1989-01-04   6.11   NaN
# 1989-01-05   6.15   NaN
# 1989-01-09   6.25  6.14
# 1989-01-10   6.24  6.17
# 1989-01-11   6.26  6.20
# 1989-01-12   6.23  6.23
# 1989-01-13   6.28  6.25
# 1989-01-16   6.31  6.27

How do I see the extensions loaded by PHP?

You asked where do you see loaded extensions in phpinfo() output.

Answer:

They are listed towards the bottom as separate sections/tables and ONLY if they are loaded. Here is an example of extension Curl loaded.

enter image description here ...

... enter image description here

I installed it on Linux Debian with

sudo apt-get install php7.4-curl

Rails 3.1 and Image Assets

For what it's worth, when I did this I found that no folder should be include in the path in the css file. For instance if I have app/assets/images/example.png, and I put this in my css file...

div.example { background: url('example.png'); }

... then somehow it magically works. I figured this out by running the rake assets:precompile task, which just sucks everything out of all your load paths and dumps it in a junk drawer folder: public/assets. That's ironic, IMO...

In any case this means you don't need to put any folder paths, everything in your assets folders will all end up living in one huge directory. How this system resolves file name conflicts is unclear, you may need to be careful about that.

Kind of frustrating there aren't better docs out there for this big of a change.

How to convert an address into a Google Maps Link (NOT MAP)

This is what I found from one of the Google Maps articles:

  1. Open Google Maps.
  2. Make sure the map or Street View image you'd like to embed shows up on the map.
  3. In the top left corner, click the main menu ?☰.
  4. Click Share or embed map.
  5. At the top of the box that appears, choose the Embed map tab.
  6. Choose the size you want, then copy the code and paste it into the source code of your website or blog.

Note: If you're using Maps in Lite mode, you won't be able to embed a map. Keep in mind that traffic information and some other Maps info might not be available in the embedded map.

enter image description here

How to trim white space from all elements in array?

Add commons-lang3-3.1.jar in your application build path. Use the below code snippet to trim the String array.

String array = {" String", "Tom Selleck "," Fish "};
array = StringUtils.stripAll(array);

Access Controller method from another controller in Laravel 5

This approach also works with same hierarchy of Controller files:

$printReport = new PrintReportController;

$prinReport->getPrintReport();

How do I create and read a value from cookie?

I've used accepted answer of this thread many times already. It's great piece of code: Simple and usable. But I usually use babel and ES6 and modules, so if you are like me, here is code to copy for faster developing with ES6

Accepted answer rewritten as module with ES6:

export const createCookie = ({name, value, days}) => {
  let expires;
  if (days) {
    let date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toGMTString();
  } else {
    expires = '';
  }
  document.cookie = name + '=' + value + expires + '; path=/';
};

export const getCookie = ({name}) => {
  if (document.cookie.length > 0) {
    let c_start = document.cookie.indexOf(name + '=');
    if (c_start !== -1) {
      c_start = c_start + name.length + 1;
      let c_end = document.cookie.indexOf(';', c_start);
      if (c_end === -1) {
        c_end = document.cookie.length;
      }
      return unescape(document.cookie.substring(c_start, c_end));
    }
  }
  return '';
};

And after this you can simply import it as any module (path of course may vary):

import {createCookie, getCookie} from './../helpers/Cookie';

Correct way to populate an Array with a Range in Ruby

Sounds like you're doing this:

0..10.to_a

The warning is from Fixnum#to_a, not from Range#to_a. Try this instead:

(0..10).to_a

Convert normal date to unix timestamp

new Date('2012.08.10').getTime() / 1000

Check the JavaScript Date documentation.

get jquery `$(this)` id

Do you mean that for a select element with an id of "next" you need to perform some specific script?

$("#next").change(function(){
    //enter code here
});

Bloomberg Open API

I don't think so. The API's will provide access to delayed quotes, there is no way that real time data or tick data, will be provided for free.

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

Have you tried doing a full "clean" and then rebuild in Eclipse (Project->Clean...)?

Are you able to compile and run with "javac" and "java" straight from the command line? Does that work properly?

If you right click on your project, go to "Properties" and then go to "Java Build Path", are there any suspicious entries under any of the tabs? This is essentially your CLASSPATH.

In the Eclipse preferences, you may also want to double check the "Installed JREs" section in the "Java" section and make sure it matches what you think it should.

You definitely have either a stale .class file laying around somewhere or you're getting a compile-time/run-time mismatch in the versions of Java you're using.

Disable time in bootstrap date time picker

I tried all of the solutions posted here but none of them worked for me. I managed to disable the time by using this line of code in my jQuery:

$('#datetimepicker4').datetimepicker({
    format: 'YYYY-MM-DD'
});

This set the format to date only and disabled the time completely. Hope this helps.

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

Imagine that we have 3 buttons for example

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(mCorkyListener);
        button2.setOnClickListener(mCorkyListener);
        button3.setOnClickListener(mCorkyListener);

    }

    // Create an anonymous implementation of OnClickListener
    private View.OnClickListener mCorkyListener = new View.OnClickListener() {
        public void onClick(View v) {
            // do something when the button is clicked 
            // Yes we will handle click here but which button clicked??? We don't know

        }
    };

}

So what we will do?

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(mCorkyListener);
        button2.setOnClickListener(mCorkyListener);
        button3.setOnClickListener(mCorkyListener);

    }

    // Create an anonymous implementation of OnClickListener
    private View.OnClickListener mCorkyListener = new View.OnClickListener() {
        public void onClick(View v) {
            // do something when the button is clicked
            // Yes we will handle click here but which button clicked??? We don't know

            // So we will make
            switch (v.getId() /*to get clicked view id**/) {
                case R.id.corky:

                    // do something when the corky is clicked

                    break;
                case R.id.corky2:

                    // do something when the corky2 is clicked

                    break;
                case R.id.corky3:

                    // do something when the corky3 is clicked

                    break;
                default:
                    break;
            }
        }
    };

}

Or we can do this:

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something when the corky is clicked
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something when the corky2 is clicked
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something when the corky3 is clicked
            }
        });

    }

}

Or we can implement View.OnClickListener and i think it's the best way:

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        Button button2 = (Button)findViewById(R.id.corky2);
        Button button3 = (Button)findViewById(R.id.corky3);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // do something when the button is clicked
        // Yes we will handle click here but which button clicked??? We don't know

        // So we will make
        switch (v.getId() /*to get clicked view id**/) {
            case R.id.corky:

                // do something when the corky is clicked

                break;
            case R.id.corky2:

                // do something when the corky2 is clicked

                break;
            case R.id.corky3:

                // do something when the corky3 is clicked

                break;
            default:
                break;
        }
    }
}

Finally there is no real differences here Just "Way better than the other"

Eclipse Error: "Failed to connect to remote VM"

Remove your proxy from eclipse!

Go to network Connections within General Preferences ( Windows -> Preferences ) and set "Active Provider" to "Direct"

remove proxy

Reboot your Eclipse after that

Latex Multiple Linebreaks

You can use the setspace package which gives you spacing environments, e.g.:

\documentclass{article}
\usepackage{setspace}
\begin{document}
\doublespace
my line of text blah blah blah

new line of text with blank line between
\end{document}

Or use a verbatim environment to control the layout of your code precisely.

Converting from hex to string

 string hexString = "8E2";
 int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
 Console.WriteLine(num);
 //Output: 2274

From https://msdn.microsoft.com/en-us/library/bb311038.aspx

Where does Chrome store cookies?

You can find a solution on SuperUser :

Chrome cookies folder in Windows 7:-

C:\Users\your_username\AppData\Local\Google\Chrome\User Data\Default\
You'll need a program like SQLite Database Browser to read it.

For Mac OS X, the file is located at :-
~/Library/Application Support/Google/Chrome/Default/Cookies

Host binding and Host listening

This is the simple example to use both of them:

import {
  Directive, HostListener, HostBinding
}
from '@angular/core';

@Directive({
  selector: '[Highlight]'
})
export class HighlightDirective {
  @HostListener('mouseenter') mouseover() {
    this.backgroundColor = 'green';
  };

  @HostListener('mouseleave') mouseleave() {
    this.backgroundColor = 'white';
  }

  @HostBinding('style.backgroundColor') get setColor() {
     return this.backgroundColor;
  };

  private backgroundColor = 'white';
  constructor() {}

}

Introduction:

  1. HostListener can bind an event to the element.

  2. HostBinding can bind a style to the element.

  3. this is directive, so we can use it for

    Some Text
  4. So according to the debug, we can find that this div has been binded style = "background-color:white"

    Some Text
  5. we also can find that EventListener of this div has two event: mouseenter and mouseleave. So when we move the mouse into the div, the colour will become green, mouse leave, the colour will become white.

Open Popup window using javascript

To create a popup you'll need the following script:

<script language="javascript" type="text/javascript">

function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}


</script>

Then, you link to it by:

  <a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>

If you want you can call the function directly from document.ready also. Or maybe from another function.

Spring Boot how to hide passwords in properties file

In additional to the popular K8s, jasypt or vault solutions, there's also Karmahostage. It enables you to do:

@EncryptedValue("${application.secret}")
private String application;

It works the same way jasypt does, but encryption happens on a dedicated saas solution, with a more fine-grained ACL model attached to it.

Copy a variable's value into another

the question is already solved since quite a long time, but for future reference a possible solution is

b = a.slice(0);

Be careful, this works correctly only if a is a non-nested array of numbers and strings

Git merge two local branches

on branchB do $git checkout branchA to switch to branch A

on branchA do $git merge branchB

That's all you need.

How can I enable MySQL's slow query log without restarting MySQL?

Try SET GLOBAL slow_query_log = 'ON'; and perhaps FLUSH LOGS;

This assumes you are using MySQL 5.1 or later. If you are using an earlier version, you'll need to restart the server. This is documented in the MySQL Manual. You can configure the log either in the config file or on the command line.

How do I read a response from Python Requests?

Requests doesn't have an equivalent to Urlib2's read().

>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True

It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.

Edit for Python 3:

Python now handles data types differently. response.content returns a sequence of bytes (integers that represent ASCII) while response.text is a string (sequence of chars).

Thus,

>>> print response.content == response.text
False

>>> print str(response.content) == response.text
True

How do I initialize an empty array in C#?

string[] a = new string[0];

or short notation:

string[] a = { };

The preferred way now is:

var a = Array.Empty<string>();

I have written a short regular expression that you can use in Visual Studio if you want to replace zero-length allocations e.g. new string[0]. Use Find (search) in Visual Studio with Regular Expression option turned on:

new[ ][a-zA-Z0-9]+\[0\]

Now Find All or F3 (Find Next) and replace all with Array.Empty<…>() !

Bootstrap center heading

Just use "justify-content-center" in the row's class attribute.

<div class="container">
  <div class="row justify-content-center">
    <h1>This is a header</h1>
  </div>
</div>

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

iPhone and WireShark

I have successfully captured HTTP traffic using Fiddler2 as a proxy, which can be installed on any Windows PC on your network.

  1. In Fiddler, Tools -> Fiddler Options -> Connections -> [x] Allow remote computers to connect.
  2. Make sure your windows firewall is disabled.
  3. On the iphone/ipod, go to your wireless settings, use a manual proxy server, enter the fiddler machine's ip address and the same port (defaults to 8888).

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.

@GetMapping(value="/person/{id}/", 
            params="format=json",
            produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
    Person person = personMapRepository.findPerson(id);
    return ResponseEntity.ok(person);
} 
@GetMapping(value="/person/{id}/", 
            params="format=xml",
            produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
    return GetPerson(id); // delegate
}

How to validate an OAuth 2.0 access token for a resource server?

Update Nov. 2015: As per Hans Z. below - this is now indeed defined as part of RFC 7662.

Original Answer: The OAuth 2.0 spec (RFC 6749) doesn't clearly define the interaction between a Resource Server (RS) and Authorization Server (AS) for access token (AT) validation. It really depends on the AS's token format/strategy - some tokens are self-contained (like JSON Web Tokens) while others may be similar to a session cookie in that they just reference information held server side back at the AS.

There has been some discussion in the OAuth Working Group about creating a standard way for an RS to communicate with the AS for AT validation. My company (Ping Identity) has come up with one such approach for our commercial OAuth AS (PingFederate): https://support.pingidentity.com/s/document-item?bundleId=pingfederate-93&topicId=lzn1564003025072.html#lzn1564003025072__section_N10578_N1002A_N10001. It uses REST based interaction for this that is very complementary to OAuth 2.0.

Check if MySQL table exists or not

MySQL way:

SHOW TABLES LIKE 'pattern';

There's also a deprecated PHP function for listing all db tables, take a look at http://php.net/manual/en/function.mysql-list-tables.php

Checkout that link, there are plenty of useful insight on the comments over there.

Pass a datetime from javascript to c# (Controller)

I found that I needed to wrap my datetime string like this:

"startdate": "\/Date(" + date() + ")\/"

Took me an hour to figure out how to enable the WCF service to give me back the error message which told me that XD

Center a H1 tag inside a DIV

<div id="AlertDiv" style="width:600px;height:400px;border:SOLID 1px;">
    <h1 style="width:100%;height:10%;text-align:center;position:relative;top:40%;">Yes</h1>
</div>

You can try the code here:

http://htmledit.squarefree.com/

How to use source: function()... and AJAX in JQuery UI autocomplete

When you ask about:

Blockquote // But what now? How do I display my data? Blockquote

you need to map an array of object, that way:

response([{label: 'result_name', value: 'result_id'},]);

That way when you use the select event of the autocomplete plugin, you can see the result bellow;

Result of the select event

You can use the select event that way:

jQuery("#field").autocomplete({
      source: function (request, response) {

      },
      minLength: 3,
      select: function(event, ui)
      {
        console.log(ui);
      }
  });

I hope that it can help and complement the answers.

How to vertically align an image inside a div

There is a super easy solution with flexbox!

.frame {
    display: flex;
    align-items: center;
}

How can I URL encode a string in Excel VBA?

None of the solutions here worked for me out of the box, but it was most likely due my lack of experience with VBA. It might also be because I simply copied and pasted some of the functions above, not knowing details that maybe are necessary to make them work on a VBA for applications environment.

My needs were simply to send xmlhttp requests using urls that contained some special characters of the Norwegian language. Some of the solutions above encode even colons, which made the urls unsuitable for what I needed.

I then decided to write my own URLEncode function. It does not use more clever programming such as the one from @ndd and @Tom. I am not a very experienced programmer, but I had to make this done sooner.

I realized that the problem was that my server didn't accept UTF-16 encodings, so I had to write a function that would convert UTF-16 to UTF-8. A good source of information was found here and here.

I haven't tested it extensively to check if it works with url with characters that have higher unicode values and which would produce more than 2 bytes of utf-8 characters. I am not saying it will decode everything that needs to be decoded (but it is easy to modify to include/exclude characters on the select case statement) nor that it will work with higher characters, as I haven't fully tested. But I am sharing the code because it might help someone who is trying to understand the issue.

Any comments are welcome.

Public Function URL_Encode(ByVal st As String) As String

    Dim eachbyte() As Byte
    Dim i, j As Integer 
    Dim encodeurl As String
    encodeurl = "" 

    eachbyte() = StrConv(st, vbFromUnicode)

    For i = 0 To UBound(eachbyte)

        Select Case eachbyte(i)
        Case 0
        Case 32
            encodeurl = encodeurl & "%20"

        ' I am not encoding the lower parts, not necessary for me
        Case 1 To 127
            encodeurl = encodeurl & Chr(eachbyte(i))
        Case Else

            Dim myarr() As Byte
            myarr = utf16toutf8(eachbyte(i))
            For j = LBound(myarr) To UBound(myarr) - 1
                encodeurl = encodeurl & "%" & Hex(myarr(j))
            Next j
        End Select
    Next i
    URL_Encode = encodeurl 
End Function

Public Function utf16toutf8(ByVal thechars As Variant) As Variant
    Dim numbytes As Integer
    Dim byte1 As Byte
    Dim byte2 As Byte
    Dim byte3 As Byte
    Dim byte4 As Byte
    Dim byte5 As Byte 
    Dim i As Integer  
    Dim temp As Variant
    Dim stri As String

    byte1 = 0
    byte2 = byte3 = byte4 = byte5 = 128

    ' Test to see how many bytes the utf-8 char will need
    Select Case thechars
        Case 0 To 127
            numbytes = 1
        Case 128 To 2047
            numbytes = 2
        Case 2048 To 65535
            numbytes = 3
        Case 65536 To 2097152
            numbytes = 4
        Case Else
            numbytes = 5
    End Select

    Dim returnbytes() As Byte
    ReDim returnbytes(numbytes)


    If numbytes = 1 Then
        returnbytes(0) = thechars
        GoTo finish
    End If


    ' prepare the first byte
    byte1 = 192

    If numbytes > 2 Then
        For i = 3 To numbytes
            byte1 = byte1 / 2
            byte1 = byte1 + 128
        Next i
    End If
    temp = 0
    stri = ""
    If numbytes = 5 Then
        temp = thechars And 63

        byte5 = temp + 128
        returnbytes(4) = byte5
        thechars = thechars / 12
        stri = byte5
    End If

    If numbytes >= 4 Then

        temp = 0
        temp = thechars And 63
        byte4 = temp + 128
        returnbytes(3) = byte4
        thechars = thechars / 12
        stri = byte4 & stri
    End If

    If numbytes >= 3 Then

        temp = 0
        temp = thechars And 63
        byte3 = temp + 128
        returnbytes(2) = byte3
        thechars = thechars / 12
        stri = byte3 & stri
    End If

    If numbytes >= 2 Then

        temp = 0
        temp = thechars And 63
        byte2 = temp Or 128
        returnbytes(1) = byte2
        thechars = Int(thechars / (2 ^ 6))
        stri = byte2 & stri
    End If

    byte1 = thechars Or byte1
    returnbytes(0) = byte1

    stri = byte1 & stri

    finish:
       utf16toutf8 = returnbytes()
End Function

Function return value in PowerShell

PowerShell has really wacky return semantics - at least when viewed from a more traditional programming perspective. There are two main ideas to wrap your head around:

  • All output is captured, and returned
  • The return keyword really just indicates a logical exit point

Thus, the following two script blocks will do effectively the exact same thing:

$a = "Hello, World"
return $a

 

$a = "Hello, World"
$a
return

The $a variable in the second example is left as output on the pipeline and, as mentioned, all output is returned. In fact, in the second example you could omit the return entirely and you would get the same behavior (the return would be implied as the function naturally completes and exits).

Without more of your function definition I can't say why you are getting a PSMethod object. My guess is that you probably have something a few lines up that is not being captured and is being placed on the output pipeline.

It is also worth noting that you probably don't need those semicolons - unless you are nesting multiple expressions on a single line.

You can read more about the return semantics on the about_Return page on TechNet, or by invoking the help return command from PowerShell itself.

AngularJS ui router passing data between states without URL

The params object is included in $stateParams, but won't be part of the url.

1) In the route configuration:

$stateProvider.state('edit_user', {
    url: '/users/:user_id/edit',
    templateUrl: 'views/editUser.html',
    controller: 'editUserCtrl',
    params: {
        paramOne: { objectProperty: "defaultValueOne" },  //default value
        paramTwo: "defaultValueTwo"
    }
});

2) In the controller:

.controller('editUserCtrl', function ($stateParams, $scope) {       
    $scope.paramOne = $stateParams.paramOne;
    $scope.paramTwo = $stateParams.paramTwo;
});

3A) Changing the State from a controller

$state.go("edit_user", {
    user_id: 1,                
    paramOne: { objectProperty: "test_not_default1" },
    paramTwo: "from controller"
});

3B) Changing the State in html

<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>

Example Plunker

Spark java.lang.OutOfMemoryError: Java heap space

Broadly speaking, spark Executor JVM memory can be divided into two parts. Spark memory and User memory. This is controlled by property spark.memory.fraction - the value is between 0 and 1. When working with images or doing memory intensive processing in spark applications, consider decreasing the spark.memory.fraction. This will make more memory available to your application work. Spark can spill, so it will still work with less memory share.

The second part of the problem is division of work. If possible, partition your data into smaller chunks. Smaller data possibly needs less memory. But if that is not possible, you are sacrifice compute for memory. Typically a single executor will be running multiple cores. Total memory of executors must be enough to handle memory requirements of all concurrent tasks. If increasing executor memory is not a option, you can decrease the cores per executor so that each task gets more memory to work with. Test with 1 core executors which have largest possible memory you can give and then keep increasing cores until you find the best core count.

How do I sort a dictionary by value?

Just learned relevant skill from Python for Everybody.

You may use a temporary list to help you to sort the dictionary:

#Assume dictionary to be:
d = {'apple': 500.1, 'banana': 1500.2, 'orange': 1.0, 'pineapple': 789.0}

# create a temporary list
tmp = []

# iterate through the dictionary and append each tuple into the temporary list 
for key, value in d.items():
    tmptuple = (value, key)
    tmp.append(tmptuple)

# sort the list in ascending order
tmp = sorted(tmp)

print (tmp)

If you want to sort the list in descending order, simply change the original sorting line to:

tmp = sorted(tmp, reverse=True)

Using list comprehension, the one liner would be:

#Assuming the dictionary looks like
d = {'apple': 500.1, 'banana': 1500.2, 'orange': 1.0, 'pineapple': 789.0}
#One liner for sorting in ascending order
print (sorted([(v, k) for k, v in d.items()]))
#One liner for sorting in descending order
print (sorted([(v, k) for k, v in d.items()], reverse=True))

Sample Output:

#Asending order
[(1.0, 'orange'), (500.1, 'apple'), (789.0, 'pineapple'), (1500.2, 'banana')]
#Descending order
[(1500.2, 'banana'), (789.0, 'pineapple'), (500.1, 'apple'), (1.0, 'orange')]

Return Max Value of range that is determined by an Index & Match lookup

You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.

=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))

SNAPSHOT

enter image description here

Generate insert script for selected records?

I created the following procedure:

if object_id('tool.create_insert', 'P') is null
begin
  exec('create procedure tool.create_insert as');
end;
go

alter procedure tool.create_insert(@schema    varchar(200) = 'dbo',
                                   @table     varchar(200),
                                   @where     varchar(max) = null,
                                   @top       int = null,
                                   @insert    varchar(max) output)
as
begin
  declare @insert_fields varchar(max),
          @select        varchar(max),
          @error         varchar(500),
          @query         varchar(max);

  declare @values table(description varchar(max));

  set nocount on;

  -- Get columns
  select @insert_fields = isnull(@insert_fields + ', ', '') + c.name,
         @select = case type_name(c.system_type_id)
                      when 'varchar' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + cast(' + c.name + ' as varchar) + '''''''', ''null'')'
                      when 'datetime' then isnull(@select + ' + '', '' + ', '') + ' isnull('''''''' + convert(varchar, ' + c.name + ', 121) + '''''''', ''null'')'
                      else isnull(@select + ' + '', '' + ', '') + 'isnull(cast(' + c.name + ' as varchar), ''null'')'
                    end
    from sys.columns c with(nolock)
         inner join sys.tables t with(nolock) on t.object_id = c.object_id
         inner join sys.schemas s with(nolock) on s.schema_id = t.schema_id
   where s.name = @schema
     and t.name = @table;

  -- If there's no columns...
  if @insert_fields is null or @select is null
  begin
    set @error = 'There''s no ' + @schema + '.' + @table + ' inside the target database.';
    raiserror(@error, 16, 1);
    return;
  end;

  set @insert_fields = 'insert into ' + @schema + '.' + @table + '(' + @insert_fields + ')';

  if isnull(@where, '') <> '' and charindex('where', ltrim(rtrim(@where))) < 1
  begin
    set @where = 'where ' + @where;
  end
  else
  begin
    set @where = '';
  end;

  set @query = 'select ' + isnull('top(' + cast(@top as varchar) + ')', '') + @select + ' from ' + @schema + '.' + @table + ' with (nolock) ' + @where;

  insert into @values(description)
  exec(@query);

  set @insert = isnull(@insert + char(10), '') + '--' + upper(@schema + '.' + @table);

  select @insert = @insert + char(10) + @insert_fields + char(10) + 'values(' + v.description + ');' + char(10) + 'go' + char(10)
    from @values v
   where isnull(v.description, '') <> '';
end;
go

Then you can use it that way:

declare @insert varchar(max),
        @part   varchar(max),
        @start  int,
        @end    int;

set @start = 1;

exec tool.create_insert @schema = 'dbo',
                        @table = 'myTable',
                        @where  = 'Fk_CompanyId = 1',
                        @insert = @insert output;

-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
  set @end = charindex(char(10), @insert);

  if @end = 0
  begin
    set @end = len(@insert) + 1;
  end;

  print substring(@insert, @start, @end - 1);
  set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;

The output would be something like that:

--DBO.MYTABLE
insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(1, 'AMX', 1, 10.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(2, 'ABC', 1, 11.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(3, 'APEX', 1, 12.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(4, 'AMX', 1, 10.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(5, 'ABC', 1, 11.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(6, 'APEX', 1, 12.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(7, 'AMX', 2, 10.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(8, 'ABC', 2, 11.00);
go

insert into dbo.myTable(Pk_Id, ProductName, Fk_CompanyId, Price)
values(9, 'APEX', 2, 12.00);
go

If you just want to get a range of rows, use the @top parameter as bellow:

declare @insert varchar(max),
        @part   varchar(max),
        @start  int,
        @end    int;

set @start = 1;

exec tool.create_insert @schema = 'dbo',
                        @table = 'myTable',
                        @top    = 100,
                        @insert = @insert output;

-- Print one line to avoid the maximum 8000 characters problem
while len(@insert) > 0
begin
  set @end = charindex(char(10), @insert);

  if @end = 0
  begin
    set @end = len(@insert) + 1;
  end;

  print substring(@insert, @start, @end - 1);
  set @insert = substring(@insert, @end + 1, len(@insert) - @end + 1);
end;

How can I select checkboxes using the Selenium Java WebDriver?

Step 1:

The object locator supposed to be used here is XPath. So derive the XPath for those two checkboxes.

String housingmoves="//label[contains(text(),'housingmoves')]/preceding-sibling::input";
String season_country_homes="//label[contains(text(),'Seaside & Country Homes')]/preceding-sibling::input";

Step 2:

Perform a click on the checkboxes

driver.findElement(By.xpath(housingmoves)).click();
driver.findElement(By.xpath(season_country_homes)).click();

Rock, Paper, Scissors Game Java

int w =0 , l =0, d=0, i=0;
    Scanner sc = new Scanner(System.in);

// try tentimes
    while (i<10) {


        System.out.println("scissor(1) ,Rock(2),Paper(3) ");
        int n = sc.nextInt();
        int m =(int)(Math.random()*3+1);


        if(n==m){

            System.out.println("Com:"+m +"so>>> " + "draw");
            d++;


        }else if ((n-1)%3==(m%3)){
            w++;
            System.out.println("Com:"+m +"so>>> " +"win");
        }
        else if(n >=4 )
        {
            System.out.println("pleas enter correct number)");


    }
        else {
            System.out.println("Com:"+m +"so>>> " +"lose");
            l++;

        }
        i++;

Replace all occurrences of a string in a data frame

I had the problem, I had to replace "Not Available" with NA and my solution goes like this

data <- sapply(data,function(x) {x <- gsub("Not Available",NA,x)})

How to get a password from a shell script without echoing

Here is another way to do it:

#!/bin/bash
# Read Password
echo -n Password: 
read -s password
echo
# Run Command
echo $password

The read -s will turn off echo for you. Just replace the echo on the last line with the command you want to run.

Is the NOLOCK (Sql Server hint) bad practice?

I agree with some comments about NOLOCK hint and especially with those saying "use it when it's appropriate". If the application written poorly and is using concurrency inappropriate way – that may cause the lock escalation. Highly transactional table also are getting locked all the time due to their nature. Having good index coverage won't help with retrieving the data, but setting ISOLATION LEVEL to READ UNCOMMITTED does. Also I believe that using NOLOCK hint is safe in many cases when the nature of changes is predictable. For example – in manufacturing when jobs with travellers are going through different processes with lots of inserts of measurements, you can safely execute query against the finished job with NOLOCK hint and this way avoid collision with other sessions that put PROMOTED or EXCLUSIVE locks on the table/page. The data you access in this case is static, but it may reside in a very transactional table with hundreds of millions of records and thousands updates/inserts per minute. Cheers

Adding click event listener to elements with the same class

You have to use querySelectorAll as you need to select all elements with the said class, again since querySelectorAll is an array you need to iterate it and add the event handlers

var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
    deleteLinks[i].addEventListener('click', function (event) {
        event.preventDefault();

        var choice = confirm("sure u want to delete?");
        if (choice) {
            return true;
        }
    });
}

ECMAScript 6 arrow function that returns an object

You may wonder, why the syntax is valid (but not working as expected):

var func = p => { foo: "bar" }

It's because of JavaScript's label syntax:

So if you transpile the above code to ES5, it should look like:

var func = function (p) {
  foo:
  "bar"; //obviously no return here!
}

Get last 30 day records from today date in SQL Server

This Should Work Fine

SELECT * FROM product 
WHERE pdate BETWEEN datetime('now', '-30 days') AND datetime('now', 'localtime')

How to get a unix script to run every 15 seconds?

I would use cron to run a script every minute, and make that script run your script four times with a 15-second sleep between runs.

(That assumes your script is quick to run - you could adjust the sleep times if not.)

That way, you get all the benefits of cron as well as your 15 second run period.

Edit: See also @bmb's comment below.

Check if a value is in an array (C#)

   string[] array = { "cat", "dot", "perls" };

// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perls");
bool b = Array.Exists(array, element => element == "python");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));

// Display bools.
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
----------------------------output-----------------------------------

1)True 2)False 3)True 4)False

How to select and change value of table cell with jQuery?

You can do this :

<table id="table_header">
<tr>
   <td contenteditable="true">a</td>
   <td contenteditable="true">b</td>
   <td contenteditable="true">c</td>
</tr>
</table>

How to configure custom PYTHONPATH with VM and PyCharm?

To me the solution was to go to

Run > Edit Configuration > Defaults > Python

then manage the

  • "Add content roots to PYTHONPATH" and
  • "Add source root to PYTHONPATH"

checkboxes, as well as setting the "Working directory" field.

If you have set up your own Run/Debug Configurations then you might want to go to

Run > Edit Configuration > Python > [Whatever you called your config]

and edit it there.

My problem was that I wanted to have my whole repository included in my PyCharm 2016.2 project, but only a subfolder was the actual python source code root. I added it as "Source Root" by right clicking the folder then

Mark directory as > Source Root

Then unchecking "Add content roots to PYTHONPATH" and checking "Add source root to PYTHONPATH" in the Run/Debug config menu. I then checked the folder pathing by doing:

import sys
logger.info(sys.path)

This outputed:

[
    '/usr/local/my_project_root/my_sources_root', 
    '/usr/local/my_project_root/my_sources_root', 
    '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', 
    '/usr/lib/python3.4/lib-dynload', 
    '/usr/local/lib/python3.4/dist-packages', 
    '/usr/lib/python3/dist-packages'
]

However, without the fix it said:

[
    '/usr/local/my_project_root/my_sources_root', 
    '/usr/local/my_project_root',                   <-- NOT WANTED
    '/usr/lib/python3.4', 
    '/usr/lib/python3.4/plat-x86_64-linux-gnu', 
    '/usr/lib/python3.4/lib-dynload', 
    '/usr/local/lib/python3.4/dist-packages', 
    '/usr/lib/python3/dist-packages'
]

Which meant I got the project root folder included. This messed up the pathing for me.

Navigation bar show/hide

In Swift 4.2 and Xcode 10

self.navigationController?.isNavigationBarHidden = true  //Hide
self.navigationController?.isNavigationBarHidden = false  //Show

If you don't want to display Navigation bar only in 1st VC, but you want display in 2nd VC onword's

In your 1st VC write this code.

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true  //Hide
}

override func viewWillDisappear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = false  //Show
}

Using OR & AND in COUNTIFS

Using array formula.

=SUM(COUNT(IF(D1:D5="Yes",COUNT(D1:D5),"")),COUNT(IF(D1:D5="No",COUNT(D1:D5),"")),COUNT(IF(D1:D5="Agree",COUNT(D1:D5),"")))

PRESS = CTRL + SHIFT + ENTER.

How do I find the install time and date of Windows?

Ever wanted to find out your PC’s operating system installation date? Here is a quick and easy way to find out the date and time at which your PC operating system installed(or last upgraded).

Open the command prompt (start-> run -> type cmd-> hit enter) and run the following command

systeminfo | find /i "install date"

In couple of seconds you will see the installation date

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

In my case it was an old dependency that was using compile for the transitive dependencies : com.jakewharton.hugo

After removing it from my gradle it compiled.

connecting to mysql server on another PC in LAN

Users who can Install MySQL Workbench on MySQL Server Machine

If you use or have MySQL Workbench on the MySQL Server PC you can do this with just a few clicks. Recommend only for development environment.

  1. Connect to MySQL Server

Connect to MySQL Server with MySQL Workbench

  1. Find this option Users and Privileges from Navigator and click on it.

Users and Privileges - MySQL Workbench

  1. Select root user and change value for Limit to Hosts Matching to %.

Users and Privileges - MySQL Workbench

  1. The click Apply at the bottom.

This should enable root user to access MySQL Server from remote machine.

How do I auto-resize an image to fit a 'div' container?

Edit: Previous table-based image positioning had issues in Internet Explorer 11 (max-height doesn't work in display:table elements). I've replaced it with inline based positioning which not only works fine in both Internet Explorer 7 and Internet Explorer 11, but it also requires less code.


Here is my take on the subject. It'll only work if the container has a specified size (max-width and max-height don't seem to get along with containers that don't have concrete size), but I wrote the CSS content in a way that allows it to be reused (add picture-frame class and px125 size class to your existing container).

In CSS:

.picture-frame
{
    vertical-align: top;
    display: inline-block;
    text-align: center;
}

.picture-frame.px125
{
    width: 125px;
    height: 125px;
    line-height: 125px;
}

.picture-frame img
{
    margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */
    max-width: 100%;
    max-height: 100%;
    display: inline-block;
    vertical-align: middle;
    border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */
}

And in HTML:

<a href="#" class="picture-frame px125">
    <img src="http://i.imgur.com/lesa2wS.png"/>
</a>

DEMO

_x000D_
_x000D_
/* Main style */_x000D_
_x000D_
.picture-frame_x000D_
{_x000D_
    vertical-align: top;_x000D_
    display: inline-block;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.picture-frame.px32_x000D_
{_x000D_
    width: 32px;_x000D_
    height: 32px;_x000D_
    line-height: 32px;_x000D_
}_x000D_
_x000D_
.picture-frame.px125_x000D_
{_x000D_
    width: 125px;_x000D_
    height: 125px;_x000D_
    line-height: 125px;_x000D_
}_x000D_
_x000D_
.picture-frame img_x000D_
{_x000D_
    margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */_x000D_
    max-width: 100%;_x000D_
    max-height: 100%;_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
    border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */_x000D_
}_x000D_
_x000D_
/* Extras */_x000D_
_x000D_
.picture-frame_x000D_
{_x000D_
    padding: 5px;_x000D_
}_x000D_
_x000D_
.frame_x000D_
{_x000D_
    border:1px solid black;_x000D_
}
_x000D_
<p>32px</p>_x000D_
<a href="#" class="picture-frame px32 frame">_x000D_
    <img src="http://i.imgur.com/lesa2wS.png"/>_x000D_
</a>_x000D_
<a href="#" class="picture-frame px32 frame">_x000D_
    <img src="http://i.imgur.com/kFMJxdZ.png"/>_x000D_
</a>_x000D_
<a href="#" class="picture-frame px32 frame">_x000D_
    <img src="http://i.imgur.com/BDabZj0.png"/>_x000D_
</a>_x000D_
<p>125px</p>_x000D_
<a href="#" class="picture-frame px125 frame">_x000D_
    <img src="http://i.imgur.com/lesa2wS.png"/>_x000D_
</a>_x000D_
<a href="#" class="picture-frame px125 frame">_x000D_
    <img src="http://i.imgur.com/kFMJxdZ.png"/>_x000D_
</a>_x000D_
<a href="#" class="picture-frame px125 frame">_x000D_
    <img src="http://i.imgur.com/BDabZj0.png"/>_x000D_
</a>
_x000D_
_x000D_
_x000D_


Edit: Possible further improvement using JavaScript (upscaling images):

function fixImage(img)
{
    var $this = $(img);
    var parent = $this.closest('.picture-frame');
    if ($this.width() == parent.width() || $this.height() == parent.height())
        return;

    if ($this.width() > $this.height())
        $this.css('width', parent.width() + 'px');
    else
        $this.css('height', parent.height() + 'px');
}

$('.picture-frame img:visible').each(function
{
    if (this.complete)
        fixImage(this);
    else
        this.onload = function(){ fixImage(this) };
});

How to remove error about glyphicons-halflings-regular.woff2 not found

For me, the problem was twofold: First, the version of IIS I was dealing with didn't know about the .woff2 MIME type, only about .woff. I fixed that using IIS Manager at the server level, not at the web app level, so the setting wouldn't get overridden with each new app deployment. (Under IIS Manager, I went to MIME types, and added the missing .woff2, then updated .woff.)

Second, and more importantly, I was bundling bootstrap.css along with some other files as "~/bundles/css/site". Meanwhile, my font files were in "~/fonts". bootstrap.css looks for the glyphicon fonts in "../fonts", which translated to "~/bundles/fonts" -- wrong path.

In other words, my bundle path was one directory too deep. I renamed it to "~/bundles/siteCss", and updated all the references to it that I found in my project. Now bootstrap looked in "~/fonts" for the glyphicon files, which worked. Problem solved.

Before I fixed the second problem above, none of the glyphicon font files were loading. The symptom was that all instances of glyphicon glyphs in the project just showed an empty box. However, this symptom only occurred in the deployed versions of the web app, not on my dev machine. I'm still not sure why that was the case.

How can I use std::maps with user-defined types as key?

Keys must be comparable, but you haven't defined a suitable operator< for your custom class.

Is there an equivalent of lsusb for OS X

How about ioreg? The output's much more detailed than the profiler, but it's a bit dense.

Source: https://lists.macosforge.org/pipermail/macports-users/2008-July/011115.html

getting the table row values with jquery

$(document).ready(function () {
        $("#tbl_Customer tbody tr .companyname").click(function () {

            var comapnyname = $(this).closest(".trclass").find(".companyname").text();
            var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
            var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
            var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
            var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
           // var clickedCell = $(this);
            alert(comapnyname);
            alert(CompanyAddress);
            alert(CompanyEmail);
            alert(CompanyContactNumber);
            alert(CompanyContactPerson);

            //alert(clickedCell.text());
        });
    });

How can I call controller/view helper methods from the console in Ruby on Rails?

Here is how to make an authenticated POST request, using Refinery as an example:

# Start Rails console
rails console
# Get the login form
app.get '/community_members/sign_in'
# View the session
app.session.to_hash
# Copy the CSRF token "_csrf_token" and place it in the login request.
# Log in from the console to create a session
app.post '/community_members/login', {"authenticity_token"=>"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=",  "refinery_user[login]"=>'chloe', 'refinery_user[password]'=>'test'}
# View the session to verify CSRF token is the same
app.session.to_hash
# Copy the CSRF token "_csrf_token" and place it in the request. It's best to edit this in Notepad++
app.post '/refinery/blog/posts', {"authenticity_token"=>"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=", "switch_locale"=>"en", "post"=>{"title"=>"Test", "homepage"=>"0", "featured"=>"0", "magazine"=>"0", "refinery_category_ids"=>["1282"], "body"=>"Tests do a body good.", "custom_teaser"=>"", "draft"=>"0", "tag_list"=>"", "published_at(1i)"=>"2014", "published_at(2i)"=>"5", "published_at(3i)"=>"27", "published_at(4i)"=>"21", "published_at(5i)"=>"20", "custom_url"=>"", "source_url_title"=>"", "source_url"=>"", "user_id"=>"56", "browser_title"=>"", "meta_description"=>""}, "continue_editing"=>"false", "locale"=>:en}

You might find these useful too if you get an error:

app.cookies.to_hash
app.flash.to_hash
app.response # long, raw, HTML

What does a circled plus mean?

It is XOR. Another name for the XOR function is addition without carry. I suppose that's how the symbol might make sense.

latex large division sign in a math formula

I found the answer I was looking for. The thing to use here is the construct of

\left \middle \right

For example, in this case, two possible solutions are:

$\left( {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right) $

Or, in case the brackets are not necessary:

$\left. {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right. $

Extracting time from POSIXct

I can't find anything that deals with clock times exactly, so I'd just use some functions from package:lubridate and work with seconds-since-midnight:

require(lubridate)
clockS = function(t){hour(t)*3600+minute(t)*60+second(t)}
plot(clockS(times),val)

You might then want to look at some of the axis code to figure out how to label axes nicely.

How do I tell matplotlib that I am done with a plot?

Just enter plt.hold(False) before the first plt.plot, and you can stick to your original code.

Import txt file and having each line as a list

Do not create separate lists; create a list of lists:

results = []
with open('inputfile.txt') as inputfile:
    for line in inputfile:
        results.append(line.strip().split(','))

or better still, use the csv module:

import csv

results = []
with open('inputfile.txt', newline='') as inputfile:
    for row in csv.reader(inputfile):
        results.append(row)

Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file.

Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append() just process that line right there.

Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:

import csv

with open('inputfile.txt', newline='') as inputfile:
    results = list(csv.reader(inputfile))

How to get current page URL in MVC 3

public static string GetCurrentWebsiteRoot()
{
    return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
}

Laravel Eloquent: Ordering results of all()

You could still use sortBy (at the collection level) instead of orderBy (at the query level) if you still want to use all() since it returns a collection of objects.

Ascending Order

$results = Project::all()->sortBy("name");

Descending Order

$results = Project::all()->sortByDesc("name");

Check out the documentation about Collections for more details.

https://laravel.com/docs/5.1/collections

SQL INSERT INTO from multiple tables

If I'm understanding you correctly, you should be able to do this in one query, joining table1 and table2 together:

INSERT INTO table3 { name, age, sex, city, id, number}
SELECT p.name, p.age, p.sex, p.city, p.id, c.number
FROM table1 p
INNER JOIN table2 c ON c.Id = p.Id

How can I change the image of an ImageView?

Just to go a little bit further in the matter, you can also set a bitmap directly, like this:

ImageView imageView = new ImageView(this);  
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);

Of course, this technique is only useful if you need to change the image.

Count cells that contain any text

COUNTIF function will only count cells that contain numbers in your specified range.

COUNTA(range) will count all values in the list of arguments. Text entries and numbers are counted, even when they contain an empty string of length 0.

Example: Function in A7 =COUNTA(A1:A6)

Range:

A1 a

A2 b

A3 banana

A4 42

A5

A6

A7 4 -> result

Google spreadsheet function list contains a list of all available functions for future reference https://support.google.com/drive/table/25273?hl=en.

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

To view your iOS device's console in Safari on your Mac (Mac only apparently):

  1. On your iOS device, go to Settings > Safari > Advanced and switch on Web Inspector
  2. On your iOS device, load your web page in Safari
  3. Connect your device directly to your Mac
  4. On your Mac, if you've not already got Safari's Developer menu activated, go to Preferences > Advanced, and select "Show Develop menu in menu bar"
  5. On your Mac, go to Develop > [your iOS device name] > [your web page]

Safari's Inspector will appear showing a console for your iOS device.

How to handle iframe in Selenium WebDriver using java

Below approach of frame handling : When no id or name is given incase of nested frame

WebElement element =driver.findElement(By.xpath(".//*[@id='block-block19']//iframe"));
driver.switchTo().frame(element);
driver.findElement(By.xpath(".//[@id='carousel']/li/div/div[3]/a")).click();

php - get numeric index of associative array

echo array_search("car",array_keys($a));

How to merge two files line by line in Bash

Try following.

pr -tmJ a.txt b.txt > c.txt

Ruby on Rails generates model field:type - what are the options for field:type?

Remember to not capitalize your text when writing this command. For example:

Do write:

rails g model product title:string description:text image_url:string price:decimal

Do not write:

rails g Model product title:string description:text image_url:string price:decimal

At least it was a problem to me.

Declaring an unsigned int in Java

We needed unsigned numbers to model MySQL's unsigned TINYINT, SMALLINT, INT, BIGINT in jOOQ, which is why we have created jOOU, a minimalistic library offering wrapper types for unsigned integer numbers in Java. Example:

import static org.joou.Unsigned.*;

// and then...
UByte    b = ubyte(1);
UShort   s = ushort(1);
UInteger i = uint(1);
ULong    l = ulong(1);

All of these types extend java.lang.Number and can be converted into higher-order primitive types and BigInteger. Hope this helps.

(Disclaimer: I work for the company behind these libraries)

Is null reference possible?

If your intention was to find a way to represent null in an enumeration of singleton objects, then it's a bad idea to (de)reference null (it C++11, nullptr).

Why not declare static singleton object that represents NULL within the class as follows and add a cast-to-pointer operator that returns nullptr ?

Edit: Corrected several mistypes and added if-statement in main() to test for the cast-to-pointer operator actually working (which I forgot to.. my bad) - March 10 2015 -

// Error.h
class Error {
public:
  static Error& NOT_FOUND;
  static Error& UNKNOWN;
  static Error& NONE; // singleton object that represents null

public:
  static vector<shared_ptr<Error>> _instances;
  static Error& NewInstance(const string& name, bool isNull = false);

private:
  bool _isNull;
  Error(const string& name, bool isNull = false) : _name(name), _isNull(isNull) {};
  Error() {};
  Error(const Error& src) {};
  Error& operator=(const Error& src) {};

public:
  operator Error*() { return _isNull ? nullptr : this; }
};

// Error.cpp
vector<shared_ptr<Error>> Error::_instances;
Error& Error::NewInstance(const string& name, bool isNull = false)
{
  shared_ptr<Error> pNewInst(new Error(name, isNull)).
  Error::_instances.push_back(pNewInst);
  return *pNewInst.get();
}

Error& Error::NOT_FOUND = Error::NewInstance("NOT_FOUND");
//Error& Error::NOT_FOUND = Error::NewInstance("UNKNOWN"); Edit: fixed
//Error& Error::NOT_FOUND = Error::NewInstance("NONE", true); Edit: fixed
Error& Error::UNKNOWN = Error::NewInstance("UNKNOWN");
Error& Error::NONE = Error::NewInstance("NONE");

// Main.cpp
#include "Error.h"

Error& getError() {
  return Error::UNKNOWN;
}

// Edit: To see the overload of "Error*()" in Error.h actually working
Error& getErrorNone() {
  return Error::NONE;
}

int main(void) {
  if(getError() != Error::NONE) {
    return EXIT_FAILURE;
  }

  // Edit: To see the overload of "Error*()" in Error.h actually working
  if(getErrorNone() != nullptr) {
    return EXIT_FAILURE;
  }
}

how to toggle (hide/show) a table onClick of <a> tag in java script

Your anchor tag should be:

  <a id="loginLink" onclick="showHideTable();" href="#">Login</a>

And You javascript function :

function showHideTable()
{
   if (document.getElementById("loginTable").style.display == "none" ) {
       document.getElementById("loginTable").style.display="";

   } else {
      document.getElementById("loginTable").style.display="none";

}

how to convert binary string to decimal?

Use the radix parameter of parseInt:

var binary = "1101000";
var digit = parseInt(binary, 2);
console.log(digit);

Android 6.0 Marshmallow. Cannot write to SD Card

Android changed how permissions work with Android 6.0 that's the reason for your errors. You have to actually request and check if the permission was granted by user to use. So permissions in manifest file will only work for api below 21. Check this link for a snippet of how permissions are requested in api23 http://android-developers.blogspot.nl/2015/09/google-play-services-81-and-android-60.html?m=1

Code:-

If (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
            return;
        }`


` @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_RC) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //permission granted  start reading
            } else {
                Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

refresh leaflet map: map container is already initialized

Before initializing map check for is the map is already initiated or not

var container = L.DomUtil.get('map');
      if(container != null){
        container._leaflet_id = null;
      }

Java maximum memory on Windows XP

I think it has more to do with how Windows is configured as hinted by this response: Java -Xmx Option

Some more testing: I was able to allocate 1300MB on an old Windows XP machine with only 768MB physical RAM (plus virtual memory). On my 2GB RAM machine I can only get 1220MB. On various other corporate machines (with older Windows XP) I was able to get 1400MB. The machine with a 1220MB limit is pretty new (just purchased from Dell), so maybe it has newer (and more bloated) Windows and DLLs (it's running Window XP Pro Version 2002 SP2).

iOS 7 status bar overlapping UI

Better to have this things in info.plist

<key>UIStatusBarHidden</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>

this makes no status bar at all.

Spring - download response as a file

I've wrestled with this myself, trying to make it work from the server. Couldn't. Instead...

  1. To clarify on @dnc253's answer, $window.open(URL) is a method for having an Angular application open a given URL in another window. (It's really just a testable angular proxy for the universal window.open().) This is a great solution, preserves your history, and gets the file downloaded and possibly renders it in that fresh browser window if that's supported. But it often runs into popup blockers, which is a huge problem for reliability. Users often simply don't understand what's going on with them. So, if you don't mind immediately downloading the file with the current window, you can simply use the equally effective universal javascript method: location.href = "uriString", which works like a charm for me. Angular doesn't even realize anything has happened. I call it in a promise handler for once my POST/PUT operation has completed. If need be, have the POST/PUT return the URL to call, if you can't already infer it. You'll get the same behavior for the user as if it had downloaded in response to the PUT/POST. For example:

    $http.post(url, payload).then(function(returnData){
        var uriString = parseReturn(returnData);
        location.href="uriString"
    })
    
  2. You can, in fact, download something directly from an XHR request, but it requires full support for the HTML5 file API and is usually more trouble than it's worth unless you need to perform local transformations upon the file before you make it available to the user. (Sadly, I lack the time to provide details on that but there are other SO posts about using it.)

Assign JavaScript variable to Java Variable in JSP

As JavaScript is client side and JSP is Server side.

So Javascript does not execute until it gets to the browser, But Java executes on the server. So, Java does not know the value of the JavaScript variable.

However you assign value of Java variable to JavaScript variable.

How can I bind a background color in WPF/XAML?

The Background property expects a Brush object, not a string. Change the type of the property to Brush and initialize it thus:

Background = new SolidColorBrush(Colors.Red);

Large Numbers in Java

Here is an example which gets big numbers very quickly.

import java.math.BigInteger;

/*
250000th fib # is: 36356117010939561826426 .... 10243516470957309231046875
Time to compute: 3.5 seconds.
1000000th fib # is: 1953282128707757731632 .... 93411568996526838242546875
Time to compute: 58.1 seconds.
*/
public class Main {
    public static void main(String... args) {
        int place = args.length > 0 ? Integer.parseInt(args[0]) : 250 * 1000;
        long start = System.nanoTime();
        BigInteger fibNumber = fib(place);
        long time = System.nanoTime() - start;

        System.out.println(place + "th fib # is: " + fibNumber);
        System.out.printf("Time to compute: %5.1f seconds.%n", time / 1.0e9);
    }

    private static BigInteger fib(int place) {
        BigInteger a = new BigInteger("0");
        BigInteger b = new BigInteger("1");
        while (place-- > 1) {
            BigInteger t = b;
            b = a.add(b);
            a = t;
        }
        return b;
    }
}

Insert multiple lines into a file after specified pattern using shell script

Here is a more generic solution based on @rindeal solution which does not work on MacOS/BSD (/r expects a file):

cat << DOC > input.txt
abc
cdef
line
DOC
$ cat << EOF | sed '/^cdef$/ r /dev/stdin' input.txt
line 1
line 2
EOF

# outputs:
abc
cdef
line 1
line 2
line

This can be used to pipe anything into the file at the given position:

$ date | sed '/^cdef$/ r /dev/stdin' input.txt

# outputs
abc
cdef
Tue Mar 17 10:50:15 CET 2020
line

Also, you could add multiple commands which allows deleting the marker line cdef:

$ date | sed '/^cdef$/ {
  r /dev/stdin
  d
}' input.txt

# outputs
abc
Tue Mar 17 10:53:53 CET 2020
line

Is the buildSessionFactory() Configuration method deprecated in Hibernate

It's as simple as this: the JBoss docs are not 100% perfectly well-maintained. Go with what the JavaDoc says: buildSessionFactory(ServiceRegistry serviceRegistry).

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

It could be hardware. It could be something complicated...but I'd take a stab at suggesting that somewhere your threading code is not protecting some collection (such as a dictionary) with an appropriate lock.

What OS and service pack are you running?

Powershell import-module doesn't find modules

I think that the Import-Module is trying to find the module in the default directory C:\Windows\System32\WindowsPowerShell\v1.0\Modules.

Try to put the full path, or copy it to C:\Windows\System32\WindowsPowerShell\v1.0\Modules

Flutter command not found

Use the following steps for setup

  1. Download from Flutter SDK for Mac https://flutter.dev/docs/get-started/install/macos

  2. Extract the Flutter SDK zip (saved in Downloads) file using terminal. If you want to extract the Flutter SDK in fluttrerDevelopment folder

    $ cd ~/fluttrerDevelopment

    $ unzip ~/Downloads/flutter_macos_1.20.1-stable.zip

  3. Add the flutter tool to your path:

    $ export PATH=“$PATH:pwd/flutter/bin"

  4. If you have only Xcode setup in your machine then run

    $ flutter create my_first_flutter_app

    $ cd my_first_flutter_app

    $ flutter run

ASP.NET MVC ActionLink and post method

This has been a difficult problem for me to solve. How can I build a dynamic link in razor and html that can call an action method and pass a value or values to a specific action method? I considered several options including a custom html helper. I just came up with a simple and elegant solution.

The view

@model IEnumerable<MyMvcApp.Models.Product>

@using (Html.BeginForm()) {

     <table>
         <thead>
             <tr>
                 <td>Name</td>
                 <td>Price</td>
                 <td>Quantity</td>
            </tr>
        </thead>
        @foreach (Product p in Model.Products)
        {
            <tr>
                <td><a href="@Url.Action("Edit", "Product", p)">@p.Name</a></td>
                <td>@p.Price.ToString()</td>
                <td>@p.Quantity.ToString()</td>
            </tr>
         }
    </table>
}

The action method

public ViewResult Edit(Product prod)
{
    ContextDB contextDB = new ContextDB();

    Product product = contextDB.Products.Single(p => p.ProductID == prod.ProductId);

    product = prod;

    contextDB.SaveChanges();

    return View("Edit");
}

The point here is that Url.Action does not care whether the action method is a GET or a POST. It will access either type of method. You can pass your data to the action method using

@Url.Action(string actionName, string controllerName, object routeValues)

the routeValues object. I have tried this and it works. No, you are not technically doing a post or submitting the form but if the routeValues object contains your data, it doesnt matter if its a post or a get. You can use a particular action method signature to select the right method.

How to position two divs horizontally within another div

Via Bootstrap Grid, you can easily get the cross browser compatible solution.

<div class="container">     
  <div class="row">
    <div class="col-sm-6" style="background-color:lavender;">
      Div1       
    </div>
    <div class="col-sm-6" style="background-color:lavenderblush;">
          Div2
    </div>
  </div>
</div>

jsfiddle: http://jsfiddle.net/DTcHh/4197/

How can we redirect a Java program console output to multiple files?

You could use a "variable" inside the output filename, for example:

/tmp/FetchBlock-${current_date}.txt

current_date:

Returns the current system time formatted as yyyyMMdd_HHmm. An optional argument can be used to provide alternative formatting. The argument must be valid pattern for java.util.SimpleDateFormat.

Or you can also use a system_property or an env_var to specify something dynamic (either one needs to be specified as arguments)

How do I rename a repository on GitHub?

  1. open this url (https://github.com/) from your browser

  2. Go to repositories at the Right end of the page

  3. Open the link of repository that you want to rename

  4. click Settings (you will find in the Navigation bar)

  5. At the top you will find a box Called (Repository name) where you write the new name

  6. Press Rename

What is for Python what 'explode' is for PHP?

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

ERROR: Error 1005: Can't create table (errno: 121)

I faced this error (errno 121) but it was caused by mysql-created intermediate tables that had been orphaned, preventing me from altering a table even though no such constraint name existed across any of my tables. At some point, my MySQL had crashed or failed to cleanup an intermediate table (table name starting with a #sql-) which ended up presenting me with an error such as: Can't create table '#sql-' (errno 121) when trying to run an ALTER TABLE with certain constraint names.

According to the docs at http://dev.mysql.com/doc/refman/5.7/en/innodb-troubleshooting-datadict.html , you can search for these orphan tables with:

SELECT * FROM INFORMATION_SCHEMA.INNODB_SYS_TABLES WHERE NAME LIKE '%#sql%';

The version I was working with was 5.1, but the above command only works on versions >= 5.6 (manual is incorrect about it working for 5.5 or earlier, because INNODB_SYS_TABLES does not exist in such versions). I was able to find the orphaned temporary table (which did not match the one named in the message) by searching my mysql data directory in command line:

find . -iname '#*'

After discovering the filename, such as #sql-9ad_15.frm, I was able to drop that orphaned table in MySQL:

USE myschema;
DROP TABLE `#mysql50##sql-9ad_15`;

After doing so, I was then able to successfully run my ALTER TABLE.

For completeness, as per the MySQL documentation linked, "the #mysql50# prefix tells MySQL to ignore file name safe encoding introduced in MySQL 5.1."

How to annotate MYSQL autoincrement field with JPA annotations

As you have define the id in int type at the database creation, you have to use the same data type in the model class too. And as you have defined the id to auto increment in the database, you have to mention it in the model class by passing value 'GenerationType.AUTO' into the attribute 'strategy' within the annotation @GeneratedValue. Then the code becomes as below.

@Entity
public class Operator{

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;

  private String username;

  private String password;

  private Integer active;

  //Getters and setters...
}

Dynamic function name in javascript?

This will basically do it at the most simple level:

"use strict";
var name = "foo";
var func = new Function(
     "return function " + name + "(){ alert('sweet!')}"
)();

//call it, to test it
func();

If you want to get more fancy, I have a written an article on "Dynamic function names in JavaScript".

Android camera intent

Try the following I found here

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
    String result = data.toURI();
    // ...
  }
}

Custom li list-style with font-awesome icon

I did two things inspired by @OscarJovanny comment, with some hacks.

Step 1:

  • Download icons file as svg from Here, as I only need only this icon from font awesome

Step 2:

<style>
ul {
    list-style-type: none;
    margin-left: 10px;
}

ul li {
    margin-bottom: 12px;
    margin-left: -10px;
    display: flex;
    align-items: center;
}

ul li::before {
    color: transparent;
    font-size: 1px;
    content: " ";
    margin-left: -1.3em;
    margin-right: 15px;
    padding: 10px;
    background-color: orange;
    -webkit-mask-image: url("./assets/img/check-circle-solid.svg");
    -webkit-mask-size: cover;
}
</style>

Results

enter image description here

Oracle date to string conversion

Try this. Oracle has this feature to distinguish the millennium years..

As you mentioned, if your column is a varchar, then the below query will yield you 1989..

select to_date(column_name,'dd/mm/rr') from table1;

When the format rr is used in year, the following would be done by oracle.

if rr->00 to 49 ---> result will be 2000 - 2049, if rr->50 to 99 ---> result will be 1950 - 1999

Enabling HTTPS on express.js

I ran into a similar issue with getting SSL to work on a port other than port 443. In my case I had a bundle certificate as well as a certificate and a key. The bundle certificate is a file that holds multiple certificates, node requires that you break those certificates into separate elements of an array.

    var express = require('express');
    var https = require('https');
    var fs = require('fs');

    var options = {
      ca: [fs.readFileSync(PATH_TO_BUNDLE_CERT_1), fs.readFileSync(PATH_TO_BUNDLE_CERT_2)],
      cert: fs.readFileSync(PATH_TO_CERT),
      key: fs.readFileSync(PATH_TO_KEY)
    };

    app = express()

    app.get('/', function(req,res) {
        res.send('hello');
    });

    var server = https.createServer(options, app);

    server.listen(8001, function(){
        console.log("server running at https://IP_ADDRESS:8001/")
    });

In app.js you need to specify https and create the server accordingly. Also, make sure that the port you're trying to use is actually allowing inbound traffic.

How to split large text file in windows?

you can split using a third party software http://www.hjsplit.org/, for example give yours input that could be upto 9GB and then split, in my case I split 10 MB each enter image description here

C Programming: How to read the whole file contents into a buffer

Here is what I would recommend.

It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.

The idea is that we read the input in large-ish chunks (READALL_CHUNK), dynamically reallocating the buffer as we need it. We only use realloc(), fread(), ferror(), and free():

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

/* Size of each input chunk to be
   read and allocate for. */
#ifndef  READALL_CHUNK
#define  READALL_CHUNK  262144
#endif

#define  READALL_OK          0  /* Success */
#define  READALL_INVALID    -1  /* Invalid parameters */
#define  READALL_ERROR      -2  /* Stream error */
#define  READALL_TOOMUCH    -3  /* Too much input */
#define  READALL_NOMEM      -4  /* Out of memory */

/* This function returns one of the READALL_ constants above.
   If the return value is zero == READALL_OK, then:
     (*dataptr) points to a dynamically allocated buffer, with
     (*sizeptr) chars read from the file.
     The buffer is allocated for one extra char, which is NUL,
     and automatically appended after the data.
   Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
    char  *data = NULL, *temp;
    size_t size = 0;
    size_t used = 0;
    size_t n;

    /* None of the parameters can be NULL. */
    if (in == NULL || dataptr == NULL || sizeptr == NULL)
        return READALL_INVALID;

    /* A read error already occurred? */
    if (ferror(in))
        return READALL_ERROR;

    while (1) {

        if (used + READALL_CHUNK + 1 > size) {
            size = used + READALL_CHUNK + 1;

            /* Overflow check. Some ANSI C compilers
               may optimize this away, though. */
            if (size <= used) {
                free(data);
                return READALL_TOOMUCH;
            }

            temp = realloc(data, size);
            if (temp == NULL) {
                free(data);
                return READALL_NOMEM;
            }
            data = temp;
        }

        n = fread(data + used, 1, READALL_CHUNK, in);
        if (n == 0)
            break;

        used += n;
    }

    if (ferror(in)) {
        free(data);
        return READALL_ERROR;
    }

    temp = realloc(data, used + 1);
    if (temp == NULL) {
        free(data);
        return READALL_NOMEM;
    }
    data = temp;
    data[used] = '\0';

    *dataptr = data;
    *sizeptr = used;

    return READALL_OK;
}

Above, I've used a constant chunk size, READALL_CHUNK == 262144 (256*1024). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.

The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.

For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK, perhaps #define READALL_CHUNK 2097152 (2 MiB).

Because the definition of READALL_CHUNK is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152 command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.

Submit form on pressing Enter with AngularJS

Just wanted to point out that in the case of having a hidden submit button, you can just use the ngShow directive and set it to false like so:

HTML

<form ng-submit="myFunc()">
    <input type="text" name="username">
    <input type="submit" value="submit" ng-show="false">
</form>

Paste in insert mode?

Just add map:

" ~/.vimrc
inoremap <c-p> <c-r>*

restart vim and when press Crtl+p in insert mode, copied text will be pasted

How to make an Android device vibrate? with different frequency?

Above answer is very correct but I'm giving an easy step to do it:

 private static final long[] THREE_CYCLES = new long[] { 100, 1000, 1000,  1000, 1000, 1000 };

  public void longVibrate(View v) 
  {
     vibrateMulti(THREE_CYCLES);
  }

  private void vibrateMulti(long[] cycles) {
      NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
      Notification notification = new Notification();

      notification.vibrate = cycles; 
      notificationManager.notify(0, notification);
  }

And then in your xml file:

<button android:layout_height="wrap_content" 
        android:layout_width ="wrap_content" 
        android:onclick      ="longVibrate" 
        android:text         ="VibrateThrice">
</button>

That's the easiest way.

How do I generate sourcemaps when using babel and webpack?

On Webpack 2 I tried all 12 devtool options. The following options link to the original file in the console and preserve line numbers. See the note below re: lines only.

https://webpack.js.org/configuration/devtool

devtool best dev options

                                build   rebuild      quality                       look
eval-source-map                 slow    pretty fast  original source               worst
inline-source-map               slow    slow         original source               medium
cheap-module-eval-source-map    medium  fast         original source (lines only)  worst
inline-cheap-module-source-map  medium  pretty slow  original source (lines only)  best

lines only

Source Maps are simplified to a single mapping per line. This usually means a single mapping per statement (assuming you author is this way). This prevents you from debugging execution on statement level and from settings breakpoints on columns of a line. Combining with minimizing is not possible as minimizers usually only emit a single line.

REVISITING THIS

On a large project I find ... eval-source-map rebuild time is ~3.5s ... inline-source-map rebuild time is ~7s

How can I trigger a Bootstrap modal programmatically?

I wanted to do this the angular (2/4) way, here is what I did:

<div [class.show]="visible" [class.in]="visible" class="modal fade" id="confirm-dialog-modal" role="dialog">
..
</div>`

Important things to note:

  • visible is a variable (boolean) in the component which governs modal's visibility.
  • show and in are bootstrap classes.

An example component & html

Component

@ViewChild('rsvpModal', { static: false }) rsvpModal: ElementRef;
..
@HostListener('document:keydown.escape', ['$event'])
  onEscapeKey(event: KeyboardEvent) {
    this.hideRsvpModal();
  }
..
  hideRsvpModal(event?: Event) {
    if (!event || (event.target as Element).classList.contains('modal')) {
      this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'none');
      this.renderer.removeClass(this.rsvpModal.nativeElement, 'show');
      this.renderer.addClass(document.body, 'modal-open');
    }
  }
  showRsvpModal() {
    this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'block');
    this.renderer.addClass(this.rsvpModal.nativeElement, 'show');
    this.renderer.removeClass(document.body, 'modal-open');
  }

Html

<!--S:RSVP-->
<div class="modal fade" #rsvpModal role="dialog" aria-labelledby="niviteRsvpModalTitle" (click)="hideRsvpModal($event)">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="niviteRsvpModalTitle">

                </h5>
                <button type="button" class="close" (click)="hideRsvpModal()" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary bg-white text-dark"
                    (click)="hideRsvpModal()">Close</button>
            </div>
        </div>
    </div>
</div>
<!--E:RSVP-->

"Initializing" variables in python?

I know you have already accepted another answer, but I think the broader issue needs to addressed - programming style that is suitable to the current language.

Yes, 'initialization' isn't needed in Python, but what you are doing isn't initialization. It is just an incomplete and erroneous imitation of initialization as practiced in other languages. The important thing about initialization in static typed languages is that you specify the nature of the variables.

In Python, as in other languages, you do need to give variables values before you use them. But giving them values at the start of the function isn't important, and even wrong if the values you give have nothing to do with values they receive later. That isn't 'initialization', it's 'reuse'.

I'll make some notes and corrections to your code:

def main():
   # doc to define the function
   # proper Python indentation
   # document significant variables, especially inputs and outputs
   # grade_1, grade_2, grade_3, average - id these
   # year - id this
   # fName, lName, ID, converted_ID 

   infile = open("studentinfo.txt", "r") 
   # you didn't 'intialize' this variable

   data = infile.read()  
   # nor this  

   fName, lName, ID, year = data.split(",")
   # this will produce an error if the file does not have the right number of strings
   # 'year' is now a string, even though you 'initialized' it as 0

   year = int(year)
   # now 'year' is an integer
   # a language that requires initialization would have raised an error
   # over this switch in type of this variable.

   # Prompt the user for three test scores
   grades = eval(input("Enter the three test scores separated by a comma: "))
   # 'eval' ouch!
   # you could have handled the input just like you did the file input.

   grade_1, grade_2, grade_3 = grades   
   # this would work only if the user gave you an 'iterable' with 3 values
   # eval() doesn't ensure that it is an iterable
   # and it does not ensure that the values are numbers. 
   # What would happen with this user input: "'one','two','three',4"?

   # Create a username 
   uName = (lName[:4] + fName[:2] + str(year)).lower()

   converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
   # earlier you 'initialized' converted_ID
   # initialization in a static typed language would have caught this typo
   # pseudo-initialization in Python does not catch typos
   ....

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Bash if statement with multiple conditions throws an error

You can get some inspiration by reading an entrypoint.sh script written by the contributors from MySQL that checks whether the specified variables were set.

As the script shows, you can pipe them with -a, e.g.:

if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
    ...
fi

Sizing elements to percentage of screen width/height

You could build a Column/Row with Flexible or Expanded children that have flex values that add up to the percentages you want.

You may also find the AspectRatio widget useful.

Passing data to a bootstrap modal

For updating an href value, for example, I would do something like:

<a href="#myModal" data-toggle="modal" data-url="http://example.com">Show modal</a>

$('#myModal').on('show.bs.modal', function (e) {
    var url = $(e.relatedTarget).data('url');
    $(e.currentTarget).find('.any-class').attr("href", "url");
})

Move the most recent commit(s) to a new branch with Git

You can do this is just 3 simple step that i used.

1) make new branch where you want to commit you recent update.

git branch <branch name>

2) Find Recent Commit Id for commit on new branch.

git log

3) Copy that commit id note that Most Recent commit list take place on top. so you can find your commit. you also find this via message.

git cherry-pick d34bcef232f6c...

you can also provide some rang of commit id.

git cherry-pick d34bcef...86d2aec

Now your job done. If you picked correct id and correct branch then you will success. So before do this be careful. else another problem can occur.

Now you can push your code

git push

Cut Corners using CSS

We had the problem of different background colors for our cutted elements. And we only wanted upper right und bottom left corner.

enter image description here

_x000D_
_x000D_
body {_x000D_
 background-color: rgba(0,0,0,0.3)_x000D_
 _x000D_
}_x000D_
_x000D_
.box {_x000D_
 position: relative;_x000D_
 display: block;_x000D_
 background: blue;_x000D_
 text-align: center;_x000D_
 color: white;_x000D_
 padding: 15px;_x000D_
 margin: 50px;_x000D_
}_x000D_
_x000D_
.box:before,_x000D_
.box:after {_x000D_
 content: "";_x000D_
 position: absolute;_x000D_
 left: 0; _x000D_
 right: 0;_x000D_
 bottom: 100%;_x000D_
 border-bottom: 15px solid blue;_x000D_
 border-left: 15px solid transparent;_x000D_
 border-right: 15px solid transparent;_x000D_
}_x000D_
_x000D_
.box:before{_x000D_
 border-left: 15px solid blue;_x000D_
}_x000D_
_x000D_
.box:after{_x000D_
 border-right: 15px solid blue;_x000D_
}_x000D_
_x000D_
.box:after {_x000D_
 bottom: auto;_x000D_
 top: 100%;_x000D_
 border-bottom: none;_x000D_
 border-top: 15px solid blue;_x000D_
}_x000D_
_x000D_
_x000D_
/* Active box */_x000D_
.box.active{_x000D_
 background: white;_x000D_
 color: black;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
.active:before,_x000D_
.active:after {_x000D_
 border-bottom: 15px solid white;_x000D_
}_x000D_
_x000D_
.active:before{_x000D_
 border-left: 15px solid white;_x000D_
}_x000D_
_x000D_
.active:after{_x000D_
 border-right: 15px solid white;_x000D_
}_x000D_
_x000D_
.active:after {_x000D_
 border-bottom: none;_x000D_
 border-top: 15px solid white;_x000D_
}
_x000D_
<div class="box">_x000D_
 Some text goes here. Some text goes here. Some text goes here. Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>Some text goes here.<br/>_x000D_
</div>_x000D_
<div class="box">_x000D_
 Some text goes here._x000D_
</div>_x000D_
<div class="box active">_x000D_
 Some text goes here._x000D_
 <span class="border-bottom"></span>_x000D_
</div>_x000D_
<div class="box">_x000D_
 Some text goes here._x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I add raw data body to an axios request?

I got same problem. So I looked into the axios document. I found it. you can do it like this. this is easiest way. and super simple.

https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format

var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

You can use .then,.catch.

How to force R to use a specified factor level as reference in a regression?

Others have mentioned the relevel command which is the best solution if you want to change the base level for all analyses on your data (or are willing to live with changing the data).

If you don't want to change the data (this is a one time change, but in the future you want the default behavior again), then you can use a combination of the C (note uppercase) function to set contrasts and the contr.treatments function with the base argument for choosing which level you want to be the baseline.

For example:

lm( Sepal.Width ~ C(Species,contr.treatment(3, base=2)), data=iris )

How to make an executable JAR file?

A jar file is simply a file containing a collection of java files. To make a jar file executable, you need to specify where the main Class is in the jar file. Example code would be as follows.

public class JarExample {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // your logic here
            }
        });
    }
}

Compile your classes. To make a jar, you also need to create a Manifest File (MANIFEST.MF). For example,

Manifest-Version: 1.0
Main-Class: JarExample

Place the compiled output class files (JarExample.class,JarExample$1.class) and the manifest file in the same folder. In the command prompt, go to the folder where your files placed, and create the jar using jar command. For example (if you name your manifest file as jexample.mf)

jar cfm jarexample.jar jexample.mf *.class

It will create executable jarexample.jar.

How to get the part of a file after the first line that matches a regular expression?

grep -A 10000000 'TERMINATE' file

  • is much, much faster than sed especially working on really big file. It works up to 10M lines (or whatever you put in) so no harm in making this big enough to handle about anything you hit.

Git credential helper - update password

None of these answers ended up working for my Git credential issue. Here is what did work if anyone needs it (I'm using Git 1.9 on Windows 8.1).

To update your credentials, go to Control PanelCredential ManagerGeneric Credentials. Find the credentials related to your Git account and edit them to use the updated password.

Reference: How to update your Git credentials on Windows

Note that to use the Windows Credential Manager for Git you need to configure the credential helper like so:

git config --global credential.helper wincred

If you have multiple GitHub accounts that you use for different repositories, then you should configure credentials to use the full repository path (rather than just the domain, which is the default):

git config --global credential.useHttpPath true

How to duplicate sys.stdout to a log file?

None of the answers above really seems to answer the problem posed. I know this is an old thread, but I think this problem is a lot simpler than everyone is making it:

class tee_err(object):

 def __init__(self):
    self.errout = sys.stderr

    sys.stderr = self

    self.log = 'logfile.log'
    log = open(self.log,'w')
    log.close()

 def write(self, line):

    log = open(self.log,'a')
    log.write(line)
    log.close()   

    self.errout.write(line)

Now this will repeat everything to the normal sys.stderr handler and your file. Create another class tee_out for sys.stdout.

How to put a jar in classpath in Eclipse?

As of rev 17 of the Android Developer Tools, the correct way to add a library jar when.using the tools and Eclipse is to create a directory called libs on the same level as your src and assets directories and then drop the jar in there. Nothing else.required, the tools take care of all the rest for you automatically.

Converting NSString to NSDictionary / JSON

Swift 3:

if let jsonString = styleDictionary as? String {
    let objectData = jsonString.data(using: String.Encoding.utf8)
    do {
        let json = try JSONSerialization.jsonObject(with: objectData!, options: JSONSerialization.ReadingOptions.mutableContainers) 
        print(String(describing: json)) 

    } catch {
        // Handle error
        print(error)
    }
}

Difference between "or" and || in Ruby?

Both or and || evaluate to true if either operand is true. They evaluate their second operand only if the first is false.

As with and, the only difference between or and || is their precedence.

Just to make life interesting, and and or have the same precedence, while && has a higher precedence than ||.

How to add jQuery to an HTML page?

You can include JQuery using any of the following:

  • Link Using jQuery with a CDN

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

  • Download Jquery From Here and include in your project
  • Download latest version using this link

Your code placement can look something like this

  • Your Jquery should be included before using it any where else it will throw an error

```

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
    $('input[type=radio]').change(function() {

    $('input[type=radio]').each(function(index) {
        $(this).closest('tr').removeClass('selected');
    });

        $(this).closest('tr').addClass('selected');
    });
});
</script>

```

Including .cpp files

Because your program now contains two copies of the foo function, once inside foo.cpp and once inside main.cpp

Think of #include as an instruction to the compiler to copy/paste the contents of that file into your code, so you'll end up with a processed main.cpp that looks like this

#include <iostream> // actually you'll get the contents of the iostream header here, but I'm not going to include it!
int foo(int a){
    return ++a;
}

int main(int argc, char *argv[])
{
int x=42;
std::cout << x <<std::endl;
std::cout << foo(x) << std::endl;
return 0;
}

and foo.cpp

int foo(int a){
    return ++a;
}

hence the multiple definition error

How do you clear the focus in javascript?

.focus() and then .blur() something else arbitrary on your page. Since only one element can have the focus, it is transferred to that element and then removed.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I was failing to send a body on a DELETE that required one and was getting this message as a result.

How to specify line breaks in a multi-line flexbox layout?

I think the traditional way is flexible and fairly easy to understand:

Markup

<div class="flex-grid">
    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>

    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>
    <div class="col-4">.col-4</div>

    <div class="col-3">.col-3</div>
    <div class="col-9">.col-9</div>

    <div class="col-6">.col-6</div>
    <div class="col-6">.col-6</div>
</div>

Create grid.css file:

.flex-grid {
  display: flex;
  flex-flow: wrap;
}

.col-1 {flex: 0 0 8.3333%}
.col-2 {flex: 0 0 16.6666%}
.col-3 {flex: 0 0 25%}
.col-4 {flex: 0 0 33.3333%}
.col-5 {flex: 0 0 41.6666%}
.col-6 {flex: 0 0 50%}
.col-7 {flex: 0 0 58.3333%}
.col-8 {flex: 0 0 66.6666%}
.col-9 {flex: 0 0 75%}
.col-10 {flex: 0 0 83.3333%}
.col-11 {flex: 0 0 91.6666%}
.col-12 {flex: 0 0 100%}

[class*="col-"] {
  margin: 0 0 10px 0;

  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

@media (max-width: 400px) {
  .flex-grid {
    display: block;
  }
}

I've created an example (jsfiddle)

Try to resize the window under 400px, it's responsive!!

pip installing in global site-packages instead of virtualenv

For Python 3ers

Try updating. I had this exact same problem and tried Chases' answer, however no success. The quickest way to refactor this is to update your Python Minor / Patch version if possible. I noticed that I was running 3.5.1 and updated to 3.5.2. Pyvenv once again works.

How to properly apply a lambda function into a pandas data frame column

You need mask:

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)

Another solution with loc and boolean indexing:

sample.loc[sample['PR'] < 90, 'PR'] = np.nan

Sample:

import pandas as pd
import numpy as np

sample = pd.DataFrame({'PR':[10,100,40] })
print (sample)
    PR
0   10
1  100
2   40

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
print (sample)
      PR
0    NaN
1  100.0
2    NaN
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
print (sample)
      PR
0    NaN
1  100.0
2    NaN

EDIT:

Solution with apply:

sample['PR'] = sample['PR'].apply(lambda x: np.nan if x < 90 else x)

Timings len(df)=300k:

sample = pd.concat([sample]*100000).reset_index(drop=True)

In [853]: %timeit sample['PR'].apply(lambda x: np.nan if x < 90 else x)
10 loops, best of 3: 102 ms per loop

In [854]: %timeit sample['PR'].mask(sample['PR'] < 90, np.nan)
The slowest run took 4.28 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.71 ms per loop

Why do some functions have underscores "__" before and after the function name?

Added an example to understand the use of __ in python. Here is the list of All __

https://docs.python.org/3/genindex-all.html#_

Certain classes of identifiers (besides keywords) have special meanings. Any use of * names, in any other context, that does not follow explicitly documented use, is subject to breakage without warning

Access restriction using __

"""
Identifiers:
-  Contain only (A-z, 0-9, and _ )
-  Start with a lowercase letter or _.
-  Single leading _ :  private
-  Double leading __ :  strong private
-  Start & End  __ : Language defined Special Name of Object/ Method
-  Class names start with an uppercase letter.
-

"""


class BankAccount(object):
    def __init__(self, name, money, password):
        self.name = name            # Public
        self._money = money         # Private : Package Level
        self.__password = password  # Super Private

    def earn_money(self, amount):
        self._money += amount
        print("Salary Received: ", amount, " Updated Balance is: ", self._money)

    def withdraw_money(self, amount):
        self._money -= amount
        print("Money Withdraw: ", amount, " Updated Balance is: ", self._money)

    def show_balance(self):
        print(" Current Balance is: ", self._money)


account = BankAccount("Hitesh", 1000, "PWD")  # Object Initalization

# Method Call
account.earn_money(100)

# Show Balance
print(account.show_balance())

print("PUBLIC ACCESS:", account.name)  # Public Access

# account._money is accessible because it is only hidden by convention
print("PROTECTED ACCESS:", account._money)  # Protected Access

# account.__password will throw error but account._BankAccount__password will not
# because __password is super private
print("PRIVATE ACCESS:", account._BankAccount__password)

# Method Call
account.withdraw_money(200)

# Show Balance
print(account.show_balance())

# account._money is accessible because it is only hidden by convention
print(account._money)  # Protected Access

Uppercase first letter of variable

You can use text-transform: capitalize; for this work -

HTML -

<input type="text" style="text-transform: capitalize;" />

JQuery -

$(document).ready(function (){
   var asdf = "WERTY UIOP";
   $('input').val(asdf.toLowerCase());
});

Try This

Note: It's only change visual representation of the string. If you alert this string it's always show original value of the string.

Setting network adapter metric priority in Windows 7

I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.

Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.

After this, Windows started prioritize Ethernet adapter.

Renaming the current file in Vim

If you use git and already have the tpope's plugin fugitive.vim then simply:

:Gmove newname

This will:

  1. Rename your file on disk.
  2. Rename the file in git repo.
  3. Reload the file into the current buffer.
  4. Preserve undo history.

If your file was not yet added to a git repo then first add it:

:Gwrite

Disable beep of Linux Bash on Windows 10

Find the location of the .bash_profile file and enter the following into the file:

setterm -blength 0

Which will set the amount of time the beep happens to 0 and thus no beep.

How can I clear the SQL Server query cache?

Note that neither DBCC DROPCLEANBUFFERS; nor DBCC FREEPROCCACHE; is supported in SQL Azure / SQL Data Warehouse.

However, if you need to reset the plan cache in SQL Azure, you can alter one of the tables in the query (for instance, just add then remove a column), this will have the side-effect of removing the plan from the cache.

I personally do this as a way of testing query performance without having to deal with cached plans.

More details about SQL Azure Procedure Cache here

How to do ToString for a possibly null object?

C# 6.0 Edit:

With C# 6.0 we can now have a succinct, cast-free version of the orignal method:

string s = myObj?.ToString() ?? "";

Or even using interpolation:

string s = $"{myObj}";

Original Answer:

string s = (myObj ?? String.Empty).ToString();

or

string s = (myObjc ?? "").ToString()

to be even more concise.

Unfortunately, as has been pointed out you'll often need a cast on either side to make this work with non String or Object types:

string s = (myObjc ?? (Object)"").ToString()
string s = ((Object)myObjc ?? "").ToString()

Therefore, while it maybe appears elegant, the cast is almost always necessary and is not that succinct in practice.

As suggested elsewhere, I recommend maybe using an extension method to make this cleaner:

public static string ToStringNullSafe(this object value)
{
    return (value ?? string.Empty).ToString();
}

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Hope this will help little more :-

var string = "123456789"

If you want a substring after some particular index.

var indexStart  =  string.index(after: string.startIndex )// you can use any index in place of startIndex
var strIndexStart   = String (string[indexStart...])//23456789

If you want a substring after removing some string at the end.

var indexEnd  =  string.index(before: string.endIndex)
var strIndexEnd   = String (string[..<indexEnd])//12345678

you can also create indexes with the following code :-

var  indexWithOffset =  string.index(string.startIndex, offsetBy: 4)

What is the email subject length limit?

I don't believe that there is a formal limit here, and I'm pretty sure there isn't any hard limit specified in the RFC either, as you found.

I think that some pretty common limitations for subject lines in general (not just e-mail) are:

  • 80 Characters
  • 128 Characters
  • 256 Characters

Obviously, you want to come up with something that is reasonable. If you're writing an e-mail client, you may want to go with something like 256 characters, and obviously test thoroughly against big commercial servers out there to make sure they serve your mail correctly.

Hope this helps!

Proper usage of .net MVC Html.CheckBoxFor

I was having a problem with ASP.NET MVC 5 where CheckBoxFor would not check my checkboxes on server-side validation failure even though my model clearly had the value set to true. My Razor markup/code looked like:

@Html.CheckBoxFor(model => model.MyBoolValue, new { @class = "mySpecialClass" } )

To get this to work, I had to change this to:

@{
    var checkboxAttributes = Model.MyBoolValue ?
        (object) new { @class = "mySpecialClass", @checked = "checked" } :
        (object) new { @class = "mySpecialClass" };
}
@Html.CheckBox("MyBoolValue", checkboxAttributes)

Angular - "has no exported member 'Observable'"

Just remove /Observable from 'rxjs/Observable';

If you then get Cannot find module 'rxjs-compat/Observable' just put below line to thr terminal and press enter.

npm install --save rxjs-compat

How to append rows to an R data frame

Lets take a vector 'point' which has numbers from 1 to 5

point = c(1,2,3,4,5)

if we want to append a number 6 anywhere inside the vector then below command may come handy

i) Vectors

new_var = append(point, 6 ,after = length(point))

ii) columns of a table

new_var = append(point, 6 ,after = length(mtcars$mpg))

The command append takes three arguments:

  1. the vector/column to be modified.
  2. value to be included in the modified vector.
  3. a subscript, after which the values are to be appended.

simple...!! Apologies in case of any...!

How to find index of an object by key and value in an javascript array

function getIndexByAttribute(list, attr, val){
    var result = null;
    $.each(list, function(index, item){
        if(item[attr].toString() == val.toString()){
           result = index;
           return false;     // breaks the $.each() loop
        }
    });
    return result;
}

How do I show the changes which have been staged?

If you have more than one file with staged changes, it may more practical to use git add -i, then select 6: diff, and finally pick the file(s) you are interested in.

PHP Fatal error: Cannot access empty property

As I see in your code, it seems you are following an old documentation/tutorial about OOP in PHP based on PHP4 (OOP wasn't supported but adapted somehow to be used in a simple ways), since PHP5 an official support was added and the notation has been changed from what it was.

Please see this code review here:

<?php
class my_class{

    public $my_value = array();

    function __construct( $value ) { // the constructor name is __construct instead of the class name
        $this->my_value[] = $value;
    }
    function set_value ($value){
    // Error occurred from here as Undefined variable: my_value
        $this->my_value = $value; // remove the $ sign
    }

}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c'); // your array variable here will be replaced by a simple string 
// $a->my_class('d'); // you can call this if you mean calling the contructor 


// at this stage you can't loop on the variable since it have been replaced by a simple string ('c')
foreach ($a->my_value as &$value) { // look for foreach samples to know how to use it well
    echo $value;
}

?>

I hope it helps

Why does python use 'else' after for and while loops?

I was just trying to make sense of it again myself. I found that the following helps!

• Think of the else as being paired with the if inside the loop (instead of with the for) - if condition is met then break the loop, else do this - except it's one else paired with multiple ifs!
• If no ifs were satisfied at all, then do the else.
• The multiple ifs can also actually be thought of as if-elifs!

Search a text file and print related lines in Python?

searchfile = open("file.txt", "r")
for line in searchfile:
    if "searchphrase" in line: print line
searchfile.close()

To print out multiple lines (in a simple way)

f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

The comma in print l, prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.

Or better yet (stealing back from Mark Ransom):

with open("file.txt", "r") as f:
    searchlines = f.readlines()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

How can I compare strings in C using a `switch` statement?

This is how you do it. No, not really.

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


 #define p_ntohl(u) ({const uint32_t Q=0xFF000000;       \
                     uint32_t S=(uint32_t)(u);           \
                   (*(uint8_t*)&Q)?S:                    \
                   ( (S<<24)|                            \
                     ((S<<8)&0x00FF0000)|                \
                     ((S>>8)&0x0000FF00)|                \
                     ((S>>24)&0xFF) );  })

main (void)
{
    uint32_t s[0x40]; 
    assert((unsigned char)1 == (unsigned char)(257));
    memset(s, 0, sizeof(s));
    fgets((char*)s, sizeof(s), stdin);

    switch (p_ntohl(s[0])) {
        case 'open':
        case 'read':
        case 'seek':
            puts("ok");
            break;
        case 'rm\n\0':
            puts("not authorized");
            break;
        default:
            puts("unrecognized command");  
    }
    return 0;
}

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

You can't directly get an iterator for an array.

But you can use a List, backed by your array, and get an ierator on this list. For that, your array must be an Integer array (instead of an int array):

Integer[] arr={1,2,3};
List<Integer> arrAsList = Arrays.asList(arr);
Iterator<Integer> iter = arrAsList.iterator();

Note: it is only theory. You can get an iterator like this, but I discourage you to do so. Performances are not good compared to a direct iteration on the array with the "extended for syntax".

Note 2: a list construct with this method doesn't support all methods (since the list is backed by the array which have a fixed size). For example, "remove" method of your iterator will result in an exception.

How can I fill a div with an image while keeping it proportional?

An old question but deserves an update as now there is a way.

The correct CSS based answer is to use object-fit: cover, which works like background-size: cover. Positioning would be taken care of by object-position attribute, which defaults to centering.

But there is no support for it in any IE / Edge browsers, or Android < 4.4.4. Also, object-position is not supported by Safari, iOS or OSX. Polyfills do exist, object-fit-images seems to give best support.

For more details on how the property works, see CSS Tricks article on object-fit for explanation and demo.

How to see data from .RData file?

I think the problem is that you load isfar data.frame but you overwrite it by value returned by load.

Try either:

load("C:/Users/isfar.RData") 
head(isfar)

Or more general way

load("C:/Users/isfar.RData", ex <- new.env())
ls.str(ex) 

AngularJS : ng-click not working

Just add the function reference to the $scope in the controller:

for example if you want the function MyFunction to work in ng-click just add to the controller:

app.controller("MyController", ["$scope", function($scope) {
   $scope.MyFunction = MyFunction;
}]);

GUI-based or Web-based JSON editor that works like property explorer

Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.

Based on JSON Schema

Commercial (No endorsement intended or implied, may or may not meet requirement)

jQuery

YAML

See Also

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

How to convert string date to Timestamp in java?

You can convert String to Timestamp:

String inDate = "01-01-1990"
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Timestamp ts = new Timestamp(((java.util.Date)df.parse(inDate)).getTime());

How to make a background 20% transparent on Android

See screenshot

I have taken three Views. In the first view I set full (no alpha) color, on the second view I set half (0.5 alpha) color, and on the third view I set light color (0.2 alpha).

You can set any color and get color with alpha by using the below code:

File activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:gravity = "center"
    android:orientation = "vertical"
    tools:context = "com.example.temp.MainActivity" >

    <View
        android:id = "@+id/fullColorView"
        android:layout_width = "100dip"
        android:layout_height = "100dip" />

    <View
        android:id = "@+id/halfalphaColorView"
        android:layout_width = "100dip"
        android:layout_height = "100dip"
        android:layout_marginTop = "20dip" />

    <View
        android:id = "@+id/alphaColorView"
        android:layout_width = "100dip"
        android:layout_height = "100dip"
        android:layout_marginTop = "20dip" />

</LinearLayout>

File MainActivity.java

public class MainActivity extends Activity {

    private View fullColorView, halfalphaColorView, alphaColorView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fullColorView = (View)findViewById(R.id.fullColorView);
        halfalphaColorView = (View)findViewById(R.id.halfalphaColorView);
        alphaColorView = (View)findViewById(R.id.alphaColorView);

        fullColorView.setBackgroundColor(Color.BLUE);
        halfalphaColorView.setBackgroundColor(getColorWithAlpha(Color.BLUE, 0.5f));
        alphaColorView.setBackgroundColor(getColorWithAlpha(Color.BLUE, 0.2f));
    }


    private int getColorWithAlpha(int color, float ratio) {
        int newColor = 0;
        int alpha = Math.round(Color.alpha(color) * ratio);
        int r = Color.red(color);
        int g = Color.green(color);
        int b = Color.blue(color);
        newColor = Color.argb(alpha, r, g, b);
        return newColor;
    }
}

Kotlin version:

private fun getColorWithAlpha(color: Int, ratio: Float): Int {
  return Color.argb(Math.round(Color.alpha(color) * ratio), Color.red(color), Color.green(color), Color.blue(color))
}

Done

expected constructor, destructor, or type conversion before ‘(’ token

This is not only a 'newbie' scenario. I just ran across this compiler message (GCC 5.4) when refactoring a class to remove some constructor parameters. I forgot to update both the declaration and definition, and the compiler spit out this unintuitive error.

The bottom line seems to be this: If the compiler can't match the definition's signature to the declaration's signature it thinks the definition is not a constructor and then doesn't know how to parse the code and displays this error. Which is also what happened for the OP: std::string is not the same type as string so the declaration's signature differed from the definition's and this message was spit out.

As a side note, it would be nice if the compiler looked for almost-matching constructor signatures and upon finding one suggested that the parameters didn't match rather than giving this message.

How to determine if a String has non-alphanumeric characters?

string.matches("^\\W*$"); should do what you want, but it does not include whitespace. string.matches("^(?:\\W|\\s)*$"); does match whitespace as well.

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

Look in the Cmakelists.txt if you find ARM you need to install C++ for ARM

It's these packages:

C++ Universal Windows Platform for ARM64 "Not Required"

Visual C++ Compilers and libraries for ARM "Not Required"

Visual C++ Compilers and libraries for ARM64 "Very Likely Required"

Required for finding Threads on ARM 
enable_language(C) 
enable_language(CXX)

Then the problems

No CMAKE_C_COMPILER could be found.

No CMAKE_CXX_COMPILER could be found.

Might disappear unless you specify c compiler like clang, and maybe installing clang will work in other favour.

You can with optional remove in cmakelists.txt both with # before enable_language if you are not compiling for ARM.

How do I decompile a .NET EXE into readable C# source code?

I'm surprised no one has mentioned dnSpy. dnSpy is a debugger and .NET assembly editor. You can use it to edit and debug assemblies even if you don't have any source code available.

Main features:

  • Debug .NET and Unity assemblies
  • Edit .NET and Unity assemblies
  • Light and dark themes

It is open source and one of most widely used reverse engineering tool for dot net.

How to open child forms positioned within MDI parent in VB.NET?

You will want to set the MdiParent property of your new form to the name of the MDI parent form, as follows:

dim form as new yourform
form.show()
form.MdiParent = nameParent

How can I plot a confusion matrix?

@bninopaul 's answer is not completely for beginners

here is the code you can "copy and run"

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt

array = [[13,1,1,0,2,0],
         [3,9,6,0,1,0],
         [0,0,16,2,0,0],
         [0,0,0,13,0,0],
         [0,0,0,0,15,0],
         [0,0,1,0,0,15]]

df_cm = pd.DataFrame(array, range(6), range(6))
# plt.figure(figsize=(10,7))
sn.set(font_scale=1.4) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}) # font size

plt.show()

result

How to delete from select in MySQL?

DELETE 
  p1
  FROM posts AS p1 
CROSS JOIN (
  SELECT ID FROM posts GROUP BY id HAVING COUNT(id) > 1
) AS p2
USING (id)

Error QApplication: no such file or directory

Well, It's a bit late for this but I've just started learning Qt and maybe this could help somebody out there:

If you're using Qt Creator then when you've started creating the project you were asked to choose a kit to be used with your project, Let's say you chose Desktop Qt <version-here> MinGW 64-bit. For Qt 5, If you opened the Qt folder of your installation, you'll find a folder with the version of Qt installed as its name inside it, here you can find the kits you can choose from.

You can go to /PATH/FOR/Qt/mingw<version>_64/include and here you'll find all the includes you can use in your program, just search for QApplication and you'll find it inside the folder QtWidgets, So you can use #include <QtWidgets/QApplication> since the path starts from the include folder.

The same goes for other headers if you're stuck with any and for other kits.

Note: "all the includes you can use" doesn't mean these are the only ones you can use, If you include iostream for example then the compiler will include it from /PATH/FOR/Qt/Tools/mingw<version>_64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/iostream

What does '--set-upstream' do?

When you push to a remote and you use the --set-upstream flag git sets the branch you are pushing to as the remote tracking branch of the branch you are pushing.

Adding a remote tracking branch means that git then knows what you want to do when you git fetch, git pull or git push in future. It assumes that you want to keep the local branch and the remote branch it is tracking in sync and does the appropriate thing to achieve this.

You could achieve the same thing with git branch --set-upstream-to or git checkout --track. See the git help pages on tracking branches for more information.