Programs & Examples On #Updatable views

How to display list of repositories from subversion server

Doesn't your access to SVN work just like a Web service? When I access the top directory of my SVN server, I get a page that's essentially a Table Of Contents of the whole works. It's an Unordered List that I can simply scan through.

EDIT: Here's how I would do it from the command line:

wget http://user:password@svn-url/ -O - | grep \<li\>

Get date from input form within PHP

    <?php
if (isset($_POST['birthdate'])) {
    $timestamp = strtotime($_POST['birthdate']); 
    $date=date('d',$timestamp);
    $month=date('m',$timestamp);
    $year=date('Y',$timestamp);
}
?>  

Finding index of character in Swift String

Swift 5.0

public extension String {  
  func indexInt(of char: Character) -> Int? {
    return firstIndex(of: char)?.utf16Offset(in: self)
  }
}

Swift 4.0

public extension String {  
  func indexInt(of char: Character) -> Int? {
    return index(of: char)?.encodedOffset        
  }
}

Swift's guard keyword

From Apple documentation:

Guard Statement

A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.

Synatx:

guard condition else {
    statements
}

Advantage:

1. By using guard statement we can get rid of deeply nested conditionals whose sole purpose is validating a set of requirements.

2. It was designed specifically for exiting a method or function early.

if you use if let below is the code how it looks.

  let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

        if error == nil {
            if let  statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 {
                if let data = data {

                    //Process Data Here.
                    print("Data: \(data)")

                } else {
                    print("No data was returned by the request!")
                }
            } else {
                print("Your request returned a status code other than 2XX!")
            }
        } else {
            print("Error Info: \(error.debugDescription)")
        }
    }
    task.resume()

Using guard you can transfer control out of a scope if one or more conditions aren't met.

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            /* GUARD: was there an error? */
            guard (error == nil) else {
                print("There was an error with your request: \(error)")
                return
            }

            /* GUARD: Did we get a successful 2XX response? */
            guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
                print("Your request returned a status code other than 2XX!")
                return
            }

            /* GUARD: was there any data returned? */
            guard let data = data else {
                print("No data was returned by the request!")
                return
            }

            //Process Data Here.
            print("Data: \(data)")
}
task.resume()

Reference:

1. Swift 2: Exit Early With guard 2. Udacity 3. Guard Statement

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

Scrollview vertical and horizontal in android

Try this

<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:id="@+id/Sview" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        xmlns:android="http://schemas.android.com/apk/res/android">
<HorizontalScrollView 
   android:id="@+id/hview" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content">
<ImageView .......
 [here xml code for image]
</ImageView>
</HorizontalScrollView>
</ScrollView>

How to iterate over associative arrays in Bash

declare -a arr
echo "-------------------------------------"
echo "Here another example with arr numeric"
echo "-------------------------------------"
arr=( 10 200 3000 40000 500000 60 700 8000 90000 100000 )

echo -e "\n Elements in arr are:\n ${arr[0]} \n ${arr[1]} \n ${arr[2]} \n ${arr[3]} \n ${arr[4]} \n ${arr[5]} \n ${arr[6]} \n ${arr[7]} \n ${arr[8]} \n ${arr[9]}"

echo -e " \n Total elements in arr are : ${arr[*]} \n"

echo -e " \n Total lenght of arr is : ${#arr[@]} \n"

for (( i=0; i<10; i++ ))
do      echo "The value in position $i for arr is [ ${arr[i]} ]"
done

for (( j=0; j<10; j++ ))
do      echo "The length in element $j is ${#arr[j]}"
done

for z in "${!arr[@]}"
do      echo "The key ID is $z"
done
~

How to create separate AngularJS controller files?

Not so graceful, but the very much simple in implementation solution - using global variable.

In the "first" file:


window.myApp = angular.module("myApp", [])
....

in the "second" , "third", etc:


myApp.controller('MyController', function($scope) {
    .... 
    }); 

Java client certificates over HTTPS/SSL

If you are dealing with a web service call using the Axis framework, there is a much simpler answer. If all want is for your client to be able to call the SSL web service and ignore SSL certificate errors, just put this statement before you invoke any web services:

System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory");

The usual disclaimers about this being a Very Bad Thing to do in a production environment apply.

I found this at the Axis wiki.

Converting cv::Mat to IplImage*

cv::Mat is the new type introduce in OpenCV2.X while the IplImage* is the "legacy" image structure.

Although, cv::Mat does support the usage of IplImage in the constructor parameters, the default library does not provide function for the other way. You will need to extract the image header information manually. (Do remember that you need to allocate the IplImage structure, which is lack in your example).

What does the "+" (plus sign) CSS selector mean?

The + sign means select an "adjacent sibling"

For example, this style will apply from the second <p>:

_x000D_
_x000D_
p + p {
   font-weight: bold;
} 
_x000D_
<div>
   <p>Paragraph 1</p>
   <p>Paragraph 2</p>
</div>
_x000D_
_x000D_
_x000D_


Example

See this JSFiddle and you will understand it: http://jsfiddle.net/7c05m7tv/ (Another JSFiddle: http://jsfiddle.net/7c05m7tv/70/)


Browser Support

Adjacent sibling selectors are supported in all modern browsers.


Learn more

How to start a background process in Python?

Use subprocess.Popen() with the close_fds=True parameter, which will allow the spawned subprocess to be detached from the Python process itself and continue running even after Python exits.

https://gist.github.com/yinjimmy/d6ad0742d03d54518e9f

import os, time, sys, subprocess

if len(sys.argv) == 2:
    time.sleep(5)
    print 'track end'
    if sys.platform == 'darwin':
        subprocess.Popen(['say', 'hello'])
else:
    print 'main begin'
    subprocess.Popen(['python', os.path.realpath(__file__), '0'], close_fds=True)
    print 'main end'

LINQ query to return a Dictionary<string, string>

Look at the ToLookup and/or ToDictionary extension methods.

MongoDB via Mongoose JS - What is findByID?

findById is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here.

Example:

// Search by ObjectId
var id = "56e6dd2eb4494ed008d595bd";
UserModel.findById(id, function (err, user) { ... } );

Functionally, it's the same as calling:

UserModel.findOne({_id: id}, function (err, user) { ... });

Note that Mongoose will cast the provided id value to the type of _id as defined in the schema (defaulting to ObjectId).

How to set session timeout dynamically in Java web applications?

Is there a way to set the session timeout programatically

There are basically three ways to set the session timeout value:

  • by using the session-timeout in the standard web.xml file ~or~
  • in the absence of this element, by getting the server's default session-timeout value (and thus configuring it at the server level) ~or~
  • programmatically by using the HttpSession. setMaxInactiveInterval(int seconds) method in your Servlet or JSP.

But note that the later option sets the timeout value for the current session, this is not a global setting.

How to check if an environment variable exists and get its value?

NEW_VAR=""
if [[ ${ENV_VAR} && ${ENV_VAR-x} ]]; then
  NEW_VAR=${ENV_VAR}
else
  NEW_VAR="new value"
fi

Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?

This limitation, which was only due to historical, code legacy reasons, has been lifted in recent versions of MySQL:

Changes in MySQL 5.6.5 (2012-04-10, Milestone 8)

Previously, at most one TIMESTAMP column per table could be automatically initialized or updated to the current date and time. This restriction has been lifted. Any TIMESTAMP column definition can have any combination of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses. In addition, these clauses now can be used with DATETIME column definitions. For more information, see Automatic Initialization and Updating for TIMESTAMP and DATETIME.

http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html

Conversion hex string into ascii in bash command line

The echo -e must have been failing for you because of wrong escaping. The following code works fine for me on a similar output from your_program with arguments:

echo -e $(your_program with arguments | sed -e 's/0x\(..\)\.\?/\\x\1/g')

Please note however that your original hexstring consists of non-printable characters.

How to wait in a batch script?

What about:

@echo off
set wait=%1
echo waiting %wait% s
echo wscript.sleep %wait%000 > wait.vbs
wscript.exe wait.vbs
del wait.vbs

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

To determine your server's support for .NET Framework 4.5 and later versions (tested through 4.5.2): If you don't have Registry access on the server, but have app publish rights to that server, create an MVC 5 app with a trivial controller, like this:

using System.Web.Mvc;

namespace DotnetVersionTest.Controllers
{
    public class DefaultController : Controller
    {
        public string Index()
        {
            return "simple .NET version test...";
        }
    }
}

Then in your Web.config, walk through the desired .NET Framework versions in the following section, changing the targetFramework values as desired:

<system.web>
    <customErrors mode="Off"/>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
</system.web>

Publish each target to your server, then browse to <app deploy URL>/Default. If your server supports the target framework, then the simple string will display from your trivial Controller. If not, you'll receive an error like the following:

Example of unsupported .NET 4.5.2 on server

So in this case, my target server doesn't yet support .NET Framework 4.5.2.

How do I run msbuild from the command line using Windows SDK 7.1?

Your bat file could be like:

CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319

msbuild C:\Users\mmaratt\Desktop\BladeTortoise\build\ALL_BUILD.vcxproj

PAUSE

EXIT

CodeIgniter: 404 Page Not Found on Live Server

I had the same problem. Changing controlers first letter to uppercase helped.

How can I set up an editor to work with Git on Windows?

This is the one symptom of greater issues. Notably that you have something setting TERM=dumb. Other things that don't work properly are the less command which says you don't have a fully functional terminal.

It seems like this is most commonly caused by having TERM set to something in your global Windows environment variables. For me, the issue came up when I installed Strawberry Perl some information about this is on the msysgit bug for this problem as well as several solutions.

The first solution is to fix it in your ~/.bashrc by adding:

export TERM=msys

You can do this from the Git Bash prompt like so:

echo "export TERM=msys" >> ~/.bashrc

The other solution, which ultimately is what I did because I don't care about Strawberry Perl's reasons for adding TERM=dumb to my environment settings, is to go and remove the TERM=dumb as directed in this comment on the msysgit bug report.

Control Panel/System/Advanced/Environment Variables... (or similar, depending on your version of Windows) is where sticky environment variables are set on Windows. By default, TERM is not set. If TERM is set in there, then you (or one of the programs you have installed - e.g. Strawberry Perl) has set it. Delete that setting, and you should be fine.

Similarly if you use Strawberry Perl and care about the CPAN client or something like that, you can leave the TERM=dumb alone and use unset TERM in your ~/.bashrc file which will have a similar effect to setting an explicit term as above.

Of course, all the other solutions are correct in that you can use git config --global core.editor $MYFAVORITEEDITOR to make sure that Git uses your favorite editor when it needs to launch one for you.

How to get pip to work behind a proxy server

At least for pip 1.3.1, it honors the http_proxy and https_proxy environment variables. Make sure you define both, as it will access the PYPI index using https.

export https_proxy="http://<proxy.server>:<port>"
pip install TwitterApi

Prime numbers between 1 to 100 in C Programming Language

#include<stdio.h>
main()
{
    int i,j,k;
    for(i=2;i<=100;i++)
    {
        k=0;
        for(j=2;j<=i;j++)
        {
            if(i%j==0)
            k++;
        }
        if(k==1)
        printf("%d\t",i);
    }
}

Extract the last substring from a cell

Try this:

Right(RC[-1],Len(RC[-1])-InStrRev(RC[-1]," "))

Catching "Maximum request length exceeded"

After tag

<security>
     <requestFiltering>
         <requestLimits maxAllowedContentLength="4500000" />
     </requestFiltering>
</security>

add the following tag

 <httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" subStatusCode="13" />
  <error statusCode="404" subStatusCode="13" prefixLanguageFilePath="" path="http://localhost/ErrorPage.aspx" responseMode="Redirect" />
</httpErrors>

you can add the Url to the error page...

Where does pip install its packages?

One can import the package then consult its help

import statsmodels
help(sm)

At the very bottom of the help there is a section FILE that indicates where this package was installed.

This solution was tested with at least matplotlib (3.1.2) and statsmodels (0.11.1) (python 3.8.2).

How to take off line numbers in Vi?

For turning off line numbers, any of these commands will work:

  1. :set nu!
  2. :set nonu
  3. :set number!
  4. :set nonumber

Run Executable from Powershell script with parameters

Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.

$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'

& $app $arg1 $arg2 $arg3

How to set up java logging using a properties file? (java.util.logging)

I have tried your code in above code don't use [preferences.load(configFile);] statement and it will work.here is running sample code

public static void main(String[]s)
{

    Logger log = Logger.getLogger("MyClass");
    try {
    FileInputStream fis =  new FileInputStream("p.properties");
    LogManager.getLogManager().readConfiguration(fis);
    log.setLevel(Level.FINE);
    log.addHandler(new java.util.logging.ConsoleHandler());
    log.setUseParentHandlers(false);

    log.info("starting myApp");
    fis.close();

    } 
    catch(IOException e) {
    e.printStackTrace();
    }
}

