SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

In my case it worked when I had opened SQL Server Management Studio with Administrator credentials and I right-clicked on the database and select "Go online" or something like this.

How to check cordova android version of a cordova/phonegap project?

The current platform version of a cordova app can be checked by the following command

cordova platform version android

And can be upgraded using the command

cordova platform update android

You can replace android by any of your platform choice like "ios" or some else.

This only applies to android platform. I have not checked. You can try replacing android in the code segments to try for other platforms.

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.

A new version of OSX or XCode was installed and Apple wants you to agree to their Terms and Conditions. So just launch Xcode and "Agree" to them.

How to create a global variable?

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

Could not open input file: artisan

What did the trick for me was to do cd src from my project directoy, and then use the php artisan command, since my artisan file was in the src folder. Here is my project structure:

project
|__ config
|__ src
    |__ app
    |__ ..
    |__ artisan  // hello there!
    |__ ...
|__ ...

How to use <md-icon> in Angular Material?

<md-button class="md-fab md-primary" md-theme="cyan" aria-label="Profile">
    <md-icon icon="/img/icons/ic_people_24px.svg" style="width: 24px; height: 24px;"></md-icon>
</md-button>

source: https://material.angularjs.org/#/demo/material.components.button

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

If this happens and you are using Let's Encrypt / certbot, the reason is most likely that you used chain.pem instead of fullchain.pem.

It should be something like this:

ssl_certificate /etc/certbot/live/example.com/fullchain.pem;
ssl_certificate_key /etc/certbot/live/example.com/privkey.pem;

See certbot docs “Where are my certificates?”

How to find length of dictionary values

To find all of the lengths of the values in a dictionary you can do this:

lengths = [len(v) for v in d.values()]

How to get current domain name in ASP.NET

HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use

HttpContext.Current.Request.Url.Port 

Excel - programm cells to change colour based on another cell

Use conditional formatting.

You can enter a condition using any cell you like and a format to apply if the formula is true.

How to call a method function from another class?

You need to understand the difference between classes and objects. From the Java tutorial:

An object is a software bundle of related state and behavior

A class is a blueprint or prototype from which objects are created

You've defined the prototypes but done nothing with them. To use an object, you need to create it. In Java, we use the new keyword.

new Date();

You will need to assign the object to a variable of the same type as the class the object was created from.

Date d = new Date();

Once you have a reference to the object you can interact with it

d.date("01", "12", "14");

The exception to this is static methods that belong to the class and are referenced through it

public class MyDate{
  public static date(){ ... }
}

...
MyDate.date();

In case you aren't aware, Java already has a class for representing dates, you probably don't want to create your own.

Can you delete data from influxdb?

Because InfluxDB is a bit painful about deletes, we use a schema that has a boolean field called "ForUse", which looks like this when posting via the line protocol (v0.9):

your_measurement,your_tag=foo ForUse=TRUE,value=123.5 1262304000000000000

You can overwrite the same measurement, tag key, and time with whatever field keys you send, so we do "deletes" by setting "ForUse" to false, and letting retention policy keep the database size under control.

Since the overwrite happens seamlessly, you can retroactively add the schema too. Noice.

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

You probably want to have a list of supported encodings. For each file, try each encoding in turn, maybe starting with UTF-8. Every time you catch the MalformedInputException, try the next encoding.

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

This is my error code:

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "The Microsoft Access database engine could not find the object 'ByStore$'. Make sure the object exists and that you spell its name and the path name correctly. If 'ByStore$' is not a local object, check your network connection or contact the server administrator.".

Msg 7350, Level 16, State 2, Procedure PeopleCounter_daily, Line 26

Cannot get the column information from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

My problem was the excel file was missing at the path. Just put the file with the correct sheet will do.

.ssh/config file for windows (git)

For me worked only adding the config or ssh_config file that was on the dir ~/.ssh/config on my Linux system on the c:\Program Files\Git\etc\ssh\ directory on Windows.

In some git versions we need to edit the C:\Users\<username>\AppData\Local\Programs\Git\etc\ssh\ssh_config file.

After that, I was able to use all the alias and settings that I normally used on my Linux connecting or pushing via SSH on the Git Bash.

how to use python2.7 pip instead of default pip

as noted here, this is what worked best for me:

sudo apt-get install python3 python3-pip python3-setuptools

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

How to count the NaN values in a column in pandas DataFrame

Lets assume df is a pandas DataFrame.

Then,

df.isnull().sum(axis = 0)

This will give number of NaN values in every column.

If you need, NaN values in every row,

df.isnull().sum(axis = 1)

Angular ng-if not true

Just use for True:

<li ng-if="area"></li>

and for False:

<li ng-if="area === false"></li>

How to merge a Series and DataFrame

