Programs & Examples On #Localtime

How to Convert UTC Date To Local time Zone in MySql Select Query

In my case, where the timezones are not available on the server, this works great:

SELECT CONVERT_TZ(`date_field`,'+00:00',@@global.time_zone) FROM `table`

Note: global.time_zone uses the server timezone. You have to make sure, that it has the desired timezone!

Get the current time in C

If you just need the time without the date.

  time_t rawtime;
  struct tm * timeinfo;
  time( &rawtime );
  timeinfo = localtime( &rawtime );
  printf("%02d:%02d:%02d", timeinfo->tm_hour, timeinfo->tm_min, 
    timeinfo->tm_sec);

How to convert java.sql.timestamp to LocalDate (java8) java.time?

I'll slightly expand @assylias answer to take time zone into account. There are at least two ways to get LocalDateTime for specific time zone.

You can use setDefault time zone for whole application. It should be called before any timestamp -> java.time conversion:

public static void main(String... args) {
    TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    TimeZone.setDefault(utcTimeZone);
    ...
    timestamp.toLocalDateTime().toLocalDate();
}

Or you can use toInstant.atZone chain:

timestamp.toInstant()
        .atZone(ZoneId.of("UTC"))
        .toLocalDate();

Convert UTC datetime string to local datetime

Here is a quick and dirty version that uses the local systems settings to work out the time difference. NOTE: This will not work if you need to convert to a timezone that your current system is not running in. I have tested this with UK settings under BST timezone

from datetime import datetime
def ConvertP4DateTimeToLocal(timestampValue):
   assert isinstance(timestampValue, int)

   # get the UTC time from the timestamp integer value.
   d = datetime.utcfromtimestamp( timestampValue )

   # calculate time difference from utcnow and the local system time reported by OS
   offset = datetime.now() - datetime.utcnow()

   # Add offset to UTC time and return it
   return d + offset

How to convert local time string to UTC?

Here's a summary of common Python time conversions.

Some methods drop fractions of seconds, and are marked with (s). An explicit formula such as ts = (d - epoch) / unit can be used instead (thanks jfs).

  • struct_time (UTC) ? POSIX (s):
    calendar.timegm(struct_time)
  • Naïve datetime (local) ? POSIX (s):
    calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
    (exception during DST transitions, see comment from jfs)
  • Naïve datetime (UTC) ? POSIX (s):
    calendar.timegm(dt.utctimetuple())
  • Aware datetime ? POSIX (s):
    calendar.timegm(dt.utctimetuple())
  • POSIX ? struct_time (UTC, s):
    time.gmtime(t)
    (see comment from jfs)
  • Naïve datetime (local) ? struct_time (UTC, s):
    stz.localize(dt, is_dst=None).utctimetuple()
    (exception during DST transitions, see comment from jfs)
  • Naïve datetime (UTC) ? struct_time (UTC, s):
    dt.utctimetuple()
  • Aware datetime ? struct_time (UTC, s):
    dt.utctimetuple()
  • POSIX ? Naïve datetime (local):
    datetime.fromtimestamp(t, None)
    (may fail in certain conditions, see comment from jfs below)
  • struct_time (UTC) ? Naïve datetime (local, s):
    datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
    (can't represent leap seconds, see comment from jfs)
  • Naïve datetime (UTC) ? Naïve datetime (local):
    dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
  • Aware datetime ? Naïve datetime (local):
    dt.astimezone(tz).replace(tzinfo=None)
  • POSIX ? Naïve datetime (UTC):
    datetime.utcfromtimestamp(t)
  • struct_time (UTC) ? Naïve datetime (UTC, s):
    datetime.datetime(*struct_time[:6])
    (can't represent leap seconds, see comment from jfs)
  • Naïve datetime (local) ? Naïve datetime (UTC):
    stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
    (exception during DST transitions, see comment from jfs)
  • Aware datetime ? Naïve datetime (UTC):
    dt.astimezone(UTC).replace(tzinfo=None)
  • POSIX ? Aware datetime:
    datetime.fromtimestamp(t, tz)
    (may fail for non-pytz timezones)
  • struct_time (UTC) ? Aware datetime (s):
    datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)
    (can't represent leap seconds, see comment from jfs)
  • Naïve datetime (local) ? Aware datetime:
    stz.localize(dt, is_dst=None)
    (exception during DST transitions, see comment from jfs)
  • Naïve datetime (UTC) ? Aware datetime:
    dt.replace(tzinfo=UTC)

Source: taaviburns.ca

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

In my case, it was Subversion, TortoiseSVN clinging to those files, so I just clicked on SVN in the Eclipse menu and then disconnect. Worked for me.

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

You could try this registry hack:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
"DeadGWDetectDefault"=dword:00000001
"KeepAliveTime"=dword:00120000

If it works, just keep increasing the KeepAliveTime. It is currently set for 2 minutes.

Angular redirect to login page

Here's an updated example using Angular 4 (also compatible with Angular 5 - 8)

Routes with home route protected by AuthGuard

import { Routes, RouterModule } from '@angular/router';

import { LoginComponent } from './login/index';
import { HomeComponent } from './home/index';
import { AuthGuard } from './_guards/index';

const appRoutes: Routes = [
    { path: 'login', component: LoginComponent },

    // home route protected by auth guard
    { path: '', component: HomeComponent, canActivate: [AuthGuard] },

    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

export const routing = RouterModule.forRoot(appRoutes);

AuthGuard redirects to login page if user isn't logged in

Updated to pass original url in query params to login page

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

For the full example and working demo you can check out this post

Format an Excel column (or cell) as Text in C#?

I've recently battled with this problem as well, and I've learned two things about the above suggestions.

  1. Setting the numberFormatting to @ causes Excel to left-align the value, and read it as if it were text, however, it still truncates the leading zero.
  2. Adding an apostrophe at the beginning results in Excel treating it as text and retains the zero, and then applies the default text format, solving both problems.

The misleading aspect of this is that you now have a different value in the cell. Fortuately, when you copy/paste or export to CSV, the apostrophe is not included.

Conclusion: use the apostrophe, not the numberFormatting in order to retain the leading zeros.

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

If you have the milliseconds since the Epoch and want to convert them to a local date using the current local timezone, you can use

LocalDate date =
    Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate();

but keep in mind that even the system’s default time zone may change, thus the same long value may produce different result in subsequent runs, even on the same machine.

Further, keep in mind that LocalDate, unlike java.util.Date, really represents a date, not a date and time.

Otherwise, you may use a LocalDateTime:

LocalDateTime date =
    LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());

How do I check how many options there are in a dropdown menu?

var length = $('#mySelectList').children('option').length;

or

var length = $('#mySelectList > option').length;

This assumes your <select> list has an ID of mySelectList.

Why does this AttributeError in python occur?

AttributeError is raised when attribute of the object is not available.

An attribute reference is a primary followed by a period and a name:

attributeref ::= primary "." identifier

To return a list of valid attributes for that object, use dir(), e.g.:

dir(scipy)

So probably you need to do simply: import scipy.sparse

How to add multiple classes to a ReactJS Component?


Generally people do like

<div className={  ['head', style.class1 , Style.class2].join(' ')  }><div>

But you can choose to Create a function to do this job

function joinAll(...classes) {
  return classes.join(" ")
}

then call it like:-

<div className={joinAll('head', style.class1 , style.class2)}><div>

Get the client IP address using PHP

The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables.

However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.

The below both functions are equivalent with the difference only in how and from where the values are retrieved.

getenv() is used to get the value of an environment variable in PHP.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

$_SERVER is an array that contains server variables created by the web server.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

Use Ant for running program with command line arguments

The only effective mechanism for passing parameters into a build is to use Java properties:

ant -Done=1 -Dtwo=2

The following example demonstrates how you can check and ensure the expected parameters have been passed into the script

<project name="check" default="build">

    <condition property="params.set">
        <and>
            <isset property="one"/>
            <isset property="two"/>
        </and>
    </condition>

    <target name="check">
        <fail unless="params.set">
        Must specify the parameters: one, two
        </fail>
    </target>

    <target name="build" depends="check">
        <echo>
        one = ${one}
        two = ${two}
        </echo>
    </target>

</project>

Getting and removing the first character of a string

substring is definitely best, but here's one strsplit alternative, since I haven't seen one yet.

> x <- 'hello stackoverflow'
> strsplit(x, '')[[1]][1]
## [1] "h"

or equivalently

> unlist(strsplit(x, ''))[1]
## [1] "h"

And you can paste the rest of the string back together.

> paste0(strsplit(x, '')[[1]][-1], collapse = '')
## [1] "ello stackoverflow"

How to use PDO to fetch results array in PHP?

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

Results:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

Angular 6 Material mat-select change method removed

The changed it from change to selectionChange.

<mat-select (change)="doSomething($event)">

is now

<mat-select (selectionChange)="doSomething($event)">

https://material.angular.io/components/select/api

shorthand c++ if else statement

try this:

bigInt.sign = number < 0 ? 0 : 1

Maven: mvn command not found

I followed this tutorial: How to install Maven on Windows

But running mvn -version, I still got:

mvn: command not found

So, I closed the current git window, and opened a new one. Everything went okay :)

Regex for checking if a string is strictly alphanumeric

See the documentation of Pattern.

Assuming US-ASCII alphabet (a-z, A-Z), you could use \p{Alnum}.

A regex to check that a line contains only such characters is "^[\\p{Alnum}]*$".

That also matches empty string. To exclude empty string: "^[\\p{Alnum}]+$".

Is try-catch like error handling possible in ASP Classic?

For anytone who has worked in ASP as well as more modern languages, the question will provoke a chuckle. In my experience using a custom error handler (set up in IIS to handle the 500;100 errors) is the best option for ASP error handling. This article describes the approach and even gives you some sample code / database table definition.

http://www.15seconds.com/issue/020821.htm

Here is a link to Archive.org's version

How do I get an OAuth 2.0 authentication token in C#

I used ADAL.NET/ Microsoft Identity Platform to achieve this. The advantage of using it was that we get a nice wrapper around the code to acquire AccessToken and we get additional features like Token Cache out-of-the-box. From the documentation:

Why use ADAL.NET ?

ADAL.NET V3 (Active Directory Authentication Library for .NET) enables developers of .NET applications to acquire tokens in order to call secured Web APIs. These Web APIs can be the Microsoft Graph, or 3rd party Web APIs.

Here is the code snippet:

    // Import Nuget package: Microsoft.Identity.Client
    public class AuthenticationService
    {
         private readonly List<string> _scopes;
         private readonly IConfidentialClientApplication _app;

        public AuthenticationService(AuthenticationConfiguration authentication)
        {

             _app = ConfidentialClientApplicationBuilder
                         .Create(authentication.ClientId)
                         .WithClientSecret(authentication.ClientSecret)
                         .WithAuthority(authentication.Authority)
                         .Build();

           _scopes = new List<string> {$"{authentication.Audience}/.default"};
       }

       public async Task<string> GetAccessToken()
       {
           var authenticationResult = await _app.AcquireTokenForClient(_scopes) 
                                                .ExecuteAsync();
           return authenticationResult.AccessToken;
       }
   }

Getting Java version at runtime

These articles seem to suggest that checking for 1.5 or 1.6 prefix should work, as it follows proper version naming convention.

Sun Technical Articles

Where Sticky Notes are saved in Windows 10 1607

It worked for me when HDD with win8.1 crashed and my new HDD has win10. Important to know - Create Legacy folder mentioned in this link. - Remember to rename the StickyNotes.snt to ThresholdNotes.snt. - Restart the app

Find details here https://www.reddit.com/r/Windows10/comments/4wxfds/transfermigrate_sticky_notes_to_new_anniversary/

Converting Decimal to Binary Java

Well, you can use while loop, like this,

import java.util.Scanner;

public class DecimalToBinaryExample
{
    public static void main(String[] args)
    {
        int num;
        int a = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a decimal number : ");
        num = sc.nextInt();
        int binary[] = new int[100];

        while(num != 0)
        {
            binary[a] = num % 2;
            num = num / 2;
            a++;
        }

        System.out.println("The binary value is : ");
        for(int b = a - 1; b >= 0; b--)
        {
            System.out.println("" + binary[b]);
        }
        sc.close();
    }
}

You can refer example below for some good explanation,

convert decimal to binary example.

Finding out the name of the original repository you cloned from in Git

git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'

It was tested with three different URL styles:

echo "Fetch URL: http://user@pass:gitservice.org:20080/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: Fetch URL: [email protected]:home1-oss/oss-build.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'
echo "Fetch URL: https://github.com/owner/repo.git" | ruby -ne 'puts /^\s*Fetch.*(:|\/){1}([^\/]+\/[^\/]+).git/.match($_)[2] rescue nil'

What's the difference between %s and %d in Python string formatting?

%d and %s are placeholders, they work as a replaceable variable. For example, if you create 2 variables

variable_one = "Stackoverflow"
variable_two = 45

you can assign those variables to a sentence in a string using a tuple of the variables.

variable_3 = "I was searching for an answer in %s and found more than %d answers to my question"

Note that %s works for String and %d work for numerical or decimal variables.

if you print variable_3 it would look like this

print(variable_3 % (variable_one, variable_two))

I was searching for an answer in StackOverflow and found more than 45 answers to my question.

Resolve absolute path from relative path and/or file name

In batch files, as in standard C programs, argument 0 contains the path to the currently executing script. You can use %~dp0 to get only the path portion of the 0th argument (which is the current script) - this path is always a fully qualified path.

You can also get the fully qualified path of your first argument by using %~f1, but this gives a path according to the current working directory, which is obviously not what you want.

Personally, I often use the %~dp0%~1 idiom in my batch file, which interpret the first argument relative to the path of the executing batch. It does have a shortcoming though: it miserably fails if the first argument is fully-qualified.

If you need to support both relative and absolute paths, you can make use of Frédéric Ménez's solution: temporarily change the current working directory.

Here's an example that'll demonstrate each of these techniques:

@echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"

rem Temporarily change the current working directory, to retrieve a full path 
rem   to the first parameter
pushd .
cd %~dp0
echo batch-relative %%~f1 is "%~f1"
popd

If you save this as c:\temp\example.bat and the run it from c:\Users\Public as

c:\Users\Public>\temp\example.bat ..\windows

...you'll observe the following output:

%~dp0 is "C:\temp\"
%0 is "\temp\example.bat"
%~dpnx0 is "C:\temp\example.bat"
%~f1 is "C:\Users\windows"
%~dp0%~1 is "C:\temp\..\windows"
batch-relative %~f1 is "C:\Windows"

the documentation for the set of modifiers allowed on a batch argument can be found here: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/call

How do I vertically center text with CSS?

You can try this basic approach:

_x000D_
_x000D_
div {_x000D_
  height: 100px;_x000D_
  line-height: 100px;_x000D_
  text-align: center;_x000D_
  border: 2px dashed #f69c55;_x000D_
}
_x000D_
<div>_x000D_
  Hello World!_x000D_
</div>
_x000D_
_x000D_
_x000D_

It only works for a single line of text though, because we set the line's height to the same height as the containing box element.


A more versatile approach

This is another way to align text vertically. This solution will work for a single line and multiple lines of text, but it still requires a fixed height container:

_x000D_
_x000D_
div {_x000D_
  height: 100px;_x000D_
  line-height: 100px;_x000D_
  text-align: center;_x000D_
  border: 2px dashed #f69c55;_x000D_
}_x000D_
span {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
  line-height: normal;_x000D_
}
_x000D_
<div>_x000D_
  <span>Hello World!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The CSS just sizes the <div>, vertically center aligns the <span> by setting the <div>'s line-height equal to its height, and makes the <span> an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the <span>, so its contents will flow naturally inside the block.


Simulating table display

And here is another option, which may not work on older browsers that don't support display: table and display: table-cell (basically just Internet Explorer 7). Using CSS we simulate table behavior (since tables support vertical alignment), and the HTML is the same as the second example:

_x000D_
_x000D_
div {_x000D_
  display: table;_x000D_
  height: 100px;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
  border: 2px dashed #f69c55;_x000D_
}_x000D_
span {_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<div>_x000D_
  <span>Hello World!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Using absolute positioning

This technique uses an absolutely positioned element setting top, bottom, left and right to 0. It is described in more detail in an article in Smashing Magazine, Absolute Horizontal And Vertical Centering In CSS.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  height: 100px;_x000D_
  width: 100%;_x000D_
  border: 2px dashed #f69c55;_x000D_
}
_x000D_
<div>_x000D_
  <span>Hello World!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to parse a CSV in a Bash script?

Using awk:

export INDEX=2
export VALUE=bar

awk -F, '$'$INDEX' ~ /^'$VALUE'$/ {print}' inputfile.csv

Edit: As per Dennis Williamson's excellent comment, this could be much more cleanly (and safely) written by defining awk variables using the -v switch:

awk -F, -v index=$INDEX -v value=$VALUE '$index == value {print}' inputfile.csv

Jeez...with variables, and everything, awk is almost a real programming language...

json.dumps vs flask.jsonify

The choice of one or another depends on what you intend to do. From what I do understand:

  • jsonify would be useful when you are building an API someone would query and expect json in return. E.g: The REST github API could use this method to answer your request.

  • dumps, is more about formating data/python object into json and work on it inside your application. For instance, I need to pass an object to my representation layer where some javascript will display graph. You'll feed javascript with the Json generated by dumps.

Difference between readFile() and readFileSync()

readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish. let's take an example for non-blocking.

following method read a file as a non-blocking way

var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        console.log(data);
});

