Programs & Examples On #Activity state

Where's my invalid character (ORA-00911)

Of the top of my head, can you try to use the 'q' operator for the string literal

something like

insert all
  into domo_queries values (q'[select 
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = 'CHQ PeopleSoft FS']')
select * from dual;

Note that the single quotes of your predicate are not escaped, and the string sits between q'[...]'.

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

The only way to have multiple, separately accessible functions in a single file is to define STATIC METHODS using object-oriented programming. You'd access the function as myClass.static1(), myClass.static2() etc.

OOP functionality is only officially supported since R2008a, so unless you want to use the old, undocumented OOP syntax, the answer for you is no, as explained by @gnovice.

EDIT

One more way to define multiple functions inside a file that are accessible from the outside is to create a function that returns multiple function handles. In other words, you'd call your defining function as [fun1,fun2,fun3]=defineMyFunctions, after which you could use out1=fun1(inputs) etc.

Creating an empty list in Python

Here is how you can test which piece of code is faster:

% python -mtimeit  "l=[]"
10000000 loops, best of 3: 0.0711 usec per loop

% python -mtimeit  "l=list()"
1000000 loops, best of 3: 0.297 usec per loop

However, in practice, this initialization is most likely an extremely small part of your program, so worrying about this is probably wrong-headed.

Readability is very subjective. I prefer [], but some very knowledgable people, like Alex Martelli, prefer list() because it is pronounceable.

Order of execution of tests in TestNG

Tests like unit tests? What for? Tests HAVE to be independant, otherwise.... you can not run a test individually. If they are independent, why even interfere? Plus - what is an "order" if you run them in multiple threads on multiple cores?

How do I set a program to launch at startup

Add an app to run automatically at startup in Windows 10

Step 1: Select the Windows Start button and scroll to find the app you want to run at startup.

Step 2: Right-click the app, select More, and then select Open file location. This opens the location where the shortcut to the app is saved. If there isn't an option for Open file location, it means the app can't run at startup.

Step 3: With the file location open, press the Windows logo key + R, type shell:startup, then select OK. This opens the Startup folder.

Step 4: Copy and paste the shortcut to the app from the file location to the Startup folder.

How to test a variable is null in python

Testing for name pointing to None and name existing are two semantically different operations.

To check if val is None:

if val is None:
    pass  # val exists and is None

To check if name exists:

try:
    val
except NameError:
    pass  # val does not exist at all

A simple jQuery form validation script

you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

<script type="text/javascript">
$(document).ready(function(){
    $("#formID").validate({
    rules :{
        "data[User][name]" : {
            required : true
        }
    },
    messages :{
        "data[User][name]" : {
            required : 'Enter username'
        }
    }
    });
});
</script>

You can see required : true same there is many more property like for email you can define email : true for number number : true

How to call a VbScript from a Batch File without opening an additional command prompt

rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"

OR

rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"

You can also add the option //e:vbscript to make sure the scripting engine will recognize your script as a vbscript.

Windows/DOS batch files doesn't require escaping \ like *nix.

You can still use "C:\Users\guest\Desktop\123\MyScript.vbs", but this requires the user has *.vbs associated to wscript.

View's getWidth() and getHeight() returns 0

Gone views returns 0 as height if app in background. This my code (1oo% works)

fun View.postWithTreeObserver(postJob: (View, Int, Int) -> Unit) {
    viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            measure(widthSpec, heightSpec)
            postJob(this@postWithTreeObserver, measuredWidth, measuredHeight)
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                @Suppress("DEPRECATION")
                viewTreeObserver.removeGlobalOnLayoutListener(this)
            } else {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        }
    })
}

Getting a Request.Headers value

if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
    // header is present and set to "true"
}

How to Create Multiple Where Clause Query Using Laravel Eloquent?

You may use in several ways,

$results = User::where([
    ['column_name1', '=', $value1],
    ['column_name2', '<', $value2],
    ['column_name3', '>', $value3]
])->get();

You can also use like this,

$results = User::orderBy('id','DESC');
$results = $results->where('column1','=', $value1);
$results = $results->where('column2','<',  $value2);
$results = $results->where('column3','>',  $value3);
$results = $results->get();

How to add directory to classpath in an application run profile in IntelliJ IDEA?

You need not specify the classes folder. Intellij should be able to load it. You will get this error if "Project Compiler output" is blank.

Just make sure that below value is set: Project Settings -> Project -> Project Compiler output to your projectDir/out folder

How can I create download link in HTML?

To link to the file, do the same as any other page link:

<a href="...">link text</a>

To force things to download even if they have an embedded plugin (Windows + QuickTime = ugh), you can use this in your htaccess / apache2.conf:

AddType application/octet-stream EXTENSION

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

jQuery AJAX form data serialize using PHP

Try this its working..

    <script>
      $(function () {
          $('form').on('submit', function (e) {
              e.preventDefault();
              $.ajax({
                  type: 'post',
                  url: '<?php echo base_url();?>student_ajax/insert',
                  data: $('form').serialize(),
                  success: function (response) {
                      alert('form was submitted');
                  }
                  error:function() {
                      alert('fail');
                  }
              });
          });
      });
    </script>

How to use font-family lato?

Please put this code in head section

<link href='http://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>

and use font-family: 'Lato', sans-serif; in your css. For example:

h1 {
    font-family: 'Lato', sans-serif;
    font-weight: 400;
}

Or you can use manually also

Generate .ttf font from fontSquiral

and can try this option

    @font-face {
        font-family: "Lato";
        src: url('698242188-Lato-Bla.eot');
        src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
        url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
        url('698242188-Lato-Bla.woff') format('woff'),
        url('698242188-Lato-Bla.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}

Called like this

body {
  font-family: 'Lato', sans-serif;
}

How to POST URL in data of a curl request

I don't think it's necessary to use semi-quotes around the variables, try:

curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"

%2f is the escape code for a /.

http://www.december.com/html/spec/esccodes.html

Also, do you need to specify a port? ( just checking :) )

How to sort by dates excel?

It's actually really easy. Highlight the DATE column and make sure that its set as date in Excel. Highlight everything you want to change, Then go to [DATA]>[SORT]>[COLUMN] and set sorting by date. Hope it helps.

Cutting the videos based on start and end time using ffmpeg

ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 -c copy cut.mp4 

Use -c copy for make in instantly. In that case ffmpeg will not re-encode video, just will cut to according size.

How to bring back "Browser mode" in IE11?

How to bring back “Browser mode” in IE11?

Easy way to bring back is just go to Emulation (ctrl +8)

and do change user agent string. (see attached image)

enter image description here

AWK to print field $2 first, then field $1

The awk is ok. I'm guessing the file is from a windows system and has a CR (^m ascii 0x0d) on the end of the line.

This will cause the cursor to go to the start of the line after $2.

Use dos2unix or vi with :se ff=unix to get rid of the CRs.

How to add a string to a string[] array? There's no .Add function

This code works great for preparing the dynamic values Array for spinner in Android:

    List<String> yearStringList = new ArrayList<>();
    yearStringList.add("2017");
    yearStringList.add("2018");
    yearStringList.add("2019");


    String[] yearStringArray = (String[]) yearStringList.toArray(new String[yearStringList.size()]);

Deleting specific rows from DataTable

Before everyone jumps on the 'You can't delete rows in an Enumeration' bandwagon, you need to first realize that DataTables are transactional, and do not technically purge changes until you call AcceptChanges()

If you are seeing this exception while calling Delete, you are already in a pending-changes data state. For instance, if you have just loaded from the database, calling Delete would throw an exception if you were inside a foreach loop.

BUT! BUT!

If you load rows from the database and call the function 'AcceptChanges()' you commit all of those pending changes to the DataTable. Now you can iterate through the list of rows calling Delete() without a care in the world, because it simply ear-marks the row for Deletion, but is not committed until you again call AcceptChanges()

I realize this response is a bit dated, but I had to deal with a similar issue recently and hopefully this saves some pain for a future developer working on 10-year-old code :)


P.s. Here is a simple code example added by Jeff:

C#

YourDataTable.AcceptChanges(); 
foreach (DataRow row in YourDataTable.Rows) {
    // If this row is offensive then
    row.Delete();
} 
YourDataTable.AcceptChanges();

VB.Net

ds.Tables(0).AcceptChanges()
For Each row In ds.Tables(0).Rows
    ds.Tables(0).Rows(counter).Delete()
    counter += 1
Next
ds.Tables(0).AcceptChanges()

nginx missing sites-available directory

I tried sudo apt install nginx-full. You will get all the required packages.

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

The location of jfxrt.jar in Oracle Java 7 is:

<JRE_HOME>/lib/jfxrt.jar

The location of jfxrt.jar in Oracle Java 8 is:

<JRE_HOME>/lib/ext/jfxrt.jar

The <JRE_HOME> will depend on where you installed the Oracle Java and may differ between Linux distributions and installations.

jfxrt.jar is not in the Linux OpenJDK 7 (which is what you are using).


An open source package which provides JavaFX 8 for Debian based systems such as Ubuntu is available. To install this package it is necessary to install both the Debian OpenJDK 8 package and the Debian OpenJFX package. I don't run Debian, so I'm not sure where the Debian OpenJFX package installs jfxrt.jar.


Use Oracle Java 8.

With Oracle Java 8, JavaFX is both included in the JDK and is on the default classpath. This means that JavaFX classes will automatically be found both by the compiler during the build and by the runtime when your users use your application. So using Oracle Java 8 is currently the best solution to your issue.

OpenJDK for Java 8 could include JavaFX (as JavaFX for Java 8 is now open source), but it will depend on the OpenJDK package assemblers as to whether they choose to include JavaFX 8 with their distributions. I hope they do, as it should help remove the confusion you experienced in your question and it also provides a great deal more functionality in OpenJDK.

My understanding is that although JavaFX has been included with the standard JDK since version JDK 7u6

Yes, but only the Oracle JDK.

The JavaFX version bundled with Java 7 was not completely open source so it could not be included in the OpenJDK (which is what you are using).

In you need to use Java 7 instead of Java 8, you could download the Oracle JDK for Java 7 and use that. Then JavaFX will be included with Java 7. Due to the way Oracle configured Java 7, JavaFX won't be on the classpath. If you use Java 7, you will need to add it to your classpath and use appropriate JavaFX packaging tools to allow your users to run your application. Some tools such as e(fx)clipse and NetBeans JavaFX project type will take care of classpath issues and packaging tasks for you.

How to bundle vendor scripts separately and require them as needed with Webpack?

I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.

Vendor bundle.

You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor), and file name that will be generated (vendor.js).

new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),

Now important part, you have to now specify what does it mean vendor library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor bundle. in your case it should look something like:

entry: {
    app: 'entry.js',
    vendor: ['jquery', 'jquery.plugin1']
}

JQuery as global

Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:

new webpack.ProvidePlugin({
    $: "jquery"
})

And now you can just use $ anywhere in your code - webpack will automatically convert that to

require('jquery')

I hope it helped. you can also look at my webpack configuration file that is here

I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)


Edit:

To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:

new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),

and then declare different extenral libraries for different files:

entry: {
    page1: ['entry.js'],
    page2: ['entry2.js'],
    "vendor-page1": [
        'lodash'
    ],
    "vendor-page2": [
        'jquery'
    ]
},

If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.

How to deal with the URISyntaxException

A space is encoded to %20 in URLs, and to + in forms submitted data (content type application/x-www-form-urlencoded). You need the former.

Using Guava:

dependencies {
     compile 'com.google.guava:guava:28.1-jre'
}

You can use UrlEscapers:

String encodedString = UrlEscapers.urlFragmentEscaper().escape(inputString);

Don't use String.replace, this would only encode the space. Use a library instead.

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

Essentially it means you don't have the index you are trying to reference. For example:

df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)

will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:

df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)

Hope that answers your question!

Illegal pattern character 'T' when parsing a date string to java.util.Date

Update for Java 8 and higher

You can now simply do Instant.parse("2015-04-28T14:23:38.521Z") and get the correct thing now, especially since you should be using Instant instead of the broken java.util.Date with the most recent versions of Java.

You should be using DateTimeFormatter instead of SimpleDateFormatter as well.

Original Answer:

The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.

This works with the input with the trailing Z as demonstrated:

In the pattern the T is escaped with ' on either side.

The pattern for the Z at the end is actually XXX as documented in the JavaDoc for SimpleDateFormat, it is just not very clear on actually how to use it since Z is the marker for the old TimeZone information as well.

Q2597083.java

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

public class Q2597083
{
    /**
     * All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
     */
    public static final TimeZone UTC;

    /**
     * @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
     */
    public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    /**
     * 0001-01-01T00:00:00.000Z
     */
    public static final Date BEGINNING_OF_TIME;

    /**
     * 292278994-08-17T07:12:55.807Z
     */
    public static final Date END_OF_TIME;

    static
    {
        UTC = TimeZone.getTimeZone("UTC");
        TimeZone.setDefault(UTC);
        final Calendar c = new GregorianCalendar(UTC);
        c.set(1, 0, 1, 0, 0, 0);
        c.set(Calendar.MILLISECOND, 0);
        BEGINNING_OF_TIME = c.getTime();
        c.setTime(new Date(Long.MAX_VALUE));
        END_OF_TIME = c.getTime();
    }

    public static void main(String[] args) throws Exception
    {

        final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
        sdf.setTimeZone(UTC);
        System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
        System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
        System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
        System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
        System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
        System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
    }
}

Produces the following output:

sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994

Why plt.imshow() doesn't display the image?

If you want to print the picture using imshow() you also execute plt.show()

GridLayout (not GridView) how to stretch all children evenly

This is a fairly old question, but obviously of interest to a lot of people. For a simple layout of 4 buttons like this, it seems that a TableLayout is the easiest way to accomplish the desired result.

Here's some example code showing the first 2 rows of a table with 6 columns spanning the width of its parent. The LinearLayout and ImageView in each cell are used to allow for the "turning on and off" of an image within the cell while having the color of the cell persist.

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1,2,3,4,5,6"
    android:background="@drawable/vertical_radio_button_background"
    android:padding="2dp">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/brown"
            android:tag="13"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="1"
            android:background="@color/brown">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/maraschino"
            android:tag="9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="2"
            android:background="@color/maraschino">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/cayenne"
            android:tag="22"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="3"
            android:background="@color/cayenne">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/maroon"
            android:tag="18"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="4"
            android:background="@color/maroon">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/plum"
            android:tag="3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="5"
            android:background="@color/plum">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/eggplant"
            android:tag="15"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="6"
            android:background="@color/eggplant">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/plum2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="1"
            android:background="@color/plum">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/lavender"
            android:tag="14"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="2"
            android:background="@color/lavender">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/carnation"
            android:tag="16"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="3"
            android:background="@color/carnation">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/light_pink"
            android:tag="23"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="4"
            android:background="@color/light_pink">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/strawberry"
            android:tag="10"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="5"
            android:background="@color/strawberry">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/magenta"
            android:tag="20"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="6"
            android:background="@color/magenta">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>
    </TableRow>
</TableLayout>

Insert at first position of a list in Python

Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

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

On the command prompt, do:

netstat -nb

What is the difference between syntax and semantics in programming languages?

He drinks rice (wrong semantic- meaningless, right syntax- grammar)

Hi drink water (right semantic- has meaning, wrong syntax- grammar)

Timeout function if it takes too long to finish