If df is a pandas.DataFrame then df['new_col']= Series list_object of length len(df) will add the or Series list_object as a column named 'new_col'. df['new_col']= scalar (such as 5 or 6 in your case) also works and is equivalent to df['new_col']= [scalar]*len(df)

So a two-line code serves the purpose:

df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]})
s = pd.Series({'s1':5, 's2':6})
for x in s.index:    
    df[x] = s[x]

Output: 
   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

Convert object array to hash map, indexed by an attribute value of the Object

With lodash, this can be done using keyBy:

var arr = [
    { key: 'foo', val: 'bar' },
    { key: 'hello', val: 'world' }
];

var result = _.keyBy(arr, o => o.key);

console.log(result);
// Object {foo: Object, hello: Object}

How to detect if user select cancel InputBox VBA Excel

If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...

EDIT to properly differentiate between empty string and cancel, according to this answer.

Your example

Private Sub test()
    Dim result As String
    result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
    If StrPtr(result) = 0 Then
        MsgBox ("User canceled!")
    ElseIf result = vbNullString Then
        MsgBox ("User didn't enter anything!")
    Else
        MsgBox ("User entered " & result)
    End If
End Sub

Would tell the user they canceled when they delete the default string, or they click cancel.

See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

Warning about `$HTTP_RAW_POST_DATA` being deprecated

I just got the solution to this problem from a friend. he said: Add ob_start(); under your session code. You can add exit(); under the header. I tried it and it worked. Hope this helps

This is for those on a rented Hosting sever who do not have access to php.init file.

The view didn't return an HttpResponse object. It returned None instead

Because the view must return render, not just call it. Change the last line to

return render(request, 'auth_lifecycle/user_profile.html',
           context_instance=RequestContext(request))

Click events on Pie Charts in Chart.js

I have an elegant solution to this problem. If you have multiple dataset, identifying which dataset was clicked gets tricky. The _datasetIndex always returns zero. But this should do the trick. It will get you the label and the dataset label as well. Please note ** this.getElementAtEvent** is without the s in getElement

options: {
   onClick: function (e, items) {
    var firstPoint = this.getElementAtEvent(e)[0];
    if (firstPoint) {
      var label = firstPoint._model.label;
      var val = firstPoint._model.datasetLabel;
      console.log(label+" - "+val);
    }
    
  }
}

How to set ANDROID_HOME path in ubuntu?

Initially go to your home and press Ctrl + H it will show you hidden files now look for .bashrc file, open it with any text editor then place below lines at the end of file.

export ANDROID_HOME=/home/varun/Android/Sdk
export PATH=$PATH:/home/varun/Android/Sdk/tools
export PATH=$PATH:/home/varun/Android/Sdk/platform-tools

Please change /home/varun/Android/Sdk path to your SDK path. Do the same for tools and platform-tools.

After this save .bashrc file and close it.

Now you are ready to use ADB commands on terminal.

Manually install Gradle and use it in Android Studio

(There are 2 solutions mentioned in existing answers that might work, but the preferred one - manually download gradle for gradlew, is lack of essential details, and cause it fail. So, I would add a summary with missing details to save the unnecessary time wasted, in case others encounter into the same issue.)

There are 2 possible solutions:


Solution A: Use location gradle, and delete gradlew related files. (not recommend)

Refer to this answer from this post: https://stackoverflow.com/a/29198101/

Tips:

  • I tried, it works, though this is not suggested for gradle use in general.
  • And, with this solution, each time open project, android-studio will ask to confirm whether to use gradlew instead, it's kinda annoying.

Solution B: Download gradle distribution manually for gradlew. (recommended)

Android Studio will download gradle to sub dir named by a hash.
To download manually, need to download to the exact sub dir named by the hash.

Steps:

  • Get the hash.
    • Start android-studio.
    • Create a basic project.
    • Then it will create the hash, and start to download gradle.
      e.g .gradle/wrapper/dists/gradle-4.10.1-all/455itskqi2qtf0v2sja68alqd/
    • Close android-studio.
    • Find the download process, by android-studio.
      e.g ps -aux grep | android
    • Kill all the related android processes.
    • Remove the blank project.
  • Download gradle by hand.
  • Start Android Studio and try again.
    • Create a new blank project again.
    • Then it shouldn't need to download gradle again.
    • It will uncompress gradle in the the same dir.
      e.g .gradle/wrapper/dists/gradle-4.10.1-all/455itskqi2qtf0v2sja68alqd/gradle-4.10.1/
    • And starts to sync dependencies, indexing, and build.

Tips:

  • After restart Android Studio & creating blank project again, if you see it says waiting for other process to download the distribution.
    That means you didn't kill the previous download process, kill it first, then remove blank project, then create a new project to confirm again.
  • Each version of Android Studio might use different gradle version, thus might need to repeat this process once, when Android Studio is upgraded.