How to display Wordpress search results?

WordPress include tags, categories and taxonomies in search results

This code is taken from http://atiblog.com/custom-search-results/

Some functions here are taken from twentynineteen theme.Because it is made on this theme.

This code example will help you to include tags, categories or any custom taxonomy in your search. And show the posts contaning these tags or categories.

You need to modify your search.php of your theme to do so.

<?php
$search=get_search_query();
$all_categories = get_terms( array('taxonomy' => 'category','hide_empty' => true) ); 
$all_tags = get_terms( array('taxonomy' => 'post_tag','hide_empty' => true) );
//if you have any custom taxonomy
$all_custom_taxonomy = get_terms( array('taxonomy' => 'your-taxonomy-slug','hide_empty' => true) );

$mcat=array();
$mtag=array();
$mcustom_taxonomy=array();

foreach($all_categories as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcat,$all->term_id);
}
}

foreach($all_tags as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mtag,$all->term_id);
}
}

foreach($all_custom_taxonomy as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcustom_taxonomy,$all->term_id);
}
}

$matched_posts=array();
$args1= array( 'post_status' => 'publish','posts_per_page' => -1,'tax_query' =>array('relation' => 'OR',array('taxonomy' => 'category','field' => 'term_id','terms' =>$mcat),array('taxonomy' => 'post_tag','field' => 'term_id','terms' =>$mtag),array('taxonomy' => 'custom_taxonomy','field' => 'term_id','terms' =>$mcustom_taxonomy)));

$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
array_push($matched_posts,get_the_id());
//echo '<li>' . get_the_id() . '</li>';
}
wp_reset_postdata();
} else {

}

?>
<?php
// now we will do the normal wordpress search
$query2 = new WP_Query( array( 's' => $search,'posts_per_page' => -1 ) );
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
array_push($matched_posts,get_the_id());
}
wp_reset_postdata();
} else {

}
$matched_posts= array_unique($matched_posts);
$matched_posts=array_values(array_filter($matched_posts));
//print_r($matched_posts);
?>

<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query3 = new WP_Query( array( 'post_type'=>'any','post__in' => $matched_posts ,'paged' => $paged) );
if ( $query3->have_posts() ) {
while ( $query3->have_posts() ) {
$query3->the_post();
get_template_part( 'template-parts/content/content', 'excerpt' );
}
twentynineteen_the_posts_navigation();
wp_reset_postdata();
} else {

}
?>

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

It's worth noting that this error can also happen if the target table or column you're using in the REFERENCES portion simply doesn't exist.

Closing Applications

for me best solotion this is

 Thread.CurrentThread.Abort();

and force close app.

Max retries exceeded with URL in requests

Adding my own experience :

r = requests.get(download_url)

when I tried to download a file specified in the url.

The error was

HTTPSConnectionPool(host, port=443): Max retries exceeded with url (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

I corrected it by adding verify = False in the function as follows :

r = requests.get(download_url + filename)
open(filename, 'wb').write(r.content)

CSS Animation and Display None

You can manage to have a pure CSS implementation with max-height

#main-image{
    max-height: 0;
    overflow: hidden;
    background: red;
   -prefix-animation: slide 1s ease 3.5s forwards;
}

@keyframes slide {
  from {max-height: 0;}
  to {max-height: 500px;}
}

You might have to also set padding, margin and border to 0, or simply padding-top, padding-bottom, margin-top and margin-bottom.

I updated the demo of Duopixel here : http://jsfiddle.net/qD5XX/231/

How to update core-js to core-js@3 dependency?

How about reinstalling the node module? Go to the root directory of the project and remove the current node modules and install again.

These are the commands : rm -rf node_modules npm install

OR

npm uninstall -g react-native-cli and

npm install -g react-native-cli

Python: tf-idf-cosine: to find document similarity

Here is a function that compares your test data against the training data, with the Tf-Idf transformer fitted with the training data. Advantage is that you can quickly pivot or group by to find the n closest elements, and that the calculations are down matrix-wise.

def create_tokenizer_score(new_series, train_series, tokenizer):
    """
    return the tf idf score of each possible pairs of documents
    Args:
        new_series (pd.Series): new data (To compare against train data)
        train_series (pd.Series): train data (To fit the tf-idf transformer)
    Returns:
        pd.DataFrame
    """

    train_tfidf = tokenizer.fit_transform(train_series)
    new_tfidf = tokenizer.transform(new_series)
    X = pd.DataFrame(cosine_similarity(new_tfidf, train_tfidf), columns=train_series.index)
    X['ix_new'] = new_series.index
    score = pd.melt(
        X,
        id_vars='ix_new',
        var_name='ix_train',
        value_name='score'
    )
    return score

train_set = pd.Series(["The sky is blue.", "The sun is bright."])
test_set = pd.Series(["The sun in the sky is bright."])
tokenizer = TfidfVectorizer() # initiate here your own tokenizer (TfidfVectorizer, CountVectorizer, with stopwords...)
score = create_tokenizer_score(train_series=train_set, new_series=test_set, tokenizer=tokenizer)
score

   ix_new   ix_train    score
0   0       0       0.617034
1   0       1       0.862012

How do I format a number with commas in T-SQL?

/*
  #------------------------------------------------------------------------#
  #            SQL Query Script                                            #
  #            ----------------                                            #
  # Funcion.:  dbo.fn_nDerecha ( Numero, Pos_Enteros, Pos_Decimales )      #
  #    Numero        : es el Numero o Valor a formatear                    #
  #    Pos_Enteros   : es la cantidad posiciones para Enteros              #
  #    Pos_Decimales : es la cantidad posiciones para Decimales            #
  #                                                                        #
  # OBJETIVO:  Formatear los Numeros con Coma y Justificado a la Derecha   #
  #  Por Ejemplo:                                                          #
  #   dbo.fn_nDerecha ( Numero, 9, 2 )         Resultado = ---,---,--9.99  #
  #               dado  Numero = 1234.56       Resultado =       1,234.56  #
  #               dado  Numero = -1.56         Resultado =          -1.56  #
  #               dado  Numero = -53783423.56  Resultado = -53,783,423.56  #
  #                                                                        #
  # Autor...:  Francisco Eugenio Cabrera Perez                             #
  # Fecha...:  Noviembre 25, 2015                                          #
  # Pais....:  Republica Dominicana                                        #
  #------------------------------------------------------------------------#
*/



CREATE FUNCTION [dbo].[fn_nDerecha]
(
    -- Agregue Argumentos, para personalizar la funcion a su conveniencia
    @Numero_str    varchar(max)
   ,@Pos_Enteros   int
   ,@Pos_Decimales int
)
RETURNS varchar(max)
AS
BEGIN
  --  Declare la variable del RETURN aqui, en este caso es RESULT
  declare @RESULTADO varchar(max)
  set     @RESULTADO = '****'

  -----------------------------------------------  --
  declare @Numero_num numeric(28,12)
  set     @Numero_num =
  (
  case when isnumeric(@Numero_str) = 0 
       then 0
       else round (convert( numeric(28,12), @Numero_str), @Pos_Decimales)
  end
  )
  --  -----------------------------------------------  --
  --  Aumenta @Pos_Enteros de @RESULTADO,
  --      si las posiciones de Enteros del dato @Numero_str es Mayor...
  --
  declare   @Num_Pos_Ent int
  set       @Num_Pos_Ent = len ( convert( varchar, convert(int, abs(@Numero_num) ) ) )
  --
  declare   @Pos_Ent_Mas int
  set       @Pos_Ent_Mas =
  (
  case when @Num_Pos_Ent > @Pos_Enteros
       then @Num_Pos_Ent - @Pos_Enteros
       else 0
  end
  )
  set       @Pos_Enteros = @Pos_Enteros + @Pos_Ent_Mas
  --
  --  -----------------------------------------------  --
  declare @p_Signo_ctd       int
  set     @p_Signo_ctd       = (case when @Numero_num < 1 then 1 else 0 end)
  --
  declare @p_Comas_ctd       int
  set     @p_Comas_ctd       = ( @Pos_Enteros - 1 ) / 3
  --
  declare @p_Punto_ctd       int
  set     @p_Punto_ctd       = (case when @Pos_Decimales > 0 then 1 else 0 end)
  --
  declare @p_input_Longitud  int
  set     @p_input_Longitud  = ( @p_Signo_ctd + @Pos_Enteros ) +
                                 @p_Punto_ctd + @Pos_Decimales
  --
  declare @p_output_Longitud int
  set     @p_output_Longitud = ( @p_Signo_ctd + @Pos_Enteros   + @p_Comas_ctd )
                             + ( @p_Punto_ctd + @Pos_Decimales )
  --
  --  ===================================================================  --


  declare @Valor_str varchar(max)
  set     @Valor_str = str(@Numero_num, @p_input_Longitud, @Pos_Decimales)

  declare @V_Ent_str varchar(max)
  set     @V_Ent_str = 
  (case when @Pos_Decimales > 0 
        then substring( @Valor_str, 0, charindex('.', @Valor_str, 0) )
        else            @Valor_str end)
  --
  declare @V_Dec_str varchar(max)
  set     @V_Dec_str = 
  (case when @Pos_Decimales > 0 
        then '.' + right(@Valor_str, @Pos_Decimales)
        else '' end)
  --
  set @V_Ent_str = convert(VARCHAR, convert(money, @V_Ent_str), 1) 
  set @V_Ent_str = substring( @V_Ent_str, 0, charindex('.', @V_Ent_str, 0) )
  --


  set @RESULTADO    = @V_Ent_str + @V_Dec_str 
  --
  set @RESULTADO = ( replicate( ' ', @p_output_Longitud - len(@RESULTADO) ) + @RESULTADO )
  --

  --  ===================================================================  -

-- =================================================================== -

  RETURN @RESULTADO
END

  --  ===================================================================  --

/* This function needs 3 arguments: the First argument is the @Numero_str which the Number as data input, and the other 2 arguments specify how the information will be formatted for the output, those arguments are @Pos_Enteros and @Pos_Decimales which specify how many Integers and Decimal places you want to show for the Number you pass as input argument. */

Why do we have to override the equals() method in Java?

To answer your question, firstly I would strongly recommend looking at the Documentation.

Without overriding the equals() method, it will act like "==". When you use the "==" operator on objects, it simply checks to see if those pointers refer to the same object. Not if their members contain the same value.

We override to keep our code clean, and abstract the comparison logic from the If statement, into the object. This is considered good practice and takes advantage of Java's heavily Object Oriented Approach.

Which command in VBA can count the number of characters in a string variable?

Try this:

word = "habit"
findchar = 'b"
replacechar = ""
charactercount = len(word) - len(replace(word,findchar,replacechar))

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

The basis logic for such behavior is that Generics follow a mechanism of type erasure. So at run time you have no way if identifying the type of collection unlike arrays where there is no such erasure process. So coming back to your question...

So suppose there is a method as given below:

add(List<Animal>){
    //You can add List<Dog or List<Cat> and this will compile as per rules of polymorphism
}

Now if java allows caller to add List of type Animal to this method then you might add wrong thing into collection and at run time too it will run due to type erasure. While in case of arrays you will get a run time exception for such scenarios...

Thus in essence this behavior is implemented so that one cannot add wrong thing into collection. Now I believe type erasure exists so as to give compatibility with legacy java without generics....

Calling onclick on a radiobutton list using javascript

I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick event handler for the radio buttons:

<html>
 <head>
  <script type="text/javascript">
    window.onload = function() {

        var ex1 = document.getElementById('example1');
        var ex2 = document.getElementById('example2');
        var ex3 = document.getElementById('example3');

        ex1.onclick = handler;
        ex2.onclick = handler;
        ex3.onclick = handler;

    }

    function handler() {
        alert('clicked');
    }
  </script>
 </head>
 <body>
  <input type="radio" name="example1" id="example1" value="Example 1" />
  <label for="example1">Example 1</label>
  <input type="radio" name="example2" id="example2" value="Example 2" />
  <label for="example1">Example 2</label>
  <input type="radio" name="example3" id="example3" value="Example 3" />
  <label for="example1">Example 3</label>
 </body>
</html>

Creating a mock HttpServletRequest out of a url string?

Here it is how to use MockHttpServletRequest:

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

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

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

jQuery DataTable overflow and text-wrapping issues

Using the classes "responsive nowrap" on the table element should do the trick.

How to specify "does not contain" in dplyr filter

Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)

Setting the value of checkbox to true or false with jQuery