following is read a file as blocking or synchronous way.

var data = fs.readFileSync(filename);

LOL...If you don't want readFileSync() as blocking way then take reference from the following code. (Native)

var fs = require('fs');
function readFileAsSync(){
    new Promise((resolve, reject)=>{
        fs.readFile(filename, "utf8", function(err, data) {
                if (err) throw err;
                resolve(data);
        });
    });
}

async function callRead(){
    let data = await readFileAsSync();
    console.log(data);
}

callRead();

it's mean behind scenes readFileSync() work same as above(promise) base.

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

What you could do is have the selected attribute on the <select> tag be an attribute of this.state that you set in the constructor. That way, the initial value you set (the default) and when the dropdown changes you need to change your state.

constructor(){
  this.state = {
    selectedId: selectedOptionId
  }
}

dropdownChanged(e){
  this.setState({selectedId: e.target.value});
}

render(){
  return(
    <select value={this.selectedId} onChange={this.dropdownChanged.bind(this)}>
      {option_id.map(id =>
        <option key={id} value={id}>{options[id].name}</option>
      )}
    </select>
  );
}

Enterprise app deployment doesn't work on iOS 7.1

I can confirm it works, But You have to put html AND plist on dropbox. It works also for non-enterprise OTA, i.e. You want to share app with your dev. team.

I did:

a) on my site I made a page with this link:

.. href="https://dl.dropboxusercontent.com/u//(your DB id)/ipa.html">MyApp

b) on DropBox I wrote another HTML page:

.. https://dl.dropboxusercontent.com/u/(your DB id)/MyApp.plist"> Tap to Install MyApp

c) moved plist on DropBox but leaving it to POINT to my old server (no https)

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

try this

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/upkia"/>
<corners android:radius="10dp"
    android:topRightRadius="0dp"
    android:bottomRightRadius="0dp" />
</shape>

Bootstrap 4 File Input

Bootstrap 4

More details are here https://learncodeweb.com/snippets/browse-button-in-bootstrap-4-with-select-image-preview/

Today I need to create a browse button with multi-upload files option all above snippets are not good for me.

The official Bootstrap example is also not working when I select multiple files.

I come up with this code may be will help others in the future.

<div class="container mt-5">
  <h1 class="text-center">Bootstrap 4 Upload multiple files</h1>
  <div class="col-sm-4 mr-auto ml-auto border p-4">
  <form method="post" enctype="multipart/form-data" action="upload.php">
    <div class="form-group">
      <label><strong>Upload Files</strong></label>
      <div class="custom-file">
        <input type="file" name="files[]" multiple class="custom-file-input form-control" id="customFile">
        <label class="custom-file-label" for="customFile">Choose file</label>
      </div>
    </div>
    <div class="form-group">
      <button type="submit" name="upload" value="upload" id="upload" class="btn btn-block btn-dark"><i class="fa fa-fw fa-upload"></i> Upload</button>
    </div>
  </form>
</div>

The js code is given below.

$(document).ready(function() {
  $('input[type="file"]').on("change", function() {
    let filenames = [];
    let files = document.getElementById("customFile").files;
    if (files.length > 1) {
      filenames.push("Total Files (" + files.length + ")");
    } else {
      for (let i in files) {
        if (files.hasOwnProperty(i)) {
          filenames.push(files[i].name);
        }
      }
    }
    $(this)
      .next(".custom-file-label")
      .html(filenames.join(","));
  });
});

The working code example is given here with bootstrap 3 and bootstrap 4.3.1.

https://codepen.io/mianzaid/pen/GeEbYV

raw_input function in Python

It presents a prompt to the user (the optional arg of raw_input([arg])), gets input from the user and returns the data input by the user in a string. See the docs for raw_input().

Example:

name = raw_input("What is your name? ")
print "Hello, %s." % name

This differs from input() in that the latter tries to interpret the input given by the user; it is usually best to avoid input() and to stick with raw_input() and custom parsing/conversion code.

Note: This is for Python 2.x

Can I do a max(count(*)) in SQL?

Just order by count(*) desc and you'll get the highest (if you combine it with limit 1)

Websocket onerror - how to read error description?

The error Event the onerror handler receives is a simple event not containing such information:

If the user agent was required to fail the WebSocket connection or the WebSocket connection is closed with prejudice, fire a simple event named error at the WebSocket object.

You may have better luck listening for the close event, which is a CloseEvent and indeed has a CloseEvent.code property containing a numerical code according to RFC 6455 11.7 and a CloseEvent.reason string property.

Please note however, that CloseEvent.code (and CloseEvent.reason) are limited in such a way that network probing and other security issues are avoided.

Vuex - Computed property "name" was assigned to but it has no setter

For me it was changing.

this.name = response.data;

To what computed returns so;

this.$store.state.name = response.data;

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

How do I decrease the size of my sql server log file?

You have to shrink & backup the log a several times to get the log file to reduce in size, this is because the the log file pages cannot be re-organized as data files pages can be, only truncated. For a more detailed explanation check this out.

WARNING : Detaching the db & deleting the log file is dangerous! don't do this unless you'd like data loss

How to check if iframe is loaded or it has a content?

Try this.

<script>
function checkIframeLoaded() {
    // Get a handle to the iframe element
    var iframe = document.getElementById('i_frame');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if loading is complete
    if (  iframeDoc.readyState  == 'complete' ) {
        //iframe.contentWindow.alert("Hello");
        iframe.contentWindow.onload = function(){
            alert("I am loaded");
        };
        // The loading is complete, call the function we want executed once the iframe is loaded
        afterLoading();
        return;
    } 

    // If we are here, it is not loaded. Set things up so we check   the status again in 100 milliseconds
    window.setTimeout(checkIframeLoaded, 100);
}

function afterLoading(){
    alert("I am here");
}
</script>

<body onload="checkIframeLoaded();"> 

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

in "String.xml" you can notice any String or value you want to use, here are two examples:

<string name="app_name">My Calculator App
    </string>
<color name="color_menu_home">#ffcccccc</color>

Used for the layout.xml: android:text="@string/app_name"

The advantage: you can use them as often you want, you only need to link them in your Layout-xml, and you can change the String-Content easily in the strings.xml, without searching in your source-code for the right position. Important for changing language, you only need to replace the strings.xml - file