The process for timing out an operations is described in the documentation for signal.

The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.

Note that this will only work on UNIX.

Here's an implementation that creates a decorator (save the following code as timeout.py).

from functools import wraps
import errno
import os
import signal

class TimeoutError(Exception):
    pass

def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator

This creates a decorator called @timeout that can be applied to any long running functions.

So, in your application code, you can use the decorator like so:

from timeout import timeout

# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
    ...

# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
    ...

# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
    ...

HashSet vs LinkedHashSet

You should look at the source of the HashSet constructor it calls... it's a special constructor that makes the backing Map a LinkedHashMap instead of just a HashMap.

How to use session in JSP pages to get information?

Suppose you want to use, say ID in any other webpage then you can do it by following code snippet :

String id=(String)session.getAttribute("uid");

Here uid is the attribute in which you have stored the ID earlier. You can set it by:

session.setAttribute("uid",id);

int to string in MySQL

If you have a column called "col1" which is int, you cast it to String like this:

CONVERT(col1,char)

e.g. this allows you to check an int value is containing another value (here 9) like this:

CONVERT(col1,char) LIKE '%9%'

Cannot implicitly convert type 'int?' to 'int'.

Well you're casting OrdersPerHour to an int?

OrdersPerHour = (int?)dbcommand.ExecuteScalar();

Yet your method signature is int:

static int OrdersPerHour(string User)

The two have to match.


Also a quick suggestion -> Use parameters in your query, something like:

string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > ? AND User = ? AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered')";
OleDbCommand dbcommand = new OleDbCommand(query, conn);
dbcommand.Parameters.Add(curTime.AddHours(-1));
dbcommand.Parameters.Add(User);

Map enum in JPA with fixed values?

From JPA 2.1 you can use AttributeConverter.

Create an enumerated class like so:

public enum NodeType {

    ROOT("root-node"),
    BRANCH("branch-node"),
    LEAF("leaf-node");

    private final String code;

    private NodeType(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

And create a converter like this:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class NodeTypeConverter implements AttributeConverter<NodeType, String> {

    @Override
    public String convertToDatabaseColumn(NodeType nodeType) {
        return nodeType.getCode();
    }

    @Override
    public NodeType convertToEntityAttribute(String dbData) {
        for (NodeType nodeType : NodeType.values()) {
            if (nodeType.getCode().equals(dbData)) {
                return nodeType;
            }
        }

        throw new IllegalArgumentException("Unknown database value:" + dbData);
    }
}

On the entity you just need:

@Column(name = "node_type_code")

You luck with @Converter(autoApply = true) may vary by container but tested to work on Wildfly 8.1.0. If it doesn't work you can add @Convert(converter = NodeTypeConverter.class) on the entity class column.

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

In your terminal type:

code --diff file1.txt file2.txt

A tab will open up in VS Code showing the differences in the two files.

Google Map API - Removing Markers

You need to keep an array of the google.maps.Marker objects to hide (or remove or run other operations on them).

In the global scope:

var gmarkers = [];

Then push the markers on that array as you create them:

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
    title: locations[i].title,
    icon: icon,
    map:map
});

// Push your newly created marker into the array:
gmarkers.push(marker);

Then to remove them:

function removeMarkers(){
    for(i=0; i<gmarkers.length; i++){
        gmarkers[i].setMap(null);
    }
}

working example (toggles the markers)

code snippet:

_x000D_
_x000D_
var gmarkers = [];_x000D_
var RoseHulman = new google.maps.LatLng(39.483558, -87.324593);_x000D_
var styles = [{_x000D_
  stylers: [{_x000D_
    hue: "black"_x000D_
  }, {_x000D_
    saturation: -90_x000D_
  }]_x000D_
}, {_x000D_
  featureType: "road",_x000D_
  elementType: "geometry",_x000D_
  stylers: [{_x000D_
    lightness: 100_x000D_
  }, {_x000D_
    visibility: "simplified"_x000D_
  }]_x000D_
}, {_x000D_
  featureType: "road",_x000D_
  elementType: "labels",_x000D_
  stylers: [{_x000D_
    visibility: "on"_x000D_
  }]_x000D_
}];_x000D_
_x000D_
var styledMap = new google.maps.StyledMapType(styles, {_x000D_
  name: "Campus"_x000D_
});_x000D_
var mapOptions = {_x000D_
  center: RoseHulman,_x000D_
  zoom: 15,_x000D_
  mapTypeControl: true,_x000D_
  zoomControl: true,_x000D_
  zoomControlOptions: {_x000D_
    style: google.maps.ZoomControlStyle.SMALL_x000D_
  },_x000D_
  mapTypeControlOptions: {_x000D_
    mapTypeIds: ['map_style', google.maps.MapTypeId.HYBRID],_x000D_
    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU_x000D_
  },_x000D_
  scrollwheel: false,_x000D_
  streetViewControl: true,_x000D_
_x000D_
};_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map'), mapOptions);_x000D_
map.mapTypes.set('map_style', styledMap);_x000D_
map.setMapTypeId('map_style');_x000D_
_x000D_
var infowindow = new google.maps.InfoWindow({_x000D_
  maxWidth: 300,_x000D_
  infoBoxClearance: new google.maps.Size(1, 1),_x000D_
  disableAutoPan: false_x000D_
});_x000D_
_x000D_
var marker, i, icon, image;_x000D_
_x000D_
var locations = [{_x000D_
  "id": "1",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Alpha Tau Omega Fraternity",_x000D_
  "description": "<p>Alpha Tau Omega house</p>",_x000D_
  "longitude": "-87.321133",_x000D_
  "latitude": "39.484092"_x000D_
}, {_x000D_
  "id": "2",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment Commons",_x000D_
  "description": "<p>The commons area of the apartment-style residential complex</p>",_x000D_
  "longitude": "-87.329282",_x000D_
  "latitude": "39.483599"_x000D_
}, {_x000D_
  "id": "3",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment East",_x000D_
  "description": "<p>Apartment East</p>",_x000D_
  "longitude": "-87.328809",_x000D_
  "latitude": "39.483748"_x000D_
}, {_x000D_
  "id": "4",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Apartment West",_x000D_
  "description": "<p>Apartment West</p>",_x000D_
  "longitude": "-87.329732",_x000D_
  "latitude": "39.483429"_x000D_
}, {_x000D_
  "id": "5",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Baur-Sames-Bogart (BSB) Hall",_x000D_
  "description": "<p>Baur-Sames-Bogart Hall</p>",_x000D_
  "longitude": "-87.325714",_x000D_
  "latitude": "39.482382"_x000D_
}, {_x000D_
  "id": "6",_x000D_
  "category": "6",_x000D_
  "campus_location": "D3",_x000D_
  "title": "Blumberg Hall",_x000D_
  "description": "<p>Blumberg Hall</p>",_x000D_
  "longitude": "-87.328321",_x000D_
  "latitude": "39.483388"_x000D_
}, {_x000D_
  "id": "7",_x000D_
  "category": "1",_x000D_
  "campus_location": "E1",_x000D_
  "title": "The Branam Innovation Center",_x000D_
  "description": "<p>The Branam Innovation Center</p>",_x000D_
  "longitude": "-87.322614",_x000D_
  "latitude": "39.48494"_x000D_
}, {_x000D_
  "id": "8",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Chi Omega Sorority",_x000D_
  "description": "<p>Chi Omega house</p>",_x000D_
  "longitude": "-87.319905",_x000D_
  "latitude": "39.482071"_x000D_
}, {_x000D_
  "id": "9",_x000D_
  "category": "3",_x000D_
  "campus_location": "D1",_x000D_
  "title": "Cook Stadium/Phil Brown Field",_x000D_
  "description": "<p>Cook Stadium at Phil Brown Field</p>",_x000D_
  "longitude": "-87.325258",_x000D_
  "latitude": "39.485007"_x000D_
}, {_x000D_
  "id": "10",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Crapo Hall",_x000D_
  "description": "<p>Crapo Hall</p>",_x000D_
  "longitude": "-87.324368",_x000D_
  "latitude": "39.483709"_x000D_
}, {_x000D_
  "id": "11",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Delta Delta Delta Sorority",_x000D_
  "description": "<p>Delta Delta Delta</p>",_x000D_
  "longitude": "-87.317477",_x000D_
  "latitude": "39.482951"_x000D_
}, {_x000D_
  "id": "12",_x000D_
  "category": "6",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Deming Hall",_x000D_
  "description": "<p>Deming Hall</p>",_x000D_
  "longitude": "-87.325822",_x000D_
  "latitude": "39.483421"_x000D_
}, {_x000D_
  "id": "13",_x000D_
  "category": "5",_x000D_
  "campus_location": "F1",_x000D_
  "title": "Facilities Operations",_x000D_
  "description": "<p>Facilities Operations</p>",_x000D_
  "longitude": "-87.321782",_x000D_
  "latitude": "39.484916"_x000D_
}, {_x000D_
  "id": "14",_x000D_
  "category": "2",_x000D_
  "campus_location": "E3",_x000D_
  "title": "Flame of the Millennium",_x000D_
  "description": "<p>Flame of Millennium sculpture</p>",_x000D_
  "longitude": "-87.323306",_x000D_
  "latitude": "39.481978"_x000D_
}, {_x000D_
  "id": "15",_x000D_
  "category": "5",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Hadley Hall",_x000D_
  "description": "<p>Hadley Hall</p>",_x000D_
  "longitude": "-87.324046",_x000D_
  "latitude": "39.482887"_x000D_
}, {_x000D_
  "id": "16",_x000D_
  "category": "2",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Hatfield Hall",_x000D_
  "description": "<p>Hatfield Hall</p>",_x000D_
  "longitude": "-87.322340",_x000D_
  "latitude": "39.482146"_x000D_
}, {_x000D_
  "id": "17",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Hulman Memorial Union",_x000D_
  "description": "<p>Hulman Memorial Union</p>",_x000D_
  "longitude": "-87.32698",_x000D_
  "latitude": "39.483574"_x000D_
}, {_x000D_
  "id": "18",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "John T. Myers Center for Technological Research with Industry",_x000D_
  "description": "<p>John T. Myers Center for Technological Research With Industry</p>",_x000D_
  "longitude": "-87.322984",_x000D_
  "latitude": "39.484063"_x000D_
}, {_x000D_
  "id": "19",_x000D_
  "category": "6",_x000D_
  "campus_location": "A2",_x000D_
  "title": "Lakeside Hall",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.330612",_x000D_
  "latitude": "39.482804"_x000D_
}, {_x000D_
  "id": "20",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Lambda Chi Alpha Fraternity",_x000D_
  "description": "<p>Lambda Chi Alpha</p>",_x000D_
  "longitude": "-87.320999",_x000D_
  "latitude": "39.48305"_x000D_
}, {_x000D_
  "id": "21",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Logan Library",_x000D_
  "description": "<p>Logan Library</p>",_x000D_
  "longitude": "-87.324851",_x000D_
  "latitude": "39.483408"_x000D_
}, {_x000D_
  "id": "22",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Mees Hall",_x000D_
  "description": "<p>Mees Hall</p>",_x000D_
  "longitude": "-87.32778",_x000D_
  "latitude": "39.483533"_x000D_
}, {_x000D_
  "id": "23",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Moench Hall",_x000D_
  "description": "<p>Moench Hall</p>",_x000D_
  "longitude": "-87.323695",_x000D_
  "latitude": "39.483471"_x000D_
}, {_x000D_
  "id": "24",_x000D_
  "category": "1",_x000D_
  "campus_location": "G4",_x000D_
  "title": "Oakley Observatory",_x000D_
  "description": "<p>Oakley Observatory</p>",_x000D_
  "longitude": "-87.31616",_x000D_
  "latitude": "39.483789"_x000D_
}, {_x000D_
  "id": "25",_x000D_
  "category": "1",_x000D_
  "campus_location": "D2",_x000D_
  "title": "Olin Hall and Olin Advanced Learning Center",_x000D_
  "description": "<p>Olin Hall</p>",_x000D_
  "longitude": "-87.324550",_x000D_
  "latitude": "39.482796"_x000D_
}, {_x000D_
  "id": "26",_x000D_
  "category": "6",_x000D_
  "campus_location": "C3",_x000D_
  "title": "Percopo Hall",_x000D_
  "description": "<p>Percopo Hall</p>",_x000D_
  "longitude": "-87.328182",_x000D_
  "latitude": "39.482121"_x000D_
}, {_x000D_
  "id": "27",_x000D_
  "category": "6",_x000D_
  "campus_location": "G3",_x000D_
  "title": "Public Safety Office",_x000D_
  "description": "<p>The Office of Public Safety</p>",_x000D_
  "longitude": "-87.320377",_x000D_
  "latitude": "39.48191"_x000D_
}, {_x000D_
  "id": "28",_x000D_
  "category": "1",_x000D_
  "campus_location": "E2",_x000D_
  "title": "Rotz Mechanical Engineering Lab",_x000D_
  "description": "<p>Rotz Lab</p>",_x000D_
  "longitude": "-87.323247",_x000D_
  "latitude": "39.483711"_x000D_
}, {_x000D_
  "id": "28",_x000D_
  "category": "6",_x000D_
  "campus_location": "C2",_x000D_
  "title": "Scharpenberg Hall",_x000D_
  "description": "<p>Scharpenberg Hall</p>",_x000D_
  "longitude": "-87.328139",_x000D_
  "latitude": "39.483582"_x000D_
}, {_x000D_
  "id": "29",_x000D_
  "category": "6",_x000D_
  "campus_location": "G2",_x000D_
  "title": "Sigma Nu Fraternity",_x000D_
  "description": "<p>The Sigma Nu house</p>",_x000D_
  "longitude": "-87.31999",_x000D_
  "latitude": "39.48374"_x000D_
}, {_x000D_
  "id": "30",_x000D_
  "category": "6",_x000D_
  "campus_location": "E4",_x000D_
  "title": "South Campus / Rose-Hulman Ventures",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.330623",_x000D_
  "latitude": "39.417646"_x000D_
}, {_x000D_
  "id": "31",_x000D_
  "category": "6",_x000D_
  "campus_location": "C3",_x000D_
  "title": "Speed Hall",_x000D_
  "description": "<p>Speed Hall</p>",_x000D_
  "longitude": "-87.326632",_x000D_
  "latitude": "39.482121"_x000D_
}, {_x000D_
  "id": "32",_x000D_
  "category": "3",_x000D_
  "campus_location": "C1",_x000D_
  "title": "Sports and Recreation Center",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.3272",_x000D_
  "latitude": "39.484874"_x000D_
}, {_x000D_
  "id": "33",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Triangle Fraternity",_x000D_
  "description": "<p>Triangle fraternity</p>",_x000D_
  "longitude": "-87.32113",_x000D_
  "latitude": "39.483659"_x000D_
}, {_x000D_
  "id": "34",_x000D_
  "category": "6",_x000D_
  "campus_location": "B3",_x000D_
  "title": "White Chapel",_x000D_
  "description": "<p>The White Chapel</p>",_x000D_
  "longitude": "-87.329367",_x000D_
  "latitude": "39.482481"_x000D_
}, {_x000D_
  "id": "35",_x000D_
  "category": "6",_x000D_
  "campus_location": "F2",_x000D_
  "title": "Women's Fraternity Housing",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320753",_x000D_
  "latitude": "39.482401"_x000D_
}, {_x000D_
  "id": "36",_x000D_
  "category": "3",_x000D_
  "campus_location": "E1",_x000D_
  "title": "Intramural Fields",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.321267",_x000D_
  "latitude": "39.485934"_x000D_
}, {_x000D_
  "id": "37",_x000D_
  "category": "3",_x000D_
  "campus_location": "A3",_x000D_
  "title": "James Rendel Soccer Field",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.332135",_x000D_
  "latitude": "39.480933"_x000D_
}, {_x000D_
  "id": "38",_x000D_
  "category": "3",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Art Nehf Field",_x000D_
  "description": "<p>Art Nehf Field</p>",_x000D_
  "longitude": "-87.330923",_x000D_
  "latitude": "39.48022"_x000D_
}, {_x000D_
  "id": "39",_x000D_
  "category": "3",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Women's Softball Field",_x000D_
  "description": "<p></p>",_x000D_
  "longitude": "-87.329904",_x000D_
  "latitude": "39.480278"_x000D_
}, {_x000D_
  "id": "40",_x000D_
  "category": "3",_x000D_
  "campus_location": "D1",_x000D_
  "title": "Joy Hulbert Tennis Courts",_x000D_
  "description": "<p>The Joy Hulbert Outdoor Tennis Courts</p>",_x000D_
  "longitude": "-87.323767",_x000D_
  "latitude": "39.485595"_x000D_
}, {_x000D_
  "id": "41",_x000D_
  "category": "6",_x000D_
  "campus_location": "B2",_x000D_
  "title": "Speed Lake",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.328134",_x000D_
  "latitude": "39.482779"_x000D_
}, {_x000D_
  "id": "42",_x000D_
  "category": "5",_x000D_
  "campus_location": "F1",_x000D_
  "title": "Recycling Center",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320098",_x000D_
  "latitude": "39.484593"_x000D_
}, {_x000D_
  "id": "43",_x000D_
  "category": "1",_x000D_
  "campus_location": "F3",_x000D_
  "title": "Army ROTC",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.321342",_x000D_
  "latitude": "39.481992"_x000D_
}, {_x000D_
  "id": "44",_x000D_
  "category": "2",_x000D_
  "campus_location": "  ",_x000D_
  "title": "Self Made Man",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.326272",_x000D_
  "latitude": "39.484481"_x000D_
}, {_x000D_
  "id": "P1",_x000D_
  "category": "4",_x000D_
  "title": "Percopo Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.328756",_x000D_
  "latitude": "39.481587"_x000D_
}, {_x000D_
  "id": "P2",_x000D_
  "category": "4",_x000D_
  "title": "Speed Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.327361",_x000D_
  "latitude": "39.481694"_x000D_
}, {_x000D_
  "id": "P3",_x000D_
  "category": "4",_x000D_
  "title": "Main Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.326245",_x000D_
  "latitude": "39.481446"_x000D_
}, {_x000D_
  "id": "P4",_x000D_
  "category": "4",_x000D_
  "title": "Lakeside Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.330848",_x000D_
  "latitude": "39.483284"_x000D_
}, {_x000D_
  "id": "P5",_x000D_
  "category": "4",_x000D_
  "title": "Hatfield Hall Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.321417",_x000D_
  "latitude": "39.482398"_x000D_
}, {_x000D_
  "id": "P6",_x000D_
  "category": "4",_x000D_
  "title": "Women's Fraternity Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.320977",_x000D_
  "latitude": "39.482315"_x000D_
}, {_x000D_
  "id": "P7",_x000D_
  "category": "4",_x000D_
  "title": "Myers and Facilities Parking",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.322243",_x000D_
  "latitude": "39.48417"_x000D_
}, {_x000D_
  "id": "P8",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.323241",_x000D_
  "latitude": "39.484758"_x000D_
}, {_x000D_
  "id": "P9",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.323617",_x000D_
  "latitude": "39.484311"_x000D_
}, {_x000D_
  "id": "P10",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.325714",_x000D_
  "latitude": "39.484584"_x000D_
}, {_x000D_
  "id": "P11",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.32778",_x000D_
  "latitude": "39.484145"_x000D_
}, {_x000D_
  "id": "P12",_x000D_
  "category": "4",_x000D_
  "title": "",_x000D_
  "description": "",_x000D_
  "image": "",_x000D_
  "longitude": "-87.329035",_x000D_
  "latitude": "39.4848"_x000D_
}];_x000D_
_x000D_
for (i = 0; i < locations.length; i++) {_x000D_
_x000D_
  var marker = new google.maps.Marker({_x000D_
    position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),_x000D_
    title: locations[i].title,_x000D_
    map: map_x000D_
  });_x000D_
  gmarkers.push(marker);_x000D_
  google.maps.event.addListener(marker, 'click', (function(marker, i) {_x000D_
    return function() {_x000D_
      if (locations[i].description !== "" || locations[i].title !== "") {_x000D_
        infowindow.setContent('<div class="content" id="content-' + locations[i].id +_x000D_
          '" style="max-height:300px; font-size:12px;"><h3>' + locations[i].title + '</h3>' +_x000D_
          '<hr class="grey" />' +_x000D_
          hasImage(locations[i]) +_x000D_
          locations[i].description) + '</div>';_x000D_
        infowindow.open(map, marker);_x000D_
      }_x000D_
    }_x000D_
  })(marker, i));_x000D_
}_x000D_
_x000D_
function toggleMarkers() {_x000D_
  for (i = 0; i < gmarkers.length; i++) {_x000D_
    if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null);_x000D_
    else gmarkers[i].setMap(map);_x000D_
  }_x000D_
}_x000D_
_x000D_
function hasImage(location) {_x000D_
  return '';_x000D_
}
_x000D_
html,_x000D_
body,_x000D_
#map {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>_x000D_
<div id="controls">_x000D_
  <input type="button" value="Toggle All Markers" onClick="toggleMarkers()" />_x000D_