UPDATED: Using prop instead of attr

 <input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE"/>

 $('#vehicleChkBox').change(function(){
     cb = $(this);
     cb.val(cb.prop('checked'));
 });

OUT OF DATE:

Here is the jsfiddle

<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE" />

$('#vehicleChkBox').change(function(){
     if($(this).attr('checked')){
          $(this).val('TRUE');
     }else{
          $(this).val('FALSE');
     }
});

Java Regex to Validate Full Name allow only Spaces and Letters

check this out.

String name validation only accept alphabets and spaces
public static boolean validateLetters(String txt) {

    String regx = "^[a-zA-Z\\s]+$";
    Pattern pattern = Pattern.compile(regx,Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(txt);
    return matcher.find();

}

Omit rows containing specific column of NA

It is possible to use na.omit for data.table:

na.omit(data, cols = c("x", "z"))

Parse JSON from JQuery.ajax success data

Try the jquery each function to walk through your json object:

$.each(data,function(i,j){
    content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
    $('#ProductList').append(content);
});

When to use Interface and Model in TypeScript / Angular

Use Class instead of Interface that is what I discovered after all my research.

Why? A class alone is less code than a class-plus-interface. (anyway you may require a Class for data model)

Why? A class can act as an interface (use implements instead of extends).

Why? An interface-class can be a provider lookup token in Angular dependency injection.

from Angular Style Guide

Basically a Class can do all, what an Interface will do. So may never need to use an Interface.

Decode JSON with unknown structure

You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;

package main

import (
    "fmt"
    "encoding/json"
)

type Data struct {
    Votes *Votes `json:"votes"`
    Count string `json:"count,omitempty"`
}

type Votes struct {
    OptionA string `json:"option_A"`
}

func main() {
    s := `{ "votes": { "option_A": "3" } }`
    data := &Data{
        Votes: &Votes{},
    }
    err := json.Unmarshal([]byte(s), data)
    fmt.Println(err)
    fmt.Println(data.Votes)
    s2, _ := json.Marshal(data)
    fmt.Println(string(s2))
    data.Count = "2"
    s3, _ := json.Marshal(data)
    fmt.Println(string(s3))
}

https://play.golang.org/p/ScuxESTW5i

Based on your most recent comment you could address that by using an interface{} to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{} which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.

Laravel: Using try...catch with DB::transaction()

In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction() but instead wrap your code in DB::beginTransaction and DB::commit/DB::rollback():

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

See the transaction docs.

How to configure postgresql for the first time?

You probably need to update your pg_hba.conf file. This file controls what users can log in from what IP addresses. I think that the postgres user is pretty locked-down by default.

How does one check if a table exists in an Android SQLite database?

 // @param db, readable database from SQLiteOpenHelper

 public boolean doesTableExist(SQLiteDatabase db, String tableName) {
        Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '" + tableName + "'", null);

    if (cursor != null) {
        if (cursor.getCount() > 0) {
            cursor.close();
            return true;
        }
        cursor.close();
    }
    return false;
}
  • sqlite maintains sqlite_master table containing information of all tables and indexes in database.
  • So here we are simply running SELECT command on it, we'll get cursor having count 1 if table exists.

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

Why is there no Char.Empty like String.Empty?

use

myString.Replace ("c", "")

How to remove all CSS classes using jQuery/JavaScript?

$("#item").removeClass();

Calling removeClass with no parameters will remove all of the item's classes.


You can also use (but is not necessarily recommended, the correct way is the one above):

$("#item").removeAttr('class');
$("#item").attr('class', '');
$('#item')[0].className = '';

If you didn't have jQuery, then this would be pretty much your only option:

document.getElementById('item').className = '';

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

findByInventoryIdIn(List<Long> inventoryIdList) should do the trick.

The HTTP request parameter format would be like so:

Yes ?id=1,2,3
No  ?id=1&id=2&id=3

The complete list of JPA repository keywords can be found in the current documentation listing. It shows that IsIn is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn and IsNotIn.

How to output git log with the first line only?

Have you tried this?

git log --pretty=oneline --abbrev-commit

The problem is probably that you are missing an empty line after the first line. The command above usually works for me, but I just tested on a commit without empty second line. I got the same result as you: the whole message on one line.

Empty second line is a standard in git commit messages. The behaviour you see was probably implemented on purpose.

The first line of a commit message is meant to be a short description. If you cannot make it in a single line you can use several, but git considers everything before the first empty line to be the "short description". oneline prints the whole short description, so all your 3 rows.

How can I list all commits that changed a specific file?

On Linux you can use gitk for this.

It can be installed using "sudo apt-get install git-gui gitk". It can be used to see commits of a specific file by "gitk <Filename>".

How to stop event bubbling on checkbox click

In angularjs this should works:

event.preventDefault(); 
event.stopPropagation();

Is the 'as' keyword required in Oracle to define an alias?

There is no difference between both, AS is just a more explicit way of mentioning the alias which is good because some dependent libraries depends on this small keyword. e.g. JDBC 4.0. Depend on use of it, different behaviour can be observed.

See this. I would always suggest to use the full form of semantic to avoid such issues.

What's the console.log() of java?

Use the Android logging utility.

http://developer.android.com/reference/android/util/Log.html

Log has a bunch of static methods for accessing the different log levels. The common thread is that they always accept at least a tag and a log message.

Tags are a way of filtering output in your log messages. You can use them to wade through the thousands of log messages you'll see and find the ones you're specifically looking for.

You use the Log functions in Android by accessing the Log.x objects (where the x method is the log level). For example:

Log.d("MyTagGoesHere", "This is my log message at the debug level here");
Log.e("MyTagGoesHere", "This is my log message at the error level here");

I usually make it a point to make the tag my class name so I know where the log message was generated too. Saves a lot of time later on in the game.

You can see your log messages using the logcat tool for android:

adb logcat

Or by opening the eclipse Logcat view by going to the menu bar

Window->Show View->Other then select the Android menu and the LogCat view

get parent's view from a layout

The RelativeLayout (i.e. the ViewParent) should have a resource Id defined in the layout file (for example, android:id=@+id/myParentViewId). If you don't do that, the call to getId will return null. Look at this answer for more info.

Correct way to populate an Array with a Range in Ruby

This is another way:

irb> [*1..10]

=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

@import vs #import - iOS 7

Nice answer you can find in book Learning Cocoa with Objective-C (ISBN: 978-1-491-90139-7)

Modules are a new means of including and linking files and libraries into your projects. To understand how modules work and what benefits they have, it is important to look back into the history of Objective-C and the #import statement Whenever you want to include a file for use, you will generally have some code that looks like this:

#import "someFile.h"

Or in the case of frameworks:

#import <SomeLibrary/SomeFile.h>

Because Objective-C is a superset of the C programming language, the #import state- ment is a minor refinement upon C’s #include statement. The #include statement is very simple; it copies everything it finds in the included file into your code during compilation. This can sometimes cause significant problems. For example, imagine you have two header files: SomeFileA.h and SomeFileB.h; SomeFileA.h includes SomeFileB.h, and SomeFileB.h includes SomeFileA.h. This creates a loop, and can confuse the coimpiler. To deal with this, C programmers have to write guards against this type of event from occurring.

When using #import, you don’t need to worry about this issue or write header guards to avoid it. However, #import is still just a glorified copy-and-paste action, causing slow compilation time among a host of other smaller but still very dangerous issues (such as an included file overriding something you have declared elsewhere in your own code.)

Modules are an attempt to get around this. They are no longer a copy-and-paste into source code, but a serialised representation of the included files that can be imported into your source code only when and where they’re needed. By using modules, code will generally compile faster, and be safer than using either #include or #import.

Returning to the previous example of importing a framework:

#import <SomeLibrary/SomeFile.h>

To import this library as a module, the code would be changed to:

@import SomeLibrary;

This has the added bonus of Xcode linking the SomeLibrary framework into the project automatically. Modules also allow you to only include the components you really need into your project. For example, if you want to use the AwesomeObject component in the AwesomeLibrary framework, normally you would have to import everything just to use the one piece. However, using modules, you can just import the specific object you want to use:

@import AwesomeLibrary.AwesomeObject;

For all new projects made in Xcode 5, modules are enabled by default. If you want to use modules in older projects (and you really should) they will have to be enabled in the project’s build settings. Once you do that, you can use both #import and @import statements in your code together without any concern.

Tensorflow import error: No module named 'tensorflow'

for python 3.8 version go for anaconda navigator then go for environments --> then go for base(root)----> not installed from drop box--->then search for tensorflow then install it then run the program.......hope it may helpful

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

How to replace a substring of a string

You need to create the variable to assign the new value to, like this:

String str = string.replaceAll("abcd","dddd");

PHP call Class method / function

As th function is not using $this at all, you can add a static keyword just after public and then call

Functions::filter($_GET['params']);

Avoiding the creation of an object just for one method call

Spaces cause split in path with PowerShell

Just put ${yourpathtofile/folder}

PowerShell does not count spaces; to tell PowerShell to consider the whole path including spaces, add your path in between ${ & }.

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Buttons

Buttons are simple to disable as disabled is a button property which is handled by the browser:

<input type="submit" class="btn" value="My Input Submit" disabled/>
<input type="button" class="btn" value="My Input Button" disabled/>
<button class="btn" disabled>My Button</button>

To disable these with a custom jQuery function, you'd simply make use of fn.extend():

// Disable function
jQuery.fn.extend({
    disable: function(state) {
        return this.each(function() {
            this.disabled = state;
        });
    }
});

// Disabled with:
$('input[type="submit"], input[type="button"], button').disable(true);

// Enabled with:
$('input[type="submit"], input[type="button"], button').disable(false);

JSFiddle disabled button and input demo.

Otherwise you'd make use of jQuery's prop() method:

$('button').prop('disabled', true);
$('button').prop('disabled', false);

Anchor Tags

It's worth noting that disabled isn't a valid property for anchor tags. For this reason, Bootstrap uses the following styling on its .btn elements:

.btn.disabled, .btn[disabled] {
    cursor: default;
    background-image: none;
    opacity: 0.65;
    filter: alpha(opacity=65);
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
    color: #333;
    background-color: #E6E6E6;
}

Note how the [disabled] property is targeted as well as a .disabled class. The .disabled class is what is needed to make an anchor tag appear disabled.

<a href="http://example.com" class="btn">My Link</a>

Of course, this will not prevent links from functioning when clicked. The above link will take us to http://example.com. To prevent this, we can add in a simple piece of jQuery code to target anchor tags with the disabled class to call event.preventDefault():

$('body').on('click', 'a.disabled', function(event) {
    event.preventDefault();
});

We can toggle the disabled class by using toggleClass():

jQuery.fn.extend({
    disable: function(state) {
        return this.each(function() {
            var $this = $(this);
            $this.toggleClass('disabled', state);
        });
    }
});

// Disabled with:
$('a').disable(true);

// Enabled with:
$('a').disable(false);

JSFiddle disabled link demo.


Combined

We can then extend the previous disable function made above to check the type of element we're attempting to disable using is(). This way we can toggleClass() if it isn't an input or button element, or toggle the disabled property if it is:

// Extended disable function
jQuery.fn.extend({
    disable: function(state) {
        return this.each(function() {
            var $this = $(this);
            if($this.is('input, button, textarea, select'))
              this.disabled = state;
            else
              $this.toggleClass('disabled', state);
        });
    }
});

// Disabled on all:
$('input, button, a').disable(true);

// Enabled on all:
$('input, button, a').disable(false);

Full combined JSFiddle demo.

It's worth further noting that the above function will also work on all input types.

Insert data using Entity Framework model

I'm using EF6, and I find something strange,

Suppose Customer has constructor with parameter ,

if I use new Customer(id, "name"), and do

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name") );
    db.SaveChanges();
 }

It run through without error, but when I look into the DataBase, I find in fact that the data Is NOT be Inserted,

But if I add the curly brackets, use new Customer(id, "name"){} and do

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name"){} );
    db.SaveChanges();
 }

the data will then actually BE Inserted,

seems the Curly Brackets make the difference, I guess that only when add Curly Brackets, entity framework will recognize this is a real concrete data.

On postback, how can I check which control cause postback in Page_Init event

I see that there is already some great advice and methods suggest for how to get the post back control. However I found another web page (Mahesh blog) with a method to retrieve post back control ID.

I will post it here with a little modification, including making it an extension class. Hopefully it is more useful in that way.