How to get the device's IMEI/ESN programmatically in android?

to get IMEI (international mobile equipment identifier)

public String getIMEI(Activity activity) {
    TelephonyManager telephonyManager = (TelephonyManager) activity
            .getSystemService(Context.TELEPHONY_SERVICE);
    return telephonyManager.getDeviceId();
}

to get device unique id

public String getDeviceUniqueID(Activity activity){
    String device_unique_id = Secure.getString(activity.getContentResolver(),
            Secure.ANDROID_ID);
    return device_unique_id;
}

Find duplicates and delete all in notepad++

You need the textFX plugin. Then, just follow these instructions:

Paste the text into Notepad++ (CTRL+V). ...
Mark all the text (CTRL+A). ...
Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column)
Duplicates and blank lines have been removed and the data has been sorted alphabetically.

Personally, I would use sort -i -u source >dest instead of notepad++

C Linking Error: undefined reference to 'main'

You should provide output file name after -o option. In your case runexp.o is treated as output file name, not input object file and thus your main function is undefined.

Jquery- Get the value of first td in table

$(".hit").click(function(){
   var values = [];
   var table = $(this).closest("table");
   table.find("tr").each(function() {
      values.push($(this).find("td:first").html());
   });

   alert(values);    
});

You should avoid $(".hit") it's really inefficient. Try using event delegation instead.

Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install

My 2 cents on this error, even if not related to an export/import scenario:

when adding the mobile provisioning certificate (i.e. the PROV file), DO NOT drag the file from Finder to Keychain Access. Instead, just double click the PROV file within Finder, while keeping the Keychain Access application running somewhere.

I've actually seen my former provisioning item in Keychain (the one with yellow light) being substituted with a new, green one with same name and app ID. HTH

hibernate could not get next sequence value

I would also like to add a few notes about a MySQL-to-PostgreSQL migration:

  1. In your DDL, in the object naming prefer the use of '_' (underscore) character for word separation to the camel case convention. The latter works fine in MySQL but brings a lot of issues in PostgreSQL.
  2. The IDENTITY strategy for @GeneratedValue annotation in your model class-identity fields works fine for PostgreSQLDialect in hibernate 3.2 and superior. Also, The AUTO strategy is the typical setting for MySQLDialect.
  3. If you annotate your model classes with @Table and set a literal value to these equal to the table name, make sure you did create the tables to be stored under public schema.

That's as far as I remember now, hope these tips can spare you a few minutes of trial and error fiddling!

case statement in where clause - SQL Server

simply do the select:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))

Getting the array length of a 2D array in Java

.length = number of rows / column length

[0].length = number of columns / row length

How to debug when Kubernetes nodes are in 'Not Ready' state

I found applying the network and rebooting both the nodes did the trick for me.

kubectl apply -f [podnetwork].yaml

ImportError: No module named google.protobuf

Had the same issue and I resolved it by using :

conda install protobuf

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

Ok, I faced the problem before. Since push notification requires serverside implementation, for me recreating profile was not an option. So I found this solution WITHOUT creating new provisioning profile.

Xcode is not properly selecting the correct provisioning profile although we are selecting it correctly.

First go to organizer. On the Devices tab, Provisioning profile from Library list, select the intended profile we are trying to use. Right click on it and then "Reveal Profile in Finder".

enter image description here

The correct profile will be selected in the opened Finder window. Note the name.

enter image description here

Now go to Xcode > Log Navigator. Select filter for "All" and "All Messages". Now in the last phase(Build Target) look for the step called "ProcessProductPackaging" expand it. Note the provisioning profile name. They should NOT match if you are having the error. enter image description here

Now in the Opened Finder window delete the rogue provisioning profile which Xcode is using. Now build again. The error should be resolved. If not repeat the process to find another rogue profile to remove it.

Hope this helps.

How to change maven logging level to display only warning and errors?

If you are using Logback, just put this logback-test.xml file into src/test/resources directory:

<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>
<root level="INFO">
    <appender-ref ref="STDOUT" />
</root>
</configuration>

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

One more way:

CREATE OR REPLACE TYPE TYPE_TABLE_OF_VARCHAR2 AS TABLE OF VARCHAR(100);
-- ...
SELECT field1, field2, field3
  FROM table1
  WHERE name IN (
    SELECT * FROM table (SELECT CAST(? AS TYPE_TABLE_OF_VARCHAR2) FROM dual)
  );

I don't consider it's optimal, but it works. The hint /*+ CARDINALITY(...) */ would be very useful because Oracle does not understand cardinality of the array passed and can't estimate optimal execution plan.

As another alternative - batch insert into temporary table and using the last in subquery for IN predicate.

pass **kwargs argument to another function with **kwargs

The ** syntax tells Python to collect keyword arguments into a dictionary. The save2 is passing it down as a non-keyword argument (a dictionary object). The openX is not seeing any keyword arguments so the **args doesn't get used. It's instead getting a third non-keyword argument (the dictionary). To fix that change the definition of the openX function.

def openX(filename, mode, kwargs):
    pass

Pycharm does not show plot

In non-interactive env, we have to use plt.show(block=True)

Ruby on Rails - Import Data from a CSV file

The smarter_csv gem was specifically created for this use-case: to read data from CSV file and quickly create database entries.

  require 'smarter_csv'
  options = {}
  SmarterCSV.process('input_file.csv', options) do |chunk|
    chunk.each do |data_hash|
      Moulding.create!( data_hash )
    end
  end

You can use the option chunk_size to read N csv-rows at a time, and then use Resque in the inner loop to generate jobs which will create the new records, rather than creating them right away - this way you can spread the load of generating entries to multiple workers.

See also: https://github.com/tilo/smarter_csv

Difference between setUp() and setUpBeforeClass()

Think of "BeforeClass" as a static initializer for your test case - use it for initializing static data - things that do not change across your test cases. You definitely want to be careful about static resources that are not thread safe.

Finally, use the "AfterClass" annotated method to clean up any setup you did in the "BeforeClass" annotated method (unless their self destruction is good enough).

"Before" & "After" are for unit test specific initialization. I typically use these methods to initialize / re-initialize the mocks of my dependencies. Obviously, this initialization is not specific to a unit test, but general to all unit tests.

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

JavaScript for handling Tab Key press

Use TAB & TAB+SHIFT in a Specified container or element

Source