</div>_x000D_
<div id="map"></div>
_x000D_
_x000D_
_x000D_

Android studio doesn't list my phone under "Choose Device"

For about 3 weeks, I faced the same problem.

After googling and trying and asking without solutions, I found that there was an Unknown Device called Android Composite ADB Interface in the Device Manager.

I had a look on this and finally resolved it by downloading the ADB Driver from here. (Maybe you need to troubleshoot your PC but the installer will tell you this.)

Does JavaScript have the interface type (such as Java's 'interface')?

Hope, that anyone who's still looking for an answer finds it helpful.

You can try out using a Proxy (It's standard since ECMAScript 2015): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

latLngLiteral = new Proxy({},{
    set: function(obj, prop, val) {
        //only these two properties can be set
        if(['lng','lat'].indexOf(prop) == -1) {
            throw new ReferenceError('Key must be "lat" or "lng"!');
        }

        //the dec format only accepts numbers
        if(typeof val !== 'number') {
            throw new TypeError('Value must be numeric');
        }

        //latitude is in range between 0 and 90
        if(prop == 'lat'  && !(0 < val && val < 90)) {
            throw new RangeError('Position is out of range!');
        }
        //longitude is in range between 0 and 180
        else if(prop == 'lng' && !(0 < val && val < 180)) {
            throw new RangeError('Position is out of range!');
        }

        obj[prop] = val;

        return true;
    }
});

Then you can easily say:

myMap = {}
myMap.position = latLngLiteral;

Simulating Key Press C#

Here's an example...

static class Program
{
    [DllImport("user32.dll")]
    public static extern int SetForegroundWindow(IntPtr hWnd);

    [STAThread]
    static void Main()
    {
        while(true)
        {
            Process [] processes = Process.GetProcessesByName("iexplore");

            foreach(Process proc in processes)
            {
                SetForegroundWindow(proc.MainWindowHandle);
                SendKeys.SendWait("{F5}");
            }

            Thread.Sleep(5000);
        }
    }
}

a better one... less anoying...

static class Program
{
    const UInt32 WM_KEYDOWN = 0x0100;
    const int VK_F5 = 0x74;

    [DllImport("user32.dll")]
    static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);

    [STAThread]
    static void Main()
    {
        while(true)
        {
            Process [] processes = Process.GetProcessesByName("iexplore");

            foreach(Process proc in processes)
                PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_F5, 0);

            Thread.Sleep(5000);
        }
    }
}

Ruby, Difference between exec, system and %x() or Backticks

They do different things. exec replaces the current process with the new process and never returns. system invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.

Disable Chrome strict MIME type checking

The server should respond with the correct MIME Type for JSONP application/javascript and your request should tell jQuery you are loading JSONP dataType: 'jsonp'

Please see this answer for further details ! You can also have a look a this one as it explains why loading .js file with text/plain won't work.

How to clear a textbox using javascript

Simple one

onfocus="javascript:this.value=''" onblur="javascript: if(this.value==''){this.value='Search...';}"

How to sort an ArrayList?

An alternative way to order a List is using the Collections framework;

in this case using the SortedSet (the bean in the list should implement Comparable, so Double is ok):

List<Double> testList;
...
SortedSet<Double> sortedSet= new TreeSet<Double>();
for(Double number: testList) {
   sortedSet.add(number);
}
orderedList=new ArrayList(sortedSet);

In general, to order by an attribute of a bean in the list,put all the elements of the list in a SortedMap, using as a key the attribute, then get the values() from the SortedMap (the attribute should implement Comparable):

List<Bean> testList;
...
SortedMap<AttributeType,Bean> sortedMap= new TreeMap<AttributeType, Bean>();
for(Bean bean : testList) {
   sortedMap.put(bean.getAttribute(),bean);
}
orderedList=new ArrayList(sortedMap.values());

How to Customize the time format for Python logging?

if using logging.config.fileConfig with a configuration file use something like:

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

Passing HTML to template using Flask/Jinja2

From the jinja docs section HTML Escaping:

When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.

Example:

 <div class="info">
   {{data.email_content|safe}}
 </div>

How do I print the type or class of a variable in Swift?

You can still access the class, through className (which returns a String).

There are actually several ways to get the class, for example classForArchiver, classForCoder, classForKeyedArchiver (all return AnyClass!).

You can't get the type of a primitive (a primitive is not a class).

Example:

var ivar = [:]
ivar.className // __NSDictionaryI

var i = 1
i.className // error: 'Int' does not have a member named 'className'

If you want to get the type of a primitive, you have to use bridgeToObjectiveC(). Example:

var i = 1
i.bridgeToObjectiveC().className // __NSCFNumber

No route matches "/users/sign_out" devise rails 3

the ':method => :delete' in page is 'data-method="delete"' so your page must have jquery_ujs.js, it will submit link with method delete not method get

Force sidebar height 100% using CSS (with a sticky bottom image)?

I have run into this issue several times on different projects, but I have found a solution that works for me. You have to use four div tags - one that contains the sidebar, the main content, and a footer.

First, style the elements in your stylesheet:

#container {
width: 100%;
background: #FFFAF0;
}

.content {
width: 950px;
float: right;
padding: 10px;
height: 100%;
background: #FFFAF0;
}

.sidebar {
width: 220px;
float: left;
height: 100%;
padding: 5px;
background: #FFFAF0;
}

#footer {
clear:both;
background:#FFFAF0;
}

You can edit the different elements however you want to, just be sure you dont change the footer property "clear:both" - this is very important to leave in.

Then, simply set up your web page like this:

<div id=”container”>
<div class=”sidebar”></div>
<div class=”content”></div>
<div id=”footer”></div>
</div>

I wrote a more in-depth blog post about this at http://blog.thelibzter.com/how-to-make-a-sidebar-extend-the-entire-height-of-its-container. Please let me know if you have any questions. Hope this helps!

Assign one struct to another in C

Yes, you can assign one instance of a struct to another using a simple assignment statement.

  • In the case of non-pointer or non pointer containing struct members, assignment means copy.

  • In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.

Let us see this first hand:

#include <stdio.h>

struct Test{
    int foo;
    char *bar;
};