/// <summary>
/// Gets the ID of the post back control.
/// 
/// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
/// </summary>
/// <param name = "page">The page.</param>
/// <returns></returns>
public static string GetPostBackControlId(this Page page)
{
    if (!page.IsPostBack)
        return string.Empty;

    Control control = null;
    // first we will check the "__EVENTTARGET" because if post back made by the controls
    // which used "_doPostBack" function also available in Request.Form collection.
    string controlName = page.Request.Params["__EVENTTARGET"];
    if (!String.IsNullOrEmpty(controlName))
    {
        control = page.FindControl(controlName);
    }
    else
    {
        // if __EVENTTARGET is null, the control is a button type and we need to
        // iterate over the form collection to find it

        // ReSharper disable TooWideLocalVariableScope
        string controlId;
        Control foundControl;
        // ReSharper restore TooWideLocalVariableScope

        foreach (string ctl in page.Request.Form)
        {
            // handle ImageButton they having an additional "quasi-property" 
            // in their Id which identifies mouse x and y coordinates
            if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
            {
                controlId = ctl.Substring(0, ctl.Length - 2);
                foundControl = page.FindControl(controlId);
            }
            else
            {
                foundControl = page.FindControl(ctl);
            }

            if (!(foundControl is IButtonControl)) continue;

            control = foundControl;
            break;
        }
    }

    return control == null ? String.Empty : control.ID;
}

Update (2016-07-22): Type check for Button and ImageButton changed to look for IButtonControl to allow postbacks from third party controls to be recognized.

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

This can now be done without JS, just pure CSS. So, anyone trying to do this for modern browsers should look into using position: sticky instead.

Currently, both Edge and Chrome have a bug where position: sticky doesn't work on thead or tr elements, however it's possible to use it on th elements, so all you need to do is just add this to your code:

th {
  position: sticky;
  top: 50px;  /* 0px if you don't have a navbar, but something is required */
  background: white;
}

Note: you'll need a background color for them, or you'll be able to see through the sticky title bar.

This has very good browser support.

Demo with your code (HTML unaltered, above 5 lines of CSS added, all JS removed):

_x000D_
_x000D_
body {_x000D_
    padding-top:50px;_x000D_
}_x000D_
table.floatThead-table {_x000D_
    border-top: none;_x000D_
    border-bottom: none;_x000D_
    background-color: #fff;_x000D_
}_x000D_
_x000D_
th {_x000D_
  position: sticky;_x000D_
  top: 50px;_x000D_
  background: white;_x000D_
}
_x000D_
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Fixed navbar -->_x000D_
<div class="navbar navbar-default navbar-fixed-top">_x000D_
    <div class="container">_x000D_
        <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span>_x000D_
 <span class="icon-bar"></span>_x000D_
 <span class="icon-bar"></span>_x000D_
_x000D_
            </button> <a class="navbar-brand" href="#">Project name</a>_x000D_
_x000D_
        </div>_x000D_
        <div class="collapse navbar-collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
                <li class="active"><a href="#">Home</a>_x000D_
_x000D_
                </li>_x000D_
                <li><a href="#about">About</a>_x000D_
_x000D_
                </li>_x000D_
                <li><a href="#contact">Contact</a>_x000D_
_x000D_
                </li>_x000D_
                <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>_x000D_
_x000D_
                    <ul class="dropdown-menu">_x000D_
                        <li><a href="#">Action</a>_x000D_
_x000D_
                        </li>_x000D_
                        <li><a href="#">Another action</a>_x000D_
_x000D_
                        </li>_x000D_
                        <li><a href="#">Something else here</a>_x000D_
_x000D_
                        </li>_x000D_
                        <li class="divider"></li>_x000D_
                        <li class="dropdown-header">Nav header</li>_x000D_
                        <li><a href="#">Separated link</a>_x000D_
_x000D_
                        </li>_x000D_
                        <li><a href="#">One more separated link</a>_x000D_
_x000D_
                        </li>_x000D_
                    </ul>_x000D_
                </li>_x000D_
            </ul>_x000D_
        </div>_x000D_
        <!--/.nav-collapse -->_x000D_
    </div>_x000D_
</div>_x000D_
<!-- Begin page content -->_x000D_
<div class="container">_x000D_
    <div class="page-header">_x000D_
         <h1>Sticky Table Headers</h1>_x000D_
_x000D_
    </div>_x000D_
    <p class="lead">If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.</p>_x000D_
    <p class="lead">If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.</p>_x000D_
    <p class="lead">If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.</p>_x000D_
    <table class="table table-striped sticky-header">_x000D_
        <thead>_x000D_
            <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
            <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
    <p class="lead">If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.</p>_x000D_
    <p class="lead">If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.</p>_x000D_
    <p class="lead">If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.</p>_x000D_
    <p class="lead">If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.</p>_x000D_
    <p class="lead">If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.</p>_x000D_
    <p class="lead">If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.</p>_x000D_
    <p class="lead">If the page is tall and all of the table is visible, then it won't stick. Make your viewport short.</p>_x000D_
     <h3>Table 2</h3>_x000D_
_x000D_
    <table class="table table-striped sticky-header">_x000D_
        <thead>_x000D_
            <tr>_x000D_
                <th>#</th>_x000D_
                <th>New Table</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
            <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can I loop through a table variable in T-SQL?

My two cents.. From KM.'s answer, if you want to drop one variable, you can do a countdown on @RowsToProcess instead of counting up.

DECLARE @RowsToProcess  int;

DECLARE @table1 TABLE (RowID int not null primary key identity(1,1), col1 int )  
INSERT into @table1 (col1) SELECT col1 FROM table2
SET @RowsToProcess = @@ROWCOUNT 

WHILE @RowsToProcess > 0 -- Countdown
BEGIN
    SELECT *
        FROM @table1
        WHERE RowID=@RowsToProcess

    --do your thing here--

    SET @RowsToProcess = @RowsToProcess - 1; -- Countdown
END

Bootstrap modal not displaying

Maybe a very rare scenario but I can't add a comment so leaving this here in case it helps someone: I had a similar issue dealing with someone else's code, modal wasn't displaying when I added ".fade" class, issue was some CSS for .modal-backdrop:

.modal-backdrop {display: none;}

After removing that, modal shows up fine.

Google Chrome form autofill and its yellow background

This fixes the problem on both Safari and Chrome

if(navigator.userAgent.toLowerCase().indexOf("chrome") >= 0 || navigator.userAgent.toLowerCase().indexOf("safari") >= 0){
window.setInterval(function(){
    $('input:-webkit-autofill').each(function(){
        var clone = $(this).clone(true, true);
        $(this).after(clone).remove();
    });
}, 20);
}

Good way of getting the user's location in Android

In my experience, I've found it best to go with the GPS fix unless it's not available. I don't know much about other location providers, but I know that for GPS there are a few tricks that can be used to give a bit of a ghetto precision measure. The altitude is often a sign, so you could check for ridiculous values. There is the accuracy measure on Android location fixes. Also if you can see the number of satellites used, this can also indicate the precision.

An interesting way of getting a better idea of the accuracy could be to ask for a set of fixes very rapidly, like ~1/sec for 10 seconds and then sleep for a minute or two. One talk I've been to has led to believe that some android devices will do this anyway. You would then weed out the outliers (I've heard Kalman filter mentioned here) and use some kind of centering strategy to get a single fix.

Obviously the depth you get to here depends on how hard your requirements are. If you have particularly strict requirement to get THE BEST location possible, I think you'll find that GPS and network location are as similar as apples and oranges. Also GPS can be wildly different from device to device.

Increase number of axis ticks

The upcoming version v3.3.0 of ggplot2 will have an option n.breaks to automatically generate breaks for scale_x_continuous and scale_y_continuous

    devtools::install_github("tidyverse/ggplot2")

    library(ggplot2)

    plt <- ggplot(mtcars, aes(x = mpg, y = disp)) +
      geom_point()

    plt + 
      scale_x_continuous(n.breaks = 5)

enter image description here

    plt + 
      scale_x_continuous(n.breaks = 10) +
      scale_y_continuous(n.breaks = 10)

enter image description here

Lazy Method for Reading Big File in Python?

To write a lazy function, just use yield:

def read_in_chunks(file_object, chunk_size=1024):
    """Lazy function (generator) to read a file piece by piece.
    Default chunk size: 1k."""
    while True:
        data = file_object.read(chunk_size)
        if not data:
            break
        yield data


with open('really_big_file.dat') as f:
    for piece in read_in_chunks(f):
        process_data(piece)

Another option would be to use iter and a helper function:

f = open('really_big_file.dat')
def read1k():
    return f.read(1024)

for piece in iter(read1k, ''):
    process_data(piece)

If the file is line-based, the file object is already a lazy generator of lines:

for line in open('really_big_file.dat'):
    process_data(line)

What is the best alternative IDE to Visual Studio

The other great thing about SharpDevelop is the ability to translate solutions between the two big managed .NET languages VB.NET and C#. I believe it doesn't work for "websites" but it does for web application projects.

Regex to remove all special characters from string?

It really depends on your definition of special characters. I find that a whitelist rather than a blacklist is the best approach in most situations:

tmp = Regex.Replace(n, "[^0-9a-zA-Z]+", "");

You should be careful with your current approach because the following two items will be converted to the same string and will therefore be indistinguishable:

"TRA-12:123"
"TRA-121:23"

jQuery checkbox checked state changed event

Try this "html-approach" which is acceptable for small JS projects

_x000D_
_x000D_
function msg(animal,is) {
  console.log(animal, is.checked);   // Do stuff
}
_x000D_
<input type="checkbox" oninput="msg('dog', this)" />Do you have a dog? <br>
<input type="checkbox" oninput="msg('frog',this)" />Do you have a frog?<br>
...
_x000D_
_x000D_
_x000D_

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

You are almost there, all you need is start anchor (^) and end anchor ($):

^[0-9]{1,45}$

\d is short for the character class [0-9]. You can use that as:

^\d{1,45}$

The anchors force the pattern to match entire input, not just a part of it.


Your regex [0-9]{1,45} looks for 1 to 45 digits, so string like foo1 also get matched as it contains 1.

^[0-9]{1,45} looks for 1 to 45 digits but these digits must be at the beginning of the input. It matches 123 but also 123foo

[0-9]{1,45}$ looks for 1 to 45 digits but these digits must be at the end of the input. It matches 123 but also foo123

^[0-9]{1,45}$ looks for 1 to 45 digits but these digits must be both at the start and at the end of the input, effectively it should be entire input.

Remove all line breaks from a long string of text

A method taking into consideration

  • additional white characters at the beginning/end of string
  • additional white characters at the beginning/end of every line
  • various end-line characters

it takes such a multi-line string which may be messy e.g.

test_str = '\nhej ho \n aaa\r\n   a\n '

and produces nice one-line string

>>> ' '.join([line.strip() for line in test_str.strip().splitlines()])
'hej ho aaa a'

UPDATE: To fix multiple new-line character producing redundant spaces:

' '.join([line.strip() for line in test_str.strip().splitlines() if line.strip()])

This works for the following too test_str = '\nhej ho \n aaa\r\n\n\n\n\n a\n '

What is the difference between a generative and a discriminative algorithm?

A generative algorithm model will learn completely from the training data and will predict the response.

A discriminative algorithm job is just to classify or differentiate between the 2 outcomes.

How to convert a string into double and vice versa?

convert text entered in textfield to integer

double mydouble=[_myTextfield.text doubleValue];

rounding to the nearest double

mydouble=(round(mydouble));

rounding to the nearest int(considering only positive values)

int myint=(int)(mydouble);

converting from double to string

myLabel.text=[NSString stringWithFormat:@"%f",mydouble];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];

converting from int to string

myLabel.text=[NSString stringWithFormat:@"%d",myint];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

Change the "WHILE" to "while". Because php is case sensitive like c/c++.

"No such file or directory" but it exists

I had this issue and the reason was EOL in some editors such as Notepad++. You can check it in Edit menu/EOL conversion. Unix(LF) should be selected. I hope it would be useful.

How to check for valid email address?

The Python standard library comes with an e-mail parsing function: email.utils.parseaddr().

It returns a two-tuple containing the real name and the actual address parts of the e-mail:

>>> from email.utils import parseaddr
>>> parseaddr('[email protected]')
('', '[email protected]')

>>> parseaddr('Full Name <[email protected]>')
('Full Name', '[email protected]')

>>> parseaddr('"Full Name with quotes and <[email protected]>" <[email protected]>')
('Full Name with quotes and <[email protected]>', '[email protected]')

And if the parsing is unsuccessful, it returns a two-tuple of empty strings:

>>> parseaddr('[invalid!email]')
('', '')

An issue with this parser is that it's accepting of anything that is considered as a valid e-mail address for RFC-822 and friends, including many things that are clearly not addressable on the wide Internet:

>>> parseaddr('invalid@example,com') # notice the comma
('', 'invalid@example')