BTW:

  • Here is the dir layout on my Linux
    (For Android Studio 3.3.1, which use gradle 4.10.1)

    eric@eric-pc:~/.gradle/wrapper$ tree -L 4

    .
    +-- dists
        +-- gradle-4.10.1-all
            +-- 455itskqi2qtf0v2sja68alqd
                +-- gradle-4.10.1
                +-- gradle-4.10.1-all.zip
                +-- gradle-4.10.1-all.zip.lck
                +-- gradle-4.10.1-all.zip.ok
    
    

Suggestions to Android-Studio

  • Since it's so slow when download gradle distrbution within Android Studio.
    It's better to provide an option to choose local gradle installation dir or .zip file to be used by gradlew.

Correct modification of state arrays in React.js

The simplest way with ES6:

this.setState(prevState => ({
    array: [...prevState.array, newElement]
}))

Mac OS X and multiple Java versions

Uninstall jdk8, install jdk7, then reinstall jdk8.

My approach to switching between them (in .profile) :

export JAVA_7_HOME=$(/usr/libexec/java_home -v1.7)
export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_9_HOME=$(/usr/libexec/java_home -v9)

alias java7='export JAVA_HOME=$JAVA_7_HOME'
alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java9='export JAVA_HOME=$JAVA_9_HOME'

#default java8
export JAVA_HOME=$JAVA_8_HOME

Then you can simply type java7 or java8 in a terminal to switch versions.

(edit: updated to add Dylans improvement for Java 9)

Global constants file in Swift

Consider enumerations. These can be logically broken up for separate use cases.

enum UserDefaultsKeys: String {
    case SomeNotification = "aaaaNotification"
    case DeviceToken = "deviceToken"
}

enum PhotoMetaKeys: String {
    case Orientation = "orientation_hv"
    case Size = "size"
    case DateTaken = "date_taken"
}

One unique benefit happens when you have a situation of mutually exclusive options, such as:

for (key, value) in photoConfigurationFile {
    guard let key = PhotoMetaKeys(rawvalue: key) else {
        continue // invalid key, ignore it
    }
    switch (key) {
    case.Orientation: {
        photo.orientation = value
    }
    case.Size: {
        photo.size = value
    }
    }
}

In this example, you will receive a compile error because you have not handled the case of PhotoMetaKeys.DateTaken.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

My issue was that i had multiple versions of MS SQL express installed. I went to installation folder C:/ProgramFiles/MicrosoftSQL Server/ where i found 3 versions of it. I deleted 2 folders, and left only MSSQL13.SQLEXPRESS which solved the problem.

Wildcard string comparison in Javascript

if(mas[i].indexOf("bird") == 0)
    //there is bird

You.can read about indexOf here: http://www.w3schools.com/jsref/jsref_indexof.asp

How to create RecyclerView with multiple view type?

If you want to use it in conjunction with Android Data Binding look into the https://github.com/evant/binding-collection-adapter - it is by far the best solution for the multiple view types RecyclerView I have even seen.

you may use it like

var items: AsyncDiffPagedObservableList<BaseListItem> =
        AsyncDiffPagedObservableList(GenericDiff)

    val onItemBind: OnItemBind<BaseListItem> =
        OnItemBind { itemBinding, _, item -> itemBinding.set(BR.item, item.layoutRes) }

and then in the layout where list is

 <androidx.recyclerview.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                app:enableAnimations="@{false}"
                app:scrollToPosition="@{viewModel.scrollPosition}"

                app:itemBinding="@{viewModel.onItemBind}"
                app:items="@{viewModel.items}"

                app:reverseLayoutManager="@{true}"/>

your list items must implement BaseListItem interface that looks like this

interface BaseListItem {
    val layoutRes: Int
}

and item view should look something like this

<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
                name="item"
                type="...presentation.somescreen.list.YourListItem"/>
    </data>

   ...

</layout>

Where YourListItem implements BaseListItem

Hope it will help someone.

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

Another solution is to migrate the database to e.g 2012 when you "export" the DB from e.g. Sql Server manager 2014. This is done in menu Tasks-> generate scripts when right-click on DB. Just follow this instruction:

https://www.mssqltips.com/sqlservertip/2810/how-to-migrate-a-sql-server-database-to-a-lower-version/

It generates an scripts with everything and then in your SQL server manager e.g. 2012 run the script as specified in the instruction. I have performed the test with success.

scp files from local to remote machine error: no such file or directory

i had a kind of similar problem. i tried to copy from a server to my desktop and always got the same message for the local path. the problem was, i already was logged in to my server per ssh, so it was searching for the local path in the server path.

solution: i had to log out and run the command again and it worked

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