int main(){
    struct Test t1;
    struct Test t2;
    t1.foo = 1;
    t1.bar = malloc(100 * sizeof(char));
    strcpy(t1.bar, "t1 bar value");
    t2.foo = 2;
    t2.bar = malloc(100 * sizeof(char));
    strcpy(t2.bar, "t2 bar value");
    printf("t2 foo and bar before copy: %d %s\n", t2.foo, t2.bar);
    t2 = t1;// <---- ASSIGNMENT
    printf("t2 foo and bar after copy: %d %s\n", t2.foo, t2.bar);
    //The following 3 lines of code demonstrate that foo is deep copied and bar is shallow copied
    strcpy(t1.bar, "t1 bar value changed");
    t1.foo = 3;
    printf("t2 foo and bar after t1 is altered: %d %s\n", t2.foo, t2.bar);
    return 0;
}

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had a related issue working within Spyder, but the problem seems to be the relationship between the escape character ( "\") and the "\" in the path name Here's my illustration and solution (note single \ vs double \\ ):

path =   'C:\Users\myUserName\project\subfolder'
path   # 'C:\\Users\\myUserName\\project\subfolder'
os.listdir(path)              # gives windows error
path =   'C:\\Users\\myUserName\\project\\subfolder'
os.listdir(path)              # gives expected behavior

How to keep indent for second line in ordered lists via CSS?

Update

This answer is outdated. You can do this a lot more simply, as pointed out in another answer below:

ul {
  list-style-position: outside;
}

See https://www.w3schools.com/cssref/pr_list-style-position.asp

Original Answer

I'm surprised to see this hasn't been solved yet. You can make use of the browser's table layout algorithm (without using tables) like this:

ol {
    counter-reset: foo;
    display: table;
}

ol > li {
    counter-increment: foo;
    display: table-row;
}

ol > li::before {
    content: counter(foo) ".";
    display: table-cell; /* aha! */
    text-align: right;
}

Demo: http://jsfiddle.net/4rnNK/1/

enter image description here

To make it work in IE8, use the legacy :before notation with one colon.

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

Read MS Exchange email in C#

It's a mess. MAPI or CDO via a .NET interop DLL is officially unsupported by Microsoft--it will appear to work fine, but there are problems with memory leaks due to their differing memory models. You could use CDOEX, but that only works on the Exchange server itself, not remotely; useless. You could interop with Outlook, but now you've just made a dependency on Outlook; overkill. Finally, you could use Exchange 2003's WebDAV support, but WebDAV is complicated, .NET has poor built-in support for it, and (to add insult to injury) Exchange 2007 nearly completely drops WebDAV support.

What's a guy to do? I ended up using AfterLogic's IMAP component to communicate with my Exchange 2003 server via IMAP, and this ended up working very well. (I normally seek out free or open-source libraries, but I found all of the .NET ones wanting--especially when it comes to some of the quirks of 2003's IMAP implementation--and this one was cheap enough and worked on the first try. I know there are others out there.)

If your organization is on Exchange 2007, however, you're in luck. Exchange 2007 comes with a SOAP-based Web service interface that finally provides a unified, language-independent way of interacting with the Exchange server. If you can make 2007+ a requirement, this is definitely the way to go. (Sadly for me, my company has a "but 2003 isn't broken" policy.)

If you need to bridge both Exchange 2003 and 2007, IMAP or POP3 is definitely the way to go.

javascript - match string against the array of regular expressions

You could use .test() which returns a boolean value when is find what your looking for in another string:

var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = new RegExp('\\b' + 'else' + '\\b', 'i');
var FoundIt = thisString.test(thisExpressions);  
if (FoundIt) { /* DO STUFF */ }

Custom format for time command

To use the Bash builtin time rather than /bin/time you can set this variable:

TIMEFORMAT='%3R'

which will output the real time that looks like this:

5.009

or

65.233

The number specifies the precision and can range from 0 to 3 (the default).

You can use:

TIMEFORMAT='%3lR'

to get output that looks like:

3m10.022s

The l (ell) gives a long format.

Table scroll with HTML and CSS

For those wondering how to implement Garry's solution with more than one header this is it:

_x000D_
_x000D_
#wrapper {_x000D_
  width: 235px;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border: 1px solid black;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
  width: 100px;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
thead>tr {_x000D_
  position: relative;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
tbody {_x000D_
  display: block;_x000D_
  height: 80px;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>column1</th>_x000D_
        <th>column2</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>row1</td>_x000D_
        <td>row1</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>row2</td>_x000D_
        <td>row2</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>row3</td>_x000D_
        <td>row3</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>row4</td>_x000D_
        <td>row4</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make links in a TextView clickable?

by using linkify: Linkify take a piece of text and a regular expression and turns all of the regex matches in the text into clickable links

TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("http://www.domain.com");
Linkify.addLinks(textView, Linkify.WEB_URLS);

Don't forget to

import android.widget.TextView;

gradle build fails on lint task

As for me, it's a bad and quick solution for your problem :

android { 
  lintOptions { 
    abortOnError false 
  }
}

Better solution is solving problem in your code, because lint tool checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization.

This problem most frequently occurring when:

  • Layout include unresolved symbols or missing some attribute
  • Other structural issues, such as use of deprecated elements or API calls that are not supported by the target API versions, might lead to code failing to run correctly.

Find your bugs by Inspect Code in Android Studio: Improve Your Code with Lint

Create mysql table directly from CSV file using the CSV Storage engine?

I have made a Windows command line tool that do just that.

You can download it here: http://commandline.dk/csv2ddl.htm

Usage:

C:\Temp>csv2ddl.exe mysql test.csv test.sql

Or

C:\Temp>csv2ddl.exe mysql advanced doublequote comma test.csv test.sql

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

This meta tag is used by all responsive web pages, that is those that are designed to layout well across device types - phone, tablet, and desktop. The attributes do what they say. However, as MDN's Using the viewport meta tag to control layout on mobile browsers indicates,

On high dpi screens, pages with initial-scale=1 will effectively be zoomed by browsers.

I've found that the following ensures that the page displays with zero zoom by default.

<meta name="viewport" content="width=device-width, initial-scale=0.86, maximum-scale=3.0, minimum-scale=0.86">

Export and Import all MySQL databases at one time

I wrote this comment already more than 4 years ago and decided now to make it to an answer.

The script from jruzafa can be a bit simplified:

#!/bin/bash

USER="zend"
PASSWORD=""
ExcludeDatabases="Database|information_schema|performance_schema|mysql"
databases=`mysql -u $USER -p$PASSWORD -e "SHOW DATABASES;" | tr -d "| " | egrep -v $ExcludeDatabases`

for db in $databases; do
    echo "Dumping database: $db"
    mysqldump -u $USER -p$PASSWORD --databases $db > `date +%Y%m%d`.$db.sql
    # gzip $OUTPUT`date +%Y%m%d`.$db.sql
done

Note:

  1. The excluded databases - prevalently the system tables - are provided in the variable ExcludeDatabases
  2. Please be aware that the password is provided in the command line. This is considered as insecure. Study this question.

How can I view all historical changes to a file in SVN

There's no built-in command for it, so I usually just do something like this:

#!/bin/bash

# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs.  The first revision of the file is emitted as
# full text since there's not previous version to compare it to.

function history_of_file() {
    url=$1 # current url of file
    svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {

#       first revision as full text
        echo
        read r
        svn log -r$r $url@HEAD
        svn cat -r$r $url@HEAD
        echo

#       remaining revisions as differences to previous revision
        while read r
        do
            echo
            svn log -r$r $url@HEAD
            svn diff -c$r $url@HEAD
            echo
        done
    }
}

Then, you can call it with:

history_of_file $1

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

Change encoding in notepad++ UTF-8 with BOM. That is how it worked for me

Checking oracle sid and database name

Type on sqlplus command prompt

SQL> select * from global_name;

then u will be see result on command prompt

SQL ORCL.REGRESS.RDBMS.DEV.US.ORACLE.COM

Here first one "ORCL" is database name,may be your system "XE" and other what was given on oracle downloading time.

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

As it turns out, one should not forget to include jacson dependency into the pom file. This solved the issue for me:

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

how to get current month and year

You can use this:

<p>&copy; <%: DateTime.Now.Year %> - My ASP.NET Application</p>

jQuery - selecting elements from inside a element

You can use any one these [starting from the fastest]

$("#moo") > $("#foo #moo") > $("div#foo span#moo") > $("#foo span") > $("#foo > #moo")

Take a look

keyCode values for numeric keypad?

Little bit cleared @A.Morel's answer. You might beware of keyboard language layout. Some keyboard layouts changed default numeric keys to symbols.

let key = parseInt(e.key)
if (isNaN(key)) {
  console.log("is not numeric")
}
else {
  console.log("is numeric")
}

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Sample database for exercise

You could try the classic MySQL world database.

The world.sql file is available for download here:

http://dev.mysql.com/doc/index-other.html

Just scroll down to Example Databases and you will find it.

Returning an array using C

You can't return arrays from functions in C. You also can't (shouldn't) do this:

char *returnArray(char array []){
 char returned [10];
 //methods to pull values from array, interpret them, and then create new array
 return &(returned[0]); //is this correct?
} 

returned is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.

You will need to dynamically allocate the memory inside of the function or fill a preallocated buffer provided by the caller.

Option 1:

dynamically allocate the memory inside of the function (caller responsible for deallocating ret)

char *foo(int count) {
    char *ret = malloc(count);
    if(!ret)
        return NULL;

    for(int i = 0; i < count; ++i) 
        ret[i] = i;

    return ret;
}

Call it like so:

int main() {
    char *p = foo(10);
    if(p) {
        // do stuff with p
        free(p);
    }

    return 0;
}

Option 2:

fill a preallocated buffer provided by the caller (caller allocates buf and passes to the function)

void foo(char *buf, int count) {
    for(int i = 0; i < count; ++i)
        buf[i] = i;
}

And call it like so:

int main() {
    char arr[10] = {0};
    foo(arr, 10);
    // No need to deallocate because we allocated 
    // arr with automatic storage duration.
    // If we had dynamically allocated it
    // (i.e. malloc or some variant) then we 
    // would need to call free(arr)
}

How to auto adjust the <div> height according to content in it?

If you haven't gotten the answer yet, your "float:left;" is messing up what you want. In your HTML create a container below your closing tags that have floating applied. For this container, include this as your style:

#container {
clear:both;
}

Done.

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Simple GUI Java calculator

assuming that string1 is your whole operation

use mdas

double result;
string recurAndCheck(string operation){
  if(operation.indexOf("/")){
     String leftSide = recurAndCheck(operation.split("/")[0]);
     string rightSide = recurAndCheck(operation.split("/")[1]);
     result = Double.parseDouble(leftSide)/Double.parseDouble(rightSide);

  } else if (..continue w/ *...) {
    //same as above but change / with *
  } else if (..continue w/ -) { 
    //change as above but change with -
  } else if (..continuew with +) {
    //change with add
  } else {
    return;
  }
}

How to get absolute path to file in /resources folder of your project

You need to specifie path started from /

URL resource = YourClass.class.getResource("/abc");
Paths.get(resource.toURI()).toFile();

Javascript equivalent of php's strtotime()?

Yes, it is. And it is supported in all major browser:

var ts = Date.parse("date string");

The only difference is that this function returns milliseconds instead of seconds, so you need to divide the result by 1000.

Check what valid formats can JavaScript parse.

What good technology podcasts are out there?

My favorite has been the Stack Overflow podcast just because it is reality based. ALT.NET has good content. Software Engineering Radio and Hanselminutes are informative. ThoughtWorks is marginal for me.

I'll try the others!

AngularJS ng-if with multiple conditions

you can also try with && for mandatory constion if both condtion are true than work

//div ng-repeat="(k,v) in items"

<div ng-if="(k == 'a' &&  k == 'b')">
    <!-- SOME CONTENT -->
</div>

Javascript call() & apply() vs bind()?

The main concept behind all this methods is Function burrowing.

Function borrowing allows us to use the methods of one object on a different object without having to make a copy of that method and maintain it in two separate places. It is accomplished through the use of . call() , . apply() , or . bind() , all of which exist to explicitly set this on the method we are borrowing

  1. Call invokes the function immediately and allows you to pass in arguments one by one
  2. Apply invokes the function immediately and allows you to pass in arguments as an array.
  3. Bind returns a new function, and you can invoke/call it anytime you want by invoking a function.

Below is an example of all this methods

let name =  {
    firstname : "Arham",
    lastname : "Chowdhury",
}
printFullName =  function(hometown,company){
    console.log(this.firstname + " " + this.lastname +", " + hometown + ", " + company)
}

CALL

the first argument e.g name inside call method is always a reference to (this) variable and latter will be function variable

printFullName.call(name,"Mumbai","Taufa");     //Arham Chowdhury, Mumbai, Taufa

APPLY

apply method is same as the call method the only diff is that, the function arguments are passed in Array list

printFullName.apply(name, ["Mumbai","Taufa"]);     //Arham Chowdhury, Mumbai, Taufa

BIND

bind method is same as call except that ,the bind returns a function that can be used later by invoking it (does'nt call it immediately)

let printMyNAme = printFullName.bind(name,"Mumbai","Taufa");

printMyNAme();      //Arham Chowdhury, Mumbai, Taufa

printMyNAme() is the function which invokes the function

below is the link for jsfiddle

https://codepen.io/Arham11/pen/vYNqExp

How to enable bulk permission in SQL Server

Try this:

USE master;

GO;
 
GRANT ADMINISTER BULK OPERATIONS TO shira;

Output (echo/print) everything from a PHP Array

You can use print_r to get human-readable output. But to display it as text we add "echo '';"

echo ''; print_r($row);

JAVA Unsupported major.minor version 51.0

This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7

You may also check Unsupported major.minor version 51.0

Linq to Entities - SQL "IN" clause

You need to turn it on its head in terms of the way you're thinking about it. Instead of doing "in" to find the current item's user rights in a predefined set of applicable user rights, you're asking a predefined set of user rights if it contains the current item's applicable value. This is exactly the same way you would find an item in a regular list in .NET.

There are two ways of doing this using LINQ, one uses query syntax and the other uses method syntax. Essentially, they are the same and could be used interchangeably depending on your preference:

Query Syntax:

var selected = from u in users
               where new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights)
               select u

foreach(user u in selected)
{
    //Do your stuff on each selected user;
}

Method Syntax:

var selected = users.Where(u => new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights));

foreach(user u in selected)
{
    //Do stuff on each selected user;
}

My personal preference in this instance might be method syntax because instead of assigning the variable, I could do the foreach over an anonymous call like this:

foreach(User u in users.Where(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
    //Do stuff on each selected user;
}

Syntactically this looks more complex, and you have to understand the concept of lambda expressions or delegates to really figure out what's going on, but as you can see, this condenses the code a fair amount.

It all comes down to your coding style and preference - all three of my examples do the same thing slightly differently.

An alternative way doesn't even use LINQ, you can use the same method syntax replacing "where" with "FindAll" and get the same result, which will also work in .NET 2.0:

foreach(User u in users.FindAll(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
    //Do stuff on each selected user;
}

Get push notification while App in foreground iOS

For Swift 5

1) Confirm the delegate to the AppDelegate with UNUserNotificationCenterDelegate

2) UNUserNotificationCenter.current().delegate = self in didFinishLaunch

3) Implement the below the method in AppDelegate.

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
     print("Push notification received in foreground.")
     completionHandler([.alert, .sound, .badge])
}

That's it!

How to hide action bar before activity is created, and then show it again?

Put your splash screen in a separate activity and use startActivityForResult from your main activity's onCreate method to display it. This works because, according to the docs:

As a special case, if you call startActivityForResult() with a requestCode >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your activity, then your window will not be displayed until a result is returned back from the started activity. This is to avoid visible flickering when redirecting to another activity.

You should probably do this only if the argument to onCreate is null (indicating a fresh launch of your activity, as opposed to a restart due to a configuration change).

PHP absolute path to root

This is my way to find the rootstart. Create at ROOT start a file with name mainpath.php

<?php 
## DEFINE ROOTPATH
$check_data_exist = ""; 

$i_surf = 0;

// looking for mainpath.php at the aktiv folder or higher folder

while (!file_exists($check_data_exist."mainpath.php")) {
  $check_data_exist .= "../"; 
  $i_surf++;
  // max 7 folder deep
  if ($i_surf == 7) { 
   return false;
  }
}

define("MAINPATH", ($check_data_exist ? $check_data_exist : "")); 
?>

For me is that the best and easiest way to find them. ^^

Moment.js with ReactJS (ES6)

run npm i moment react-moment --save

you can use this in your component,

import Moment from 'react-moment';

const date = new Date();
<Moment format='MMMM Do YYYY, h:mm:ss a'>{date}</Moment>

will give you sth like this :
enter image description here

How to pass arguments and redirect stdin from a file to program run in gdb?

If you want to have bare run command in gdb to execute your program with redirections and arguments, you can use set args:

% gdb ./a.out
(gdb) set args arg1 arg2 <file
(gdb) run

I was unable to achieve the same behaviour with --args parameter, gdb fiercely escapes the redirections, i.e.

% gdb --args echo 1 2 "<file"
(gdb) show args
Argument list to give program being debugged when it is started is "1 2 \<file".
(gdb) run
...
1 2 <file
...

This one actually redirects the input of gdb itself, not what we really want here

% gdb --args echo 1 2 <file
zsh: no such file or directory: file

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

You can open the DevTools in Chrome with CTRL+I on Windows (or CMD+I Mac), and Firefox with F12, then select the Console tab), and check the XPath by typing $x("your_xpath_here").
This will return an array of matched values. If it is empty, you know there is no match on the page.

Firefox v66 (April 2019):

Firefox v66 console xpath

Chrome v69 (April 2019):

Chrome v69 console xpath

How to add a custom Ribbon tab using VBA?

In addition to Roi-Kyi Bryant answer, this code fully works in Excel 2010. Press ALT + F11 and VBA editor will pop up. Double click on ThisWorkbook on the left side, then paste this code:

Private Sub Workbook_Activate()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

ribbonXML = "<mso:customUI      xmlns:mso='http://schemas.microsoft.com/office/2009/07/customui'>" & vbNewLine
ribbonXML = ribbonXML + "  <mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:qat/>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "      <mso:tab id='reportTab' label='My Actions' insertBeforeQ='mso:TabFormat'>" & vbNewLine
ribbonXML = ribbonXML + "        <mso:group id='reportGroup' label='Reports' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <mso:button id='runReport' label='Trim' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='AppointmentColor3'      onAction='TrimSelection'/>" & vbNewLine
ribbonXML = ribbonXML + "        </mso:group>" & vbNewLine
ribbonXML = ribbonXML + "      </mso:tab>" & vbNewLine
ribbonXML = ribbonXML + "    </mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "  </mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "</mso:customUI>"