>>> parseaddr('invalid-email')
('', 'invalid-email')

So, as @TokenMacGuy put it, the only definitive way of checking an e-mail address is to send an e-mail to the expected address and wait for the user to act on the information inside the message.

However, you might want to check for, at least, the presence of an @-sign on the second tuple element, as @bvukelic suggests:

>>> '@' in parseaddr("invalid-email")[1]
False

If you want to go a step further, you can install the dnspython project and resolve the mail servers for the e-mail domain (the part after the '@'), only trying to send an e-mail if there are actual MX servers:

>>> from dns.resolver import query
>>> domain = 'foo@[email protected]'.rsplit('@', 1)[-1]
>>> bool(query(domain, 'MX'))
True
>>> query('example.com', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NoAnswer
>>> query('not-a-domain', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NXDOMAIN

You can catch both NoAnswer and NXDOMAIN by catching dns.exception.DNSException.

And Yes, foo@[email protected] is a syntactically valid address. Only the last @ should be considered for detecting where the domain part starts.

Find (and kill) process locking port 3000 on Mac

TL;DR:

lsof -ti tcp:3000 -sTCP:LISTEN | xargs kill

If you're in a situation where there are both clients and servers using the port, e.g.:

$ lsof -i tcp:3000
COMMAND     PID         USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
node       2043 benjiegillam   21u  IPv4 0xb1b4330c68e5ad61      0t0  TCP localhost:3000->localhost:52557 (ESTABLISHED)
node       2043 benjiegillam   22u  IPv4 0xb1b4330c8d393021      0t0  TCP localhost:3000->localhost:52344 (ESTABLISHED)
node       2043 benjiegillam   25u  IPv4 0xb1b4330c8eaf16c1      0t0  TCP localhost:3000 (LISTEN)
Google    99004 benjiegillam  125u  IPv4 0xb1b4330c8bb05021      0t0  TCP localhost:52557->localhost:3000 (ESTABLISHED)
Google    99004 benjiegillam  216u  IPv4 0xb1b4330c8e5ea6c1      0t0  TCP localhost:52344->localhost:3000 (ESTABLISHED)

then you probably don't want to kill both.

In this situation you can use -sTCP:LISTEN to only show the pid of processes that are listening. Combining this with the -t terse format you can automatically kill the process:

lsof -ti tcp:3000 -sTCP:LISTEN | xargs kill

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

For imported maven project and JDK 1.7 do the following:

  1. Delete project from Eclipse (keep files)
  2. Delete .settings directory, .project and .classpath files inside your project directory.
  3. Modify your pom.xml file, add following properties (make sure following settings are not overridden by explicit maven-compiler-plugin definition in your POM)

    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    
  4. Import updated project into Eclipse.

LinearLayout not expanding inside a ScrollView

All the answers here didn't work (completely) for me. Just to recap what we wanna do for a complete answer: We have a ScrollView, supposedly filling the device's viewport, thus we set fillViewport to "true" in the layout xml. Then, inside the ScrollView, we have a LinearLayout containing everything else, and that LinearLayout should be at least as high as its parent ScrollView, so stuff that's supposed to be on the bottom (of the LinearLayout) is actually, as we want it, at the bottom of the screen (or at the bottom of the ScrollView, in case the LinearLayout's content has more hight than the screen.

Example activity_main.xml layout:

<ScrollView
    android:id="@+id/layout_scrollwrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    android:layout_alignParentTop="true"
    android:layout_above="@+id/layout_footer"
    >
<LinearLayout
    android:id="@+id/layout_scrollwrapper_inner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
...content which might or might not be higher than screen height...
</LinearLayout>
</ScrollView>

Then, in the activity's onCreate, we "wait" for the LinearLayout's layouting to be done (implying it's parent's layouting is also already done) and then set it's minimum height to the ScrollView's height. Thus it also works in case the ScrollView does not occupy the whole screen height. Whether you call .post(...) on the ScrollView or the inner LinearLayout should not make that much of a difference, if one doesn't work for you, try the other.

public class MainActivity extends AppCompatActivity {

@Override // Activity
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LinearLayout linearLayoutWrapper = findViewById(R.id.layout_scrollwrapper_inner);

    ...

    linearLayoutWrapper.post(() -> {
        linearLayoutWrapper.setMinimumHeight(((ScrollView)linearLayoutWrapper.getParent()).getHeight());
    });
}
...
}

Sadly, it's not an xml-only solution, but it works well enough for me, hope it also helps some other tortured android dev scouring the interwebs in search for a solution to this problem ;D

How to install PostgreSQL's pg gem on Ubuntu?

I was trying to setup a Rails project in my freshly installed Ubuntu 16.04. I ran into the same issue while running bundle. Running

sudo apt-get install aptitude

followed by

sudo apt-get install libpq-dev

Solved it for me.

Safely turning a JSON string into an object

Just for fun, here is a way using a function:

 jsonObject = (new Function('return ' + jsonFormatData))()

Could someone explain this for me - for (int i = 0; i < 8; i++)

for (int i = 0; i < 8; i++)

It's a for loop, which will execute the next statement a number of times, depending on the conditions inside the parenthesis.

for (int i = 0; i < 8; i++)

Start by setting i = 0

for (int i = 0; i < 8; i++)

Continue looping while i < 8.

for (int i = 0; i < 8; i++)

Every time you've been around the loop, increase i by 1.

For example;

for (int i = 0; i < 8; i++)
    do(i);

will call do(0), do(1), ... do(7) in order, and stop when i reaches 8 (ie i < 8 is false)

Common MySQL fields and their appropriate data types

Since you're going to be dealing with data of a variable length (names, email addresses), then you'd be wanting to use VARCHAR. The amount of space taken up by a VARCHAR field is [field length] + 1 bytes, up to max length 255, so I wouldn't worry too much about trying to find a perfect size. Take a look at what you'd imagine might be the longest length might be, then double it and set that as your VARCHAR limit. That said...:

I generally set email fields to be VARCHAR(100) - i haven't come up with a problem from that yet. Names I set to VARCHAR(50).

As the others have said, phone numbers and zip/postal codes are not actually numeric values, they're strings containing the digits 0-9 (and sometimes more!), and therefore you should treat them as a string. VARCHAR(20) should be well sufficient.

Note that if you were to store phone numbers as integers, many systems will assume that a number starting with 0 is an octal (base 8) number! Therefore, the perfectly valid phone number "0731602412" would get put into your database as the decimal number "124192010"!!

What value could I insert into a bit type column?

Generally speaking, for boolean or bit data types, you would use 0 or 1 like so:

UPDATE tbl SET bitCol = 1 WHERE bitCol = 0

See also:

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Just wishing to avoid the console error, I solved this using a similar approach to Artur's earlier answer, following these steps:

  1. Downloaded the YouTube Iframe API (from https://www.youtube.com/iframe_api) to a local yt-api.js file.
  2. Removed the code which inserted the www-widgetapi.js script.
  3. Downloaded the www-widgetapi.js script (from https://s.ytimg.com/yts/jsbin/www-widgetapi-vfl7VfO1r/www-widgetapi.js) to a local www-widgetapi.js file.
  4. Replaced the targetOrigin argument in the postMessage call which was causing the error in the console, with a "*" (indicating no preference - see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage).
  5. Appended the modified www-widgetapi.js script to the end of the yt-api.js script.

This is not the greatest solution (patched local script to maintain, losing control of where messages are sent) but it solved my issue.

Please see the security warning about removing the targetOrigin URI stated here before using this solution - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Patched yt-api.js example

How to validate an email address in PHP

Use below code:

// Variable to check
$email = "[email protected]";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo("Email is a valid email address");
} else {
  echo("Oppps! Email is not a valid email address");
}

What is the difference between JDK and JRE?

JDK includes the JRE plus command-line development tools such as compilers and debuggers that are necessary or useful for developing applets and applications.

JRE is basically the Java Virtual Machine where your Java programs run on. It also includes browser plugins for Applet execution.

JDK is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

So, Basically JVM < JRE < JDK as per @Jaimin Patel said.

How to generate and auto increment Id with Entity Framework

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

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

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

How to test if a file is a directory in a batch script?

You can do it like so:

IF EXIST %VAR%\NUL ECHO It's a directory

However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows:

FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory

The %%~si converts %%i to an 8.3 filename. To see all the other tricks you can perform with FOR variables enter HELP FOR at a command prompt.

(Note - the example given above is in the format to work in a batch file. To get it work on the command line, replace the %% with % in both places.)

jquery - is not a function error

When converting an ASP.Net webform prototype to a MVC site I got these errors:

TypeError: $(...).accordion is not a function
$("#accordion").accordion(


$('#dialog').dialog({
TypeError: $(...).dialog is not a function

It worked fine in the webforms. The problem/solution was this line in the _Layout.cshtml

@Scripts.Render("~/bundles/jquery")

Comment it out to see if the errors go away. Then fix it in the BundlesConfig:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

Git Push ERROR: Repository not found

I was getting the same error coz I change my github user name, then I do this:

git remote -v

then:

git remote set-url newname newurl 
git push -u origin master

this time I was able to push to the repository. I hope this helps.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

Changing the port number for the local development helped me Thanks @Rinay Ashokan. I have done all the trouble shooting and finally found that the project configurations are stored in the IIS express for the port number. enter image description here

How to pass arguments to entrypoint in docker-compose.yml

I was facing the same issue with jenkins ssh slave 'jenkinsci/ssh-slave'. However, my case was a bit complicated because it was necessary to pass an argument which contained spaces. I've managed to do it like below (entrypoint in dockerfile is in exec form):

command: ["some argument with space which should be treated as one"]

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

Java Garbage Collection Log messages

Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).

The command line option -verbose:gc causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:

[GC 325407K->83000K(776768K), 0.2300771 secs]
[GC 325816K->83372K(776768K), 0.2454258 secs]
[Full GC 267628K->83769K(776768K), 1.8479984 secs]

Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g., 325407K->83000K from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.

The next number in parentheses (e.g., (776768K) again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.

The last item on the line (e.g., 0.2300771 secs) indicates the time taken to perform the collection; in this case approximately a quarter of a second.

The format for the major collection in the third line is similar.

The format of the output produced by -verbose:gc is subject to change in future releases.

I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?

How to determine the encoding of text?

It is, in principle, impossible to determine the encoding of a text file, in the general case. So no, there is no standard Python library to do that for you.

If you have more specific knowledge about the text file (e.g. that it is XML), there might be library functions.

Windows batch command(s) to read first line from text file

uh? imo this is much simpler

  set /p texte=< file.txt  
  echo %texte%

How to parse month full form string using DateFormat in Java?

Just to top this up to the new Java 8 API:

DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM dd, yyyy").toFormatter();
TemporalAccessor ta = formatter.parse("June 27, 2007");
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
assertThat(d.getYear(), is(107));
assertThat(d.getMonth(), is(5));

A bit more verbose but you also see that the methods of Date used are deprecated ;-) Time to move on.

Disable a Button

If you want the button to stay static without the "pressed" appearance:

// Swift 2
editButton.userInteractionEnabled = false 

// Swift 3
editButton.isUserInteractionEnabled = false 

Remember:

1) Your IBOutlet is --> @IBOutlet weak var editButton: UIButton!

2) Code above goes in viewWillAppear

Read and Write CSV files including unicode with Python 2.7

Another alternative:

Use the code from the unicodecsv package ...

https://pypi.python.org/pypi/unicodecsv/

>>> import unicodecsv as csv
>>> from io import BytesIO
>>> f = BytesIO()
>>> w = csv.writer(f, encoding='utf-8')
>>> _ = w.writerow((u'é', u'ñ'))
>>> _ = f.seek(0)
>>> r = csv.reader(f, encoding='utf-8')
>>> next(r) == [u'é', u'ñ']
True

This module is API compatible with the STDLIB csv module.

How to drop SQL default constraint without knowing its name?

declare @table_name nvarchar(100)
declare @col_name nvarchar(100)
declare @constraint nvarchar(100)
set @table_name = N'TableName'
set @col_name = N'ColumnName'

IF EXISTS (select       c.*
    from        sys.columns c 
    inner join  sys.tables t on t.object_id = c.object_id
    where       t.name = @table_name
    and         c.name = @col_name) 
BEGIN

select @constraint=d.name
from 
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where 
t.name = @table_name
and c.name = @col_name

    IF LEN(ISNULL(@constraint, '')) <> 0
    BEGIN
        DECLARE @sqlcmd VARCHAR(MAX)
        SET @sqlcmd = 'ALTER TABLE ' + QUOTENAME(@table_name) + ' DROP CONSTRAINT' + 
        QUOTENAME(@constraint);
        EXEC (@sqlcmd);

    END

END
GO

Maven project.build.directory

You can find those maven properties in the super pom.

You find the jar here:

${M2_HOME}/lib/maven-model-builder-3.0.3.jar

Open the jar with 7-zip or some other archiver (or use the jar tool).

Navigate to

org/apache/maven/model

There you'll find the pom-4.0.0.xml.

It contains all those "short cuts":

<project>
    ...
    <build>
        <directory>${project.basedir}/target</directory>
        <outputDirectory>${project.build.directory}/classes</outputDirectory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
        <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
        <scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
        <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/resources</directory>
            </testResource>
        </testResources>
        ...
    </build>
    ...
</project>

Update

After some lobbying I am adding a link to the pom-4.0.0.xml. This allows you to see the properties without opening up the local jar file.

Search a text file and print related lines in Python?

searchfile = open("file.txt", "r")
for line in searchfile:
    if "searchphrase" in line: print line
searchfile.close()

To print out multiple lines (in a simple way)

f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

The comma in print l, prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.

Or better yet (stealing back from Mark Ransom):

with open("file.txt", "r") as f:
    searchlines = f.readlines()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

Swift Alamofire: How to get the HTTP response status code

you may check the following code for status code handler by alamofire

    let request = URLRequest(url: URL(string:"url string")!)    
    Alamofire.request(request).validate(statusCode: 200..<300).responseJSON { (response) in
        switch response.result {
        case .success(let data as [String:Any]):
            completion(true,data)
        case .failure(let err):
            print(err.localizedDescription)
            completion(false,err)
        default:
            completion(false,nil)
        }
    }

if status code is not validate it will be enter the failure in switch case

Check line for unprintable characters while reading text file

Just found out that with the Java NIO (java.nio.file.*) you can easily write:

List<String> lines=Files.readAllLines(Paths.get("/tmp/test.csv"), StandardCharsets.UTF_8);
for(String line:lines){
  System.out.println(line);
}

instead of dealing with FileInputStreams and BufferedReaders...

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query) $query is a string, the $result will be the resource

$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection

if(mysqli_num_rows($result) > 0 ){....}

UPDATE

Base in your edit just change:

if(is_resource($query) && mysqli_num_rows($query) > 0 ){
        $query = mysqli_fetch_assoc($query);
        echo $email . " email exists " .  $query["email"] . "\n";

By

if(is_resource($result) && mysqli_num_rows($result) == 1 ){
        $row = mysqli_fetch_assoc($result);
         echo $email . " email exists " .  $row["email"] . "\n";

and you will be fine

UPDATE 2

A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter

SELECT IF( EXISTS (
                  SELECT *
                  FROM `Table`
                  WHERE `email` = @Email)
          , 1, 0) as `Exist`

and retrieve the value in php

Pseudocodigo:

 $query = Call MYSQL_SP($EMAIL);
 $result = mysqli_query($conn,$query);
 $row = mysqli_fetch_array($result)
 $exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';

How to run python script on terminal (ubuntu)?

Sorry, Im a newbie myself and I had this issue:

./hello.py: line 1: syntax error near unexpected token "Hello World"' ./hello.py: line 1:print("Hello World")'

I added the file header for the python 'deal' as #!/usr/bin/python

Then simple executed the program with './hello.py'

How to truncate milliseconds off of a .NET DateTime

Instead of dropping the milliseconds then comparing, why not compare the difference?

DateTime x; DateTime y;
bool areEqual = (x-y).TotalSeconds == 0;

or

TimeSpan precision = TimeSpan.FromSeconds(1);
bool areEqual = (x-y).Duration() < precision;

Google Maps API v2: How to make markers clickable?

I have edited the given above example...

public class YourActivity extends implements OnMarkerClickListener
{
    ......

    private void setMarker()
    {
        .......
        googleMap.setOnMarkerClickListener(this);

        myMarker = googleMap.addMarker(new MarkerOptions()
                    .position(latLng)
                    .title("My Spot")
                    .snippet("This is my spot!")
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        ......
    }

    @Override
    public boolean onMarkerClick(Marker marker) {

       Toast.makeText(this,marker.getTitle(),Toast.LENGTH_LONG).show();
    }
}

How to parse JSON response from Alamofire API in Swift?

like above mention you can use SwiftyJSON library and get your values like i have done below

Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
    (request, response, data, error) in

var json = JSON(data: data!)

       println(json)   
       println(json["productList"][1])                 

}

my json product list return from script

{ "productList" :[

{"productName" : "PIZZA","id" : "1","productRate" : "120.00","productDescription" : "PIZZA AT 120Rs","productImage" : "uploads\/pizza.jpeg"},

{"productName" : "BURGER","id" : "2","productRate" : "100.00","productDescription" : "BURGER AT Rs 100","productImage" : "uploads/Burgers.jpg"}    
  ]
}

output :

{
  "productName" : "BURGER",
  "id" : "2",
  "productRate" : "100.00",
  "productDescription" : "BURGER AT Rs 100",
  "productImage" : "uploads/Burgers.jpg"
}

Android: textview hyperlink

android:autoLink="web" simply works if you have full links in your HTML. The following will be highlighted in blue and clickable:

Property [title] does not exist on this collection instance

$about = DB::where('page', 'about-me')->first(); 

in stead of get().

It works on my project. Thanks.

How do I get IntelliJ to recognize common Python modules?

This is how i solved my problem (i have imported the project and it was showing there only, newly created files were not showing those errors):

1) Command + alt + R (Control in case of windows

2) Debug window will appear, select your file and press right arrow (->) and choose Edit then press enter (Edit configuration setting window will appear)

3) Under configuration, at the bottom you can see the error (please select a module with a valid python sdk), So in Python Interpreter, check Use Specified Interpreter, then in drop down you select your Python version

(In case python is not there download python plugin for intelliJ using following link https://www.jetbrains.com/help/idea/2016.3/installing-updating-and-uninstalling-repository-plugins.html

4) Click on apply then close it.

Bingo it's done.

Common HTTPclient and proxy

Here is how to do that with the last version of HTTPClient (4.3.4)

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpHost target = new HttpHost("localhost", 443, "https");
        HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .build();
        HttpGet request = new HttpGet("/");
        request.setConfig(config);

        System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(target, request);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

CURRENT_DATE/CURDATE() not working as default DATE value

create table the_easy_way(
  capture_ts DATETIME DEFAULT CURRENT_TIMESTAMP,
  capture_dt DATE AS (DATE(capture_ts))
)

(MySQL 5.7)

How can one grab a stack trace in C?

There's backtrace(), and backtrace_symbols():

From the man page:

#include <execinfo.h>
#include <stdio.h>
...
void* callstack[128];
int i, frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (i = 0; i < frames; ++i) {
    printf("%s\n", strs[i]);
}
free(strs);
...

One way to use this in a more convenient/OOP way is to save the result of backtrace_symbols() in an exception class constructor. Thus, whenever you throw that type of exception you have the stack trace. Then, just provide a function for printing it out. For example:

class MyException : public std::exception {

    char ** strs;
    MyException( const std::string & message ) {
         int i, frames = backtrace(callstack, 128);
         strs = backtrace_symbols(callstack, frames);
    }

    void printStackTrace() {
        for (i = 0; i < frames; ++i) {
            printf("%s\n", strs[i]);
        }
        free(strs);
    }
};

...

try {
   throw MyException("Oops!");
} catch ( MyException e ) {
    e.printStackTrace();
}

Ta da!

Note: enabling optimization flags may make the resulting stack trace inaccurate. Ideally, one would use this capability with debug flags on and optimization flags off.

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

I was getting this error too, although my issue was that I kept switching between two corporate networks via my Virtual Machine, with different access credentials. I had to run the command prompt:

ipconfig /renew

After this my network issues were resolved and I could connect once again to SQL.

Install MySQL on Ubuntu without a password prompt

Another way to make it work:

echo "mysql-server-5.5 mysql-server/root_password password root" | debconf-set-selections
echo "mysql-server-5.5 mysql-server/root_password_again password root" | debconf-set-selections
apt-get -y install mysql-server-5.5

Note that this simply sets the password to "root". I could not get it to set a blank password using simple quotes '', but this solution was sufficient for me.

Based on a solution here.

JQuery add class to parent element

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

lodash multi-column sortBy descending

Is there some handy way of defining direction per column?

No. You cannot specify the sort order other than by a callback function that inverses the value. Not even this is possible for a multicolumn sort.

You might be able to do

 _.each(array_of_objects, function(o) {
     o.typeDesc = -o.type; // assuming a number
 });
 _.sortBy(array_of_objects, ['typeDesc', 'name'])

For everything else, you will need to resort to the native .sort() with a custom comparison function:

 array_of_objects.sort(function(a, b) {
     return a.type - b.type // asc
         || +(b.name>a.name)||-(a.name>b.name) // desc
         || …;
 });

Access denied for user 'test'@'localhost' (using password: YES) except root user

For annoying searching getting here after searching for this error message:

Access denied for user 'someuser@somewhere' (using password: YES)

The issue for me was not enclosing the password in quotes. eg. I needed to use -p'password' instead of -ppassword

Numpy, multiply array with scalar

Using .multiply() (ufunc multiply)

a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0 

np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])