Try restarting the mysql or starting it if it wasn't started already. Type this within terminal.

mysql.server restart

To auto start go to the following link below:

How to auto-load MySQL on startup on OS X Yosemite / El Capitan

How to get JSON object from Razor Model object in javascript

In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().

It should be as simple as:

<script>
  var json = @Json.Serialize(Model.CollegeInformationlist);
</script>

How can I backup a Docker-container with its data-volumes?

The following command will run tar in a container with all named data volumes mounted, and redirect the output into a file:

docker run --rm `docker volume list -q | egrep -v '^.{64}$' | awk '{print "-v " $1 ":/mnt/" $1}'` alpine tar -C /mnt -cj . > data-volumes.tar.bz2

Make sure to test the resulting archive in case something went wrong:

tar -tjf data-volumes.tar.bz2

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

Error C1083: Cannot open include file: 'stdafx.h'

Add #include "afxwin.h" in your source file. It will solve your issue.

Changing text of UIButton programmatically swift

In Swift 3, 4, 5:

button.setTitle("Button Title", for: .normal)

Otherwise:

button.setTitle("Button Title", forState: UIControlState.Normal)

Also an @IBOutlet has to declared for the button.

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

For my case link did NOT work as follow

ln -s /usr/bin/nodejs /usr/bin/node

But you can open /usr/local/bin/lessc as root, and change the first line from node to nodejs.

-#!/usr/bin/env node

+#!/usr/bin/env nodejs

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

I am late for this but i want put some more solution relevant to this.

 @GetMapping
public ResponseEntity<List<JSONObject>> getRole() {
    return ResponseEntity.ok(service.getRole());
}

Installing NumPy via Anaconda in Windows

Anaconda folder basically resides in C:\Users\\Anaconda. Try setting the PATH to this folder.

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

How to add hamburger menu in bootstrap

All you have to do is read the code on getbootstrap.com:

Codepen

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">_x000D_
  <div class="container">_x000D_
    <div class="navbar-header">_x000D_
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
    </div>_x000D_
_x000D_
    <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
      <ul class="nav navbar-nav">_x000D_
        <li><a href="index.php">Home</a></li>_x000D_
        <li><a href="about.php">About</a></li>_x000D_
        <li><a href="#portfolio">Portfolio</a></li>_x000D_
        <li><a href="#">Blog</a></li>_x000D_
        <li><a href="contact.php">Contact</a></li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Maven error :Perhaps you are running on a JRE rather than a JDK?

This is how i fixed my problem

right clik on the project > properties > Java Compiler (select the one you are using)

it was 1.5 for me but i have 1.8 installed. so i changed it to 1.8.. and voilla it worked!.

OperationalError, no such column. Django

I simple made a careless mistake of forgetting to actually apply the migration (migrate) after making migrations. Writing this just in case anyone might make the same mistake.

Appending a list or series to a pandas DataFrame as a row?

The simplest way:

my_list = [1,2,3,4,5]
df['new_column'] = pd.Series(my_list).values

Edit:

Don't forget that the length of the new list should be the same of the corresponding Dataframe.

Spring Boot, Spring Data JPA with multiple DataSources

thanks to the answers of Steve Park and Rafal Borowiec I got my code working, however, I had one issue: the DriverManagerDataSource is a "simple" implementation and does NOT give you a ConnectionPool (check http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/DriverManagerDataSource.html).

Hence, I replaced the functions which returns the DataSource for the secondDB to.

public DataSource <secondaryDB>DataSource() {
    // use DataSourceBuilder and NOT DriverManagerDataSource 
    // as this would NOT give you ConnectionPool
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.url(databaseUrl);
    dataSourceBuilder.username(username);
    dataSourceBuilder.password(password);
    dataSourceBuilder.driverClassName(driverClassName);
    return dataSourceBuilder.build();
}

Also, if do you not need the EntityManager as such, you can remove both the entityManager() and the @Bean annotation.

Plus, you may want to remove the basePackages annotation of your configuration class: maintaining it with the factoryBean.setPackagesToScan() call is sufficient.

Swift apply .uppercaseString to only the first letter of a string

For first character in word use .capitalized in swift and for whole-word use .uppercased()

resize2fs: Bad magic number in super-block while trying to open

In Centos 7 default filesystem is xfs.

xfs file system support only extend not reduce. So if you want to resize the filesystem use xfs_growfs rather than resize2fs.

xfs_growfs /dev/root_vg/root 

Note: For ext4 filesystem use

resize2fs /dev/root_vg/root

There is already an object named in the database

Make sure your solutions startup project has the correct connectionstring in the config file. Or set the -StartUpProjectName parameter when executing the update-database command. The -StartUpProjectName parameter specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.

Here is a link for ef-migration command references http://coding.abel.nu/2012/03/ef-migrations-command-reference/