we will handle TAB & TAB+SHIFT key listeners first

        $(document).ready(function() {
            lastIndex = 0;
            $(document).keydown(function(e) {
                if (e.keyCode == 9) var thisTab = $(":focus").attr("tabindex");
                if (e.keyCode == 9) {
                    if (e.shiftKey) {
                        //Focus previous input
                        if (thisTab == startIndex) {
                            $("." + tabLimitInID).find('[tabindex=' + lastIndex + ']').focus();
                            return false;
                        }
                    } else {
                        if (thisTab == lastIndex) {
                            $("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
                            return false;
                        }
                    }
                }
            });
            var setTabindexLimit = function(x, fancyID) {
                console.log(x);
                startIndex = 1;
                lastIndex = x;
                tabLimitInID = fancyID;
                $("." + tabLimitInID).find('[tabindex=' + startIndex + ']').focus();
            }
            /*Taking last tabindex=10 */
            setTabindexLimit(10, "limitTablJolly");
        });

In HTML define tabindex

        <div class="limitTablJolly">
            <a tabindex=1>link</a>    
             <a tabindex=2>link</a>    
             <a tabindex=3>link</a>    
             <a tabindex=4>link</a>    
             <a tabindex=5>link</a>    
             <a tabindex=6>link</a>    
             <a tabindex=7>link</a>    
             <a tabindex=8>link</a>    
             <a tabindex=9>link</a>    
             <a tabindex=10>link</a>   
        </div>

Where is `%p` useful with printf?

x is Unsigned hexadecimal integer ( 32 Bit )

p is Pointer address

See printf on the C++ Reference. Even if both of them would write the same, I would use %p to print a pointer.

How do I get the directory from a file's full path?

 string path= @"C:\Users\username\Desktop\FolderName"
  string Dirctory = new FileInfo(path).Name.ToString();
//output FolderName

ngrok command not found

On Windows 10, for me

ngrok http 80

behaves like this:

  • works from Command Prompt (cmd.exe)
  • does not work from Git Bash
  • does not work from Windows PowerShell

How to access a value defined in the application.properties file in Spring Boot

Currently, I know about the following three ways:

1. The @Value annotation

    @Value("${<property.name>}")
    private static final <datatype> PROPERTY_NAME;
  • In my experience there are some situations when you are not able to get the value or it is set to null. For instance, when you try to set it in a preConstruct() method or an init() method. This happens because the value injection happens after the class is fully constructed. This is why it is better to use the 3'rd option.

2. The @PropertySource annotation

<pre>@PropertySource("classpath:application.properties")

//env is an Environment variable
env.getProperty(configKey);</pre>
  • PropertySouce sets values from the property source file in an Environment variable (in your class) when the class is loaded. So you able to fetch easily afterword.
    • Accessible through System Environment variable.

3. The @ConfigurationProperties annotation.

  • This is mostly used in Spring projects to load configuration properties.
  • It initializes an entity based on property data.

    • @ConfigurationProperties identifies the property file to load.
    • @Configuration creates a bean based on configuration file variables.
    @ConfigurationProperties(prefix = "user")
    @Configuration("UserData")
    class user {
      //Property & their getter / setter
    }
    
    @Autowired
    private UserData userData;
    
    userData.getPropertyName();

How to loop and render elements in React.js without an array of objects to map?

Array.from() takes an iterable object to convert to an array and an optional map function. You could create an object with a .length property as follows:

return Array.from({length: this.props.level}, (item, index) => 
  <span className="indent" key={index}></span>
);

How to set Angular 4 background image?

this one is working for me also for internet explorer:

<div class="col imagebox" [ngStyle]="bkUrl"></div>

...

@Input() background = '571x450img';  
bkUrl = {};   
ngOnInit() {
    this.bkUrl = this.getBkUrl();
  }
getBkUrl() {
    const styles = {
      'background-image': 'url(src/assets/images/' + this.background + '.jpg)'
    };
    console.log(styles);
    return styles;
  }

What is the purpose of the vshost.exe file?

The vshost.exe feature was introduced with Visual Studio 2005 (to answer your comment).

The purpose of it is mostly to make debugging launch quicker - basically there's already a process with the framework running, just ready to load your application as soon as you want it to.

See this MSDN article and this blog post for more information.

How can I add an ampersand for a value in a ASP.net/C# app config file value

Have you tried this?

<appSettings>  
  <add key="myurl" value="http://www.myurl.com?&amp;cid=&amp;sid="/>
<appSettings>

How to window.scrollTo() with a smooth effect

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
  top: 400,_x000D_
  behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
  height: 1000px;_x000D_
  background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
  <button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Older solutions

You can do something like this:

_x000D_
_x000D_
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
  var i = 10;_x000D_
  var int = setInterval(function() {_x000D_
    window.scrollTo(0, i);_x000D_
    i += 10;_x000D_
    if (i >= 200) clearInterval(int);_x000D_
  }, 20);_x000D_
})
_x000D_
body {_x000D_
  background: #3a2613;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
_x000D_
_x000D_

ES6 recursive approach:

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
  let i = h || 0;_x000D_
  if (i < 200) {_x000D_
    setTimeout(() => {_x000D_
      window.scrollTo(0, i);_x000D_
      smoothScroll(i + 10);_x000D_
    }, 10);_x000D_
  }_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
  background: #9a6432;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
_x000D_
_x000D_

Detect encoding and make everything UTF-8

This version is for German language but you can modifiy the $CHARSETS and the $TESTCHARS

class CharsetDetector
{
private static $CHARSETS = array(
"ISO_8859-1",
"ISO_8859-15",
"CP850"
);
private static $TESTCHARS = array(
"€",
"ä",
"Ä",
"ö",
"Ö",
"ü",
"Ü",
"ß"
);
public static function convert($string)
{
    return self::__iconv($string, self::getCharset($string));
}
public static function getCharset($string)
{
    $normalized = self::__normalize($string);
    if(!strlen($normalized))return "UTF-8";
    $best = "UTF-8";
    $charcountbest = 0;
    foreach (self::$CHARSETS as $charset) {
        $str = self::__iconv($normalized, $charset);
        $charcount = 0;
        $stop   = mb_strlen( $str, "UTF-8");

        for( $idx = 0; $idx < $stop; $idx++)
        {
            $char = mb_substr( $str, $idx, 1, "UTF-8");
            foreach (self::$TESTCHARS as $testchar) {

                if($char == $testchar)
                {

                    $charcount++;
                    break;
                }
            }
        }
        if($charcount>$charcountbest)
        {
            $charcountbest=$charcount;
            $best=$charset;
        }
        //echo $text."<br />";
    }
    return $best;
}
private static function __normalize($str)
{

$len = strlen($str);
$ret = "";
for($i = 0; $i < $len; $i++){
    $c = ord($str[$i]);
    if ($c > 128) {
        if (($c > 247)) $ret .=$str[$i];
        elseif ($c > 239) $bytes = 4;
        elseif ($c > 223) $bytes = 3;
        elseif ($c > 191) $bytes = 2;
        else $ret .=$str[$i];
        if (($i + $bytes) > $len) $ret .=$str[$i];
        $ret2=$str[$i];
        while ($bytes > 1) {
            $i++;
            $b = ord($str[$i]);
            if ($b < 128 || $b > 191) {$ret .=$ret2; $ret2=""; $i+=$bytes-1;$bytes=1; break;}
            else $ret2.=$str[$i];
            $bytes--;
        }
    }
}
return $ret; 
}
private static function __iconv($string, $charset)
{
    return iconv ( $charset, "UTF-8" , $string );
}
}

How to replace url parameter with javascript/jquery?

If you look closely you'll see two surprising things about URLs: (1) they seem simple, but the details and corner cases are actually hard, (2) Amazingly JavaScript doesn't provide a full API for making working with them any easier. I think a full-fledged library is in order to avoid people re-inventing the wheel themselves or copying some random dude's clever, but likely buggy regex code snippet. Maybe try URI.js (http://medialize.github.io/URI.js/)

What's the effect of adding 'return false' to a click event listener?

The return false is saying not to take the default action, which in the case of an <a href> is to follow the link. When you return false to the onclick, then the href will be ignored.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

you can use indexing if your enumerable type is string like below

((string[])MyEnumerableStringList)[0]

find without recursion

I think you'll get what you want with the -maxdepth 1 option, based on your current command structure. If not, you can try looking at the man page for find.

Relevant entry (for convenience's sake):

-maxdepth levels
          Descend at most levels (a non-negative integer) levels of direc-
          tories below the command line arguments.   `-maxdepth  0'  means
          only  apply the tests and actions to the command line arguments.

Your options basically are:

# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f

Or:

#  DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f

Can Mockito capture arguments of a method called multiple times?

I think it should be

verify(mockBar, times(2)).doSomething(...)

Sample from mockito javadoc:

ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
verify(mock, times(2)).doSomething(peopleCaptor.capture());

List<Person> capturedPeople = peopleCaptor.getAllValues();
assertEquals("John", capturedPeople.get(0).getName());
assertEquals("Jane", capturedPeople.get(1).getName());

What USB driver should we use for the Nexus 5?

My Nexus 5 is identyfied by the id = USB\VID_18D1&PID_D001.

Use the Google USB drivers, and modify file android_winusb.inf. Find the lines:

;Google Nexus (generic)
%SingleBootLoaderInterface% = USB_Install, USB\VID_18D1&PID_4EE0

And add below:

%CompositeAdbInterface%     = USB_Install, USB\VID_18D1&PID_D001

Repeat it, because there are two sections to modify, [Google.NTx86] and [Google.NTamd64].

If you continue with problems, try this:

Connect your Nexus 5, go to Device Manager, find the Nexus 5 on "other" and right click. Select properties, details, and in selection list, and select hardware id. Write down the short ID, and modify the line with:

%CompositeAdbInterface% = USB_Install, YOUR_SHORT_ID

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

I know of enabling or disabling wifi:

WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);

where status may be true or false as per requirement.

Edit:

You also need the following permissions in your manifest file:

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> 

How can I make an EXE file from a Python program?

Auto PY to EXE - A .py to .exe converter using a simple graphical interface built using Eel and PyInstaller in Python.


py2exe is probably what you want, but it only works on Windows.
PyInstaller works on Windows and Linux.
Py2app works on the Mac.

How do I check if a SQL Server text column is empty?

DECLARE @temp as nvarchar(20)

SET @temp = NULL
--SET @temp = ''
--SET @temp = 'Test'

SELECT IIF(ISNULL(@temp,'')='','[Empty]',@temp)

Parsing HTML using Python

I recommend lxml for parsing HTML. See "Parsing HTML" (on the lxml site).

In my experience Beautiful Soup messes up on some complex HTML. I believe that is because Beautiful Soup is not a parser, rather a very good string analyzer.

MongoDB via Mongoose JS - What is findByID?

As opposed to find() which can return 1 or more documents, findById() can only return 0 or 1 document. Document(s) can be thought of as record(s).

Assign format of DateTime with data annotations?

In mvc 4 you can easily do it like following using TextBoxFor..

@Html.TextBoxFor(m => m.StartDate, "{0:MM/dd/yyyy}", new { @class = "form-control default-date-picker" })

So, you don't need to use any data annotation in model or view model class

How to display pdf in php

Simple way to display pdf files from database and we can download it.
$resume is pdf file name which comes from database.
../resume/filename is path of folder where your file is stored.

<a href="../resumes/<?php echo $resume; ?>"/><?php echo $resume; ?></a>

How to create major and minor gridlines with different linestyles in Python

A simple DIY way would be to make the grid yourself:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot([1,2,3], [2,3,4], 'ro')

for xmaj in ax.xaxis.get_majorticklocs():
  ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
  ax.axvline(x=xmin, ls='--')

for ymaj in ax.yaxis.get_majorticklocs():
  ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
  ax.axhline(y=ymin, ls='--')
plt.show()

Constants in Kotlin -- what's a recommended way to create them?

Like val, variables defined with the const keyword are immutable. The difference here is that const is used for variables that are known at compile-time.

Declaring a variable const is much like using the static keyword in Java.

Let's see how to declare a const variable in Kotlin:

const val COMMUNITY_NAME = "wiki"

And the analogous code written in Java would be:

final static String COMMUNITY_NAME = "wiki";

Adding to the answers above -

@JvmField an be used to instruct the Kotlin compiler not to generate getters/setters for this property and expose it as a field.

 @JvmField
 val COMMUNITY_NAME: "Wiki"

Static fields

Kotlin properties declared in a named object or a companion object will have static backing fields either in that named object or in the class containing the companion object.

Usually these fields are private but they can be exposed in one of the following ways:

  • @JvmField annotation;
  • lateinit modifier;
  • const modifier.

More details here - https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#instance-fields

How to change the floating label color of TextInputLayout

You don't need to use android:theme="@style/TextInputLayoutTheme" to change the floating label color, since it's going to affect to the entire theme for the small TextView used as label. Instead, you could use app:hintTextAppearance="@style/TextInputLayout.HintText" where:

<style name="TextInputLayout.HintText">
  <item name="android:textColor">?attr/colorPrimary</item>
  <item name="android:textSize">@dimen/text_tiny_size</item>
  ...
</style>

Let me know if the solution works :-)

Button Width Match Parent

This is working for me in a self contained widget.

  Widget signinButton() {
    return ButtonTheme(
      minWidth: double.infinity,
      child: new FlatButton(
        onPressed: () {},
        color: Colors.green[400],
        textColor: Colors.white,
        child: Text('Flat Button'),
      ),
    );
  }

// It can then be used in a class that contains a widget tree.

How to use jQuery Plugin with Angular 4?

You should not use jQuery in Angular. While it is possible (see other answers for this question), it is discouraged. Why?

Angular holds an own representation of the DOM in its memory and doesn't use query-selectors (functions like document.getElementById(id)) like jQuery. Instead all the DOM-manipulation is done by Renderer2 (and Angular-directives like *ngFor and *ngIf accessing that Renderer2 in the background/framework-code). If you manipulate DOM with jQuery yourself you will sooner or later...

  1. Run into synchronization problems and have things wrongly appearing or not disappearing at the right time from your screen
  2. Have performance issues in more complex components, as Angular's internal DOM-representation is bound to zone.js and its change detection-mechanism - so updating the DOM manually will always block the thread your app is running on.
  3. Have other confusing errors you don't know the origin of.
  4. Not being able to test the application correctly (Jasmine requires you to know when elements have been rendered)
  5. Not being able to use Angular Universal or WebWorkers

If you really want to include jQuery (for duck-taping some prototype that you will 100% definitively throw away), I recommend to at least include it in your package.json with npm install --save jquery instead of getting it from google's CDN.

TLDR: For learning how to manipulate the DOM in the Angular way please go through the official tour-of heroes tutorial first: https://angular.io/tutorial/toh-pt2 If you need to access elements higher up in the DOM hierarchy (parent or document body) or for some other reason directives like *ngIf, *ngFor, custom directives, pipes and other angular utilities like [style.background], [class.myOwnCustomClass] don't satisfy your needs, use Renderer2: https://www.concretepage.com/angular-2/angular-4-renderer2-example

What does "use strict" do in JavaScript, and what is the reasoning behind it?

I strongly recommend every developer to start using strict mode now. There are enough browsers supporting it that strict mode will legitimately help save us from errors we didn’t even know were in your code.

Apparently, at the initial stage there will be errors we have never encountered before. To get the full benefit, we need to do proper testing after switching to strict mode to make sure we have caught everything. Definitely we don’t just throw use strict in our code and assume there are no errors. So the churn is that it’s time to start using this incredibly useful language feature to write better code.

For example,

var person = {
    name : 'xyz',
    position : 'abc',
    fullname : function () {  "use strict"; return this.name; }
};

JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.

stringstream, string, and char* conversion confusion

stringstream.str() returns a temporary string object that's destroyed at the end of the full expression. If you get a pointer to a C string from that (stringstream.str().c_str()), it will point to a string which is deleted where the statement ends. That's why your code prints garbage.

You could copy that temporary string object to some other string object and take the C string from that one:

const std::string tmp = stringstream.str();
const char* cstr = tmp.c_str();

Note that I made the temporary string const, because any changes to it might cause it to re-allocate and thus render cstr invalid. It is therefor safer to not to store the result of the call to str() at all and use cstr only until the end of the full expression:

use_c_str( stringstream.str().c_str() );

Of course, the latter might not be easy and copying might be too expensive. What you can do instead is to bind the temporary to a const reference. This will extend its lifetime to the lifetime of the reference:

{
  const std::string& tmp = stringstream.str();   
  const char* cstr = tmp.c_str();
}

IMO that's the best solution. Unfortunately it's not very well known.

Why does my Spring Boot App always shutdown immediately after starting?

in my case i already had the maven dependency to 'spring-boot-starter-web' and the project would start fine without auto-stopping when i run it as springboot app from within the IDE. however, when i deploy it to K8s, the app would start and auto-stop immediately. So i modified my main app class to extend SpringBootServletInitializer and this seems to have fixed the auto-stopping.

@SpringBootApplication public class MyApp extends SpringBootServletInitializer {  public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);  }}

In c, in bool, true == 1 and false == 0?

More accurately anything that is not 0 is true.

So 1 is true, but so is 2, 3 ... etc.

How to change values in a tuple?

Not that this is superior, but if anyone is curious it can be done on one line with:

tuple = tuple([200 if i == 0 else _ for i, _ in enumerate(tuple)])

Command /usr/bin/codesign failed with exit code 1

If anyone uses Xcode ver. 3.x.x and upgrades from Mac OS 10.7 to 10.8, dev. tools will work just fine except the new codesign binary .. To fix that just copy the old codesign and codesign_allocate binaries (I hope you have backup) to /usr/bin/ folder and rename or backup the new one.

How to get the input from the Tkinter Text Widget?

I faced the problem of gettng entire text from Text widget and following solution worked for me :

txt.get(1.0,END)

Where 1.0 means first line, zeroth character (ie before the first!) is the starting position and END is the ending position.

Thanks to Alan Gauld in this link

How do I solve this error, "error while trying to deserialize parameter"

Do you have this namespace setup? You will have to ensure that this namespace matches the message namespace. If you can update your question with the xml input and possibly your data object that would be helpful.

[DataContract(Namespace = "http://CompanyName.com.au/ProjectName")]
public class CustomFields
{
  // ...
}

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

Plain JavaScript:

You don't need jQuery to do something trivial like this. Just use the .removeAttribute() method.

Assuming you are just targeting a single element, you can easily use the following: (example)

document.querySelector('#target').removeAttribute('style');

If you are targeting multiple elements, just loop through the selected collection of elements: (example)

var target = document.querySelectorAll('div');
Array.prototype.forEach.call(target, function(element){
    element.removeAttribute('style');
});

Array.prototype.forEach() - IE9 and above / .querySelectorAll() - IE 8 (partial) IE9 and above.

Looping through a Scripting.Dictionary using index/item number

Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.

For i = 0 To d.Count - 1
    s = d.Items()(i)
    Debug.Print s
Next i()

KEYS works the same way

For i = 0 To d.Count - 1
    Debug.Print d.Keys()(i), d.Items()(i)
Next i

This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".

Debug.Print Split("A,B,C,D", ",")(2)

SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.

Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.

POST request send json data java HttpUrlConnection

You can use this code for connect and request using http and json

try {
         
        URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
                + "&key="+key
                + "&access_token=" + access_token);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
 
        String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}";
 
        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();
 
        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }
 
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));
 
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
 
        conn.disconnect();
 
      } catch (MalformedURLException e) {
 
        e.printStackTrace();
 
      } catch (IOException e) {
 
        e.printStackTrace();
 
     }

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

Can you try to change your json without data key like below?

[{"target_id":9503123,"target_type":"user"}]

How do I find Waldo with Mathematica?

I have a quick solution for finding Waldo using OpenCV.

I used the template matching function available in OpenCV to find Waldo.

To do this a template is needed. So I cropped Waldo from the original image and used it as a template.

enter image description here

Next I called the cv2.matchTemplate() function along with the normalized correlation coefficient as the method used. It returned a high probability at a single region as shown in white below (somewhere in the top left region):

enter image description here

The position of the highest probable region was found using cv2.minMaxLoc() function, which I then used to draw the rectangle to highlight Waldo:

enter image description here

How do I deal with corrupted Git object files?

In general, fixing corrupt objects can be pretty difficult. However, in this case, we're confident that the problem is an aborted transfer, meaning that the object is in a remote repository, so we should be able to safely remove our copy and let git get it from the remote, correctly this time.

The temporary object file, with zero size, can obviously just be removed. It's not going to do us any good. The corrupt object which refers to it, d4a0e75..., is our real problem. It can be found in .git/objects/d4/a0e75.... As I said above, it's going to be safe to remove, but just in case, back it up first.

At this point, a fresh git pull should succeed.

...assuming it was going to succeed in the first place. In this case, it appears that some local modifications prevented the attempted merge, so a stash, pull, stash pop was in order. This could happen with any merge, though, and didn't have anything to do with the corrupted object. (Unless there was some index cleanup necessary, and the stash did that in the process... but I don't believe so.)

Not class selector in jQuery

You can use the :not filter selector:

$('foo:not(".someClass")')

Or not() method:

$('foo').not(".someClass")

More Info:

Using RegEX To Prefix And Append In Notepad++

Why don't you use the Notepad++ multiline editing capabilities?

Hold down Alt while selecting text (using your usual click-and-drag approach) to select text across multiple lines. This is sometimes also referred to as column editing.

You could place the cursor at the beginning of the file, Press (and hold) Alt, Shift and then just keep pressing the down-arrow or PageDown to select the lines that you want to prepend with some text :-) Easy. Multiline editing is a very useful feature of Notepad++. It's also possible in Visual Studio, in the same manner, and also in Eclipse by switching to Block Selection Mode by pressing Alt+Shift+A and then use mouse to select text across lines.

POST request with JSON body

<?php
// Example API call
$data = array(array (
    "REGION" => "MUMBAI",
    "LOCATION" => "NA",
    "STORE" => "AMAZON"));
// json encode data
$authToken = "xxxxxxxxxx";
$data_string = json_encode($data); 
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://domainyouhaveapi.com");   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type:application/json',       
    'Content-Length: ' . strlen($data_string) ,
    'API-TOKEN-KEY:'.$authToken ));   // API-TOKEN-KEY is keyword so change according to ur key word. like authorization 
// execute the request
$output = curl_exec($ch);
//echo $output;
// Check for errors
if($output === FALSE){
    die(curl_error($ch));
}
echo($output) . PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);

git: patch does not apply

In my case I was stupid enough to create the patch file incorrectly in the first place, actually diff-ing the wrong way. I ended up with the exact same error messages.

If you're on master and do git diff branch-name > branch-name.patch, this tries to remove all additions you want to happen and vice versa (which was impossible for git to accomplish since, obviously, never done additions cannot be removed).

So make sure you checkout to your branch and execute git diff master > branch-name.patch

How can I update a row in a DataTable in VB.NET?

You can access columns by index, by name and some other ways:

dtResult.Rows(i)("columnName") = strVerse

You should probably make sure your DataTable has some columns first...

Is it possible to start activity through adb shell?

adb shell am broadcast -a android.intent.action.xxx

Mention xxx as the action that you mentioned in the manifest file.

Finding elements not in a list

No, z is undefined. item contains a list of integers.

I think what you're trying to do is this:

#z defined elsewhere
item = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in item:
  if i not in z: print i

As has been stated in other answers, you may want to try using sets.

What __init__ and self do in Python?

The 'self' is a reference to the class instance

class foo:
    def bar(self):
            print "hi"

Now we can create an instance of foo and call the method on it, the self parameter is added by Python in this case:

f = foo()
f.bar()

But it can be passed in as well if the method call isn't in the context of an instance of the class, the code below does the same thing

f = foo()
foo.bar(f)

Interestingly the variable name 'self' is just a convention. The below definition will work exactly the same.. Having said that it is very strong convention which should be followed always, but it does say something about flexible nature of the language

class foo:
    def bar(s):
            print "hi"

Leap year calculation

a) The year is 365.242199 days.

b) If every year was 365 days, in 100 years we would lose 24.2199 days. That's why we add 24 days per century (every 4 years EXCEPT when divisible by 100)

c) But still we lose 0.21299 days/century. So in 4 centuries we lose 0.8796 days. That's why we add 1 day per 4 centuries (every fourth century we DO count a leap year).

d) But that means we lose -0.1204 days (we go forward) per quadricentennial (4 centuries). So in 8 quadricentennial (3200 years) we DO NOT count a leap year.

e) But that means we lose 0.0368 days per 3200 years. So in 24x3200 years (=76800years) we lose 0.8832 days. That's why we DO count a leap year.

and so on... (by then we will have destroyed the planet, so it doesn't matter)

What I cannot understand though, is why we don't count a leap year every 500 years instead of 400. In that way we would converge more rapidly to the correct time (we would lose 2.3 hours/500 years).

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

I tried both the 32-bit and 64-bit installers of both Oracle and IBM Java on Windows, and the presence of C:\Windows\SysWOW64\java.exe seems to be a reliable way to determine that 32-bit Java is available. I haven't tested older versions of these installers, but this at least looks like it should be a reliable way to test, for the most recent versions of Java.

Notepad++ change text color?

You can Change it from:

Menu Settings -> Style Configurator

See on screenshot:

enter image description here

Force IE8 Into IE7 Compatiblity Mode

You can do it in the web.config

    <httpProtocol>
        <customHeaders>
            <add name="X-UA-Compatible" value="IE=7"/>
        </customHeaders>
    </httpProtocol>

I have better results with this over the above solutions. Not sure why this wasn't given as a solution. :)

Get string after character

For the text after the first = and before the next =

cut -d "=" -f2 <<< "$your_str"

or

sed -e 's#.*=\(\)#\1#' <<< "$your_str"

For all text after the first = regardless of if there are multiple =

cut -d "=" -f2- <<< "$your_str"

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

total edge case here: I had this issue installing an Arch AUR PKGBUILD file manually. In my case I needed to delete the 'pkg', 'src' and 'node_modules' folders, then it built fine without this npm error.

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

How do I get Maven to use the correct repositories?

tl;dr

All maven POMs inherit from a base Super POM.
The snippet below is part of the Super POM for Maven 3.5.4.

  <repositories>
    <repository>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
      <layout>default</layout>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
  </repositories>

How to dynamically set bootstrap-datepicker's date value?

$('#datetimepicker1').data("DateTimePicker").date('01/11/2016 10:23 AM')

Mocking static methods with Mockito

Since that method is static, it already has everything you need to use it, so it defeats the purpose of mocking. Mocking the static methods is considered to be a bad practice.

If you try to do that, it means there is something wrong with the way you want to perform testing.

Of course you can use PowerMockito or any other framework capable of doing that, but try to rethink your approach.

For example: try to mock/provide the objects, which that static method consumes instead.

How do I login and authenticate to Postgresql after a fresh install?

you can also connect to database as "normal" user (not postgres):

postgres=# \connect opensim Opensim_Tester localhost;

Password for user Opensim_Tester:    

You are now connected to database "opensim" as user "Opensim_Tester" on host "localhost" at port "5432"

How can I ping a server port with PHP?

function ping($ip){
    $output = shell_exec("ping $ip");
    var_dump($output);
}
ping('127.0.0.1');

UPDATE: If you pass an hardcoded IP (like in this example and most of the real-case scenarios), this function can be enough.

But since some users seem to be very concerned about safety, please remind to never pass user generated inputs to the shell_exec function: If the IP comes from an untrusted source, at least check it with a filter before using it.

Pass array to where in Codeigniter Active Record

From the Active Record docs:

$this->db->where_in();

Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

Access VBA | How to replace parts of a string with another string

Use Access's VBA function Replace(text, find, replacement):

Dim result As String

result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")

CodeIgniter - how to catch DB errors?

Put this code in a file called MY_Exceptions.php in application/core folder:

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Class dealing with errors as exceptions
 */
class MY_Exceptions extends CI_Exceptions
{

    /**
     * Force exception throwing on erros
     */
    public function show_error($heading, $message, $template = 'error_general', $status_code = 500)
    {
        set_status_header($status_code);

        $message = implode(" / ", (!is_array($message)) ? array($message) : $message);

        throw new CiError($message);
    }

}

/**
 * Captured error from Code Igniter
 */
class CiError extends Exception
{

}

It will make all the Code Igniter errors to be treated as Exception (CiError). Then, turn all your database debug on:

$db['default']['db_debug'] = true;

Detecting Back Button/Hash Change in URL

Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.

Tools for making latex tables in R

I'd like to add a mention of the "brew" package. You can write a brew template file which would be LaTeX with placeholders, and then "brew" it up to create a .tex file to \include or \input into your LaTeX. Something like:

\begin{tabular}{l l}
A & <%= fit$A %> \\
B & <%= fit$B %> \\
\end{tabular}

The brew syntax can also handle loops, so you can create a table row for each row of a dataframe.

How to watch and compile all TypeScript sources?

Create a file named tsconfig.json in your project root and include following lines in it:

{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "module": "commonjs",
        "target": "ES5",
        "outDir": "ts-built",
        "rootDir": "src"
    }
}

Please note that outDir should be the path of the directory to receive compiled JS files, and rootDir should be the path of the directory containing your source (.ts) files.

Open a terminal and run tsc -w, it'll compile any .ts file in src directory into .js and store them in ts-built directory.

How to change font-color for disabled input?

It seems nobody found a solution for this. I don't have one based on only css neither but by using this JavaScript trick I usually can handle disabled input fields.

Remember that disabled fields always follow the style that they got before becoming disabled. So the trick would be 1- Enabling them 2-Change the class 3- Disable them again. Since this happens very fast user cannot understand what happened.

A simple JavaScript code would be something like:

function changeDisabledClass (id, disabledClass){
var myInput=document.getElementById(id);
myInput.disabled=false;             //First make sure it is not disabled
myInput.className=disabledClass;    //change the class
myInput.disabled=true;             //Re-disable it
}

How do I check in python if an element of a list is empty?

Try:

if l[i]:
    print 'Found element!'
else:
    print 'Empty element.'

How do I localize the jQuery UI Datepicker?

  $.datepicker.setDefaults({
    closeText: "??",
    prevText: "&#x3C;??",
    nextText: "??&#x3E;",
    currentText: "??",
    monthNames: [ "??","??","??","??","??","??",
    "??","??","??","??","???","???" ],
    monthNamesShort: [ "??","??","??","??","??","??",
    "??","??","??","??","???","???" ],
    dayNames: [ "???","???","???","???","???","???","???" ],
    dayNamesShort: [ "??","??","??","??","??","??","??" ],
    dayNamesMin: [ "?","?","?","?","?","?","?" ],
    weekHeader: "?",
    dateFormat: "yy-mm-dd",
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: true,
    yearSuffix: "?"
  });

the i18n code could be copied from https://github.com/jquery/jquery-ui/tree/master/ui/i18n

Joining pandas dataframes by column names

you need to make county_ID as index for the right frame:

frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
               on=[ 'countyid' ], how='left' )

for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.

so you need to verify integrity before joining by , verify_integrity=True

Codeigniter: does $this->db->last_query(); execute a query?

For me save_queries option was turned off so,

$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;

Ref: Can't get result from $this->db->last_query(); codeigniter

How can I tell if a Java integer is null?

I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.

Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.

This indicates it only applies to hash or array elements!

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

A few years late, but I have a solution for the most recent version of WordPress, which has this same issue (WordPress-generated .htaccess files break sites, reuslting in 403 Forbidden error messages). Here's that it looks like when WordPress creates it:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

The problem is that the conditional doesn't work. It doesn't work because the module it's looking for isn't .c, it's .so. I think this is a platform-specific, or configuration-specific issue, where Mac OS and Lunix Apache installations are set up for .so AKA 'shared-object' modules. Looking for a .c module shouldn't break the conditional, I think that's a bug, but it's the issue.

Simply change the mod_rewrite.c to mod_rewrite.so and you're all set to go!

# BEGIN WordPress
<IfModule mod_rewrite.so>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

IE prompts to open or save json result from server

I changed the content-type to "text/html" instead of "application/json" server side before returning the response. Described it in a blog post, where other solutions have also been added:

http://blog.degree.no/2012/09/jquery-json-ie8ie9-treats-response-as-downloadable-file/

What does Include() do in LINQ?

I just wanted to add that "Include" is part of eager loading. It is described in Entity Framework 6 tutorial by Microsoft. Here is the link: https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application


Excerpt from the linked page:

Here are several ways that the Entity Framework can load related data into the navigation properties of an entity:

Lazy loading. When the entity is first read, related data isn't retrieved. However, the first time you attempt to access a navigation property, the data required for that navigation property is automatically retrieved. This results in multiple queries sent to the database — one for the entity itself and one each time that related data for the entity must be retrieved. The DbContext class enables lazy loading by default.

Eager loading. When the entity is read, related data is retrieved along with it. This typically results in a single join query that retrieves all of the data that's needed. You specify eager loading by using the Include method.

Explicit loading. This is similar to lazy loading, except that you explicitly retrieve the related data in code; it doesn't happen automatically when you access a navigation property. You load related data manually by getting the object state manager entry for an entity and calling the Collection.Load method for collections or the Reference.Load method for properties that hold a single entity. (In the following example, if you wanted to load the Administrator navigation property, you'd replace Collection(x => x.Courses) with Reference(x => x.Administrator).) Typically you'd use explicit loading only when you've turned lazy loading off.

Because they don't immediately retrieve the property values, lazy loading and explicit loading are also both known as deferred loading.

Read a text file in R line by line

You should take care with readLines(...) and big files. Reading all lines at memory can be risky. Below is a example of how to read file and process just one line at time:

processFile = function(filepath) {
  con = file(filepath, "r")
  while ( TRUE ) {
    line = readLines(con, n = 1)
    if ( length(line) == 0 ) {
      break
    }
    print(line)
  }

  close(con)
}

Understand the risk of reading a line at memory too. Big files without line breaks can fill your memory too.

Loading DLLs at runtime in C#

You need to create an instance of the type that expose the Output method:

static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var class1Type = DLL.GetType("DLL.Class1");

        //Now you can use reflection or dynamic to call the method. I will show you the dynamic way

        dynamic c = Activator.CreateInstance(class1Type);
        c.Output(@"Hello");

        Console.ReadLine();
     }

Random record from MongoDB

Here is a way using the default ObjectId values for _id and a little math and logic.

// Get the "min" and "max" timestamp values from the _id in the collection and the 
// diff between.
// 4-bytes from a hex string is 8 characters

var min = parseInt(db.collection.find()
        .sort({ "_id": 1 }).limit(1).toArray()[0]._id.str.substr(0,8),16)*1000,
    max = parseInt(db.collection.find()
        .sort({ "_id": -1 })limit(1).toArray()[0]._id.str.substr(0,8),16)*1000,
    diff = max - min;

// Get a random value from diff and divide/multiply be 1000 for The "_id" precision:
var random = Math.floor(Math.floor(Math.random(diff)*diff)/1000)*1000;

// Use "random" in the range and pad the hex string to a valid ObjectId
var _id = new ObjectId(((min + random)/1000).toString(16) + "0000000000000000")

// Then query for the single document:
var randomDoc = db.collection.find({ "_id": { "$gte": _id } })
   .sort({ "_id": 1 }).limit(1).toArray()[0];

That's the general logic in shell representation and easily adaptable.

So in points:

  • Find the min and max primary key values in the collection

  • Generate a random number that falls between the timestamps of those documents.

  • Add the random number to the minimum value and find the first document that is greater than or equal to that value.

This uses "padding" from the timestamp value in "hex" to form a valid ObjectId value since that is what we are looking for. Using integers as the _id value is essentially simplier but the same basic idea in the points.

Unzip a file with php

Simple PHP function to unzip. Please make sure you have zip extension installed on your server.

/**
 * Unzip
 * @param string $zip_file_path Eg - /tmp/my.zip
 * @param string $extract_path Eg - /tmp/new_dir_name
 * @return boolean
 */
function unzip(string $zip_file_path, string $extract_dir_path) {
    $zip = new \ZipArchive;
    $res = $zip->open($zip_file_path);
    if ($res === TRUE) {
        $zip->extractTo($extract_dir_path);
        $zip->close();
        return TRUE;
    } else {
        return FALSE;
    }
}

Java Programming: call an exe from Java and passing parameters

Pass your arguments in constructor itself.

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();

What does void do in java?

Void: the type modifier void states that the main method does not return any value. All parameters to a method are declared inside a prior of parenthesis. Here String args[ ] declares a parameter named args which contains an array of objects of the class type string.

iOS app 'The application could not be verified' only on one device

I resolved this issue by changing the Build System to legacy in xcode.

I had the same problem but the mentioned solutions above didn't work for me. Even I had no previous app on device, I got this error when deploying on my device.

How to do:

Simply, go to menu File > Project Setting, inside Share Project Settings, change Build System from "New Build System (default)" to "Lagacy Build System".

How to declare Return Types for Functions in TypeScript

External return type declaration to use with multiple functions:

type ValidationReturnType = string | boolean;

function isEqual(number1: number, number2: number): ValidationReturnType {
    return number1 == number2 ? true : 'Numbers are not equal.';
}

How to add dividers and spaces between items in RecyclerView?

Taken from a google search, add this ItemDecoration to your RecyclerView:

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

private Drawable mDivider;
private boolean mShowFirstDivider = false;
private boolean mShowLastDivider = false;


public DividerItemDecoration(Context context, AttributeSet attrs) {
    final TypedArray a = context
            .obtainStyledAttributes(attrs, new int[]{android.R.attr.listDivider});
    mDivider = a.getDrawable(0);
    a.recycle();
}

public DividerItemDecoration(Context context, AttributeSet attrs, boolean showFirstDivider,
        boolean showLastDivider) {
    this(context, attrs);
    mShowFirstDivider = showFirstDivider;
    mShowLastDivider = showLastDivider;
}

public DividerItemDecoration(Drawable divider) {
    mDivider = divider;
}

public DividerItemDecoration(Drawable divider, boolean showFirstDivider,
        boolean showLastDivider) {
    this(divider);
    mShowFirstDivider = showFirstDivider;
    mShowLastDivider = showLastDivider;
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
        RecyclerView.State state) {
    super.getItemOffsets(outRect, view, parent, state);
    if (mDivider == null) {
        return;
    }
    if (parent.getChildPosition(view) < 1) {
        return;
    }

    if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
        outRect.top = mDivider.getIntrinsicHeight();
    } else {
        outRect.left = mDivider.getIntrinsicWidth();
    }
}

@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
    if (mDivider == null) {
        super.onDrawOver(c, parent, state);
        return;
    }

    // Initialization needed to avoid compiler warning
    int left = 0, right = 0, top = 0, bottom = 0, size;
    int orientation = getOrientation(parent);
    int childCount = parent.getChildCount();

    if (orientation == LinearLayoutManager.VERTICAL) {
        size = mDivider.getIntrinsicHeight();
        left = parent.getPaddingLeft();
        right = parent.getWidth() - parent.getPaddingRight();
    } else { //horizontal
        size = mDivider.getIntrinsicWidth();
        top = parent.getPaddingTop();
        bottom = parent.getHeight() - parent.getPaddingBottom();
    }

    for (int i = mShowFirstDivider ? 0 : 1; i < childCount; i++) {
        View child = parent.getChildAt(i);
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

        if (orientation == LinearLayoutManager.VERTICAL) {
            top = child.getTop() - params.topMargin;
            bottom = top + size;
        } else { //horizontal
            left = child.getLeft() - params.leftMargin;
            right = left + size;
        }
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }

    // show last divider
    if (mShowLastDivider && childCount > 0) {
        View child = parent.getChildAt(childCount - 1);
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
        if (orientation == LinearLayoutManager.VERTICAL) {
            top = child.getBottom() + params.bottomMargin;
            bottom = top + size;
        } else { // horizontal
            left = child.getRight() + params.rightMargin;
            right = left + size;
        }
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }
}

private int getOrientation(RecyclerView parent) {
    if (parent.getLayoutManager() instanceof LinearLayoutManager) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
        return layoutManager.getOrientation();
    } else {
        throw new IllegalStateException(
                "DividerItemDecoration can only be used with a LinearLayoutManager.");
    }
}
}

Notice: Undefined variable: _SESSION in "" on line 9

Add

session_start();

at the beginning of your page before any HTML

You will have something like :

<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...

Don't forget to remove the space you have before

How to use XMLReader in PHP?

Most of my XML parsing life is spent extracting nuggets of useful information out of truckloads of XML (Amazon MWS). As such, my answer assumes you want only specific information and you know where it is located.

I find the easiest way to use XMLReader is to know which tags I want the information out of and use them. If you know the structure of the XML and it has lots of unique tags, I find that using the first case is the easy. Cases 2 and 3 are just to show you how it can be done for more complex tags. This is extremely fast; I have a discussion of speed over on What is the fastest XML parser in PHP?

The most important thing to remember when doing tag-based parsing like this is to use if ($myXML->nodeType == XMLReader::ELEMENT) {... - which checks to be sure we're only dealing with opening nodes and not whitespace or closing nodes or whatever.

function parseMyXML ($xml) { //pass in an XML string
    $myXML = new XMLReader();
    $myXML->xml($xml);

    while ($myXML->read()) { //start reading.
        if ($myXML->nodeType == XMLReader::ELEMENT) { //only opening tags.
            $tag = $myXML->name; //make $tag contain the name of the tag
            switch ($tag) {
                case 'Tag1': //this tag contains no child elements, only the content we need. And it's unique.
                    $variable = $myXML->readInnerXML(); //now variable contains the contents of tag1
                    break;

                case 'Tag2': //this tag contains child elements, of which we only want one.
                    while($myXML->read()) { //so we tell it to keep reading
                        if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') { // and when it finds the amount tag...
                            $variable2 = $myXML->readInnerXML(); //...put it in $variable2. 
                            break;
                        }
                    }
                    break;

                case 'Tag3': //tag3 also has children, which are not unique, but we need two of the children this time.
                    while($myXML->read()) {
                        if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') {
                            $variable3 = $myXML->readInnerXML();
                            break;
                        } else if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Currency') {
                            $variable4 = $myXML->readInnerXML();
                            break;
                        }
                    }
                    break;

            }
        }
    }
$myXML->close();
}

Container is running beyond memory limits

I had a really similar issue using HIVE in EMR. None of the extant solutions worked for me -- ie, none of the mapreduce configurations worked for me; and neither did setting yarn.nodemanager.vmem-check-enabled to false.

However, what ended up working was setting tez.am.resource.memory.mb, for example:

hive -hiveconf tez.am.resource.memory.mb=4096

Another setting to consider tweaking is yarn.app.mapreduce.am.resource.mb

How do I do a simple 'Find and Replace" in MsSQL?

like so:

BEGIN TRANSACTION; 
UPDATE table_name
  SET column_name=REPLACE(column_name,'text_to_find','replace_with_this'); 
COMMIT TRANSACTION;

Example: Replaces <script... with <a ... to eliminate javascript vulnerabilities

BEGIN TRANSACTION; UPDATE testdb
SET title=REPLACE(title,'script','a'); COMMIT TRANSACTION;

Does C# have extension properties?

No, they don't exist.

I know that the C# team was considering them at one point (or at least Eric Lippert was) - along with extension constructors and operators (those may take a while to get your head around, but are cool...) However, I haven't seen any evidence that they'll be part of C# 4.


EDIT: They didn't appear in C# 5, and as of July 2014 it doesn't look like it's going to be in C# 6 either.

Eric Lippert, the Principal Developer on the C# compiler team at Microsoft thru November 2012, blogged about this in October of 2009:

How to get json key and value in javascript?

//By using jquery json parser    
var obj = $.parseJSON('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(obj['jobtitel']);

//By using javasript json parser
var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(t['jobtitel'])

Check this jsfiddle

As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.

Source: http://api.jquery.com/jquery.parsejson/

How to move mouse cursor using C#?

First Add a Class called Win32.cs

public class Win32
{ 
    [DllImport("User32.Dll")]
    public static extern long SetCursorPos(int x, int y);

    [DllImport("User32.Dll")]
    public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int x;
        public int y;

        public POINT(int X, int Y)
        {
            x = X;
            y = Y;
        }
    }
}

You can use it then like this:

Win32.POINT p = new Win32.POINT(xPos, yPos);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

How to declare a type as nullable in TypeScript?

type MyProps = {
  workoutType: string | null;
};

Set field value with reflection

The method below sets a field on your object even if the field is in a superclass

/**
 * Sets a field value on a given object
 *
 * @param targetObject the object to set the field value on
 * @param fieldName    exact name of the field
 * @param fieldValue   value to set on the field
 * @return true if the value was successfully set, false otherwise
 */
public static boolean setField(Object targetObject, String fieldName, Object fieldValue) {
    Field field;
    try {
        field = targetObject.getClass().getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        field = null;
    }
    Class superClass = targetObject.getClass().getSuperclass();
    while (field == null && superClass != null) {
        try {
            field = superClass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            superClass = superClass.getSuperclass();
        }
    }
    if (field == null) {
        return false;
    }
    field.setAccessible(true);
    try {
        field.set(targetObject, fieldValue);
        return true;
    } catch (IllegalAccessException e) {
        return false;
    }
}

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

Remove the '#' and do

Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
                         System.Globalization.NumberStyles.AllowHexSpecifier));

Visual Studio breakpoints not being hit

I know this is not the OPs issue, but I had this happen on a project. The solution had multiple MVC projects and the wrong project was set as startup.

I had also set the configuration of the project(s) to just start process/debugger and not open a new browser window.

Visual Studio Project Properties

So on the surface it looks as if the debugger is starting up, but it does so for the wrong process. So check that and keep in mind that you can attach to multiple processes also.

Silly mistake that left me scratching my head for about 30 minutes.

Attach to both processes

Running a command as Administrator using PowerShell?

C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell is where the shortcut of PowerShell resides. It too still goes to a different location to invoke the actual 'exe' (%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe).

Since PowerShell is user-profile driven when permissions are concerned; if your username/profile has the permissions to do something then under that profile, in PowerShell you would generally be able to do it as well. That being said, it would make sense that you would alter the shortcut located under your user profile, for example, C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell.

Right-click and click properties. Click "Advanced" button under the "Shortcut" tab located right below the "Comments" text field adjacent to the right of two other buttons, "Open File Location" and "Change Icon", respectively.

Check the checkbox that reads, "Run as Administrator". Click OK, then Apply and OK. Once again right click the icon labeled 'Windows PowerShell' located in C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell and select "Pin to Start Menu/Taskbar".

Now whenever you click that icon, it will invoke the UAC for escalation. After selecting 'YES', you will notice the PowerShell console open and it will be labeled "Administrator" on the top of the screen.

To go a step further... you could right click that same icon shortcut in your profile location of Windows PowerShell and assign a keyboard shortcut that will do the exact same thing as if you clicked the recently added icon. So where it says "Shortcut Key" put in a keyboard key/button combination like: Ctrl + Alt + PP (for PowerShell). Click Apply and OK.

Now all you have to do is press that button combination you assigned and you will see UAC get invoked, and after you select 'YES' you will see a PowerShell console appear and "Administrator" displayed on the title bar.

Exception: Serialization of 'Closure' is not allowed

Direct Closure serialisation is not allowed by PHP. But you can use powefull class like PHP Super Closure : https://github.com/jeremeamia/super_closure

This class is really simple to use and is bundled into the laravel framework for the queue manager.

From the github documentation :

$helloWorld = new SerializableClosure(function ($name = 'World') use ($greeting) {
    echo "{$greeting}, {$name}!\n";
});

$serialized = serialize($helloWorld);

CodeIgniter: Create new helper?

Some code that allows you to use CI instance inside the helper:

function yourHelperFunction(){
    $ci=& get_instance();
    $ci->load->database(); 

    $sql = "select * from table"; 
    $query = $ci->db->query($sql);
    $row = $query->result();
}

How do I print the full value of a long string in gdb?

set print elements 0

From the GDB manual:

set print elements number-of-elements
Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200. Setting number-of-elements to zero means that the printing is unlimited.

How to add data via $.ajax ( serialize() + extra data ) like this

Personally, I'd append the element to the form instead of hacking the serialized data, e.g.

moredata = 'your custom data here';

// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);

// append to the form
$('#myForm').append($input);

// then..
data: $('#myForm').serialize()

That way, you don't have to worry about ? or &

How to get the azure account tenant Id?

My team really got sick of trying to find the tenant ID for our O365 and Azure projects. The devs, the support team, the sales team, everyone needs it at some point and never remembers how to do it.

So we've built this small site in the same vein as whatismyip.com. Hope you find it useful!

How to find my Microsoft 365, Azure or SharePoint Online tenant ID?

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

I came across the same issue with a .NET application, a CMS open-source called MojoPortal. In one of my themes and skin for a particular site, when browsing or testing it would grind and slow down like it was choking.

My issue was not of the "type" attribute for the CSS but it was "that other thing". My exact change was in the Web.Config. I changed all the values to FALSE for MinifyCSS, CacheCssOnserver, and CacheCSSinBrowser.

Once that was set the web site was speedy once again in production.

Copy Paste in Bash on Ubuntu on Windows

That turned out to be pretty simple. I've got it occasionally. To paste a text you simply need to right mouse button click anywhere in terminal window.

Tracking Google Analytics Page Views with AngularJS

If you're using ng-view in your Angular app you can listen for the $viewContentLoaded event and push a tracking event to Google Analytics.

Assuming you've set up your tracking code in your main index.html file with a name of var _gaq and MyCtrl is what you've defined in the ng-controller directive.

function MyCtrl($scope, $location, $window) {
  $scope.$on('$viewContentLoaded', function(event) {
    $window._gaq.push(['_trackPageView', $location.url()]);
  });
}

UPDATE: for new version of google-analytics use this one

function MyCtrl($scope, $location, $window) {
  $scope.$on('$viewContentLoaded', function(event) {
    $window.ga('send', 'pageview', { page: $location.url() });
  });
}

Remove First and Last Character C++

std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; } 
else {
    while(str.at(0) == ' ') { str.erase(0, 1);}
    while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
    return str ;
    } 
}

Spring Boot and how to configure connection details to MongoDB?

Here is How you can do in Spring Boot 2.0 by creating custom MongoClient adding Providing more control for Connection ,

Please follow github Link for Full Source Code

@Configuration
@EnableMongoRepositories(basePackages = { "com.frugalis.repository" })
@ComponentScan(basePackages = { "com.frugalis.*" })
@PropertySource("classpath:application.properties")
public class MongoJPAConfig extends AbstractMongoConfiguration {

    @Value("${com.frugalis.mongo.database}")
    private String database;
    @Value("${com.frugalis.mongo.server}")
    private String host;
    @Value("${com.frugalis.mongo.port}")
    private String port;
    @Value("${com.frugalis.mongo.username}")
    private String username;
    @Value("${com.frugalis.mongo.password}")
    private String password;


    @Override
    protected String getDatabaseName() {
        return database;
    }

    @Override
    protected String getMappingBasePackage() {
        return "com.frugalis.entity.mongo";
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoClient(), getDatabaseName());
    }

    @Override
    @Bean
    public MongoClient mongoClient() {

        List<MongoCredential> allCred = new ArrayList<MongoCredential>();
        System.out.println("???????????????????"+username+" "+database+" "+password+" "+host+" "+port);
        allCred.add(MongoCredential.createCredential(username, database, password.toCharArray()));
        MongoClient client = new MongoClient((new ServerAddress(host, Integer.parseInt(port))), allCred);
        client.setWriteConcern(WriteConcern.ACKNOWLEDGED);

        return client;
    }} 

What's the difference between & and && in MATLAB?

&& and || take scalar inputs and short-circuit always. | and & take array inputs and short-circuit only in if/while statements. For assignment, the latter do not short-circuit.

See these doc pages for more information.

What's a .sh file?

What is a file with extension .sh?

It is a Bourne shell script. They are used in many variations of UNIX-like operating systems. They have no "language" and are interpreted by your shell (interpreter of terminal commands) or if the first line is in the form

#!/path/to/interpreter

they will use that particular interpreter. Your file has the first line:

#!/bin/bash

and that means that it uses Bourne Again Shell, so called bash. It is for all practical purposes a replacement for good old sh.

Depending upon the interpreter you will have different language in which the file is written.

Keep in mind, that in UNIX world, it is not the extension of the file that determines what the file is (see How to execute a shell script).

If you come from the world of DOS/Windows, you will be familiar with files that have .bat or .cmd extensions (batch files). They are not similar in content, but are akin in design.

How to execute a shell script

Unlike some silly operating systems, *nix does not rely exclusively on extensions to determine what to do with a file. Permissions are also used. This means that if you attempt to run the shell script after downloading it, it will be the same as trying to "run" any text file. The ".sh" extension is there only for your convenience to recognize that file.

You will need to make the file executable. Let's assume that you have downloaded your file as file.sh, you can then run in your terminal:

chmod +x file.sh

chmod is a command for changing file's permissions, +x sets execute permissions (in this case for everybody) and finally you have your file name.

You can also do it in GUI. Most of the time you can right click on the file and select properties, in XUbuntu the permissions options look like this:

File permissions in XUbuntu

If you do not wish to change the permissions. You can also force the shell to run the command. In the terminal you can run:

bash file.sh

The shell should be the same as in the first line of your script.

How safe is it?

You may find it weird that you must perform another task manually in order to execute a file. But this is partially because of strong need for security.

Basically when you download and run a bash script, it is the same thing as somebody telling you "run all these commands in sequence on your computer, I promise that the results will be good and safe". Ask yourself if you trust the party that has supplied this file, ask yourself if you are sure that have downloaded the file from the same place as you thought, maybe even have a glance inside to see if something looks out of place (although that requires that you know something about *nix commands and bash programming).

Unfortunately apart from the warning above I cannot give a step-by-step description of what you should do to prevent evil things from happening with your computer; so just keep in mind that any time you get and run an executable file from someone you're actually saying, "Sure, you can use my computer to do something".

Optimum way to compare strings in JavaScript?

Well in JavaScript you can check two strings for values same as integers so yo can do this:

  • "A" < "B"
  • "A" == "B"
  • "A" > "B"

And therefore you can make your own function that checks strings the same way as the strcmp().

So this would be the function that does the same:

function strcmp(a, b)
{   
    return (a<b?-1:(a>b?1:0));  
}

How to display list of repositories from subversion server

At my company they didn't configure the server to provide a list of repositories, so svn list worked for a specific repository but not at a higher level to list all repositories.

However they installed FishEye which gives you a GUI listing the repositories https://www.atlassian.com/software/fisheye

It's a paid option, so it's not for everyone, but the functionality is nice.

ReadFile in Base64 Nodejs

I think that the following example demonstrates what you need:http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html

The essence of the article is this code part:

var fs = require('fs');

// function to encode file data to base64 encoded string
function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}

// function to create file from base64 encoded string
function base64_decode(base64str, file) {
    // create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
    var bitmap = new Buffer(base64str, 'base64');
    // write buffer to file
    fs.writeFileSync(file, bitmap);
    console.log('******** File created from base64 encoded string ********');
}

// convert image to base64 encoded string
var base64str = base64_encode('kitten.jpg');
console.log(base64str);
// convert base64 string back to image 
base64_decode(base64str, 'copy.jpg');

Search for string and get count in vi editor

:%s/string/string/g will give the answer.

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

How about:

(Updated)

$("#column_select").change(function () {
    $("#layout_select")
        .find("option")
        .show()
        .not("option[value*='" + this.value + "']").hide();

    $("#layout_select").val(
        $("#layout_select").find("option:visible:first").val());

}).change();

(assuming the third option should have a value col3)

Example: http://jsfiddle.net/cL2tt/

Notes:

  • Use the .change() event to define an event handler that executes when the value of select#column_select changes.
  • .show() all options in the second select.
  • .hide() all options in the second select whose value does not contain the value of the selected option in select#column_select, using the attribute contains selector.

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Sum values from an array of key-value pairs in JavaScript

You can use the native map method for Arrays. map Method (Array) (JavaScript)

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
             ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], 
             ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], 
             ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);
var a = 0;
myData.map( function(aa){ a += aa[1];  return a; });

a is your result

How to get key names from JSON using jq

You need to use jq 'keys[]'. For example:

echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'

Will output a line separated list:

"example1"
"example2"
"example3"

Combine multiple results in a subquery into a single comma-separated value

SELECT t.ID, 
       t.NAME, 
       (SELECT t1.SOMECOLUMN 
        FROM   TABLEB t1 
        WHERE  t1.F_ID = T.TABLEA.ID) 
FROM   TABLEA t; 

This will work for selecting from different table using sub query.

How to search contents of multiple pdf files?

If You want to see file names with pdftotext use following command:

find . -name '*.pdf' -exec echo {} \; -exec pdftotext {} - \; | grep "pattern\|pdf" 

Converting String To Float in C#

The precision of float is 7 digits. If you want to keep the whole lot, you need to use the double type that keeps 15-16 digits. Regarding formatting, look at a post about formatting doubles. And you need to worry about decimal separators in C#.

Converting a year from 4 digit to 2 digit and back again in C#

This should work for you:

public int Get4LetterYear(int twoLetterYear)
{
    int firstTwoDigits =
        Convert.ToInt32(DateTime.Now.Year.ToString().Substring(2, 2));
    return Get4LetterYear(twoLetterYear, firstTwoDigits);
}

public int Get4LetterYear(int twoLetterYear, int firstTwoDigits)
{
    return Convert.ToInt32(firstTwoDigits.ToString() + twoLetterYear.ToString());
}

public int Get2LetterYear(int fourLetterYear)
{
    return Convert.ToInt32(fourLetterYear.ToString().Substring(2, 2));
}

I don't think there are any special built-in stuff in .NET.

Update: It's missing some validation that you maybe should do. Validate length of inputted variables, and so on.

Wait .5 seconds before continuing code VB.net

In web application a timer will be the best approach.

Just fyi, in desktop application I use this instead, inside an async method.

... 
Await Task.Run(Sub()
    System.Threading.Thread.Sleep(5000)
End Sub)
...

It work for me, importantly it doesn't freeze entire screen. But again this is on desktop, i try in web application it does freeze.

What function is to replace a substring from a string in C?

Here goes mine, make them all char*, which makes calling easier...

char *strrpc(char *str,char *oldstr,char *newstr){
    char bstr[strlen(str)];
    memset(bstr,0,sizeof(bstr));
    int i;
    for(i = 0;i < strlen(str);i++){
        if(!strncmp(str+i,oldstr,strlen(oldstr))){
            strcat(bstr,newstr);
            i += strlen(oldstr) - 1;
        }else{
                strncat(bstr,str + i,1);
            }
    }

    strcpy(str,bstr);
    return str;
}

Getting the object's property name

IN ES5

E.G. you have this kind of object:

var ELEMENTS = {
    STEP_ELEMENT: { ID: "0", imageName: "el_0.png" },
    GREEN_ELEMENT: { ID: "1", imageName: "el_1.png" },
    BLUE_ELEMENT: { ID: "2", imageName: "el_2.png" },
    ORANGE_ELEMENT: { ID: "3", imageName: "el_3.png" },
    PURPLE_ELEMENT: { ID: "4", imageName: "el_4.png" },
    YELLOW_ELEMENT: { ID: "5", imageName: "el_5.png" }
};

And now if you want to have a function that if you pass '0' as a param - to get 'STEP_ELEMENT', if '2' to get 'BLUE_ELEMENT' and so for

function(elementId) {
    var element = null;

    Object.keys(ELEMENTS).forEach(function(key) {
        if(ELEMENTS[key].ID === elementId.toString()){
            element = key;
            return;
        }    
    });

    return element;
}

This is probably not the best solution to the problem but its good to give you an idea how to do it.

Cheers.

How can I clear an HTML file input with JavaScript?

That's actually quite easy.

document.querySelector('#input-field').value = '';

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

How can I list all of the files in a directory with Perl?

readdir() does that.

Check http://perldoc.perl.org/functions/readdir.html

opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
closedir DIR;

Cannot find libcrypto in Ubuntu

ld is trying to find libcrypto.sowhich is not present as seen in your locate output. You can make a copy of the libcrypto.so.0.9.8 and name it as libcrypto.so. Put this is your ld path. ( If you do not have root access then you can put it in a local path and specify the path manually )

Is it possible to get only the first character of a String?

Java strings are simply an array of char. So, char c = s[0] where s is string.

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

This helped me find the "Dynamic web project" in Eclipse 2020-12 version. Restart the eclipse and go to file->new->other->web and you will see project will be available.

In Angular, how to pass JSON object/array into directive?

What you need is properly a service:

.factory('DataLayer', ['$http',

    function($http) {

        var factory = {};
        var locations;

        factory.getLocations = function(success) {
            if(locations){
                success(locations);
                return;
            }
            $http.get('locations/locations.json').success(function(data) {
                locations = data;
                success(locations);
            });
        };

        return factory;
    }
]);

The locations would be cached in the service which worked as singleton model. This is the right way to fetch data.

Use this service DataLayer in your controller and directive is ok as following:

appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
    DataLayer.getLocations(function(data){
        $scope.locations = data;
    });
});

.directive('map', function(DataLayer) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {

            DataLayer.getLocations(function(data) {
                angular.forEach(data, function(location, key){
                    //do something
                });
            });
        }
    };
});

When should I use double or single quotes in JavaScript?

Examining the pros and cons

In favor of single quotes

  • Less visual clutter.
  • Generating HTML: HTML attributes are usually delimited by double quotes.

_x000D_
_x000D_
elem.innerHTML = '<a href="' + url + '">Hello</a>';
_x000D_
_x000D_
_x000D_ However, single quotes are just as legal in HTML.

_x000D_
_x000D_
elem.innerHTML = "<a href='" + url + "'>Hello</a>";
_x000D_
_x000D_
_x000D_

Furthermore, inline HTML is normally an anti-pattern. Prefer templates.

  • Generating JSON: Only double quotes are allowed in JSON.

_x000D_
_x000D_
myJson = '{ "hello world": true }';
_x000D_
_x000D_
_x000D_

Again, you shouldn’t have to construct JSON this way. JSON.stringify() is often enough. If not, use templates.

In favor of double quotes

  • Doubles are easier to spot if you don't have color coding. Like in a console log or some kind of view-source setup.
  • Similarity to other languages: In shell programming (Bash etc.), single-quoted string literals exist, but escapes are not interpreted inside them. C and Java use double quotes for strings and single quotes for characters.
  • If you want code to be valid JSON, you need to use double quotes.

In favor of both

There is no difference between the two in JavaScript. Therefore, you can use whatever is convenient at the moment. For example, the following string literals all produce the same string:

_x000D_
_x000D_
    "He said: \"Let's go!\""_x000D_
    'He said: "Let\'s go!"'_x000D_
    "He said: \"Let\'s go!\""_x000D_
    'He said: \"Let\'s go!\"'
_x000D_
_x000D_
_x000D_

Single quotes for internal strings and double for external. That allows you to distinguish internal constants from strings that are to be displayed to the user (or written to disk etc.). Obviously, you should avoid putting the latter in your code, but that can’t always be done.

char *array and char array[]

No. Actually it's the "same" as

char array[] = {'O', 'n', 'e', ..... 'i','c','\0');

Every character is a separate element, with an additional \0 character as a string terminator.

I quoted "same", because there are some differences between char * array and char array[]. If you want to read more, take a look at C: differences between char pointer and array

In java how to get substring from a string till a character c?

This could help:

public static String getCorporateID(String fileName) {

    String corporateId = null;

    try {
        corporateId = fileName.substring(0, fileName.indexOf("_"));
        // System.out.println(new Date() + ": " + "Corporate:
        // "+corporateId);
        return corporateId;
    } catch (Exception e) {
        corporateId = null;
        e.printStackTrace();
    }

    return corporateId;
}

How to wait for async method to complete?

Here is a workaround using a flag:

//outside your event or method, but inside your class
private bool IsExecuted = false;

private async Task MethodA()
{

//Do Stuff Here

IsExecuted = true;
}

.
.
.

//Inside your event or method

{
await MethodA();

while (!isExecuted) Thread.Sleep(200); // <-------

await MethodB();
}