How to select all textareas and textboxes using jQuery?

Simply use $(":input")

Example disabling all inputs (textarea, input text, etc):

_x000D_
_x000D_
$(":input").prop("disabled", true);
_x000D_
<form>_x000D_
  <textarea>Tetarea</textarea>_x000D_
  <input type="text" value="Text">_x000D_
  <label><input type="checkbox"> Checkbox</label>_x000D_
</form>_x000D_
_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Getting error "No such module" using Xcode, but the framework is there

For me, I fixed it be replacing any tilde (~) characters in my Custom Paths with $(HOME). Custom Paths are located in the Xcode preferences under the Locations tab.

Instantiating a generic class in Java

Use The Constructor.newInstance method. The Class.newInstance method has been deprecated since Java 9 to enhance compiler recognition of instantiation exceptions.

public class Foo<T> {   
    public Foo()
    {
        Class<T> newT = null; 
        instantiateNew(newT);
    }

    T instantiateNew(Class<?> clsT)
    {
        T newT;
        try {
            newT = (T) clsT.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return newT;
    }
}

Should try...catch go inside or outside a loop?

If it's inside, then you'll gain the overhead of the try/catch structure N times, as opposed to just the once on the outside.


Every time a Try/Catch structure is called it adds overhead to the execution of the method. Just the little bit of memory & processor ticks needed to deal with the structure. If you're running a loop 100 times, and for hypothetical sake, let's say the cost is 1 tick per try/catch call, then having the Try/Catch inside the loop costs you 100 ticks, as opposed to only 1 tick if it's outside of the loop.

Android webview slow

If there's only some few components of your webview that is slow or laggy, try adding this to the elements css:

transform: translate3d(0,0,0);
-webkit-transform: translate3d(0,0,0);

This has been the only speedhack that really had a effect on my webview. But be careful not to overuse it! (you can read more about the hack in this article.)

shell-script headers (#!/bin/sh vs #!/bin/csh)

This is known as a Shebang:

http://en.wikipedia.org/wiki/Shebang_(Unix)

#!interpreter [optional-arg]

A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).

When a shell executes the script it will use the specified interpreter.

Example:

#!/bin/bash
# file: foo.sh
echo 1

$ chmod u+x foo.sh
$ ./foo.sh
  1

Specify the date format in XMLGregorianCalendar

you don't need to specify a "SimpleDateFormat", it's simple: You must do specify the constant "DatatypeConstants.FIELD_UNDEFINED" where you don't want to show

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);

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

If you've definitely got an absolute path, use Path.GetDirectoryName(path).

If you might only get a relative name, use new FileInfo(path).Directory.FullName.

Note that Path and FileInfo are both found in the namespace System.IO.

How to check if there exists a process with a given pid in Python?

The following code works on both Linux and Windows, and not depending on external modules

import os
import subprocess
import platform
import re

def pid_alive(pid:int):
    """ Check For whether a pid is alive """


    system = platform.uname().system
    if re.search('Linux', system, re.IGNORECASE):
        try:
            os.kill(pid, 0)
        except OSError:
            return False
        else:
            return True
    elif re.search('Windows', system, re.IGNORECASE):
        out = subprocess.check_output(["tasklist","/fi",f"PID eq {pid}"]).strip()
        # b'INFO: No tasks are running which match the specified criteria.'

        if re.search(b'No tasks', out, re.IGNORECASE):
            return False
        else:
            return True
    else:
        raise RuntimeError(f"unsupported system={system}")

It can be easily enhanced in case you need

  1. other platforms
  2. other language