Duplicate Symbols for Architecture arm64

to solve this problem go to Build phases and search about duplicate file like (facebookSDK , unityads ) and delete (extension file.o) then build again .

How to change option menu icon in the action bar?

This works properly in my case:

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),
                                              R.drawable.change_pass);
toolbar.setOverflowIcon(drawable);

Timestamp with a millisecond precision: How to save them in MySQL

You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3). If you get an error, you don't have the right version.

For example, DATETIME(3) will give you millisecond resolution in your timestamps, and TIMESTAMP(6) will give you microsecond resolution on a *nix-style timestamp.

Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html

NOW(3) will give you the present time from your MySQL server's operating system with millisecond precision.

If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value

FROM_UNIXTIME(ms * 0.001)

Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.

(Notice that MySQL internal fractional arithmetic, like * 0.001, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)

If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.

If, for some reason you can't upgrade, you could consider using BIGINT or DOUBLE columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001) will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000

How to parseInt in Angular.js

Inside template this working finely.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
<input ng-model="name" value="0">
<p>My first expression: {{ (name-0) + 5 }}</p>
</div>

</body>
</html>

Find all table names with column name?

You could do this:

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;

Reference:

Specify path to node_modules in package.json

In short: It is not possible, and as it seems won't ever be supported (see here https://github.com/npm/npm/issues/775).

There are some hacky work-arrounds with using the CLI or ENV-Variables (see the current selected answer), .npmrc-Config-Files or npm link - what they all have in common: They are never just project-specific, but always some kind of global Solutions.

For me, none of those solutions are really clean because contributors to your project always need to create some special configuration or have some special knowledge - they can't just npm install and it works.

So: Either you will have to put your package.json in the same directory where you want your node_modules installed, or live with the fact that they will always be in the root-dir of your project.

check if array is empty (vba excel)

I would do this as

if isnumeric(ubound(a)) = False then msgbox "a is empty!"

How to modify WooCommerce cart, checkout pages (main theme portion)

You can use function: wc_get_page_id( 'cart' ) to get the ID of the page. This function will use the page setup as 'cart' page and not the slug. Meaning it will keep working also when you setup a different url for your 'cart' on the settings page. This works for all kind of Woocommerce special page, like 'checkout', 'shop' etc.

example:

if (wc_get_page_id( 'cart' ) == get_the_ID()) {
  // Do something.
}

Access images inside public folder in laravel

In my case it worked perfectly

<img style="border-radius: 50%;height: 50px;width: 80px;"  src="<?php echo asset("storage/TeacherImages/{$teacher->profilePic}")?>">

this is used to display image from folder i hope this will help someone looking for this type of code

Subtracting time.Duration from time in Go

Try AddDate:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    then := now.AddDate(0, -1, 0)

    fmt.Println("then:", then)
}

Produces:

now: 2009-11-10 23:00:00 +0000 UTC
then: 2009-10-10 23:00:00 +0000 UTC

Playground: http://play.golang.org/p/QChq02kisT

Implementing Singleton with an Enum (in Java)

This,

public enum MySingleton {
  INSTANCE;   
}

has an implicit empty constructor. Make it explicit instead,

public enum MySingleton {
    INSTANCE;
    private MySingleton() {
        System.out.println("Here");
    }
}

If you then added another class with a main() method like

public static void main(String[] args) {
    System.out.println(MySingleton.INSTANCE);
}

You would see

Here
INSTANCE

enum fields are compile time constants, but they are instances of their enum type. And, they're constructed when the enum type is referenced for the first time.

CakePHP 3.0 installation: intl extension missing from system

I faced the same problem today. You need to enable the intl PHP extension in your PHP configuration (.ini).

Solution Xampp (Windows)

  1. Open /xampp/php/php.ini
  2. Change ;extension=php_intl.dll to extension=php_intl.dll (remove the semicolon)
  3. Copy all the /xampp/php/ic*.dll files to /xampp/apache/bin
  4. Restart apache in the Xampp control panel

Solution Linux (thanks to Annamalai Somasundaram)

  1. Install the php5-intl extension sudo apt-get install php5-intl

    1.1. Alternatively use sudo yum install php5-intl if you are on CentOS or Fedora.

  2. Restart apache sudo service apache2 restart

Solution Mac/OSX (homebrew) (thanks to deizel)

  1. Install the php5-intl extension brew install php56-intl
  2. If you get No available formula for php56-intl follow these instructions.
  3. Restart apache sudo apachectl restart

Eventually you can run composer install to check if it's working. It will give an error if it's not.

C++ Loop through Map

Try the following

for ( const auto &p : table )
{
   std::cout << p.first << '\t' << p.second << std::endl;
} 

The same can be written using an ordinary for loop