ribbonXML = Replace(ribbonXML, """", "")

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub

Private Sub Workbook_Deactivate()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

ribbonXML = "<mso:customUI           xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">" & _
"<mso:ribbon></mso:ribbon></mso:customUI>"

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub

Don't forget to save and re-open workbook. Hope this helps!

How can I read a text file in Android?

First you store your text file in to raw folder.

private void loadWords() throws IOException {
    Log.d(TAG, "Loading words...");
    final Resources resources = mHelperContext.getResources();
    InputStream inputStream = resources.openRawResource(R.raw.definitions);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    try {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] strings = TextUtils.split(line, "-");
            if (strings.length < 2)
                continue;
            long id = addWord(strings[0].trim(), strings[1].trim());
            if (id < 0) {
                Log.e(TAG, "unable to add word: " + strings[0].trim());
            }
        }
    } finally {
        reader.close();
    }
    Log.d(TAG, "DONE loading words.");
}

How many characters in varchar(max)

See the MSDN reference table for maximum numbers/sizes.

Bytes per varchar(max), varbinary(max), xml, text, or image column: 2^31-1

There's a two-byte overhead for the column, so the actual data is 2^31-3 max bytes in length. Assuming you're using a single-byte character encoding, that's 2^31-3 characters total. (If you're using a character encoding that uses more than one byte per character, divide by the total number of bytes per character. If you're using a variable-length character encoding, all bets are off.)

Match the path of a URL, minus the filename extension

|(?<=\w)/.+(?=\.\w+$)|

  • select everything from the first literal '/' preceded by
  • look behind a Word(\w) character
  • until followed by a look ahead
    • literal '.' appended by
    • one or more Word(\w) characters
    • before the end $
  re> |(?<=\w)/.+(?=\.\w+$)|
Compile time 0.0011 milliseconds
Memory allocation (code space): 32
  Study time 0.0002 milliseconds
Capturing subpattern count = 0
No options
First char = '/'
No need char
Max lookbehind = 1
Subject length lower bound = 2
No set of starting bytes
data> http://php.net/manual/en/function.preg-match.php
Execute time 0.0007 milliseconds
 0: /manual/en/function.preg-match

|//[^/]*(.*)\.\w+$|

  • find two literal '//' followed by anything but a literal '/'
  • select everything until
  • find literal '.' followed by only Word \w characters before the end $
  re> |//[^/]*(.*)\.\w+$|
Compile time 0.0010 milliseconds
Memory allocation (code space): 28
  Study time 0.0002 milliseconds
Capturing subpattern count = 1
No options
First char = '/'
Need char = '.'
Subject length lower bound = 4
No set of starting bytes
data> http://php.net/manual/en/function.preg-match.php
Execute time 0.0005 milliseconds
 0: //php.net/manual/en/function.preg-match.php
 1: /manual/en/function.preg-match

|/[^/]+(.*)\.|

  • find literal '/' followed by at least 1 or more non literal '/'
  • aggressive select everything before the last literal '.'
  re> |/[^/]+(.*)\.|
Compile time 0.0008 milliseconds
Memory allocation (code space): 23
  Study time 0.0002 milliseconds
Capturing subpattern count = 1
No options
First char = '/'
Need char = '.'
Subject length lower bound = 3
No set of starting bytes
data> http://php.net/manual/en/function.preg-match.php
Execute time 0.0005 milliseconds
 0: /php.net/manual/en/function.preg-match.
 1: /manual/en/function.preg-match

|/[^/]+\K.*(?=\.)|

  • find literal '/' followed by at least 1 or more non literal '/'
  • Reset select start \K
  • aggressive select everything before
  • look ahead last literal '.'
  re> |/[^/]+\K.*(?=\.)|
Compile time 0.0009 milliseconds
Memory allocation (code space): 22
  Study time 0.0002 milliseconds
Capturing subpattern count = 0
No options
First char = '/'
No need char
Subject length lower bound = 2
No set of starting bytes
data> http://php.net/manual/en/function.preg-match.php
Execute time 0.0005 milliseconds
 0: /manual/en/function.preg-match

|\w+\K/.*(?=\.)|

  • find one or more Word(\w) characters before a literal '/'
  • reset select start \K
  • select literal '/' followed by
  • anything before
  • look ahead last literal '.'
  re> |\w+\K/.*(?=\.)|
Compile time 0.0009 milliseconds
Memory allocation (code space): 22
  Study time 0.0003 milliseconds
Capturing subpattern count = 0
No options
No first char
Need char = '/'
Subject length lower bound = 2
Starting byte set: 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P 
  Q R S T U V W X Y Z _ a b c d e f g h i j k l m n o p q r s t u v w x y z 
data> http://php.net/manual/en/function.preg-match.php
Execute time 0.0011 milliseconds
 0: /manual/en/function.preg-match

What is DOM element?

To find out concept of DOM element it is essential to understand concept of Dynamic HTML and DOM. Everything is started from the time that requirements of all stockholders of web pages are enhanced. They wanted the Web pages that can be more interactive, dynamic and lively. In addition, to reach this goal, developers required the tools and mechanisms that via them the presentation and content of each section of web page can be modified or manipulated. Therefore the concept of Dynamic HTML is created. To understand it, a great definition for Dynamic HTML is accessible in Wikipedia:

Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to create interactive and animated websites by using a combination of a static markup language (such as HTML), a client-side scripting language (such as JavaScript), a presentation definition language (such as CSS), and the Document Object Model (DOM).

So, writing standard DHTML web pages are standardized in three fields, including client-side scripting language (such as JavaScript), a presentation definition language (such as CSS) and uniform programming interface(API) to access and modify the Web page (Document Object Model). This activity is performed by W3C and others. Also to solve the problem of cross browser, W3C tried to reach a general consensus (with different browser vendors) about scripts to access and manipulate HTML and XML documents via Document Object Model (DOM) as a standard application programming interface (API).

But the main question is that how they designed the structure of Document Object Model to meet their needs. Their solution was simple but wonderful. They used a hierarchical structure such as tree which at the root of the tree you can find document object, also each node is equivalent of a HTML elements (DOM element). This abstraction of your web page give you a great facility to access any HTML element, style sheets, and ... . To understand it better you can map each indent of your HTML code to each level of DOM tree. Please pay attention to this example:

Your HTML:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <p>...</p>
        <ul>
            <li>...</li>
        </ul>
        <table>
            <tr>...</tr>
        </table>
    </body>
</html> 

DOM Structure:

    document
      |    .    
    <html>    .
    /   \         .
 <head> <body>  styleSheets
        /  \  \
      <p> <ul> <table>
      /     \       \
    text    <li>    <tr>  

So, each node of this hierarchical structure (DOM tree) refers to a DOM element. To learn more use tis reference

How do I use CMake?

I don't know about Windows (never used it), but on a Linux system you just have to create a build directory (in the top source directory)

mkdir build-dir

go inside it

cd build-dir

then run cmake and point to the parent directory

cmake ..

and finally run make

make

Notice that make and cmake are different programs. cmake is a Makefile generator, and the make utility is governed by a Makefile textual file. See cmake & make wikipedia pages.

NB: On Windows, cmake might operate so could need to be used differently. You'll need to read the documentation (like I did for Linux)

How to make a simple rounded button in Storyboard?

I found the easiest way to do this, is by setting the cornerRadius to half of the height of the view.

button.layer.cornerRadius = button.bounds.size.height/2

Build a basic Python iterator

First of all the itertools module is incredibly useful for all sorts of cases in which an iterator would be useful, but here is all you need to create an iterator in python:

yield

Isn't that cool? Yield can be used to replace a normal return in a function. It returns the object just the same, but instead of destroying state and exiting, it saves state for when you want to execute the next iteration. Here is an example of it in action pulled directly from the itertools function list:

def count(n=0):
    while True:
        yield n
        n += 1

As stated in the functions description (it's the count() function from the itertools module...) , it produces an iterator that returns consecutive integers starting with n.

Generator expressions are a whole other can of worms (awesome worms!). They may be used in place of a List Comprehension to save memory (list comprehensions create a list in memory that is destroyed after use if not assigned to a variable, but generator expressions can create a Generator Object... which is a fancy way of saying Iterator). Here is an example of a generator expression definition:

gen = (n for n in xrange(0,11))

This is very similar to our iterator definition above except the full range is predetermined to be between 0 and 10.

I just found xrange() (suprised I hadn't seen it before...) and added it to the above example. xrange() is an iterable version of range() which has the advantage of not prebuilding the list. It would be very useful if you had a giant corpus of data to iterate over and only had so much memory to do it in.

UnicodeEncodeError: 'latin-1' codec can't encode character

I ran into this same issue when using the Python MySQLdb module. Since MySQL will let you store just about any binary data you want in a text field regardless of character set, I found my solution here:

Using UTF8 with Python MySQLdb

Edit: Quote from the above URL to satisfy the request in the first comment...

"UnicodeEncodeError:'latin-1' codec can't encode character ..."

This is because MySQLdb normally tries to encode everythin to latin-1. This can be fixed by executing the following commands right after you've etablished the connection:

db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')

"db" is the result of MySQLdb.connect(), and "dbc" is the result of db.cursor().

Meaning of ${project.basedir} in pom.xml

There are a set of available properties to all Maven projects.

From Introduction to the POM:

project.basedir: The directory that the current project resides in.

This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml file. If your POM is located inside /path/to/project/pom.xml then this property will evaluate to /path/to/project.

Some properties are also inherited from the Super POM, which is the case for project.build.directory. It is the value inside the <project><build><directory> element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory, it is:

The directory where all files generated by the build are placed. The default value is target.

This is the directory that will hold every generated file by the build.

What does request.getParameter return?

Both if (one.length() > 0) {} and if (!"".equals(one)) {} will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo text field.

If there's any chance you can use the Expression Language to handle the parameter, you could access it with empty param.foo in an expression.

<c:if test='${not empty param.foo}'>
    This page code gets rendered.
</c:if>

Why is Python running my module when I import it, and how do I stop it?

Use the if __name__ == '__main__' idiom -- __name__ is a special variable whose value is '__main__' if the module is being run as a script, and the module name if it's imported. So you'd do something like

# imports
# class/function definitions
if __name__ == '__main__':
    # code here will only run when you invoke 'python main.py'

Removing MySQL 5.7 Completely

You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo rm -rf /var/lib/mysql

I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

Is it possible to use argsort in descending order?

Another way is to use only a '-' in the argument for argsort as in : "df[np.argsort(-df[:, 0])]", provided df is the dataframe and you want to sort it by the first column (represented by the column number '0'). Change the column-name as appropriate. Of course, the column has to be a numeric one.

jQuery if div contains this text, replace that part of the text

You can use the text method and pass a function that returns the modified text, using the native String.prototype.replace method to perform the replacement:

?$(".text_div").text(function () {
    return $(this).text().replace("contains", "hello everyone"); 
});?????

Here's a working example.

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

<!DOCTYPE html>

<html>
 <head>
   <link rel="stylesheet" type="text/css" href="main.css" />
 </head>

<body>
 <div id="page-container">
   <div id="content-wrap">
     <!-- all other page content -->
   </div>
   <footer id="footer"></footer>
 </div>
</body>

</html>


#page-container {
  position: relative;
  min-height: 100vh;
}

#content-wrap {
  padding-bottom: 2.5rem;    /* Footer height */
}

#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 2.5rem;            /* Footer height */
}

Retrieving the COM class factory for component failed

There's one more issue you might need to address if you are using the Windows 2008 Server with IIS7. The server might report the following error:

Microsoft Office Excel cannot access the file 'c:\temp\test.xls'. There are several possible reasons:

  • The file name or path does not exist.
  • The file is being used by another program.
  • The workbook you are trying to save has the same name as a currently open workbook.

The solution is posted here (look for the text posted by user Ogawa): http://social.msdn.microsoft.com/Forums/en-US/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91?prof=required

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

package com.example;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES 
{
    public void run() 
    {
        try 
        {
            String text = "Hello World";
            String key = "Bar12345Bar12345"; // 128 bit key
            // Create key and cipher
            Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            // encrypt the text
            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            byte[] encrypted = cipher.doFinal(text.getBytes());
            System.err.println(new String(encrypted));
            // decrypt the text
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            String decrypted = new String(cipher.doFinal(encrypted));
            System.err.println(decrypted);
        }
        catch(Exception e) 
        {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) 
    {
        StrongAES app = new StrongAES();
        app.run();
    }
}

What is the use of the init() usage in JavaScript?

NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass instead of myClass.

Either you can call init from your constructor function:

var myObj = new MyClass(2, true);

function MyClass(v1, v2) 
{
    // ...

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // ...

    this.init(); // <------------ added this
}

Or more simply you could just copy the body of the init function to the end of the constructor function. No need to actually have an init function at all if it's only called once.

Telling Python to save a .txt file to a certain directory on Windows and Mac

Another simple way without using import OS is,

outFileName="F:\\folder\\folder\\filename.txt"
outFile=open(outFileName, "w")
outFile.write("""Hello my name is ABCD""")
outFile.close()

How do I make a branch point at a specific commit?

If you are currently not on branch master, that's super easy:

git branch -f master 1258f0d0aae

This does exactly what you want: It points master at the given commit, and does nothing else.

If you are currently on master, you need to get into detached head state first. I'd recommend the following two command sequence:

git checkout 1258f0d0aae    #detach from master
git branch -f master HEAD   #exactly as above

#optionally reattach to master
git checkout master

Be aware, though, that any explicit manipulation of where a branch points has the potential to leave behind commits that are no longer reachable by any branches, and thus become object to garbage collection. So, think before you type git branch -f!


This method is better than the git reset --hard approach, as it does not destroy anything in the index or working directory.

Converting from Integer, to BigInteger

The method you want is BigInteger#valueOf(long val).

E.g.,

BigInteger bi = BigInteger.valueOf(myInteger.intValue());

Making a String first is unnecessary and undesired.

How can I check whether Google Maps is fully loaded?

In 2018:

var map = new google.maps.Map(...)
map.addListener('tilesloaded', function () { ... })

https://developers.google.com/maps/documentation/javascript/events

ASP.Net Download file to client browser

Just a slight addition to the above solution if you are having problem with downloaded file's name...

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");

This will return the exact file name even if it contains spaces or other characters.

Add Variables to Tuple

Another tactic not yet mentioned is using appending to a list, and then converting the list to a tuple at the end:

mylist = []
for x in range(5):
    mylist.append(x)
mytuple = tuple(mylist)
print mytuple

returns

(0, 1, 2, 3, 4)

I sometimes use this when I have to pass a tuple as a function argument, which is often necessary for the numpy functions.

When to use "ON UPDATE CASCADE"

A few days ago I've had an issue with triggers, and I've figured out that ON UPDATE CASCADE can be useful. Take a look at this example (PostgreSQL):

CREATE TABLE club
(
    key SERIAL PRIMARY KEY,
    name TEXT UNIQUE
);

CREATE TABLE band
(
    key SERIAL PRIMARY KEY,
    name TEXT UNIQUE
);

CREATE TABLE concert
(
    key SERIAL PRIMARY KEY,
    club_name TEXT REFERENCES club(name) ON UPDATE CASCADE,
    band_name TEXT REFERENCES band(name) ON UPDATE CASCADE,
    concert_date DATE
);

In my issue, I had to define some additional operations (trigger) for updating the concert's table. Those operations had to modify club_name and band_name. I was unable to do it, because of reference. I couldn't modify concert and then deal with club and band tables. I couldn't also do it the other way. ON UPDATE CASCADE was the key to solve the problem.

What's the difference between `raw_input()` and `input()` in Python 3?

In Python 2, raw_input() returns a string, and input() tries to run the input as a Python expression.

Since getting a string was almost always what you wanted, Python 3 does that with input(). As Sven says, if you ever want the old behaviour, eval(input()) works.

How to parse/format dates with LocalDateTime? (Java 8)

Parsing a string with date and time into a particular point in time (Java calls it an "Instant") is quite complicated. Java has been tackling this in several iterations. The latest one, java.time and java.time.chrono, covers almost all needs (except Time Dilation :) ).

However, that complexity brings a lot of confusion.

The key to understand date parsing is:

Why does Java have so many ways to parse a date

  1. There are several systems to measure a time. For instance, the historical Japanese calendars were derived from the time ranges of the reign of the respective emperor or dynasty. Then there is e.g. UNIX timestamp. Fortunately, the whole (business) world managed to use the same.
  2. Historically, the systems were being switched from/to, for various reasons. E.g. from Julian calendar to Gregorian calendar in 1582. So 'western' dates before that need to be treated differently.
  3. And of course the change did not happen at once. Because the calendar came from the headquarteds of some religion and other parts of Europe believed in other dieties, for instance Germany did not switch until the year 1700.

...and why is the LocalDateTime, ZonedDateTime et al. so complicated

  1. There are time zones. A time zone is basically a "stripe"*[1] of the Earth's surface whose authorities follow the same rules of when does it have which time offset. This includes summer time rules.
    The time zones change over time for various areas, mostly based on who conquers whom. And one time zone's rules change over time as well.

  2. There are time offsets. That is not the same as time zones, because a time zone may be e.g. "Prague", but that has summer time offset and winter time offset.
    If you get a timestamp with a time zone, the offset may vary, depending on what part of the year it is in. During the leap hour, the timestamp may mean 2 different times, so without additional information, it can't be reliably converted.
    Note: By timestamp I mean "a string that contains a date and/or time, optionally with a time zone and/or time offset."

  3. Several time zones may share the same time offset for certain periods. For instance, GMT/UTC time zone is the same as "London" time zone when the summer time offset is not in effect.

To make it a bit more complicated (but that's not too important for your use case) :

  1. The scientists observe Earth's dynamic, which changes over time; based on that, they add seconds at the end of individual years. (So 2040-12-31 24:00:00 may be a valid date-time.) This needs regular updates of the metadata that systems use to have the date conversions right. E.g. on Linux, you get regular updates to the Java packages including these new data.
  2. The updates do not always keep the previous behavior for both historical and future timestamps. So it may happen that parsing of the two timestamps around some time zone's change comparing them may give different results when running on different versions of the software. That also applies to comparing between the affected time zone and other time zone.

    Should this cause a bug in your software, consider using some timestamp that does not have such complicated rules, like UNIX timestamp.

  3. Because of 7, for the future dates, we can't convert dates exactly with certainty. So, for instance, current parsing of 8524-02-17 12:00:00 may be off a couple of seconds from the future parsing.

JDK's APIs for this evolved with the contemporary needs

  • The early Java releases had just java.util.Date which had a bit naive approach, assuming that there's just the year, month, day, and time. This quickly did not suffice.
  • Also, the needs of the databases were different, so quite early, java.sql.Date was introduced, with it's own limitations.
  • Because neither covered different calendars and time zones well, the Calendar API was introduced.
  • This still did not cover the complexity of the time zones. And yet, the mix of the above APIs was really a pain to work with. So as Java developers started working on global web applications, libraries that targeted most use cases, like JodaTime, got quickly popular. JodaTime was the de-facto standard for about a decade.
  • But the JDK did not integrate with JodaTime, so working with it was a bit cumbersome. So, after a very long discussion on how to approach the matter, JSR-310 was created mainly based on JodaTime.

How to deal with it in Java's java.time

Determine what type to parse a timestamp to

When you are consuming a timestamp string, you need to know what information it contains. This is the crucial point. If you don't get this right, you end up with a cryptic exceptions like "Can't create Instant" or "Zone offset missing" or "unknown zone id" etc.

Does it contain the date and the time?

  1. Does it have a time offset?
    A time offset is the +hh:mm part. Sometimes, +00:00 may be substituted with Z as 'Zulu time', UTC as Universal Time Coordinated, or GMT as Greenwich Mean Time. These also set the time zone.
    For these timestamps, you use OffsetDateTime.

  2. Does it have a time zone?
    For these timestamps, you use ZonedDateTime.
    Zone is specified either by

    • name ("Prague", "Pacific Standard Time", "PST"), or
    • "zone ID" ("America/Los_Angeles", "Europe/London"), represented by java.time.ZoneId.

    The list of time zones is compiled by a "TZ database", backed by ICAAN.

    According to ZoneId's javadoc, The zone id's can also somehow be specified as Z and offset. I'm not sure how this maps to real zones. If the timestamp, which only has a TZ, falls into a leap hour of time offset change, then it is ambiguous, and the interpretation is subject of ResolverStyle, see below.

  3. If it has neither, then the missing context is assumed or neglected. And the consumer has to decide. So it needs to be parsed as LocalDateTime and converted to OffsetDateTime by adding the missing info:

    • You can assume that it is a UTC time. Add the UTC offset of 0 hours.
    • You can assume that it is a time of the place where the conversion is happening. Convert it by adding the system's time zone.
    • You can neglect and just use it as is. That is useful e.g. to compare or substract two times (see Duration), or when you don't know and it doesn't really matter (e.g. local bus schedule).

Partial time information

  • Based on what the timestamp contains, you can take LocalDate, LocalTime, OffsetTime, MonthDay, Year, or YearMonth out of it.

If you have the full information, you can get a java.time.Instant. This is also internally used to convert between OffsetDateTime and ZonedDateTime.

Figure out how to parse it

There is an extensive documentation on DateTimeFormatter which can both parse a timestamp string and format to string.

The pre-created DateTimeFormatters should cover moreless all standard timestamp formats. For instance, ISO_INSTANT can parse 2011-12-03T10:15:30.123457Z.

If you have some special format, then you can create your own DateTimeFormatter (which is also a parser).

private static final DateTimeFormatter TIMESTAMP_PARSER = new DateTimeFormatterBuilder()
   .parseCaseInsensitive()
   .append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SX"))
   .toFormatter();

I recommend to look at the source code of DateTimeFormatter and get inspired on how to build one using DateTimeFormatterBuilder. While you're there, also have a look at ResolverStyle which controls whether the parser is LENIENT, SMART or STRICT for the formats and ambiguous information.

TemporalAccessor

Now, the frequent mistake is to go into the complexity of TemporalAccessor. This comes from how the developers were used to work with SimpleDateFormatter.parse(String). Right, DateTimeFormatter.parse("...") gives you TemporalAccessor.

// No need for this!
TemporalAccessor ta = TIMESTAMP_PARSER.parse("2011-... etc");

But, equiped with the knowledge from the previous section, you can conveniently parse into the type you need:

OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z", TIMESTAMP_PARSER);

You do not actually need to the DateTimeFormatter either. The types you want to parse have the parse(String) methods.

OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z");

Regarding TemporalAccessor, you can use it if you have a vague idea of what information there is in the string, and want to decide at runtime.

I hope I shed some light of understanding onto your soul :)

Note: There's a backport of java.time to Java 6 and 7: ThreeTen-Backport. For Android it has ThreeTenABP.

[1] Not just that they are not stripes, but there also some weird extremes. For instance, some neighboring pacific islands have +14:00 and -11:00 time zones. That means, that while on one island, there is 1st May 3 PM, on another island not so far, it is still 30 April 12 PM (if I counted correctly :) )

Deciding between HttpClient and WebClient

Unpopular opinion from 2020:

When it comes to ASP.NET apps I still prefer WebClient over HttpClient because:

  1. The modern implementation comes with async/awaitable task-based methods
  2. Has smaller memory footprint and 2x-5x faster (other answers already mention that)
  3. It's suggested to "reuse a single instance of HttpClient for the lifetime of your application". But ASP.NET has no "lifetime of application", only lifetime of a request.

C# : Out of Memory exception

As .Net progresses, so does their ability to add new 32-bit configurations that trips everyone up it seems.

If you are on .Net Framework 4.7.2 do the following:

Go to Project Properties

Build

Uncheck 'prefer 32-bit'

Cheers!

Session state can only be used when enableSessionState is set to true either in a configuration

Session State may be broken if you have the following in Web.Config:

<httpModules>
  <clear/>
</httpModules>

If this is the case, you may want to comment out such section, and you won't need any other changes to fix this issue.

dropdownlist set selected value in MVC3 Razor

I drilled down the formation of the drop down list instead of using @Html.DropDownList(). This is useful if you have to set the value of the dropdown list at runtime in razor instead of controller:

<select id="NewsCategoriesID" name="NewsCategoriesID">
    @foreach (SelectListItem option in ViewBag.NewsCategoriesID)
    {
        <option value="@option.Value" @(option.Value == ViewBag.ValueToSet ? "selected='selected'" : "")>@option.Text</option>

    }
</select>

What jar should I include to use javax.persistence package in a hibernate based application?

For JPA 2.1 the javax.persistence package can be found in here:

<dependency>
   <groupId>org.hibernate.javax.persistence</groupId>
   <artifactId>hibernate-jpa-2.1-api</artifactId>
   <version>1.0.0.Final</version>
</dependency>

See: hibernate-jpa-2.1-api on Maven Central The pattern seems to be to change the artefact name as the JPA version changes. If this continues new versions can be expected to arrive in Maven Central here: Hibernate JPA versions

The above JPA 2.1 APi can be used in conjunction with Hibernate 4.3.7, specifically:

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>4.3.7.Final</version>
</dependency>

Using querySelectorAll to retrieve direct children

Good question. At the time it was asked, a universally-implemented way to do "combinator rooted queries" (as John Resig called them) did not exist.

Now the :scope pseudo-class has been introduced. It is not supported on [pre-Chrominum] versions of Edge or IE, but has been supported by Safari for a few years already. Using that, your code could become:

let myDiv = getElementById("myDiv");
myDiv.querySelectorAll(":scope > .foo");

Note that in some cases you can also skip .querySelectorAll and use other good old-fashioned DOM API features. For example, instead of myDiv.querySelectorAll(":scope > *") you could just write myDiv.children, for example.

Otherwise if you can't yet rely on :scope, I can't think of another way to handle your situation without adding more custom filter logic (e.g. find myDiv.getElementsByClassName("foo") whose .parentNode === myDiv), and obviously not ideal if you're trying to support one code path that really just wants to take an arbitrary selector string as input and a list of matches as output! But if like me you ended up asking this question simply because you got stuck thinking "all you had was a hammer" don't forget there are a variety of other tools the DOM offers too.

Check if EditText is empty.

if(TextUtils.isEmpty(textA.getText())){
            showToast(it's Null");
        }

you can use TextUtils.isEmpty like my Example ! Good luck

Commenting multiple lines in DOS batch file

try this:

   @echo off 2>Nul 3>Nul 4>Nul

   ben ali
   mubarak
   gadeffi
   ..next ?

   echo hello Tunisia

  pause

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

I coded up an equivalent C program to experiment, and I can confirm this strange behaviour. What's more, gcc believes the 64-bit integer (which should probably be a size_t anyway...) to be better, as using uint_fast32_t causes gcc to use a 64-bit uint.

I did a bit of mucking around with the assembly:
Simply take the 32-bit version, replace all 32-bit instructions/registers with the 64-bit version in the inner popcount-loop of the program. Observation: the code is just as fast as the 32-bit version!

This is obviously a hack, as the size of the variable isn't really 64 bit, as other parts of the program still use the 32-bit version, but as long as the inner popcount-loop dominates performance, this is a good start.

I then copied the inner loop code from the 32-bit version of the program, hacked it up to be 64 bit, fiddled with the registers to make it a replacement for the inner loop of the 64-bit version. This code also runs as fast as the 32-bit version.

My conclusion is that this is bad instruction scheduling by the compiler, not actual speed/latency advantage of 32-bit instructions.

(Caveat: I hacked up assembly, could have broken something without noticing. I don't think so.)

How to revert initial git commit?

You can't. So:

rm -rf .git/
git init
git add -A
git commit -m 'Your new commit message'

Convert string to float?

Try this:

String numberStr = "3.5";
Float number = null;
try {
   number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
    System.out.println("numberStr is not a number");
}

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

In case anyone in the future had this problem, I'm using a Mac and just had to install the Command Line Tools using 'xcode-select --install'

How do I set vertical space between list items?

To apply to an entire list, use

ul.space_list li { margin-bottom: 1em; }

Then, in the html:

<ul class=space_list>
<li>A</li>
<li>B</li>
</ul>

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

How to Bold entire row 10 example:

workSheet.Cells[10, 1].EntireRow.Font.Bold = true;    

More formally:

Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[10, 1] as Xl.Range;
rng.EntireRow.Font.Bold = true;

How to Bold Specific Cell 'A10' for example:

workSheet.Cells[10, 1].Font.Bold = true;

Little more formal:

int row = 1;
int column = 1;  /// 1 = 'A' in Excel

Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[row, column] as Xl.Range;
rng.Font.Bold = true;

How to run iPhone emulator WITHOUT starting Xcode?

As the multitude of answers indicate, there are lots of different ways to address this issue. Not all of them address what is my number one issue, and what seems to be the asker's priority, as well: The ability to launch from Spotlight.

Here's the solution that works well for me, and should work with any OS X and XCode versions. I've tested it on OS X 10.11 and XCode 7.3.

Initial setup does require launching XCode, but after that, you won't need to just to get to the Simulator.

Setup

  1. Launch XCode
  2. From the XCode menu, select Open Developer Tool > Simulator
  3. In the dock, control (or right) click on the Simulator icon
  4. Select Options > Show in Finder
  5. While holding down Command and Option, drag the Simulator icon to the applications directory. This creates an alias to it.
  6. If desired, rename the alias from "Simulator" to "iOS Simulator". Whatever you name it is what it will show up as in Spotlight.

Note: There are other ways to get to the location of the Simulator app (steps 1-4), such as using Go to Folder… in the Finder, but those require knowing the location of the Simulator to begin with. Since that has changed from version to version of XCode, this way should work regardless of these changes.

Use

  1. Launch Spotlight (command-space, etc.)
  2. Type "simulator" or "ios" (if you renamed the alias).
  3. If necessary, use the down arrow to scroll to the Simulator alias. Eventually, spotlight should learn and make the alias the top choice so you can skip this step.
  4. Hit return

SQL Query to find the last day of the month

select DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-0, -1) LastDate

Select from where field not equal to Mysql Php

select * from table where fiels1 NOT LIKE 'x' AND field2 NOT LIKE 'y'

//this work in case insensitive manner

nodejs - first argument must be a string or Buffer - when using response.write with http.request

Although the question is solved, sharing knowledge for clarification of the correct meaning of the error.

The error says that the parameter needed to the concerned breaking function is not in the required format i.e. string or Buffer

The solution is to change the parameter to string

breakingFunction(JSON.stringify(offendingParameter), ... other params...);

or buffer

breakingFunction(BSON.serialize(offendingParameter), ... other params...);

remove borders around html input

your code is look like this jsfiddle.net/NTkGZ/

try

border:none;

Getting last month's date in php

Oh I figured this out, please ignore unless you have the same problem i did in which case:

$prevmonth = date("M Y",mktime(0,0,0,date("m")-1,1,date("Y")));

Stop setInterval

USE this i hope help you

var interval;

function updateDiv(){
    $.ajax({
        url: 'getContent.php',
        success: function(data){
            $('.square').html(data);
        },
        error: function(){
            /* clearInterval(interval); */
            stopinterval(); // stop the interval
            $.playSound('oneday.wav');
            $('.square').html('<span style="color:red">Connection problems</span>');
        }
    });
}

function playinterval(){
  updateDiv(); 
  interval = setInterval(function(){updateDiv();},3000); 
  return false;
}

function stopinterval(){
  clearInterval(interval); 
  return false;
}

$(document)
.on('ready',playinterval)
.on({click:playinterval},"#playinterval")
.on({click:stopinterval},"#stopinterval");

PHP display current server path

here is a test script to run on your server to see what is reliabel.

<?php
$host = gethostname();
$ip = gethostbyname($host);
echo "gethostname and gethostbyname: $host at $ip<br>";
$server = $_SERVER['SERVER_ADDR'];
echo "_SERVER[SERVER_ADDR]: $server<br>";
$my_current_ip=exec("ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'");
echo "exec ifconfig ... : $my_current_ip<br>";
$external_ip = file_get_contents("http://ipecho.net/plain");
echo "get contents ipecho.net: $external_ip<br>";
?>

The only different option in there is using fiel_get_contents rather than curl for the extrernal website lookup.

This is the result of hitting the web page on a shared hosting, free account. (actual server name and IP changed)

gethostname and gethostbyname: freesites.servercluster.com at 345.27.413.51
_SERVER[SERVER_ADDR]: 127.0.0.7
exec ifconfig ... :
get contents ipecho.net: 345.27.413.51

Why needed this? Decided to point A record at server to see if it opens the web page. Later ran script to save ip and update on ghost site on same server to lookup IP and alert if changed.

In this case, good results optained by:

gethostname() & 
gethostbyname($host)
or 
file_get_contents("http://ipecho.net/plain")

Specify JDK for Maven to use

Yet another alternative to manage multiple jdk versions is jEnv

After installation, you can simply change java version "locally" i.e. for a specific project directory by:

jenv local 1.6

This will also make mvn use that version locally, when you enable the mvn plugin:

jenv enable-plugin maven

Java, Shifting Elements in an Array

You can use the Below codes for shifting not rotating:

    int []arr = {1,2,3,4,5,6,7,8,9,10,11,12};
            int n = arr.length;
            int d = 3;

Programm for shifting array of size n by d elements towards left:

    Input : {1,2,3,4,5,6,7,8,9,10,11,12}
    Output: {4,5,6,7,8,9,10,11,12,10,11,12}

        public void shiftLeft(int []arr,int d,int n) {
            for(int i=0;i<n-d;i++) {
                arr[i] = arr[i+d];
            }
        }

Programm for shifting array of size n by d elements towards right:

    Input : {1,2,3,4,5,6,7,8,9,10,11,12}
    Output: {1,2,3,1,2,3,4,5,6,7,8,9}

        public void shiftRight(int []arr,int d,int n) {

            for(int i=n-1;i>=d;i--) {
                arr[i] = arr[i-d];
            }
        }

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

This issue is not happening in Firefox and Safari. Make sure you are using the latest version of xml2json.js. Because i faced the XML parser error in IE. In Chrome best way you should open it in server like Apache or XAMPP.

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

The Gantt charts given by Hifzan and Raja are for FCFS algorithms.

With an SJF algorithm, processes can be interrupted. That is, every process doesn't necessarily execute straight through their given burst time.

P3|P2|P4|P3|P5|P1|P5

1|2|3|5|7|8|11|14

P3 arrives at 1ms, then is interrupted by P2 and P4 since they both have smaller burst times, and then P3 resumes. P5 starts executing next, then is interrupted by P1 since P1's burst time is smaller than P5's. You must note the arrival times and be careful. These problems can be trickier than how they appear at-first-glance.

EDIT: This applies only to Preemptive SJF algorithms. A plain SJF algorithm is non-preemptive, meaning it does not interrupt a process.

Identifier is undefined

Are you missing a function declaration?

void ac_search(uint num_patterns, uint pattern_length, const char *patterns, 
               uint num_records, uint record_length, const char *records, int *matches, Node* trie);

Add it just before your implementation of ac_benchmark_search.

How can I rename a single column in a table at select?

If, like me, you are doing this for a column which then goes through COALESCE / array_to_json / ARRAY_AGG / row_to_json (PostgreSQL) and want to keep the capitals in the column name, double quote the column name, like so:

SELECT a.price AS "myFirstPrice", b.price AS "mySecondPrice"

Without the quotes (and when using those functions), my column names in camelCase would lose the capital letters.

What are the differences between the urllib, urllib2, urllib3 and requests module?

This is my understanding of what the relations are between the various "urllibs":

In the Python 2 standard library there exist two HTTP libraries side-by-side. Despite the similar name, they are unrelated: they have a different design and a different implementation.

  • urllib was the original Python HTTP client, added to the standard library in Python 1.2.
  • urllib2 was a more capable HTTP library, added in Python 1.6, intended to be eventually a replacement for urllib.

The Python 3 standard library has a new urllib, that is a merged/refactored/rewritten version of those two packages.

urllib3 is a third-party package. Despite the name, it is unrelated to the standard library packages, and there is no intention to include it in the standard library in the future.

Finally, requests internally uses urllib3, but it aims for an easier-to-use API.

vuetify center items into v-flex

wrap button inside <div class="text-xs-center">

<div class="text-xs-center">
  <v-btn primary>
    Signup
  </v-btn>
</div>

Dev uses it in his examples.


For centering buttons in v-card-actions we can add class="justify-center" (note in v2 class is text-center (so without xs):

<v-card-actions class="justify-center">
  <v-btn>
    Signup
  </v-btn>
</v-card-actions>

Codepen


For more examples with regards to centering see here

How to know user has clicked "X" or the "Close" button?

The CloseReason enumeration you found on MSDN is just for the purpose of checking whether the user closed the app, or it was due to a shutdown, or closed by the task manager, etc...

You can do different actions, according to the reason, like:

void Form_FormClosing(object sender, FormClosingEventArgs e)
{
    if(e.CloseReason == CloseReason.UserClosing)
        // Prompt user to save his data

    if(e.CloseReason == CloseReason.WindowsShutDown)
        // Autosave and clear up ressources
}

But like you guessed, there is no difference between clicking the x button, or rightclicking the taskbar and clicking 'close', or pressing Alt F4, etc. It all ends up in a CloseReason.UserClosing reason.

Use <Image> with a local file

It works exactly as you expect it to work. There's a bug https://github.com/facebook/react-native/issues/282 that prevents it from working correctly.

If you have node_modules (with react_native) in the same folder as the xcode project, you can edit node_modules/react-native/packager/packager.js and make this change: https://github.com/facebook/react-native/pull/286/files . It'll work magically :)

If your react_native is installed somewhere else and the patch doesn't work, comment on https://github.com/facebook/react-native/issues/282 to let them know about your setup.

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

The login with Facebook button on your site is linking to:

https://www.facebook.com/v2.2/dialog/oauth?client_id=1500708243571026&redirect_uri=http://openstrategynetwork.com/_oauth/facebook&display=popup&scope=email&state=eyJsb2dpblN0eWxlIjoicG9wdXAiLCJjcmVkZW50aWFsVG9rZW4iOiIwSXhEU05XamJjU0VaQWdqcmF6SXdOUWRuRFozXzc0X19lbVhGWUJTZGNYIiwiaXNDb3Jkb3ZhIjpmYWxzZX0=

Notice: redirect_uri=http://openstrategynetwork.com/_oauth/facebook

If you instead change the link to:

redirect_uri=http://openstrategynetwork.com/_oauth/facebook?close

It should work. Or, you can change the Facebook link to http://openstrategynetwork.com/_oauth/facebook

You can also add http://localhost/_oauth/facebook to the valid redirect URIs.

Facebook requires that you whitelist redirect URIs, since otherwise people could login with Facebook for your service, and then send their access token to an attacker's server! And you don't want that to happen ;]

Java random number with given length

For the follow-up question, you can get a number between 36^5 and 36^6 and convert it in base 36

UPDATED:

using this code

http://javaconfessions.com/2008/09/convert-between-base-10-and-base-62-in_28.html

It's written BaseConverterUtil.toBase36(60466176+r.nextInt(2116316160))

but in your use case, it can be optimized by using a StringBuilder and having the number in the reverse order ie 71 should be converted in Z1 instead of 1Z

EDITED:

Create a pointer to two-dimensional array

You can do it like this:

uint8_t (*matrix_ptr)[10][20] = &l_matrix;

In what cases will HTTP_REFERER be empty

It will/may be empty when the enduser

  • entered the site URL in browser address bar itself.
  • visited the site by a browser-maintained bookmark.
  • visited the site as first page in the window/tab.
  • clicked a link in an external application.
  • switched from a https URL to a http URL.
  • switched from a https URL to a different https URL.
  • has security software installed (antivirus/firewall/etc) which strips the referrer from all requests.
  • is behind a proxy which strips the referrer from all requests.
  • visited the site programmatically (like, curl) without setting the referrer header (searchbots!).

C# Call a method in a new thread

Asynchronous version:

private async Task DoAsync()
{
    await Task.Run(async () =>
    {
        //Do something awaitable here
    });
}

Countdown timer using Moment js

Although I'm sure this won't be accepted as the answer to this very old question, I came here looking for a way to do this and this is how I solved the problem.

I created a demonstration here at codepen.io.

The Html:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js" type="text/javascript"></script>
<script src="https://cdn.rawgit.com/mckamey/countdownjs/master/countdown.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript"></script>
<div>
  The time is now: <span class="now"></span>, a timer will go off <span class="duration"></span> at <span class="then"></span>
</div>
<div class="difference">The timer is set to go off <span></span></div>
<div class="countdown"></div>

The Javascript:

var now = moment(); // new Date().getTime();
var then = moment().add(60, 'seconds'); // new Date(now + 60 * 1000);

$(".now").text(moment(now).format('h:mm:ss a'));
$(".then").text(moment(then).format('h:mm:ss a'));
$(".duration").text(moment(now).to(then));
(function timerLoop() {
  $(".difference > span").text(moment().to(then));
  $(".countdown").text(countdown(then).toString());
  requestAnimationFrame(timerLoop);
})();

Output:

The time is now: 5:29:35 pm, a timer will go off in a minute at 5:30:35 pm
The timer is set to go off in a minute
1 minute

Note: 2nd line above updates as per momentjs and 3rd line above updates as per countdownjs and all of this is animated at about ~60FPS because of requestAnimationFrame()


Code Snippet:

Alternatively you can just look at this code snippet:

_x000D_
_x000D_
var now = moment(); // new Date().getTime();_x000D_
var then = moment().add(60, 'seconds'); // new Date(now + 60 * 1000);_x000D_
_x000D_
$(".now").text(moment(now).format('h:mm:ss a'));_x000D_
$(".then").text(moment(then).format('h:mm:ss a'));_x000D_
$(".duration").text(moment(now).to(then));_x000D_
(function timerLoop() {_x000D_
  $(".difference > span").text(moment().to(then));_x000D_
  $(".countdown").text(countdown(then).toString());_x000D_
  requestAnimationFrame(timerLoop);_x000D_
})();_x000D_
_x000D_
// CountdownJS: http://countdownjs.org/_x000D_
// Rawgit: http://rawgit.com/_x000D_
// MomentJS: http://momentjs.com/_x000D_
// jQuery: https://jquery.com/_x000D_
// Light reading about the requestAnimationFrame pattern:_x000D_
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/_x000D_
// https://css-tricks.com/using-requestanimationframe/
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js" type="text/javascript"></script>_x000D_
<script src="https://cdn.rawgit.com/mckamey/countdownjs/master/countdown.min.js" type="text/javascript"></script>_x000D_
<script src="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript"></script>_x000D_
<div>_x000D_
  The time is now: <span class="now"></span>,_x000D_
</div>_x000D_
<div>_x000D_
  a timer will go off <span class="duration"></span> at <span class="then"></span>_x000D_
</div>_x000D_
<div class="difference">The timer is set to go off <span></span></div>_x000D_
<div class="countdown"></div>
_x000D_
_x000D_
_x000D_

Requirements:

Optional Requirements:

Additionally here is some light reading about the requestAnimationFrame() pattern:

I found the requestAnimationFrame() pattern to be much a more elegant solution than the setInterval() pattern.

Font.createFont(..) set color and size (java.awt.Font)

To set the color of a font, you must first initialize the color by doing this:

Color maroon = new Color (128, 0, 0);

Once you've done that, you then put:

Font font = new Font ("Courier New", 1, 25); //Initializes the font
c.setColor (maroon); //Sets the color of the font
c.setFont (font); //Sets the font
c.drawString ("Your text here", locationX, locationY); //Outputs the string

Note: The 1 represents the type of font and this can be used to replace Font.PLAIN and the 25 represents the size of your font.

How to handle the click event in Listview in android?

ListView has the Item click listener callback. You should set the onItemClickListener in the ListView. Callback contains AdapterView and position as parameter. Which can give you the ListEntry.

lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
                Intent intent = new Intent(MainActivity.this, SendMessage.class);
                String message = entry.getMessage();
                intent.putExtra(EXTRA_MESSAGE, message);
                startActivity(intent);
            }
        });

Converting string into datetime

If you want only date format then you can manually convert it by passing your individual fields like:

>>> import datetime
>>> date = datetime.date(int('2017'),int('12'),int('21'))
>>> date
datetime.date(2017, 12, 21)
>>> type(date)
<type 'datetime.date'>

You can pass your split string values to convert it into date type like:

selected_month_rec = '2017-09-01'
date_formate = datetime.date(int(selected_month_rec.split('-')[0]),int(selected_month_rec.split('-')[1]),int(selected_month_rec.split('-')[2]))

You will get the resulting value in date format.

Adding a background image to a <div> element

Yes:

<div style="background-image: url(../images/image.gif); height: 400px; width: 400px;">Text here</div>

React Native version mismatch

I got this classing when TypeScript type definitions mismatched.

E.G react-native at 0.61.5 in dependencies and @types/react-native at 0.60.0 in devDependencies.

As soon as I updated devDependencies it worked. Didn't have to restart anything.

Moving from one activity to another Activity in Android

First you have to declare the activity in Manifest. It is important. You can add this inside application like this.

Given URL is not allowed by the Application configuration

For me it was the "Single Sign On" (can be seen at the bottome of the screenshot in phwd's answer) setting that was turned off.

How to save username and password with Mercurial?

While it may or may not work in your situation, I have found it useful to generate a public / private key using Putty's Pageant.

If you are also working with bitbucket (.org) it should give you the ability to provide a public key to your user account and then commands that reach out to the repository will be secured automatically.

If Pageant doesn't start up for you upon a reboot, you can add a shortcut to Pageant to your Windows "Start menu" and the shortcut may need to have a 'properties' populated with the location of your private (.ppk) file.

With this in place Mercurial and your local repositories will need to be set up to push/pull using the SSH format.

Here are some detailed instructions on Atlassian's site for Windows OR Mac/Linux.

You don't have to take my word for it and there are no doubt other ways to do it. Perhaps these steps described here are more for you:

  1. Start PuttyGen from Start -> PuTTY-> PuttyGen
  2. Generate a new key and save it as a .ppk file without a passphrase
  3. Use Putty to login to the server you want to connect to
  4. Append the Public Key text from PuttyGen to the text of ~/.ssh/authorized_keys
  5. Create a shortcut to your .ppk file from Start -> Putty to Start -> Startup
  6. Select the .ppk shortcut from the Startup menu (this will happen automatically at every startup)
  7. See the Pageant icon in the system tray? Right-click it and select “New session”
  8. Enter username@hostname in the “Host name” field
  9. You will now log in automatically.

Change name of folder when cloning from GitHub?

Here is one more answer from @Marged in comments

  1. Create a folder with the name you want
  2. Run the command below from the folder you created

    git clone <path to your online repo> .
    

How to handle floats and decimal separators with html5 input type number

My recommendation? Don't use jQuery at all. I had the same problem as you. I found that $('#my_input').val() always return some weird result.

Try to use document.getElementById('my_input').valueAsNumber instead of $("#my_input").val(); and then, use Number(your_value_retrieved) to try to create a Number. If the value is NaN, you know certainly that that's not a number.

One thing to add is when you write a number on the input, the input will actually accept almost any character (I can write the euro sign, a dollar, and all of other special characters), so it is best to retrieve the value using .valueAsNumber instead of using jQuery.

Oh, and BTW, that allows your users to add internationalization (i.e.: support commas instead of dots to create decimal numbers). Just let the Number() object to create something for you and it will be decimal-safe, so to speak.

First Heroku deploy failed `error code=H10`

I faced this same problem and none of the answers above helped me. What i did was run:

node --version

and in the package.json add the engines section with your node version:

{
  "name": "myapp",
  "description": "a really cool app",
  "version": "1.0.0",
  "engines": {
    "node": "6.11.1"
  }
}

How can I calculate the time between 2 Dates in typescript

It doesn't work because Date - Date relies on exactly the kind of type coercion TypeScript is designed to prevent.

There is a workaround this using the + prefix:

var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");

Or, if you prefer not to use Date.now():

var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));

See discussion here.

Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()

LINUX: Link all files from one to another directory

ln -s /mnt/usr/lib/* /usr/lib/

I guess, this belongs to superuser, though.

Mime type for WOFF fonts?

WOFF:

  1. Web Open Font Format
  2. It can be compiled with either TrueType or PostScript (CFF) outlines
  3. It is currently supported by FireFox 3.6+

Try to add that:

AddType application/vnd.ms-fontobject .eot
AddType application/octet-stream .otf .ttf

How to find which version of TensorFlow is installed in my system?

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

Here -c represents program passed in as string (terminates option list)

Update UI from Thread in Android

Use the AsyncTask class (instead of Runnable). It has a method called onProgressUpdate which can affect the UI (it's invoked in the UI thread).

How to return a dictionary | Python

What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:

def query(id):
    for line in file:
        table = {}
        (table["ID"],table["name"],table["city"]) = line.split(";")
        if id == int(table["ID"]):
             file.close()
             return table
    # ID not found; close file and return empty dict
    file.close()
    return {}

How do I update pip itself from inside my virtual environment?

I was in a similar situation and wanted to update urllib3 package. What worked for me was:

pip3 install --upgrade --force-reinstall --ignore-installed urllib3==1.25.3

How to export library to Jar in Android Studio?

I was able to build a library source code to compiled .jar file, using approach from this solution: https://stackoverflow.com/a/19037807/1002054

Here is the breakdown of what I did:

1. Checkout library repository

In may case it was a Volley library

2. Import library in Android Studio.

I used Android Studio 0.3.7. I've encountered some issues during that step, namely I had to copy gradle folder from new android project before I was able to import Volley library source code, this may vary depending on source code you use.

3. Modify your build.gradle file

// If your module is a library project, this is needed
//to properly recognize 'android-library' plugin
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.3'
    }
}

apply plugin: 'android-library'

android {
    compileSdkVersion 17
    buildToolsVersion = 17

    sourceSets {
        main  {
            // Here is the path to your source code
            java {
                srcDir 'src'
            }
        }
    }
}

// This is the actual solution, as in https://stackoverflow.com/a/19037807/1002054
task clearJar(type: Delete) {
    delete 'build/libs/myCompiledLibrary.jar'
}

task makeJar(type: Copy) {
    from('build/bundles/release/')
    into('build/libs/')
    include('classes.jar')
    rename ('classes.jar', 'myCompiledLibrary.jar')
}

makeJar.dependsOn(clearJar, build)

4. Run gradlew makeJar command from your project root.

I my case I had to copy gradlew.bat and gradle files from new android project into my library project root. You should find your compiled library file myCompiledLibrary.jar in build\libs directory.

I hope someone finds this useful.

Edit:

Caveat

Althought this works, you will encounter duplicate library exception while compiling a project with multiple modules, where more than one module (including application module) depends on the same jar file (eg. modules have own library directory, that is referenced in build.gradle of given module).

In case where you need to use single library in more then one module, I would recommend using this approach: Android gradle build and the support library

How to quickly test some javascript code?

Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.

Generating random numbers in Objective-C

According to the manual page for rand(3), the rand family of functions have been obsoleted by random(3). This is due to the fact that the lower 12 bits of rand() go through a cyclic pattern. To get a random number, just seed the generator by calling srandom() with an unsigned seed, and then call random(). So, the equivalent of the code above would be

#import <stdlib.h>
#import <time.h>

srandom(time(NULL));
random() % 74;

You'll only need to call srandom() once in your program unless you want to change your seed. Although you said you didn't want a discussion of truly random values, rand() is a pretty bad random number generator, and random() still suffers from modulo bias, as it will generate a number between 0 and RAND_MAX. So, e.g. if RAND_MAX is 3, and you want a random number between 0 and 2, you're twice as likely to get a 0 than a 1 or a 2.

How can I quickly sum all numbers in a file?

I have not tested this but it should work:

cat f | tr "\n" "+" | sed 's/+$/\n/' | bc

You might have to add "\n" to the string before bc (like via echo) if bc doesn't treat EOF and EOL...

fork() and wait() with two child processes

Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.

How to change owner of PostgreSql database?

ALTER DATABASE name OWNER TO new_owner;

See the Postgresql manual's entry on this for more details.

Get Substring - everything before certain char

Building on BrainCore's answer:

    int index = 0;   
    str = "223232-1.jpg";

    //Assuming we trust str isn't null 
    if (str.Contains('-') == "true")
    {
      int index = str.IndexOf('-');
    }

    if(index > 0) {
        return str.Substring(0, index);
    }
    else {
       return str;
    }

Spring Data JPA Update @Query not updating?

The underlying problem here is the 1st level cache of JPA. From the JPA spec Version 2.2 section 3.1. emphasise is mine:

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance.

This is important because JPA tracks changes to that entity in order to flush them to the database. As a side effect it also means within a single persistence context an entity gets only loaded once. This why reloading the changed entity doesn't have any effect.

You have a couple of options how to handle this:

  1. Evict the entity from the EntityManager. This may be done by calling EntityManager.detach, annotating the updating method with @Modifying(clearAutomatically = true) which evicts all entities. Make sure changes to these entities get flushed first or you might end up loosing changes.

  2. Use EntityManager.refresh().

  3. Use a different persistence context to load the entity. The easiest way to do this is to do it in a separate transaction. With Spring this can be done by having separate methods annotated with @Transactional on beans called from a bean not annotated with @Transactional. Another way is to use a TransactionTemplate which works especially nicely in tests where it makes transaction boundaries very visible.

How to get the selected item from ListView?

Though I am using kotlin, the following code answered your question. This return selected item:

val item = myListView.adapter.getItem(i).toString()

The following is the whole selecteditem Listener

myListView.setOnItemClickListener(object : OnItemClickListener {
       override fun onItemClick(parent: AdapterView<*>, view: View, i: Int,
                        id: Long) {
           val item = myListView.adapter.getItem(i).toString()

       }
    })

The code returns the item clicked by its index i as shown in the code

How to call a function, PostgreSQL

if your function does not want to return anything you should declare it to "return void" and then you can call it like this "perform functionName(parameter...);"

Add legend to ggplot2 line plot

I really like the solution proposed by @Brian Diggs. However, in my case, I create the line plots in a loop rather than giving them explicitly because I do not know apriori how many plots I will have. When I tried to adapt the @Brian's code I faced some problems with handling the colors correctly. Turned out I needed to modify the aesthetic functions. In case someone has the same problem, here is the code that worked for me.

I used the same data frame as @Brian:

data <- structure(list(month = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 
                                       1317798000, 1317884400, 1317970800, 1318057200, 
                                       1318143600, 1318230000, 1318316400, 1318402800, 
                                       1318489200, 1318575600, 1318662000, 1318748400, 
                                       1318834800, 1318921200, 1319007600, 1319094000), 
                                     class = c("POSIXct", "POSIXt"), tzone = ""),
                   TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71, 
                               25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18, 
                               25.19, 24.19, 27.65, 23.92), 
                   TempMed = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52,
                                 19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 
                                 20.45, 19.42, 19.97, 19.61), 
                   TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82, 
                               14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 16.95, 
                               17.55, 15.21, 14.22, 16.42)), 
              .Names = c("month", "TempMax", "TempMed", "TempMin"), 
              row.names = c(NA, 20L), class = "data.frame")  

In my case, I generate my.cols and my.names dynamically, but I don't want to make things unnecessarily complicated so I give them explicitly here. These three lines make the ordering of the legend and assigning colors easier.

my.cols <- heat.colors(3, alpha=1)
my.names <- c("TempMin", "TempMed", "TempMax")
names(my.cols) <- my.names

And here is the plot:

p <-  ggplot(data, aes(x = month))

for (i in 1:3){
  p <- p + geom_line(aes_(y = as.name(names(data[i+1])), colour = 
colnames(data[i+1])))#as.character(my.names[i])))
}
p + scale_colour_manual("", 
                        breaks = as.character(my.names),
                        values = my.cols)
p

enter image description here

How do I create a message box with "Yes", "No" choices and a DialogResult?

MessageBox.Show(title, text, messageboxbuttons.yes/no)

This returns a DialogResult which you can check.

For example,

if(MessageBox.Show("","",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
   //do something
}

Java getting the Enum name given the Enum Value

You should replace your getEnumNameForValue by a call to the name() method.

Display open transactions in MySQL

By using this query you can see all open transactions.

List All:

SHOW FULL PROCESSLIST  

if you want to kill a hang transaction copy transaction id and kill transaction by using this command:

KILL <id>    // e.g KILL 16543

Windows 8.1 gets Error 720 on connect VPN

This solved my 720 problem. The idea is to change the driver of the faulty WAN to another network adaptar driver, and then we are able to uninstall the WAN device and then reboot the system.

https://forums.lenovo.com/t5/Windows-8-and-8-1/SOLVED-WAN-Miniport-2-yellow-exclamation-mark-in-Device-Manager/td-p/1051981

Convert json data to a html table

I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.

Demo

_x000D_
_x000D_
var _table_ = document.createElement('table'),_x000D_
  _tr_ = document.createElement('tr'),_x000D_
  _th_ = document.createElement('th'),_x000D_
  _td_ = document.createElement('td');_x000D_
_x000D_
// Builds the HTML Table out of myList json data from Ivy restful service._x000D_
function buildHtmlTable(arr) {_x000D_
  var table = _table_.cloneNode(false),_x000D_
    columns = addAllColumnHeaders(arr, table);_x000D_
  for (var i = 0, maxi = arr.length; i < maxi; ++i) {_x000D_
    var tr = _tr_.cloneNode(false);_x000D_
    for (var j = 0, maxj = columns.length; j < maxj; ++j) {_x000D_
      var td = _td_.cloneNode(false);_x000D_
      cellValue = arr[i][columns[j]];_x000D_
      td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));_x000D_
      tr.appendChild(td);_x000D_
    }_x000D_
    table.appendChild(tr);_x000D_
  }_x000D_
  return table;_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records_x000D_
function addAllColumnHeaders(arr, table) {_x000D_
  var columnSet = [],_x000D_
    tr = _tr_.cloneNode(false);_x000D_
  for (var i = 0, l = arr.length; i < l; i++) {_x000D_
    for (var key in arr[i]) {_x000D_
      if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {_x000D_
        columnSet.push(key);_x000D_
        var th = _th_.cloneNode(false);_x000D_
        th.appendChild(document.createTextNode(key));_x000D_
        tr.appendChild(th);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  table.appendChild(tr);_x000D_
  return columnSet;_x000D_
}_x000D_
_x000D_
document.body.appendChild(buildHtmlTable([{_x000D_
    "name": "abc",_x000D_
    "age": 50_x000D_
  },_x000D_
  {_x000D_
    "age": "25",_x000D_
    "hobby": "swimming"_x000D_
  },_x000D_
  {_x000D_
    "name": "xyz",_x000D_
    "hobby": "programming"_x000D_
  }_x000D_
]));
_x000D_
_x000D_
_x000D_

Java heap terminology: young, old and permanent generations?

This seems like a common misunderstanding. In Oracle's JVM, the permanent generation is not part of the heap. It's a separate space for class definitions and related data. In Java 6 and earlier, interned strings were also stored in the permanent generation. In Java 7, interned strings are stored in the main object heap.

Here is a good post on permanent generation.

I like the descriptions given for each space in Oracle's guide on JConsole:

For the HotSpot Java VM, the memory pools for serial garbage collection are the following.

  • Eden Space (heap): The pool from which memory is initially allocated for most objects.
  • Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
  • Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
  • Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
  • Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.

Java uses generational garbage collection. This means that if you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces - Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough.

Understanding the main method of python

Python does not have a defined entry point like Java, C, C++, etc. Rather it simply executes a source file line-by-line. The if statement allows you to create a main function which will be executed if your file is loaded as the "Main" module rather than as a library in another module.

To be clear, this means that the Python interpreter starts at the first line of a file and executes it. Executing lines like class Foobar: and def foobar() creates either a class or a function and stores them in memory for later use.

How do I define global variables in CoffeeScript?

Ivo nailed it, but I'll mention that there is one dirty trick you can use, though I don't recommend it if you're going for style points: You can embed JavaScript code directly in your CoffeeScript by escaping it with backticks.

However, here's why this is usually a bad idea: The CoffeeScript compiler is unaware of those variables, which means they won't obey normal CoffeeScript scoping rules. So,

`foo = 'bar'`
foo = 'something else'

compiles to

foo = 'bar';
var foo = 'something else';

and now you've got yourself two foos in different scopes. There's no way to modify the global foo from CoffeeScript code without referencing the global object, as Ivy described.

Of course, this is only a problem if you make an assignment to foo in CoffeeScript—if foo became read-only after being given its initial value (i.e. it's a global constant), then the embedded JavaScript solution approach might be kinda sorta acceptable (though still not recommended).