Why does 'git commit' not save my changes?

if you have a subfolder, which was cloned from other git-Repository, first you have to remove the $.git$ file from the child-Repository: rm -rf .git after that you can change to parent folder and use git add -A.

Creating a copy of a database in PostgreSQL

If the database has open connections, this script may help. I use this to create a test database from a backup of the live-production database every night. This assumes that you have an .SQL backup file from the production db (I do this within webmin).

#!/bin/sh

dbname="desired_db_name_of_test_enviroment"
username="user_name"
fname="/path to /ExistingBackupFileOfLive.sql"

dropdbcmp="DROP DATABASE $dbname"
createdbcmd="CREATE DATABASE $dbname WITH OWNER = $username "

export PGPASSWORD=MyPassword



echo "**********"
echo "** Dropping $dbname"
psql -d postgres -h localhost -U "$username" -c "$dropdbcmp"

echo "**********"
echo "** Creating database $dbname"
psql -d postgres -h localhost -U "$username" -c "$createdbcmd"

echo "**********"
echo "** Loading data into database"
psql -d postgres -h localhost -U "$username" -d "$dbname" -a -f "$fname"

Force IE9 to emulate IE8. Possible?

The 1st element as in no hard returns. A hard return I guess = an empty node/element in the DOM which becomes the 1st element disabling the doc compatability meta tag.

convert string into array of integers

If the numbers can be separated by more than one space, it is safest to split the string on one or more consecutive whitespace characters (which includes tabs and regular spaces). With a regular expression, this would be \s+.

You can then map each element using the Number function to convert it. Note that parseInt will not work (i.e. arr.map(parseInt)) because map passes three arguments to the mapping function: the element, the index, and the original array. parseInt accepts the base or radix as the second parameter, so it will end up taking the index as the base, often resulting in many NaNs in the result. However, Number ignores any arguments other than the first, so it works directly.

const str = '1\t\t2   3 4';
const result = str.split(/\s+/).map(Number); //[1,2,3,4]

You could also use an anonymous function for the mapping callback with the unary plus operator to convert each element to a number.

const str = '1\t\t2   3 4';
const result = str.split(/\s+/).map(x => +x); //[1,2,3,4]

With an anonymous function for the callback, you can decide what parameters to use, so parseInt can also work.

const str = '1\t\t2   3 4';
const result = str.split(/\s+/).map(x => parseInt(x)); //[1,2,3,4]

React-Router open Link in new tab

For external link simply use an achor in place of Link:

<a rel="noopener noreferrer" href="http://url.com" target="_blank">Link Here</a>

Hash Map in Python

streetno = { 1 : "Sachin Tendulkar",
            2 : "Dravid",
            3 : "Sehwag",
            4 : "Laxman",
            5 : "Kohli" }

And to retrieve values:

name = streetno.get(3, "default value")

Or

name = streetno[3]

That's using number as keys, put quotes around the numbers to use strings as keys.

Display the current time and date in an Android application

Calendar c = Calendar.getInstance();
int month=c.get(Calendar.MONTH)+1;
String sDate = c.get(Calendar.YEAR) + "-" + month+ "-" + c.get(Calendar.DAY_OF_MONTH) +
"T" + c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);

This will give date time format like 2010-05-24T18:13:00

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

If you are using laragon open the php.ini

In the interface of laragon menu-> php-> php.ini

when you open the file look for ; extension_dir = "./"

create another one without **; ** with the path of your php version to the folder ** ext ** for example

extension_dir = "C: \ laragon \ bin \ php \ php-7.3.11-Win32-VC15-x64 \ ext"

change it save it

How to align footer (div) to the bottom of the page?

A simple solution that i use, works from IE8+

Give min-height:100% on html so that if content is less then still page takes full view-port height and footer sticks at bottom of page. When content increases the footer shifts down with content and keep sticking to bottom.

JS fiddle working Demo: http://jsfiddle.net/3L3h64qo/2/

Css

html{
  position:relative; 
  min-height: 100%;
}
/*Normalize html and body elements,this style is just good to have*/
html,body{
  margin:0;
  padding:0;
}
.pageContentWrapper{
  margin-bottom:100px;/* Height of footer*/
} 
.footer{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height:100px;
    background:#ccc;
}

Html

   <html>
    <body>
        <div class="pageContentWrapper">
            <!-- All the page content goes here-->
        </div>
        <div class="footer">
        </div>
    </body>
    </html>

Changing the image source using jQuery

I made a codepen with exactly this functionality here. I will give you a breakdown of the code here as well.

Codepen

_x000D_
_x000D_
$(function() {

  //Listen for a click on the girl button
  $('#girl-btn').click(function() {

    // When the girl button has been clicked, change the source of the #square image to be the girl PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/girl.png");
  });

  //Listen for a click on the plane button
  $('#plane-btn').click(function() {

    // When the plane button has been clicked, change the source of the #square image to be the plane PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/airplane.png");
  });

  //Listen for a click on the fruit button
  $('#fruits-btn').click(function() {

    // When the fruits button has been clicked, change the source of the #square image to be the fruits PNG
    $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/fruits.png");
  });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<img src="https://homepages.cae.wisc.edu/~ece533/images/girl.png" id="square" />
<div>
  <button id="girl-btn">Girl</button>
  <button id="plane-btn">Plane</button>
  <button id="fruits-btn">Fruits</button>

  <a href="https://homepages.cae.wisc.edu/~ece533/images/">Source of Images</a>
</div>
_x000D_
_x000D_
_x000D_

how to set the background color of the whole page in css

The problem is that the body of the page isn't actually visible. The DIVs under have width of 100% and have background colors themselves that override the body CSS.

To Fix the no-man's land, this might work. It's not elegant, but works.

#doc3 {
    margin: auto 10px;
    width: auto;
    height: 2000px;
    background-color: yellow;
}

How can I force clients to refresh JavaScript files?

This usage has been deprected: https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache

This answer is only 6 years late, but I don't see this answer in many places... HTML5 has introduced Application Cache which is used to solve this problem. I was finding that new server code I was writing was crashing old javascript stored in people's browsers, so I wanted to find a way to expire their javascript. Use a manifest file that looks like this:

CACHE MANIFEST
# Aug 14, 2014
/mycode.js

NETWORK:
*

and generate this file with a new time stamp every time you want users to update their cache. As a side note, if you add this, the browser will not reload (even when a user refreshes the page) until the manifest tells it to.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

This is what solves the problem:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <testFailureIgnore>true</testFailureIgnore>
    </configuration>
</plugin>

from Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

How to find Control in TemplateField of GridView?

Try this:

foreach(GridViewRow row in GridView1.Rows) {
    if(row.RowType == DataControlRowType.DataRow) {
        HyperLink myHyperLink = row.FindControl("myHyperLinkID") as HyperLink;
    }
}

If you are handling RowDataBound event, it's like this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        HyperLink myHyperLink = e.Row.FindControl("myHyperLinkID") as HyperLink;
    }
}

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

It's actually a quirk in Chrome, not the JavaScript library. Here's the fix:

To prevent the message appearing and also allow chrome to render the response nicely as JSON in the console, append a query string to your request URL.

e.g

var xhr_object = new XMLHttpRequest();

var url = 'mysite.com/'; // Using this one, Chrome throws error

var url = 'mysite.com/?'; // Using this one, Chrome works

xhr_object.open('POST', url, false);

What is the difference between UNION and UNION ALL?

I add an example,

UNION, it is merging with distinct --> slower, because it need comparing (In Oracle SQL developer, choose query, press F10 to see cost analysis).

UNION ALL, it is merging without distinct --> faster.

SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual
UNION
SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual;

and

SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual
UNION ALL
SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual;

missing FROM-clause entry for table

SELECT 
   AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit, 
   BillLimit, Mode, PNotes, gtab82.memno 
FROM
   VCustomer AS v1
INNER JOIN   
   gtab82 ON gtab82.memacid = v1.AcId 
WHERE (AcGrCode = '204' OR CreDebt = 'True') 
AND Masked = 'false'
ORDER BY AcName

You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer but only use it in the ON clause for uncertain reasons. You may want to review that aspect of your code.

Get first 100 characters from string, respecting full words

Yes, there is. This is a function I borrowed from a user on a different forums a a few years back, so I can't take credit for it.

//truncate a string only at a whitespace (by nogdog)
function truncate($text, $length) {
   $length = abs((int)$length);
   if(strlen($text) > $length) {
      $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
   }
   return($text);
}

Note that it automatically adds ellipses, if you don't want that just use '\\1' as the second parameter for the preg_replace call.

How to unzip gz file using Python

Maybe you want pass it to pandas also.

with gzip.open('features_train.csv.gz') as f:

    features_train = pd.read_csv(f)

features_train.head()

Disable/Enable button in Excel/VBA

I'm using excel 2010 and below VBA code worked fine for a Form Button. It removes the assigned macro from the button and assign in next command.

To disable:

ActiveSheet.Shapes("Button Name").OnAction = Empty
ActiveSheet.Shapes("Button Name").DrawingObject.Font.ColorIndex = 16

To enable:

ActiveSheet.Shapes("Button Name").OnAction = ActiveWorkbook.Name & "!Macro function Name with _Click"
ActiveSheet.Shapes("Button Name").DrawingObject.Font.ColorIndex = 1

Pls note "ActiveWorkbook.Name" stays as it is. Do not insert workbook name instead of "Name".

JDBC connection failed, error: TCP/IP connection to host failed

As the error says, you need to make sure that your sql server is running and listening on port 1433. If server is running then you need to check whether there is some firewall rule rejecting the connection on port 1433.

Here are the commands that can be useful to troubleshoot:

  1. Use netstat -a to check whether sql server is listening on the desired port
  2. As gerrytan mentioned in answer, you can try to do the telnet on the host and port

Regex pattern including all special characters

If you only rely on ASCII characters, you can rely on using the hex ranges on the ASCII table. Here is a regex that will grab all special characters in the range of 33-47, 58-64, 91-96, 123-126

[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]

However you can think of special characters as not normal characters. If we take that approach, you can simply do this

^[A-Za-z0-9\s]+

Hower this will not catch _ ^ and probably others.

Combine Points with lines with ggplot2

A small change to Paul's code so that it doesn't return the error mentioned above.

dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
           id.vars = "Species")
dat$x <- c(1:150, 1:150)
ggplot(aes(x = x, y = value, color = variable), data = dat) +  
  geom_point() + geom_line()

JavaFX "Location is required." even though it is in the same package

I've seen this error a few times now. So often that I wrote a small project, called "Simple" with a Netbeans Maven FXML application template just to go back to as a kind of 'reference model' when things go askew. For testing, I use something like this:

    String sceneFile = "/fxml/main.fxml";
    Parent root = null;
    URL    url  = null;
    try
    {
        url  = getClass().getResource( sceneFile );
        root = FXMLLoader.load( url );
        System.out.println( "  fxmlResource = " + sceneFile );
    }
    catch ( Exception ex )
    {
        System.out.println( "Exception on FXMLLoader.load()" );
        System.out.println( "  * url: " + url );
        System.out.println( "  * " + ex );
        System.out.println( "    ----------------------------------------\n" );
        throw ex;
    }

When you run that snippet and the load fails, you should see a reason, or at least a message from the FXMLLoader. Since it's a test, I throw the exception. You don't want to continue.

Things to note. This is a maven project so the resources will be relative to the resources folder, hence:

  • "/fxml/main.fxml".
  • The leading slash is required.
  • The resource passed to the FXMLLoader is case-sensitive:

    // If you load "main.fxml" and your file is called: "Main.fxml"
    // You will will see the message ...
    
    java.lang.NullPointerException: Location is required.
    
  • If you get past that "location is required" issue, then you may have a problem in the FXML

    // Something like this: // javafx.fxml.LoadException: file:/D:/sandbox/javafx/app_examples/person/target/person-00.00.01-SNAPSHOT.jar!/fxml/tableWithDetails.fxml:13

Will mean that there's a problem on Line 13, in the file, per:

  • tableWithDetails.fxml :13

In the message. At this point you need to read the FXML and see if you can spot the problem. You could try some of the tips in the related question.

For this problem, my opinion is that the file name was proper case: "Main.fxml". When the file was moved the name was probably changed or the string retyped. Good luck.

Related:

No provider for Http StaticInjectorError

In order to use Http in your app you will need to add the HttpModule to your app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';
...
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ]

EDIT

As mentioned in the comment below, HttpModule is deprecated now, use import { HttpClientModule } from '@angular/common/http'; Make sure HttpClientModule in your imports:[] array

How to use JavaScript regex over multiple lines?