for ( auto it = table.begin(); it != table.end(); ++it  )
{
   std::cout << it->first << '\t' << it->second << std::endl;
} 

Take into account that value_type for std::map is defined the following way

typedef pair<const Key, T> value_type

Thus in my example p is a const reference to the value_type where Key is std::string and T is int

Also it would be better if the function would be declared as

void output( const map<string, int> &table );

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

With:

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.7</version>
        </plugin>

Was getting the following exception:

...
Caused by: org.apache.maven.plugin.MojoExecutionException: Mark invalid
    at org.apache.maven.plugin.resources.ResourcesMojo.execute(ResourcesMojo.java:306)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:132)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    ... 25 more
Caused by: org.apache.maven.shared.filtering.MavenFilteringException: Mark invalid
    at org.apache.maven.shared.filtering.DefaultMavenFileFilter.copyFile(DefaultMavenFileFilter.java:129)
    at org.apache.maven.shared.filtering.DefaultMavenResourcesFiltering.filterResources(DefaultMavenResourcesFiltering.java:264)
    at org.apache.maven.plugin.resources.ResourcesMojo.execute(ResourcesMojo.java:300)
    ... 27 more
Caused by: java.io.IOException: Mark invalid
    at java.io.BufferedReader.reset(BufferedReader.java:505)
    at org.apache.maven.shared.filtering.MultiDelimiterInterpolatorFilterReaderLineEnding.read(MultiDelimiterInterpolatorFilterReaderLineEnding.java:416)
    at org.apache.maven.shared.filtering.MultiDelimiterInterpolatorFilterReaderLineEnding.read(MultiDelimiterInterpolatorFilterReaderLineEnding.java:205)
    at java.io.Reader.read(Reader.java:140)
    at org.apache.maven.shared.utils.io.IOUtil.copy(IOUtil.java:181)
    at org.apache.maven.shared.utils.io.IOUtil.copy(IOUtil.java:168)
    at org.apache.maven.shared.utils.io.FileUtils.copyFile(FileUtils.java:1856)
    at org.apache.maven.shared.utils.io.FileUtils.copyFile(FileUtils.java:1804)
    at org.apache.maven.shared.filtering.DefaultMavenFileFilter.copyFile(DefaultMavenFileFilter.java:114)
    ... 29 more



Then it is gone after adding maven-filtering 1.3:

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.7</version>
          <dependencies>
            <dependency>
                <groupId>org.apache.maven.shared</groupId>
                <artifactId>maven-filtering</artifactId>
                <version>1.3</version>
            </dependency>
          </dependencies>
        </plugin>

How to include js and CSS in JSP with spring MVC

you need declare resources in dispatcher servelet file.below is two declarations

<mvc:annotation-driven />
<mvc:resources location="/resources/" mapping="/resources/**" />

Putting -moz-available and -webkit-fill-available in one width (css property)

I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:

width: 100%

I had to add the CSS class into the asp:DropDownList element

Unable to open debugger port in IntelliJ IDEA

  1. Check "Run" configuration to see which port it is using (8081).
  2. Find all the other processes using that port lsof -t -i :8081
  3. Kill the processes on that port. kill PROCESS_ID
  4. Run Tomcat in Debug mode.

In my case, I wasted so much time on changing debugger port but it was not the issue. Since tomcat was not able to run on the port I chose in Run configuration, I was not able to debug my service.

React Error: Target Container is not a DOM Element

Also, the best practice of moving your <script></script> to the bottom of the html file fixes this too.

Normalize columns of pandas data frame

I think that a better way to do that in pandas is just

df = df/df.max().astype(np.float64)

Edit If in your data frame negative numbers are present you should use instead

df = df/df.loc[df.abs().idxmax()].astype(np.float64)

Which versions of SSL/TLS does System.Net.WebRequest support?

This is an important question. The SSL 3 protocol (1996) is irreparably broken by the Poodle attack published 2014. The IETF have published "SSLv3 MUST NOT be used". Web browsers are ditching it. Mozilla Firefox and Google Chrome have already done so.

Two excellent tools for checking protocol support in browsers are SSL Lab's client test and https://www.howsmyssl.com/ . The latter does not require Javascript, so you can try it from .NET's HttpClient:

// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");

File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);

// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");

The result is damning:

Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.

That's concerning. It's comparable to 2006's Internet Explorer 7.

To list exactly which protocols a HTTP client supports, you can try the version-specific test servers below:

var test_servers = new Dictionary<string, string>();
test_servers["SSL 2"] = "https://www.ssllabs.com:10200";
test_servers["SSL 3"] = "https://www.ssllabs.com:10300";
test_servers["TLS 1.0"] = "https://www.ssllabs.com:10301";
test_servers["TLS 1.1"] = "https://www.ssllabs.com:10302";
test_servers["TLS 1.2"] = "https://www.ssllabs.com:10303";

var supported = new Func<string, bool>(url =>
{
    try { return new HttpClient().GetAsync(url).Result.IsSuccessStatusCode; }
    catch { return false; }
});

var supported_protocols = test_servers.Where(server => supported(server.Value));
Console.WriteLine(string.Join(", ", supported_protocols.Select(x => x.Key)));

I'm using .NET Framework 4.6.2. I found HttpClient supports only SSL 3 and TLS 1.0. That's concerning. This is comparable to 2006's Internet Explorer 7.


Update: It turns HttpClient does support TLS 1.1 and 1.2, but you have to turn them on manually at System.Net.ServicePointManager.SecurityProtocol. See https://stackoverflow.com/a/26392698/284795

I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?

Angularjs - Pass argument to directive

Here is how I solved my problem:

Directive

app.directive("directive_name", function(){
    return {
        restrict: 'E',
        transclude: true,
        template: function(elem, attr){
           return '<div><h2>{{'+attr.scope+'}}</h2></div>';
        },
        replace: true
    };
})

Controller

$scope.building = function(data){
    var chart = angular.element(document.createElement('directive_name'));
    chart.attr('scope', data);
    $compile(chart)($scope);
    angular.element(document.getElementById('wrapper')).append(chart);
  }

I now can use different scopes through the same directive and append them dynamically.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

Per the developers, this error is not an actual failure, but rather "misleading error reports". This bug is fixed in version 40, which is available on the canary and dev channels as of 25 Oct.

Patch

How do I correctly setup and teardown for my pytest class with tests?

According to Fixture finalization / executing teardown code, the current best practice for setup and teardown is to use yield instead of return:

import pytest

@pytest.fixture()
def resource():
    print("setup")
    yield "resource"
    print("teardown")

class TestResource:
    def test_that_depends_on_resource(self, resource):
        print("testing {}".format(resource))

Running it results in

$ py.test --capture=no pytest_yield.py
=== test session starts ===
platform darwin -- Python 2.7.10, pytest-3.0.2, py-1.4.31, pluggy-0.3.1
collected 1 items

pytest_yield.py setup
testing resource
.teardown


=== 1 passed in 0.01 seconds ===

Another way to write teardown code is by accepting a request-context object into your fixture function and calling its request.addfinalizer method with a function that performs the teardown one or multiple times:

import pytest

@pytest.fixture()
def resource(request):
    print("setup")

    def teardown():
        print("teardown")
    request.addfinalizer(teardown)
    
    return "resource"

class TestResource:
    def test_that_depends_on_resource(self, resource):
        print("testing {}".format(resource))

Where does mysql store data?

I just installed MySQL Server 5.7 on Windows 10 and my.ini file is located here c:\ProgramData\MySQL\MySQL Server 5.7\my.ini.

The Data folder (where your dbs are created) is here C:/ProgramData/MySQL/MySQL Server 5.7\Data.

How to listen state changes in react.js?

Using useState with useEffect as described above is absolutely correct way. But if getSearchResults function returns subscription then useEffect should return a function which will be responsible for unsubscribing the subscription . Returned function from useEffect will run before each change to dependency(name in above case) and on component destroy

NameError: uninitialized constant (rails)

I started having this issue after upgrading from Rails 5.1 to 5.2
It got solved with:

spring stop
spring binstub --all
spring start
rails s

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Importing images from a directory (Python) to list or dictionary

from PIL import Image
import os, os.path

imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
    ext = os.path.splitext(f)[1]
    if ext.lower() not in valid_images:
        continue
    imgs.append(Image.open(os.path.join(path,f)))
   

Using momentjs to convert date to epoch then back to date

http://momentjs.com/docs/#/displaying/unix-timestamp/

You get the number of unix seconds, not milliseconds!

You you need to multiply it with 1000 or using valueOf() and don't forget to use a formatter, since you are using a non ISO 8601 format. And if you forget to pass the formatter, the date will be parsed in the UTC timezone or as an invalid date.

moment("10/15/2014 9:00", "MM/DD/YYYY HH:mm").valueOf()

How to convert entire dataframe to numeric while preserving decimals?

Using dplyr (a bit like sapply..)

df2 <- mutate_all(df1, function(x) as.numeric(as.character(x)))

which gives:

glimpse(df2)
Observations: 4
Variables: 2
$ a <dbl> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

from your df1 which was:

glimpse(df1)
Observations: 4
Variables: 2
$ a <fctr> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

I had to cast the integer equivalent to get around the fact that I'm still using .NET 4.0

System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
/* Note the property type  
   [System.Flags]
   public enum SecurityProtocolType
   {
     Ssl3 = 48,
     Tls = 192,
     Tls11 = 768,
     Tls12 = 3072,
   } 
*/