[.\n] does not work because . has no special meaning inside of [], it just means a literal .. (.|\n) would be a way to specify "any character, including a newline". If you want to match all newlines, you would need to add \r as well to include Windows and classic Mac OS style line endings: (.|[\r\n]).

That turns out to be somewhat cumbersome, as well as slow, (see KrisWebDev's answer for details), so a better approach would be to match all whitespace characters and all non-whitespace characters, with [\s\S], which will match everything, and is faster and simpler.

In general, you shouldn't try to use a regexp to match the actual HTML tags. See, for instance, these questions for more information on why.

Instead, try actually searching the DOM for the tag you need (using jQuery makes this easier, but you can always do document.getElementsByTagName("pre") with the standard DOM), and then search the text content of those results with a regexp if you need to match against the contents.

Hide div if screen is smaller than a certain width

Use media queries. Your CSS code would be:

@media screen and (max-width: 1024px) {
    .yourClass {
        display: none !important;
    }
}

Run a shell script with an html button

This is really just an expansion of BBB's answer which lead to to get my experiment working.

This script will simply create a file /tmp/testfile when you click on the button that says "Open Script".

This requires 3 files.

  1. The actual HTML Website with a button.
  2. A php script which executes the script
  3. A Script

The File Tree:

root@test:/var/www/html# tree testscript/
testscript/
+-- index.html
+-- testexec.php
+-- test.sh

1. The main WebPage:

root@test:/var/www/html# cat testscript/index.html
<form action="/testscript/testexec.php">
    <input type="submit" value="Open Script">
</form>

2. The PHP Page that runs the script and redirects back to the main page:

root@test:/var/www/html# cat testscript/testexec.php
<?php
shell_exec("/var/www/html/testscript/test.sh");
header('Location: http://192.168.1.222/testscript/index.html?success=true');
?>

3. The Script :

root@test:/var/www/html# cat testscript/test.sh

#!/bin/bash

touch /tmp/testfile

S3 Static Website Hosting Route All Paths to Index.html

The easiest solution to make Angular 2+ application served from Amazon S3 and direct URLs working is to specify index.html both as Index and Error documents in S3 bucket configuration.

enter image description here

Disabling buttons on react native

TouchableOpacity extents TouchableWithoutFeedback, so you can just use the disabled property :

<TouchableOpacity disabled={true}>
  <Text>I'm disabled</Text>
</TouchableOpacity>

React Native TouchableWithoutFeedback #disabled documentation

The new Pressable API has a disabled option too :

<Pressable disable={true}>
  {({ pressed }) => (
    <Text>I'm disabled</Text>
  )}
</Pressable>

Failed to find Build Tools revision 23.0.1

In the Gradle Console (link available in the window bottom right), you have two tabs: the error is shown in Gradle Build tab. Click on the Gradle Sync tab, then click on the Install Build Tools XX.X.X and sync project link. This will download the build version required by your project.

You may also change your project SDK version but you don't always have this option if it is imposed.

How to find the statistical mode?

Here is a function to find the mode:

mode <- function(x) {
  unique_val <- unique(x)
  counts <- vector()
  for (i in 1:length(unique_val)) {
    counts[i] <- length(which(x==unique_val[i]))
  }
  position <- c(which(counts==max(counts)))
  if (mean(counts)==max(counts)) 
    mode_x <- 'Mode does not exist'
  else 
    mode_x <- unique_val[position]
  return(mode_x)
}

Elegant way to create empty pandas DataFrame with NaN of type float

You can try this line of code:

pdDataFrame = pd.DataFrame([np.nan] * 7)

This will create a pandas dataframe of size 7 with NaN of type float:

if you print pdDataFrame the output will be:

     0
0   NaN
1   NaN
2   NaN
3   NaN
4   NaN
5   NaN
6   NaN

Also the output for pdDataFrame.dtypes is:

0    float64
dtype: object

Returning anonymous type in C#

It is actually possible to return an anonymous type from a method in a particular use-case. Let's have a look!

With C# 7 it is possible to return anonymous types from a method, although it comes with a slight constraint. We are going to use a new language feature called local function together with an indirection trick (another layer of indirection can solve any programming challenge, right?).

Here's a use-case I recently identified. I want to log all configuration values after I have loaded them from AppSettings. Why? Because there's some logic around missing values that revert to default values, some parsing and so on. An easy way to log the values after applying the logic is to put them all in a class and serialize it to a logfile (using log4net). I also want to encapsulate the complex logic of dealing with settings and separate that from whatever I need to do with them. All without creating a named class that exists just for a single use!

Let's see how to solve this using a local function that creates an anonymous type.

public static HttpClient CreateHttpClient()
{
    // I deal with configuration values in this slightly convoluted way.
    // The benefit is encapsulation of logic and we do not need to
    // create a class, as we can use an anonymous class.
    // The result resembles an expression statement that
    // returns a value (similar to expressions in F#)
    var config = Invoke(() =>
    {
        // slightly complex logic with default value
        // in case of missing configuration value
        // (this is what I want to encapsulate)
        int? acquireTokenTimeoutSeconds = null;
        if (int.TryParse(ConfigurationManager.AppSettings["AcquireTokenTimeoutSeconds"], out int i))
        {
            acquireTokenTimeoutSeconds = i;
        }

        // more complex logic surrounding configuration values ...

        // construct the aggregate configuration class as an anonymous type!
        var c = new
        {
            AcquireTokenTimeoutSeconds =
                acquireTokenTimeoutSeconds ?? DefaultAcquireTokenTimeoutSeconds,
            // ... more properties
        };

        // log the whole object for monitoring purposes
        // (this is also a reason I want encapsulation)
        Log.InfoFormat("Config={0}", c);
        return c;
    });

    // use this configuration in any way necessary...
    // the rest of the method concerns only the factory,
    // i.e. creating the HttpClient with whatever configuration
    // in my case this:
    return new HttpClient(...);

    // local function that enables the above expression
    T Invoke<T>(Func<T> func) => func.Invoke();
}

I have succeeded in constructing an anonymous class and also encapsulated the logic of dealing with complex settings management, all inside CreateHttpClient and within its own "expression". This might not be exactly what the OP wanted but it is a lightweight approach with anonymous types that is currently possible in modern C#.

TypeError: $ is not a function when calling jQuery function

Double check your jQuery references. It is possible that you are either referencing it more than once or you are calling your function too early (before jQuery is defined). You can try as mentioned in my comments and put any jQuery reference at the top of your file (in the head) and see if that helps.

If you use the encapsulation of jQuery it shouldn't help in this case. Please try it because I think it is prettier and more obvious, but if jQuery is not defined you will get the same errors.

In the end... jQuery is not currently defined.

react-router go back a page how do you configure history?

The only solution that worked for me was the most simple. No additional imports needed.

<a href="#" onClick={() => this.props.history.goBack()}>Back</a>

Tks, IamMHussain

Passing a variable from node.js to html

I have achieved this by a http API node request which returns required object from node object for HTML page at client ,

for eg: API: localhost:3000/username

returns logged in user from cache by node App object .

node route file,

app.get('/username', function(req, res) {
    res.json({ udata: req.session.user });
    });

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

Merge, update, and pull Git branches without using checkouts

git worktree add [-f] [--detach] [--checkout] [--lock] [-b <new-branch>] <path> [<commit-ish>]

You can try git worktree to have two branches open side by side, this sounds like it might be what you want but very different than some of the other answers I've seen here.

In this way you can have two separate branches tracking in the same git repo so you only have to fetch once to get updates in both work trees (rather than having to git clone twice and git pull on each)

Worktree will create a new working directory for your code where you can have a different branch checked out simultaneously instead of swapping branches in place.

When you want to remove it you can clean up with

git worktree remove [-f] <worktree>

How can I open multiple files using "with open" in Python?

Just replace and with , and you're done:

try:
    with open('a', 'w') as a, open('b', 'w') as b:
        do_something()
except IOError as e:
    print 'Operation failed: %s' % e.strerror

Proper way to get page content

The wp_trim_words function can limit the characters too by changing the $num_words variable. For anyone who might find useful.

<?php 
$id=58; 
$post = get_post($id); 
$content = apply_filters('the_content', $post->post_content); 

$customExcerpt = wp_trim_words( $content, $num_words = 26, $more = '' );
echo $customExcerpt;  
?>

"Debug certificate expired" error in Eclipse Android plugins

It's a pain to have to delete all your development .apk files, because the new certificate doesn't match so you can't upgrade them in all your AVDs. You have to get another development MAP-API key as well. There's another solution.

You can create your own debug certificate in debug.keystore with whatever expiration you want. Do this in the .android folder under your HOME directory:

keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -validity 14000

keytool.exe can be found in the JDK bin folder (e.g. C:\Program Files\Java\jdk1.6.0_31\bin\ on Windows).

ADT sets the first and last name on the certificate as "Android Debug", the organizational unit as "Android" and the two-letter country code as "US". You can leave the organization, city, and state values as "Unknown". This example uses a validity of 14000 days. You can use whatever value you like.

Convert timestamp in milliseconds to string formatted time in Java

public static String timeDifference(long timeDifference1) {
long timeDifference = timeDifference1/1000;
int h = (int) (timeDifference / (3600));
int m = (int) ((timeDifference - (h * 3600)) / 60);
int s = (int) (timeDifference - (h * 3600) - m * 60);

return String.format("%02d:%02d:%02d", h,m,s);

The name does not exist in the namespace error in XAML

In Visual Studio 2019 I was able to fix it by changing the dropdown to Release as recommended in other answers. But when I changed back to Debug mode the error appeared again.

What fixed it for me in Debug mode:

  1. Switch to Release mode
  2. Click on "Disable project code" in the XAML Designer

XAML editor: Disable project code

  1. Switch back to Debug mode => the error is gone

How to right-align and justify-align in Markdown?

As mentioned here, markdown do not support right aligned text or blocks. But the HTML result does it, via Cascading Style Sheets (CSS).

On my Jekyll Blog is use a syntax which works in markdown as well. To "terminate" a block use two spaces at the end or two times new line.

Of course you can also add a css-class with {: .right } instead of {: style="text-align: right" }.

Text to right

{: style="text-align: right" }
This text is on the right

Text as block

{: style="text-align: justify" }
This text is a block

javac : command not found

You have installed the Java Runtime Environment(JRE) but it doesn't contain javac.

So on the terminal get access to the root user sudo -i and enter the password. Type yum install java-devel, hence it will install packages of javac in fedora.

Convert a string to datetime in PowerShell

Chris Dents' answer has already covered the OPs' question but seeing as this was the top search on google for PowerShell format string as date I thought I'd give a different string example.


If like me, you get the time string like this 20190720170000.000000+000

An important thing to note is you need to use ToUniversalTime() when using [System.Management.ManagementDateTimeConverter] otherwise you get offset times against your input.

PS Code

cls
Write-Host "This example is for the 24hr clock with HH"
Write-Host "ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]"
$my_date_24hr_time   = "20190720170000.000000+000"
$date_format         = "yyyy-MM-dd HH:mm"
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_24hr_time).ToUniversalTime();
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_24hr_time).ToUniversalTime().ToSTring($date_format)
[datetime]::ParseExact($my_date_24hr_time,"yyyyMMddHHmmss.000000+000",$null).ToSTring($date_format)
Write-Host
Write-Host "-----------------------------"
Write-Host
Write-Host "This example is for the am pm clock with hh"
Write-Host "Again, ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]"
Write-Host
$my_date_ampm_time   = "20190720110000.000000+000"
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_ampm_time).ToUniversalTime();
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_ampm_time).ToUniversalTime().ToSTring($date_format)
[datetime]::ParseExact($my_date_ampm_time,"yyyyMMddhhmmss.000000+000",$null).ToSTring($date_format)

Output

This example is for the 24hr clock with HH
ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]

20 July 2019 17:00:00
2019-07-20 17:00
2019-07-20 17:00

-----------------------------

This example is for the am pm clock with hh
Again, ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]

20 July 2019 11:00:00
2019-07-20 11:00
2019-07-20 11:00

MS doc on [Management.ManagementDateTimeConverter]:

https://docs.microsoft.com/en-us/dotnet/api/system.management.managementdatetimeconverter?view=dotnet-plat-ext-3.1

How do I concatenate a string with a variable?

In javascript the "+" operator is used to add numbers or to concatenate strings. if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.

example:

1+2+3 == 6
"1"+2+3 == "123"

How to make a UILabel clickable?

As described in the above solution you should enable the user interaction first and add the tap gesture

this code has been tested using

Swift4 - Xcode 9.2

yourlabel.isUserInteractionEnabled = true
yourlabel.addGestureRecognizer(UITapGestureRecognizer(){
                //TODO 
            })