How to trap on UIViewAlertForUnsatisfiableConstraints?

You'll want to add a Symbolic Breakpoint. Apple provides an excellent guide on how to do this.

  1. Open the Breakpoint Navigator cmd+7 (cmd+8 in Xcode 9)
  2. Click the Add button in the lower left
  3. Select Add Symbolic Breakpoint...
  4. Where it says Symbol just type in UIViewAlertForUnsatisfiableConstraints

You can also treat it like any other breakpoint, turning it on and off, adding actions, or log messages.

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

Array from dictionary keys in swift

extension Array {
    public func toDictionary<Key: Hashable>(with selectKey: (Element) -> Key) -> [Key:Element] {
        var dict = [Key:Element]()
        for element in self {
            dict[selectKey(element)] = element
        }
        return dict
    }
}

How to get the azure account tenant Id?

Use the Azure CLI

az account get-access-token --query tenant --output tsv

Padding zeros to the left in postgreSQL

The to_char() function is there to format numbers:

select to_char(column_1, 'fm000') as column_2
from some_table;

The fm prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000 simply defines the number of digits you want to have.

psql (9.3.5)
Type "help" for help.

postgres=> with sample_numbers (nr) as (
postgres(>     values (1),(11),(100)
postgres(> )
postgres-> select to_char(nr, 'fm000')
postgres-> from sample_numbers;
 to_char
---------
 001
 011
 100
(3 rows)

postgres=>

For more details on the format picture, please see the manual:
http://www.postgresql.org/docs/current/static/functions-formatting.html

How to know the version of pip itself

Start Python and type import pip pip.__version__ which works for all python packages.

Why does git say "Pull is not possible because you have unmerged files"?

Theres a simple solution to it. But for that you will first need to learn the following

vimdiff

To remove conficts, you can use

git mergetool

The above command basically opens local file, mixed file, remote file (3 files in total), for each conflicted file. The local & remote files are just for your reference, and using them you can choose what to include (or not) in the mixed file. And just save and quit the file.

Laravel PHP Command Not Found

When using MacBook, refer to the snippets below;

For zsh:

echo 'export PATH="$HOME/.composer/vendor/bin:$PATH"' >>  ~/.zshrc
source ~/.zshrc

For Bash:

echo 'export PATH="$HOME/.composer/vendor/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

If two cells match, return value from third

=IF(ISNA(INDEX(B:B,MATCH(C2,A:A,0))),"",INDEX(B:B,MATCH(C2,A:A,0)))

Will return the answer you want and also remove the #N/A result that would appear if you couldn't find a result due to it not appearing in your lookup list.

Ross

background: fixed no repeat not working on mobile

I'm late to the party, but this is (unbelievably) still a problem as of the 11.05.2017. Here is a simple solution which will also work cross-platform with linear gradients:

_x000D_
_x000D_
.backgroundFixed {_x000D_
  background: linear-gradient(160deg, #2db4a8 0%, #13af3d 100%);_x000D_
  background-size: 100vw 100vh;_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 100vh;_x000D_
  width: 100vw;_x000D_
  z-index: -1000;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <meta charset="UTF-8">_x000D_
    <title>title</title>_x000D_
  </head>_x000D_
  <body>_x000D_
    <div class="backgroundFixed"></div>_x000D_
    <div class="paragraphContainer">_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
      <p>We're here to make the body scroll</p>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

Appending to list in Python dictionary

dates_dict[key] = dates_dict.get(key, []).append(date) sets dates_dict[key] to None as list.append returns None.

In [5]: l = [1,2,3]

In [6]: var = l.append(3)

In [7]: print var
None

You should use collections.defaultdict

import collections
dates_dict = collections.defaultdict(list)

HTTP Request in Swift with POST method

let session = URLSession.shared
        let url = "http://...."
        let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        var params :[String: Any]?
        params = ["Some_ID" : "111", "REQUEST" : "SOME_API_NAME"]
        do{
            request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions())
            let task = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
                if let response = response {
                    let nsHTTPResponse = response as! HTTPURLResponse
                    let statusCode = nsHTTPResponse.statusCode
                    print ("status code = \(statusCode)")
                }
                if let error = error {
                    print ("\(error)")
                }
                if let data = data {
                    do{
                        let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
                        print ("data = \(jsonResponse)")
                    }catch _ {
                        print ("OOps not good JSON formatted response")
                    }
                }
            })
            task.resume()
        }catch _ {
            print ("Oops something happened buddy")
        }

Convert timestamp to string

try this

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string  = dateFormat.format(new Date());
System.out.println(string);

you can create any format see this

How to work on UAC when installing XAMPP

You can press OK and install xampp to C:\xampp and not into program files