Programs & Examples On #Embperl

Assign output to variable in Bash

In shell, you don't put a $ in front of a variable you're assigning. You only use $IP when you're referring to the variable.

#!/bin/bash

IP=$(curl automation.whatismyip.com/n09230945.asp)

echo "$IP"

sed "s/IP/$IP/" nsupdate.txt | nsupdate

Subset of rows containing NA (missing) values in a chosen column of a data frame

NA is a special value in R, do not mix up the NA value with the "NA" string. Depending on the way the data was imported, your "NA" and "NULL" cells may be of various type (the default behavior is to convert "NA" strings to NA values, and let "NULL" strings as is).

If using read.table() or read.csv(), you should consider the "na.strings" argument to do clean data import, and always work with real R NA values.

An example, working in both cases "NULL" and "NA" cells :

DF <- read.csv("file.csv", na.strings=c("NA", "NULL"))
new_DF <- subset(DF, is.na(DF$Var2))

Control the dashed border stroke length and distance between strokes

I just recently had the same problem. I have made this work around, hope it will help someone.

HTML + tailwind

<div class="dashed-border h-14 w-full relative rounded-lg">
    <div class="w-full h-full rounded-lg bg-page z-10 relative">
        Content goes here...
    <div>
</div>

CSS

.dashed-border::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  height: calc(100% + 4px);
  transform: translateY(-50%);
  background-image: linear-gradient(to right, #333 50%, transparent 50%);
  background-size: 16px;
  z-index: 0;
  border-radius: 0.5rem;
}
.dashed-border::after {
  content: '';
  position: absolute;
  left: 50%;
  top: 0;
  height: 100%;
  width: calc(100% + 4px);
  transform: translateX(-50%);
  background-image: linear-gradient(to bottom, #333 50%, transparent 50%);
  background-size: 4px 16px;
  z-index: 1;
  border-radius: 0.5rem;
}

How to set margin with jquery?

try

el.css('margin-left',mrg+'px');

Get full query string in C# ASP.NET

Try Request.Url.Query if you want the raw querystring as a string.

Best way to check if a URL is valid

Personally I would like to use regular expression here. Bellow code perfectly worked for me.

$baseUrl     = url('/'); // for my case https://www.xrepeater.com
$posted_url  = "home";
// Test with one by one
/*$posted_url  = "/home";
$posted_url  = "xrepeater.com";
$posted_url  = "www.xrepeater.com";
$posted_url  = "http://www.xrepeater.com";
$posted_url  = "https://www.xrepeater.com";
$posted_url  = "https://xrepeater.com/services";
$posted_url  = "xrepeater.dev/home/test";
$posted_url  = "home/test";*/

$regularExpression  = "((https?|ftp)\:\/\/)?"; // SCHEME Check
$regularExpression .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass Check
$regularExpression .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP Check
$regularExpression .= "(\:[0-9]{2,5})?"; // Port Check
$regularExpression .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path Check
$regularExpression .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query String Check
$regularExpression .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor Check

if(preg_match("/^$regularExpression$/i", $posted_url)) { 
    if(preg_match("@^http|https://@i",$posted_url)) {
        $final_url = preg_replace("@(http://)+@i",'http://',$posted_url);
        // return "*** - ***Match : ".$final_url;
    }
    else { 
          $final_url = 'http://'.$posted_url;
          // return "*** / ***Match : ".$final_url;
         }
    }
else {
     if (substr($posted_url, 0, 1) === '/') { 
         // return "*** / ***Not Match :".$final_url."<br>".$baseUrl.$posted_url;
         $final_url = $baseUrl.$posted_url;
     }
     else { 
         // return "*** - ***Not Match :".$posted_url."<br>".$baseUrl."/".$posted_url;
         $final_url = $baseUrl."/".$final_url; }
}

How do I add target="_blank" to a link within a specified div?

Use this for every external link

$('a[href^="http://"], a[href^="https://"]').attr('target', '_blank');

Add/remove HTML inside div using JavaScript

make a class for that button lets say :

`<input type="button" value="+" class="b1" onclick="addRow()">`

your js should look like this :

$(document).ready(function(){
  $('.b1').click(function(){
      $('div').append('<input type="text"..etc ');
  });
});

Rename a column in MySQL

Rename MySQL Column with ALTER TABLE Command

ALTER TABLE is an essential command used to change the structure of a MySQL table. You can use it to add or delete columns, change the type of data within the columns, and even rename entire databases. The function that concerns us the most is how to utilize ALTER TABLE to rename a column.

Clauses give us additional control over the renaming process. The RENAME COLUMN and CHANGE clause both allow for the names of existing columns to be altered. The difference is that the CHANGE clause can also be used to alter the data types of a column. The commands are straightforward, and you may use the clause that fits your requirements best.

How to Use the RENAME COLUMN Clause (MySQL 8.0)

The simplest way to rename a column is to use the ALTER TABLE command with the RENAME COLUMN clause. This clause is available since MySQL version 8.0.

Let’s illustrate its simple syntax. To change a column name, enter the following statement in your MySQL shell:

ALTER TABLE your_table_name RENAME COLUMN original_column_name TO new_column_name;

Exchange the your_table_name, original_column_name, and new_column_name with your table and column names. Keep in mind that you cannot rename a column to a name that already exists in the table.

Note: The word COLUMN is obligatory for the ALTER TABLE RENAME COLUMN command. ALTER TABLE RENAME is the existing syntax to rename the entire table.

The RENAME COLUMN clause can only be used to rename a column. If you need additional functions, such as changing the data definition, or position of a column, you need to use the CHANGE clause instead.

Rename MySQL Column with CHANGE Clause

The CHANGE clause offers important additions to the renaming process. It can be used to rename a column and change the data type of that column with the same command.

Enter the following command in your MySQL client shell to change the name of the column and its definition:

ALTER TABLE your_table_name CHANGE original_column_name new_col_name data_type;

The data_type element is mandatory, even if you want to keep the existing datatype.

Use additional options to further manipulate table columns. The CHANGE also allows you to place the column in a different position in the table by using the optional FIRST | AFTER column_name clause. For example:

ALTER TABLE your_table_name CHANGE original_column_name new_col_name y_data_type AFTER column_x;

You have successfully changed the name of the column, changed the data type to y_data_type, and positioned the column after column_x.

C++ Array of pointers: delete or delete []?

delete[] monsters;

Is incorrect because monsters isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.

Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster objects.

Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)

How to create User/Database in script for Docker Postgres

By using docker-compose:

Assuming that you have following directory layout:

$MYAPP_ROOT/docker-compose.yml
           /Docker/init.sql
           /Docker/db.Dockerfile

File: docker-compose.yml

version: "3.3"
services:
  db:
    build:
      context: ./Docker
      dockerfile: db.Dockerfile
    volumes:
      - ./var/pgdata:/var/lib/postgresql/data
    ports:
      - "5432:5432"

File: Docker/init.sql

CREATE USER myUser;

CREATE DATABASE myApp_dev;
GRANT ALL PRIVILEGES ON DATABASE myApp_dev TO myUser;

CREATE DATABASE myApp_test;
GRANT ALL PRIVILEGES ON DATABASE myApp_test TO myUser;

File: Docker/db.Dockerfile

FROM postgres:11.5-alpine
COPY init.sql /docker-entrypoint-initdb.d/

Composing and starting services:

docker-compose -f docker-compose.yml up --no-start
docker-compose -f docker-compose.yml start

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

Imply bit with constant 1 or 0 in SQL Server

Enjoy this :) Without cast each value individually.

SELECT ...,
  IsCoursedBased = CAST(
      CASE WHEN fc.CourseId is not null THEN 1 ELSE 0 END
    AS BIT
  )
FROM fc

is there a post render callback for Angular JS directive?

May be am late to answer this question. But still someone may get benefit out of my answer.

I had similar issue and in my case I can not change the directive since, it is a library and change a code of the library is not a good practice. So what I did was use a variable to wait for page load and use ng-if inside my html to wait render the particular element.

In my controller:

$scope.render=false;

//this will fire after load the the page

angular.element(document).ready(function() {
    $scope.render=true;
});

In my html (in my case html component is a canvas)

<canvas ng-if="render"> </canvas>

Remove all classes that begin with a certain string

An approach I would use using simple jQuery constructs and array handling functions, is to declare an function that takes id of the control and prefix of the class and deleted all classed. The code is attached:

function removeclasses(controlIndex,classPrefix){
    var classes = $("#"+controlIndex).attr("class").split(" ");
    $.each(classes,function(index) {
        if(classes[index].indexOf(classPrefix)==0) {
            $("#"+controlIndex).removeClass(classes[index]);
        }
    });
}

Now this function can be called from anywhere, onclick of button or from code:

removeclasses("a","bg");

PHP list of specific files in a directory

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle)))
    {
        if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'xml')
        {
            $thelist .= '<li><a href="'.$file.'">'.$file.'</a></li>';
        }
    }
    closedir($handle);
}

A simple way to look at the extension using substr and strrpos

C++ JSON Serialization

There is no reflection in C++. True. But if the compiler can't provide you the metadata you need, you can provide it yourself.

Let's start by making a property struct:

template<typename Class, typename T>
struct PropertyImpl {
    constexpr PropertyImpl(T Class::*aMember, const char* aName) : member{aMember}, name{aName} {}

    using Type = T;

    T Class::*member;
    const char* name;
};

template<typename Class, typename T>
constexpr auto property(T Class::*member, const char* name) {
    return PropertyImpl<Class, T>{member, name};
}

Of course, you also can have a property that takes a setter and getter instead of a pointer to member, and maybe read only properties for calculated value you'd like to serialize. If you use C++17, you can extend it further to make a property that works with lambdas.

Ok, now we have the building block of our compile-time introspection system.

Now in your class Dog, add your metadata:

struct Dog {
    std::string barkType;
    std::string color;
    int weight = 0;

    bool operator==(const Dog& rhs) const {
        return std::tie(barkType, color, weight) == std::tie(rhs.barkType, rhs.color, rhs.weight);
    }

    constexpr static auto properties = std::make_tuple(
        property(&Dog::barkType, "barkType"),
        property(&Dog::color, "color"),
        property(&Dog::weight, "weight")
    );
};

We will need to iterate on that list. To iterate on a tuple, there are many ways, but my preferred one is this:

template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
    using unpack_t = int[];
    (void)unpack_t{(static_cast<void>(f(std::integral_constant<T, S>{})), 0)..., 0};
}

If C++17 fold expressions are available in your compiler, then for_sequence can be simplified to:

template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
    (static_cast<void>(f(std::integral_constant<T, S>{})), ...);
}

This will call a function for each constant in the integer sequence.

If this method don't work or gives trouble to your compiler, you can always use the array expansion trick.

Now that you have the desired metadata and tools, you can iterate through the properties to unserialize:

// unserialize function
template<typename T>
T fromJson(const Json::Value& data) {
    T object;

    // We first get the number of properties
    constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;

    // We iterate on the index sequence of size `nbProperties`
    for_sequence(std::make_index_sequence<nbProperties>{}, [&](auto i) {
        // get the property
        constexpr auto property = std::get<i>(T::properties);

        // get the type of the property
        using Type = typename decltype(property)::Type;

        // set the value to the member
        // you can also replace `asAny` by `fromJson` to recursively serialize
        object.*(property.member) = Json::asAny<Type>(data[property.name]);
    });

    return object;
}

And for serialize:

template<typename T>
Json::Value toJson(const T& object) {
    Json::Value data;

    // We first get the number of properties
    constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;

    // We iterate on the index sequence of size `nbProperties`
    for_sequence(std::make_index_sequence<nbProperties>{}, [&](auto i) {
        // get the property
        constexpr auto property = std::get<i>(T::properties);

        // set the value to the member
        data[property.name] = object.*(property.member);
    });

    return data;
}

If you want recursive serialization and unserialization, you can replace asAny by fromJson.

Now you can use your functions like this:

Dog dog;

dog.color = "green";
dog.barkType = "whaf";
dog.weight = 30;

Json::Value jsonDog = toJson(dog); // produces {"color":"green", "barkType":"whaf", "weight": 30}
auto dog2 = fromJson<Dog>(jsonDog);

std::cout << std::boolalpha << (dog == dog2) << std::endl; // pass the test, both dog are equal!

Done! No need for run-time reflection, just some C++14 goodness!

This code could benefit from some improvement, and could of course work with C++11 with some ajustements.

Note that one would need to write the asAny function. It's just a function that takes a Json::Value and call the right as... function, or another fromJson.

Here's a complete, working example made from the various code snippet of this answer. Feel free to use it.

As mentionned in the comments, this code won't work with msvc. Please refer to this question if you want a compatible code: Pointer to member: works in GCC but not in VS2015

Best way to convert text files between character sets?

If macOS GUI applications are your bread and butter, SubEthaEdit is the text editor I usually go to for encoding-wrangling — its "conversion preview" allows you to see all invalid characters in the output encoding, and fix/remove them.

And it's open-source now, so yay for them .

Use of exit() function

The exit() function is a type of function with a return type without an argument. It's defined by the stdlib header file.

You need to use ( exit(0) or exit(EXIT_SUCCESS)) or (exit(non-zero) or exit(EXIT_FAILURE) ).

Reactjs - setting inline styles correctly

You could also try setting style inline without using a variable, like so:

style={{"height" : "100%"}} or,

for multiple attributes: style={{"height" : "100%", "width" : "50%"}}

Can't bind to 'formGroup' since it isn't a known property of 'form'

Note : if you are working inside child module's component , then u just have to import ReactiveFormsModule in child module rather than parent app root module

How to generate auto increment field in select query

DECLARE @id INT 
SET @id = 0 
UPDATE cartemp
SET @id = CarmasterID = @id + 1 
GO

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

if (Request.Params["__EVENTTARGET"] != null)
{
  if (Request.Params["__EVENTTARGET"].ToString().Contains("myControlID"))
  {
    DoWhateverYouWant();
  }
}

Extract parameter value from url using regular expressions

I use seperate custom functions which gets all URL Parameters and URL parts . For URL parameters, (which is the final part of an URI String, http://domain.tld/urlpart/?x=a&y=b

    function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
    }

The above function will return an array consisting of url variables.

For URL Parts or functions, (which is http://domain.tld/urlpart/?x=a&y=b I use a simple uri split,

function getUrlParams() { 
    var vars = {};
    var parts = window.location.href.split('/' );
    return parts;
}

You can even combine them both to be able to use with a single call in a page or in javascript.

Redraw datatables after using ajax to refresh the table content?

I'm not sure why. But

oTable6.fnDraw();

Works for me. I put it in the next line.

Can I open a dropdownlist using jQuery

As has been stated, you can't programmatically open a <select> using JavaScript.

However, you could write your own <select> managing the entire look and feel yourself. Something like what you see for the autocomplete search terms on Google or Yahoo! or the Search for Location box at The Weather Network.

I found one for jQuery here. I have no idea whether it would meet your needs, but even if it doesn't completely meet your needs, it should be possible to modify it so it would open as the result of some other action or event. This one actually looks more promising.

Django request.GET

q = request.GET.get("q", None)
if q:
    message = 'q= %s' % q
else:
    message = 'Empty'

Clear listview content?

Just put the code ListView.Items.Clear(); on your method

How to return multiple values in one column (T-SQL)?

You can use a function with COALESCE.

CREATE FUNCTION [dbo].[GetAliasesById]
(
    @userID int
)
RETURNS varchar(max)
AS
BEGIN
    declare @output varchar(max)
    select @output = COALESCE(@output + ', ', '') + alias
    from UserAliases
    where userid = @userID

    return @output
END

GO

SELECT UserID, dbo.GetAliasesByID(UserID)
FROM UserAliases
GROUP BY UserID

GO

Pretty-print a Map in Java

Or put your logic into a tidy little class.

public class PrettyPrintingMap<K, V> {
    private Map<K, V> map;

    public PrettyPrintingMap(Map<K, V> map) {
        this.map = map;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        Iterator<Entry<K, V>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<K, V> entry = iter.next();
            sb.append(entry.getKey());
            sb.append('=').append('"');
            sb.append(entry.getValue());
            sb.append('"');
            if (iter.hasNext()) {
                sb.append(',').append(' ');
            }
        }
        return sb.toString();

    }
}

Usage:

Map<String, String> myMap = new HashMap<String, String>();

System.out.println(new PrettyPrintingMap<String, String>(myMap));

Note: You can also put that logic into a utility method.

Illegal mix of collations error in MySql

I think you should convert to utf8

--set utf8 for connection
SET collation_connection = 'utf8_general_ci'
--change CHARACTER SET of DB to utf8
ALTER DATABASE dbName CHARACTER SET utf8 COLLATE utf8_general_ci
--change CHARACTER SET of table to utf8
ALTER TABLE tableName CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci

making a paragraph in html contain a text from a file

Javascript will do the trick here.

function load() {
    var file = new XMLHttpRequest();
    file.open("GET", "http://remote.tld/random.txt", true);
    file.onreadystatechange = function() {
      if (file.readyState === 4) {  // Makes sure the document is ready to parse
        if (file.status === 200) {  // Makes sure it's found the file
          text = file.responseText;
          document.getElementById("div1").innerHTML = text;
        }
      }
    }
}

window.onLoad = load();

Can't install via pip because of egg_info error

In my case this error message appeared because the package I was trying to install (storm) was not supported for Python 3.

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

What is the difference between method overloading and overriding?

Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)
void foo(int a, float b)

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {
    void foo(double d) {
        // do something
    }
}

class Child extends Parent {

    @Override
    void foo(double d){
        // this method is overridden.  
    }
}

Android button with different background colors

As your error states, you have to define drawable attibute for the items (for some reason it is required when it comes to background definitions), so:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/red"/> <!-- pressed -->
    <item android:state_focused="true" android:drawable="@color/blue"/> <!-- focused -->
    <item android:drawable="@color/black"/> <!-- default -->
</selector>

Also note that drawable attribute doesn't accept raw color values, so you have to define the colors as resources. Create colors.xml file at res/values folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <color name="black">#000</color>
     <color name="blue">#00f</color>
     <color name="red">#f00</color>
</resources>

How to compile for Windows on Linux with gcc/g++?

I've used mingw on Linux to make Windows executables in C, I suspect C++ would work as well.

I have a project, ELLCC, that packages clang and other things as a cross compiler tool chain. I use it to compile clang (C++), binutils, and GDB for Windows. Follow the download link at ellcc.org for pre-compiled binaries for several Linux hosts.

IN vs ANY operator in PostgreSQL

(Neither IN nor ANY is an "operator". A "construct" or "syntax element".)

Logically, quoting the manual:

IN is equivalent to = ANY.

But there are two syntax variants of IN and two variants of ANY. Details:

IN taking a set is equivalent to = ANY taking a set, as demonstrated here:

But the second variant of each is not equivalent to the other. The second variant of the ANY construct takes an array (must be an actual array type), while the second variant of IN takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:

ANY is more versatile

The ANY construct is far more versatile, as it can be combined with various operators, not just =. Example:

SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');

For a big number of values, providing a set scales better for each:

Related:

Inversion / opposite / exclusion

"Find rows where id is in the given array":

SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);

Inversion: "Find rows where id is not in the array":

SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}');  -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));

All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[].

Rows with id IS NULL do not pass either of these expressions. To include NULL values additionally:

SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;

Qt jpg image display

I want to display .jpg image in an Qt UI

The simpliest way is to use QLabel for this:

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    QLabel label("<img src='image.jpg' />");
    label.show();
    return a.exec();
}

Return first N key:value pairs from dict

Did not see it on here. Will not be ordered but the simplest syntactically if you need to just take some elements from a dictionary.

n = 2
{key:value for key,value in d.items()[0:n]}

How to delete the last row of data of a pandas dataframe

DF[:-n]

where n is the last number of rows to drop.

To drop the last row :

DF = DF[:-1]

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

The property IsOneWay=true may be true in the Operational contract of the interface. Remove that property to get rid of this error.

How do I check if a Key is pressed on C++

There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.

Solution for linux and other posix compliant systems:

Here, for Morgan Mattews's code provide kbhit() functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.

Solution for windows:

For windows, Microsoft offers _kbhit()

Java, How to specify absolute value and square roots

Use the static methods in the Math class for both - there are no operators for this in the language:

double root = Math.sqrt(value);
double absolute = Math.abs(value);

(Likewise there's no operator for raising a value to a particular power - use Math.pow for that.)

If you use these a lot, you might want to use static imports to make your code more readable:

import static java.lang.Math.sqrt;
import static java.lang.Math.abs;

...

double x = sqrt(abs(x) + abs(y));

instead of

double x = Math.sqrt(Math.abs(x) + Math.abs(y));

How to write an XPath query to match two attributes?

or //div[@id='id-74385'][@class='guest clearfix']

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

Moving average or running mean

All the aforementioned solutions are poor because they lack

  • speed due to a native python instead of a numpy vectorized implementation,
  • numerical stability due to poor use of numpy.cumsum, or
  • speed due to O(len(x) * w) implementations as convolutions.

Given

import numpy
m = 10000
x = numpy.random.rand(m)
w = 1000

Note that x_[:w].sum() equals x[:w-1].sum(). So for the first average the numpy.cumsum(...) adds x[w] / w (via x_[w+1] / w), and subtracts 0 (from x_[0] / w). This results in x[0:w].mean()

Via cumsum, you'll update the second average by additionally add x[w+1] / w and subtracting x[0] / w, resulting in x[1:w+1].mean().

This goes on until x[-w:].mean() is reached.

x_ = numpy.insert(x, 0, 0)
sliding_average = x_[:w].sum() / w + numpy.cumsum(x_[w:] - x_[:-w]) / w

This solution is vectorized, O(m), readable and numerically stable.

Creating a Shopping Cart using only HTML/JavaScript

I think it is a better idea to start working with a raw data and then translate it to DOM (document object model)

I would suggest you to work with array of objects and then output it to the DOM in order to accomplish your task.

You can see working example of following code at http://www.softxml.com/stackoverflow/shoppingCart.htm

You can try following approach:

//create array that will hold all ordered products
    var shoppingCart = [];

    //this function manipulates DOM and displays content of our shopping cart
    function displayShoppingCart(){
        var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
        //ensure we delete all previously added rows from ordered products table
        while(orderedProductsTblBody.rows.length>0) {
            orderedProductsTblBody.deleteRow(0);
        }

        //variable to hold total price of shopping cart
        var cart_total_price=0;
        //iterate over array of objects
        for(var product in shoppingCart){
            //add new row      
            var row=orderedProductsTblBody.insertRow();
            //create three cells for product properties 
            var cellName = row.insertCell(0);
            var cellDescription = row.insertCell(1);
            var cellPrice = row.insertCell(2);
            cellPrice.align="right";
            //fill cells with values from current product object of our array
            cellName.innerHTML = shoppingCart[product].Name;
            cellDescription.innerHTML = shoppingCart[product].Description;
            cellPrice.innerHTML = shoppingCart[product].Price;
            cart_total_price+=shoppingCart[product].Price;
        }
        //fill total cost of our shopping cart 
        document.getElementById("cart_total").innerHTML=cart_total_price;
    }


    function AddtoCart(name,description,price){
       //Below we create JavaScript Object that will hold three properties you have mentioned:    Name,Description and Price
       var singleProduct = {};
       //Fill the product object with data
       singleProduct.Name=name;
       singleProduct.Description=description;
       singleProduct.Price=price;
       //Add newly created product to our shopping cart 
       shoppingCart.push(singleProduct);
       //call display function to show on screen
       displayShoppingCart();

    }  


    //Add some products to our shopping cart via code or you can create a button with onclick event
    //AddtoCart("Table","Big red table",50);
    //AddtoCart("Door","Big yellow door",150);
    //AddtoCart("Car","Ferrari S23",150000);






<table cellpadding="4" cellspacing="4" border="1">
    <tr>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="0">
                <thead>
                    <tr>
                        <td colspan="2">
                            Products for sale
                        </td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            Table
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Table','Big red table',50)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Door
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Door','Yellow Door',150)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Car
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Ferrari','Ferrari S234',150000)"/>
                        </td>
                    </tr>
                </tbody>

            </table>
        </td>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="1" id="orderedProductsTbl">
                <thead>
                    <tr>
                        <td>
                            Name
                        </td>
                        <td>
                            Description
                        </td>
                        <td>
                            Price
                        </td>
                    </tr>
                </thead>
                <tbody id="orderedProductsTblBody">

                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="3" align="right" id="cart_total">

                        </td>
                    </tr>
                </tfoot>
            </table>
        </td>
    </tr>
</table>

Please have a look at following free client-side shopping cart:

SoftEcart(js) is a Responsive, Handlebars & JSON based, E-Commerce shopping cart written in JavaScript with built-in PayPal integration.

Documentation

http://www.softxml.com/softecartjs-demo/documentation/SoftecartJS_free.html

Hope you will find it useful.

Removing "bullets" from unordered list <ul>

Have you tried setting

li {list-style-type: none;}

According to Need an unordered list without any bullets, you need to add this style to the li elements.

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

How do I find my host and username on mysql?

type this command

select CURRENT_USER();

You will get the username and server

Bash syntax error: unexpected end of file

I was able to cut and paste your code into a file and it ran correctly. If you execute it like this it should work:

Your "file.sh":

#!/bin/bash
# june 2011

if [ $# -lt 3 -o $# -gt 3 ]; then
   echo "Error... Usage: $0 host database username"
   exit 0
fi

The command:

$ ./file.sh arg1 arg2 arg3

Note that "file.sh" must be executable:

$ chmod +x file.sh

You may be getting that error b/c of how you're doing input (w/ a pipe, carrot, etc.). You could also try splitting the condition into two:

if [ $# -lt 3 ] || [ $# -gt 3 ]; then
   echo "Error... Usage: $0 host database username"
   exit 0
fi

Or, since you're using bash, you could use built-in syntax:

if [[ $# -lt 3 || $# -gt 3 ]]; then
   echo "Error... Usage: $0 host database username"
   exit 0
fi

And, finally, you could of course just check if 3 arguments were given (clean, maintains POSIX shell compatibility):

if [ $# -ne 3 ]; then
   echo "Error... Usage: $0 host database username"
   exit 0
fi

Comments in Markdown

kramdown—the Ruby-based markdown engine that is the default for Jekyll and thus GitHub Pages—has built-in comment support through its extension syntax:

{::comment}
This text is completely ignored by kramdown - a comment in the text.
{:/comment}

Do you see {::comment}this text{:/comment}?
{::comment}some other comment{:/}

This has the benefit of allowing in-line comments, but the downside of not being portable to other Markdown engines.

How to strip comma in Python string

This will strip all commas from the text and left justify it.

for row in inputfile:
    place = row['your_row_number_here'].strip(', ')

? ????? ??????

How do I find a stored procedure containing <text>?

Stored Procedure for find text in SP.. {Dinesh Baskaran} Trendy Global Systems pvt ltd

  create Procedure [dbo].[TextFinder]
 (@Text varchar(500),@Type varchar(2)=NULL)
AS
BEGIN





SELECT DISTINCT o.name AS ObjectName, 
CASE o.xtype 
WHEN 'C' THEN 'CHECK constraint ' 
WHEN 'D' THEN 'Default or DEFAULT constraint'
WHEN 'F' THEN 'FOREIGN KEY constraint'
WHEN 'FN' THEN 'Scalar function'
WHEN 'IF' THEN 'In-lined table-function'
WHEN 'K' THEN 'PRIMARY KEY or UNIQUE constraint'
WHEN 'L' THEN 'Log'
WHEN 'P' THEN 'Stored procedure'
WHEN 'R' THEN 'Rule'
WHEN 'RF' THEN 'Replication filter stored procedure' 
WHEN 'S' THEN 'System table'  
WHEN 'TF' THEN 'Table function' 
WHEN 'TR' THEN 'Trigger'  
WHEN 'U' THEN 'User table' 
WHEN 'V' THEN 'View' 
WHEN 'X' THEN 'Extended stored procedure' 
ELSE o.xtype 
END AS ObjectType,  

ISNULL( p.Name, '[db]') AS Location

FROM syscomments c

INNER JOIN sysobjects o ON c.id=o.id

LEFT JOIN sysobjects p ON o.Parent_obj=p.id

WHERE c.text LIKE '%' + @Text + '%' and

o.xtype = case when @Type IS NULL then o.xtype  else @Type end 


ORDER BY Location, ObjectName



END

Laravel Blade html image

as of now, you can use

<img src="{{ asset('images/foo.png') }}" alt="tag">

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

You can fix the errors by validating your input, which is something you should do regardless of course.

The following typechecks correctly, via type guarding validations

const DNATranscriber = {
    G: 'C',
    C: 'G',
    T: 'A',
    A: 'U'
};

export default class Transcriptor {
    toRna(dna: string) {
        const codons = [...dna];
        if (!isValidSequence(codons)) {
            throw Error('invalid sequence');
        }
        const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
        return transcribedRNA;
    }
}

function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
    return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
    return value in DNATranscriber;
}

It is worth mentioning that you seem to be under the misapprehention that converting JavaScript to TypeScript involves using classes.

In the following, more idiomatic version, we leverage TypeScript to improve clarity and gain stronger typing of base pair mappings without changing the implementation. We use a function, just like the original, because it makes sense. This is important! Converting JavaScript to TypeScript has nothing to do with classes, it has to do with static types.

const DNATranscriber = {
    G = 'C',
    C = 'G',
    T = 'A',
    A = 'U'
};

export default function toRna(dna: string) {
    const codons = [...dna];
    if (!isValidSequence(codons)) {
        throw Error('invalid sequence');
    }
    const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
    return transcribedRNA;
}

function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
    return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
    return value in DNATranscriber;
}

Update:

Since TypeScript 3.7, we can write this more expressively, formalizing the correspondence between input validation and its type implication using assertion signatures.

const DNATranscriber = {
    G = 'C',
    C = 'G',
    T = 'A',
    A = 'U'
} as const;

type DNACodon = keyof typeof DNATranscriber;
type RNACodon = typeof DNATranscriber[DNACodon];

export default function toRna(dna: string): RNACodon[] {
    const codons = [...dna];
    validateSequence(codons);
    const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
    return transcribedRNA;
}

function validateSequence(values: string[]): asserts values is DNACodon[] {
    if (!values.every(isValidCodon)) {
        throw Error('invalid sequence');    
    }
}
function isValidCodon(value: string): value is DNACodon {
    return value in DNATranscriber;
}

You can read more about assertion signatures in the TypeScript 3.7 release notes.

How to create a Calendar table for 100 years in Sql

This SQL Server User Defined Function resolves the problem efficiently.No recursion, no complex loops. It takes a very short time to generate.

ALTER FUNCTION [GA].[udf_GenerateCalendar]
(
     @StartDate  DATE        -- StartDate
   , @EndDate    DATE        -- EndDate
)
RETURNS @Results TABLE 
       (
           Date       DATE 
       )
AS

/**********************************************************
Purpose:   Generate a sequence of dates based on StartDate and EndDate 
***********************************************************/

BEGIN

    DECLARE @counter INTEGER = 1 

    DECLARE @days table(
        day INTEGER NOT NULL 
    )

    DECLARE @months table(
        month INTEGER NOT NULL 
    )

    DECLARE @years table(
        year INTEGER NOT NULL 
    )

    DECLARE @calendar table(
        Date DATE NOT NULL 
    )


    -- Populate generic days 
    SET @counter = 1 
    WHILE @counter <= 31 
    BEGIN 
        INSERT INTO @days 
        SELECT @counter dia 

        SELECT @counter = @counter + 1 
    END 

    -- Populate generic months 
    SET @counter = 1 
    WHILE @counter <= 12 
    BEGIN 
        INSERT INTO @months 
        SELECT @counter month 

        SELECT @counter = @counter + 1 
    END 

    -- Populate generic years 
    SET @counter = YEAR(@StartDate) 
    WHILE @counter <= YEAR(@EndDate) 
    BEGIN 
        INSERT INTO @years 
        SELECT @counter year 

        SELECT @counter = @counter + 1 
    END 

    INSERT @calendar (Date) 
    SELECT Date 
    FROM ( 
        SELECT 
            CONVERT(Date, [Date], 102) AS Date 
        FROM ( 
            SELECT 
                CAST(
                    y.year * 10000 
                    + m.month * 100 
                    + d.day 
                    AS VARCHAR(8)) AS Date 
            FROM @days d, @months m, @years y 
            WHERE 
                ISDATE(CAST(
                    y.year * 10000 
                    + m.month * 100 
                    + d.day 
                    AS VARCHAR(8)) 
                    ) = 1 
        ) A 
    ) A 

    INSERT @Results (Date) 
    SELECT Date 
    FROM @calendar 
    WHERE Date BETWEEN @StartDate AND @EndDate

   RETURN 
/*
DECLARE @StartDate DATE = '2015-08-01'
DECLARE @EndDate   DATE = '2015-08-31'
select * from [GA].[udf_GenerateCalendar](@StartDate, @EndDate)
*/
END

Loop through files in a directory using PowerShell

Give this a try:

Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files" -Filter *.log | 
Foreach-Object {
    $content = Get-Content $_.FullName

    #filter and save content to the original file
    $content | Where-Object {$_ -match 'step[49]'} | Set-Content $_.FullName

    #filter and save content to a new file 
    $content | Where-Object {$_ -match 'step[49]'} | Set-Content ($_.BaseName + '_out.log')
}

Select data from "show tables" MySQL query

Yes, SELECT from table_schema could be very usefull for system administration. If you have lot of servers, databases, tables... sometimes you need to DROP or UPDATE bunch of elements. For example to create query for DROP all tables with prefix name "wp_old_...":

SELECT concat('DROP TABLE ', table_name, ';') FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = '*name_of_your_database*'
AND table_name LIKE 'wp_old_%';

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

Build your distribution .apk from Android Studio as follow

Build --> Build Apk(s) (for unsigned build) Build --> Generate Signed APK ( for signed build)

These option builds the APK with android:testOnly="false" option which allows you to install the APK expicitly into device by the commond.

adb install yourBuilT.apk

How do I undo 'git add' before commit?

Maybe Git has evolved since you posted your question.

$> git --version
git version 1.6.2.1

Now, you can try:

git reset HEAD .

This should be what you are looking for.

Drawing Circle with OpenGL

Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius

void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
    int i;
    int triangleAmount = 20; //# of triangles used to draw circle

    //GLfloat radius = 0.8f; //radius
    GLfloat twicePi = 2.0f * PI;

    glBegin(GL_TRIANGLE_FAN);
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= triangleAmount; i++) {
        glVertex2f(
            x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
            y + ((ycenter-1)* sin(i * twicePi / triangleAmount))
        );
    }
    glEnd();
}

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your HTTP client disconnected.

This could have a couple of reasons:

  • Responding to the request took too long, the client gave up
  • You responded with something the client did not understand
  • The end-user actually cancelled the request
  • A network error occurred
  • ... probably more

You can fairly easily emulate the behavior:

URL url = new URL("http://example.com/path/to/the/file");

int numberOfBytesToRead = 200;

byte[] buffer = new byte[numberOfBytesToRead];
int numberOfBytesRead = url.openStream().read(buffer);

Remove composer

Uninstall composer

To remove just composer package itself from Ubuntu 16.04 (Xenial Xerus) execute on terminal:

sudo apt-get remove composer

Uninstall composer and it's dependent packages

To remove the composer package and any other dependant package which are no longer needed from Ubuntu Xenial.

sudo apt-get remove --auto-remove composer

Purging composer

If you also want to delete configuration and/or data files of composer from Ubuntu Xenial then this will work:

sudo apt-get purge composer

To delete configuration and/or data files of composer and it's dependencies from Ubuntu Xenial then execute:

sudo apt-get purge --auto-remove composer

https://www.howtoinstall.co/en/ubuntu/xenial/composer?action=remove

Custom method names in ASP.NET Web API

In case you're using ASP.NET 5 with ASP.NET MVC 6, most of these answers simply won't work because you'll normally let MVC create the appropriate route collection for you (using the default RESTful conventions), meaning that you won't find any Routes.MapRoute() call to edit at will.

The ConfigureServices() method invoked by the Startup.cs file will register MVC with the Dependency Injection framework built into ASP.NET 5: that way, when you call ApplicationBuilder.UseMvc() later in that class, the MVC framework will automatically add these default routes to your app. We can take a look of what happens behind the hood by looking at the UseMvc() method implementation within the framework source code:

public static IApplicationBuilder UseMvc(
    [NotNull] this IApplicationBuilder app,
    [NotNull] Action<IRouteBuilder> configureRoutes)
{
    // Verify if AddMvc was done before calling UseMvc
    // We use the MvcMarkerService to make sure if all the services were added.
    MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);

    var routes = new RouteBuilder
    {
        DefaultHandler = new MvcRouteHandler(),
        ServiceProvider = app.ApplicationServices
    };

    configureRoutes(routes);

    // Adding the attribute route comes after running the user-code because
    // we want to respect any changes to the DefaultHandler.
    routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
        routes.DefaultHandler,
        app.ApplicationServices));

    return app.UseRouter(routes.Build());
}

The good thing about this is that the framework now handles all the hard work, iterating through all the Controller's Actions and setting up their default routes, thus saving you some redundant work.

The bad thing is, there's little or no documentation about how you could add your own routes. Luckily enough, you can easily do that by using either a Convention-Based and/or an Attribute-Based approach (aka Attribute Routing).

Convention-Based

In your Startup.cs class, replace this:

app.UseMvc();

with this:

app.UseMvc(routes =>
            {
                // Route Sample A
                routes.MapRoute(
                    name: "RouteSampleA",
                    template: "MyOwnGet",
                    defaults: new { controller = "Items", action = "Get" }
                );
                // Route Sample B
                routes.MapRoute(
                    name: "RouteSampleB",
                    template: "MyOwnPost",
                    defaults: new { controller = "Items", action = "Post" }
                );
            });

Attribute-Based

A great thing about MVC6 is that you can also define routes on a per-controller basis by decorating either the Controller class and/or the Action methods with the appropriate RouteAttribute and/or HttpGet / HttpPost template parameters, such as the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;

namespace MyNamespace.Controllers
{
    [Route("api/[controller]")]
    public class ItemsController : Controller
    {
        // GET: api/items
        [HttpGet()]
        public IEnumerable<string> Get()
        {
            return GetLatestItems();
        }

        // GET: api/items/5
        [HttpGet("{num}")]
        public IEnumerable<string> Get(int num)
        {
            return GetLatestItems(5);
        }       

        // GET: api/items/GetLatestItems
        [HttpGet("GetLatestItems")]
        public IEnumerable<string> GetLatestItems()
        {
            return GetLatestItems(5);
        }

        // GET api/items/GetLatestItems/5
        [HttpGet("GetLatestItems/{num}")]
        public IEnumerable<string> GetLatestItems(int num)
        {
            return new string[] { "test", "test2" };
        }

        // POST: /api/items/PostSomething
        [HttpPost("PostSomething")]
        public IActionResult Post([FromBody]string someData)
        {
            return Content("OK, got it!");
        }
    }
}

This controller will handle the following requests:

 [GET] api/items
 [GET] api/items/5
 [GET] api/items/GetLatestItems
 [GET] api/items/GetLatestItems/5
 [POST] api/items/PostSomething

Also notice that if you use the two approaches togheter, Attribute-based routes (when defined) would override Convention-based ones, and both of them would override the default routes defined by UseMvc().

For more info, you can also read the following post on my blog.

Is it bad practice to use break to exit a loop in Java?

The JLS specifies a break is an abnormal termination of a loop. However, just because it is considered abnormal does not mean that it is not used in many different code examples, projects, products, space shuttles, etc. The JVM specification does not state either an existence or absence of a performance loss, though it is clear code execution will continue after the loop.

However, code readability can suffer with odd breaks. If you're sticking a break in a complex if statement surrounded by side effects and odd cleanup code, with possibly a multilevel break with a label(or worse, with a strange set of exit conditions one after the other), it's not going to be easy to read for anyone.

If you want to break your loop by forcing the iteration variable to be outside the iteration range, or by otherwise introducing a not-necessarily-direct way of exiting, it's less readable than break.

However, looping extra times in an empty manner is almost always bad practice as it takes extra iterations and may be unclear.

Round up to Second Decimal Place in Python

The python round function could be rounding the way not you expected.

You can be more specific about the rounding method by using Decimal.quantize

eg.

from decimal import Decimal, ROUND_HALF_UP
res = Decimal('0.25').quantize(Decimal('0.0'), rounding=ROUND_HALF_UP)
print(res) 
# prints 0.3

More reference:

https://gist.github.com/jackiekazil/6201722

Colspan all columns

For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5".

The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:

IE implements the HTML 3.2 definition, it sets colspan=0 as colspan=1.

The bug is well documented.

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:

this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);

Responsive timeline UI with Bootstrap3

"Timeline (responsive)" snippet:

This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.

You can fork this and use it as a great starting point for your specific expectations:


Here are two screenshots I took for you... wide and thin:

wide thin

Pods stuck in Terminating status

I stumbled upon this recently to free up resource in my cluster. here is the command to delete them all.

kubectl get pods --all-namespaces | grep Terminating | while read line; do 
pod_name=$(echo $line | awk '{print $2}' ) name_space=$(echo $line | awk 
'{print $1}' ); kubectl delete pods $pod_name -n $name_space --grace-period=0 --force; 
done

hope this help someone who read this

Shell script to copy files from one location to another location and rename add the current date to every file

In bash, provided you files names have no spaces:

cd /home/webapps/project1/folder1
for f in *.csv
do 
   cp -v "$f" /home/webapps/project1/folder2/"${f%.csv}"$(date +%m%d%y).csv
done

How to view file diff in git before commit

Did you try -v (or --verbose) option for git commit? It adds the diff of the commit in the message editor.

prevent iphone default keyboard when focusing an <input>

By adding the attribute readonly (or readonly="readonly") to the input field you should prevent anyone typing anything in it, but still be able to launch a click event on it.

This is also usefull in non-mobile devices as you use a date/time picker

Most recent previous business day in Python

timeboard package does this.

Suppose your date is 04 Sep 2017. In spite of being a Monday, it was a holiday in the US (the Labor Day). So, the most recent business day was Friday, Sep 1.

>>> import timeboard.calendars.US as US
>>> clnd = US.Weekly8x5()
>>> clnd('04 Sep 2017').rollback().to_timestamp().date()
datetime.date(2017, 9, 1)

In UK, 04 Sep 2017 was the regular business day, so the most recent business day was itself.

>>> import timeboard.calendars.UK as UK
>>> clnd = UK.Weekly8x5()
>>> clnd('04 Sep 2017').rollback().to_timestamp().date()
datetime.date(2017, 9, 4)

DISCLAIMER: I am the author of timeboard.

Read/Parse text file line by line in VBA

I find the FileSystemObject with a TxtStream the easiest way to read files

Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(filePath, ForReading, False)

Then with this txtStream object you have all sorts of tools which intellisense picks up (unlike using the FreeFile() method) so there is less guesswork. Plus you don' have to assign a FreeFile and hope it is actually still free since when you assigned it.

You can read a file like:

Do While Not txtStream.AtEndOfStream
    txtStream.ReadLine
Loop
txtStream.Close

NOTE: This requires a reference to Microsoft Scripting Runtime.

When to use RabbitMQ over Kafka?

The only benefit that I can think of is Transactional feature, rest all can be done by using Kafka

How do I move a table into a schema in T-SQL

Short answer:

ALTER SCHEMA new_schema TRANSFER old_schema.table_name

I can confirm that the data in the table remains intact, which is probably quite important :)

Long answer as per MSDN docs,

ALTER SCHEMA schema_name 
   TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]

If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.

Pass array to MySQL stored routine

This simulates a character array but you can substitute SUBSTR for ELT to simulate a string array

declare t_tipos varchar(255) default 'ABCDE';
declare t_actual char(1);
declare t_indice integer default 1;
while t_indice<length(t_tipos)+1 do
    set t_actual=SUBSTR(t_tipos,t_indice,1);
        select t_actual;
        set t_indice=t_indice+1;
end while;

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Bootstrap sets the height of the navbar automatically to 50px. The padding above and below links is set to 15px. I think that bootstrap is adding padding to your logo.

You can either remove some of the padding above and below your logo or you can add more padding above and below links.

Adding more padding should look something like this:

nav.navbar-inverse>li>a {
 padding-top: 25px;
 padding-bottom: 25px;
}

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

In actionPerformed(ActionEvent e) you call encrypt(), which is declared to throw Exception. However, actionPerformed neither catches this Exception (with try/catch around the call to encrypt()) nor declares that it throws Exception itself.

Your encrypt method, however, does not truly throw Exception. It swallows all Exceptions without even as much as logging a complaint. (Bad practice and bad style!)

Also, your encrypt method does the following:

public static byte[] encrypt(String toEncrypt) throws Exception {
  try{
    ....
    return encrypted; // HERE YOU CORRECTLY RETURN A VALUE
  } catch(Exception e) {
  }
  // YOU DO NOT RETURN ANYTHING HERE
}

That is, if you do catch any Exception, you discard it silently and then fall off the bottom of your encrypt method without actually returning anything. This won't compile (as you see), because a method that is declared to return a value must either return a value or throw an Exception for every single possible code path.

What's the difference between identifying and non-identifying relationships?

Let's say we have those tables:

user
--------
id
name


comments
------------
comment_id
user_id
text

relationship between those two tables will identifiying relationship. Because, comments only can be belong to its owner, not other users. for example. Each user has own comment, and when user is deleted, this user's comments also should be deleted.

Class vs. static method in JavaScript

First off, remember that JavaScript is primarily a prototypal language, rather than a class-based language1. Foo isn't a class, it's a function, which is an object. You can instantiate an object from that function using the new keyword which will allow you to create something similar to a class in a standard OOP language.

I'd suggest ignoring __proto__ most of the time because it has poor cross browser support, and instead focus on learning about how prototype works.

If you have an instance of an object created from a function2 and you access one of its members (methods, attributes, properties, constants etc) in any way, the access will flow down the prototype hierarchy until it either (a) finds the member, or (b) doesn't find another prototype.

The hierarchy starts on the object that was called, and then searches its prototype object. If the prototype object has a prototype, it repeats, if no prototype exists, undefined is returned.

For example:

foo = {bar: 'baz'};
console.log(foo.bar); // logs "baz"

foo = {};
console.log(foo.bar); // logs undefined

function Foo(){}
Foo.prototype = {bar: 'baz'};
f = new Foo();
console.log(f.bar);
// logs "baz" because the object f doesn't have an attribute "bar"
// so it checks the prototype
f.bar = 'buzz';
console.log( f.bar ); // logs "buzz" because f has an attribute "bar" set

It looks to me like you've at least somewhat understood these "basic" parts already, but I need to make them explicit just to be sure.

In JavaScript, everything is an object3.

everything is an object.

function Foo(){} doesn't just define a new function, it defines a new function object that can be accessed using Foo.

This is why you can access Foo's prototype with Foo.prototype.

What you can also do is set more functions on Foo:

Foo.talk = function () {
  alert('hello world!');
};

This new function can be accessed using:

Foo.talk();

I hope by now you're noticing a similarity between functions on a function object and a static method.

Think of f = new Foo(); as creating a class instance, Foo.prototype.bar = function(){...} as defining a shared method for the class, and Foo.baz = function(){...} as defining a public static method for the class.


ECMAScript 2015 introduced a variety of syntactic sugar for these sorts of declarations to make them simpler to implement while also being easier to read. The previous example can therefore be written as:

class Foo {
  bar() {...}

  static baz() {...}
}

which allows bar to be called as:

const f = new Foo()
f.bar()

and baz to be called as:

Foo.baz()

1: class was a "Future Reserved Word" in the ECMAScript 5 specification, but ES6 introduces the ability to define classes using the class keyword.

2: essentially a class instance created by a constructor, but there are many nuanced differences that I don't want to mislead you

3: primitive values—which include undefined, null, booleans, numbers, and strings—aren't technically objects because they're low-level language implementations. Booleans, numbers, and strings still interact with the prototype chain as though they were objects, so for the purposes of this answer, it's easier to consider them "objects" even though they're not quite.

jQuery: Adding two attributes via the .attr(); method

Multiple Attribute

var tag = "tag name";
createNode(tag, target, attribute);

createNode: function(tag, target, attribute){
    var tag = jQuery("<" + tag + ">");
    jQuery.each(attribute, function(i,v){
        tag.attr(v);
    });
    target.append(tag);
    tag.appendTo(target);
}
var attribute = [
    {"data-level": "3"},
];

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

The programming language of iOS(and Mac OS) is Objective-C and C. You have to use Xcode platform to develop iOS apps, on the next version that is now available on beta release, Xcode 4 supports also C++.

How to get the Touch position in android?

Supplemental answer

Given an OnTouchListener

private View.OnTouchListener handleTouch = new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.i("TAG", "touched down");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i("TAG", "moving: (" + x + ", " + y + ")");
                break;
            case MotionEvent.ACTION_UP:
                Log.i("TAG", "touched up");
                break;
        }

        return true;
    }
};

set on some view:

myView.setOnTouchListener(handleTouch);

This gives you the touch event coordinates relative to the view that has the touch listener assigned to it. The top left corner of the view is (0, 0). If you move your finger above the view, then y will be negative. If you move your finger left of the view, then x will be negative.

int x = (int)event.getX();
int y = (int)event.getY();

If you want the coordinates relative to the top left corner of the device screen, then use the raw values.

int x = (int)event.getRawX();
int y = (int)event.getRawY();

Related

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I ran into the above error when building and running inside Eclipse, where everything seemed to be fine, with the exception of this error. However, I discovered that a Maven build failed and that I needed to include Gson in my pom.xml. After fixing the pom.xml, everything fell into place.

MySQL Update Inner Join tables query

Try this:

UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
  b.mapy = g.longitude
WHERE  (b.mapx = '' or b.mapx = 0) and
  g.latitude > 0

Update:

Since you said the query yielded a syntax error, I created some tables that I could test it against and confirmed that there is no syntax error in my query:

mysql> create table business (business_id int unsigned primary key auto_increment, mapx varchar(255), mapy varchar(255)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)

mysql> create table business_geocode (business_geocode_id int unsigned primary key auto_increment, business_id int unsigned not null, latitude varchar(255) not null, longitude varchar(255) not null, foreign key (business_id) references business(business_id)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)

mysql> UPDATE business AS b
    -> INNER JOIN business_geocode AS g ON b.business_id = g.business_id
    -> SET b.mapx = g.latitude,
    ->   b.mapy = g.longitude
    -> WHERE  (b.mapx = '' or b.mapx = 0) and
    ->   g.latitude > 0;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0  Changed: 0  Warnings: 0

See? No syntax error. I tested against MySQL 5.5.8.

Debugging WebSocket in Google Chrome

You have 3 options: Chrome (via Developer Tools -> Network tab), Wireshark, and Fiddler (via Log tab), however they all very basic. If you have very high volume of traffic or each frame is very large, it becomes very difficult to use them for debugging.

You can however use Fiddler with FiddlerScript to inspect WebSocket traffic in the same way you inpect HTTP traffic. Few advantages of this solution are that you can leverage many other functionalities in Fiddler, such as multiple inspectors (HexView, JSON, SyntaxView), compare packets, and find packets, etc. Inspect WebSocket traffic

Please refer to my recently written article on CodeProject, which show you how to Debug/Inspect WebSocket traffic with Fiddler (with FiddlerScript). http://www.codeproject.com/Articles/718660/Debug-Inspect-WebSocket-traffic-with-Fiddler

How to get cookie expiration date / creation date from javascript?

you can't get the expiration date of a cookie through javascript because when you try to read the cookie from javascript the document.cookie return just the name and the value of the cookie as pairs

Parsing a JSON string in Ruby

Don't see any answers here that mention parsing directly to an object other than a Hash, but it is possible using the poorly-documented object_class option(see https://ruby-doc.org/stdlib-2.7.1/libdoc/json/rdoc/JSON.html):

JSON.parse('{"foo":{"bar": 2}}', object_class: OpenStruct).foo.bar
=> 2

The better way to read that option is "The ruby class that a json object turns into", which explains why it defaults to Hash. Likewise, there is an array_class option for json arrays.

PostgreSQL database default location on Linux

Default in Debian 8.1 and PostgreSQL 9.4 after the installation with the package manager apt-get

ps auxw |  grep postgres | grep -- -D
postgres 17340  0.0  0.5 226700 21756 ?        S    09:50   0:00 /usr/lib/postgresql/9.4/bin/postgres -D /var/lib/postgresql/9.4/main -c config_file=/etc/postgresql/9.4/main/postgresql.conf

so apparently /var/lib/postgresql/9.4/main.

Windows CMD command for accessing usb?

Try this batch :

@echo off
Title List of connected external devices by Hackoo
Mode con cols=100 lines=20 & Color 9E
wmic LOGICALDISK where driveType=2 get deviceID > wmic.txt
for /f "skip=1" %%b IN ('type wmic.txt') DO (echo %%b & pause & Dir %%b)
Del wmic.txt
pause

How to handle the click event in Listview in android?

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

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

join list of lists in python

If you need a list, not a generator, use list():

from itertools import chain
x = [["a","b"], ["c"]]
y = list(chain(*x))

z-index issue with twitter bootstrap dropdown menu

Just realized what's going on.

I had the navbar inside a header which was position: fixed;

Changed the z-index on the header and it's working now - guess I didn't look high enough up the containers to set the z-index initially !#@!?

Thanks.

How to change spinner text size and text color?

If all the spinners may have the same text color for their TextView items, another approach is to use a custom style for spinner dropdown items:

In res/values/styles.xml:

<resources>
    <style name="AppBaseTheme" parent="android:Theme.Light">
    </style>

    <style name="AppTheme" parent="AppBaseTheme">
        <item name="android:spinnerDropDownItemStyle">@style/mySpinnerItemStyle</item>
    </style>

    <style name="mySpinnerItemStyle" parent="@android:style/Widget.Holo.DropDownItem.Spinner">
        <item name="android:textColor">@color/my_spinner_text_color</item>
    </style>
</resources>

And define your custom color in res/values/colors.xml:

<color name="my_spinner_text_color">#808080</color>

Run bash script from Windows PowerShell

You should put the script as argument for a *NIX shell you run, equivalent to the *NIXish

sh myscriptfile

getContext is not a function

I got the same error because I had accidentally used <div> instead of <canvas> as the element on which I attempt to call getContext.

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

I had exactly the same error message. In my case, making an entry in my /etc/hosts file (on the server hosting the service) for the target server referenced in the WSDL fixed it.

Kind of a strangely worded error message..

How to Export-CSV of Active Directory Objects?

HI you can try this...

Try..

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq ""}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\ceridian\NoClockNumber_2013_02_12.csv -NoTypeInformation

Or

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq $null}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\cer

Hope it works for you.

How to check if a value is not null and not empty string in JS

Both null and an empty string are falsy values in JS. Therefore,

if (data) { ... }

is completely sufficient.

A note on the side though: I would avoid having a variable in my code that could manifest in different types. If the data will eventually be a string, then I would initially define my variable with an empty string, so you can do this:

if (data !== '') { ... }

without the null (or any weird stuff like data = "0") getting in the way.

Overlay with spinner

As an update, for Angular 7, a very good example, loading plus http interceptor, here: https://nezhar.com/blog/create-a-loading-screen-for-angular-apps/.

For version 6, you need a small adjustment when you use Subject. You need to add the generic type.

loadingStatus: Subject<boolean> = new Subject();

I'm using angular material, so instead of a loading text, you can use mat-spinner.

<mat-spinner></mat-spinner>

Update: the code from the previous page will not complete work (regarding the interceptor part), but here you have the complete solution: https://github.com/nezhar/snypy-frontend

And as Miranda recommended into comments, here is also the solution:

The loading screen component:

loading-screen.component.ts

    import { Component, ElementRef, ChangeDetectorRef, OnDestroy, AfterViewInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { LoadingScreenService } from '../services/loading-screen.service';

@Component({
  selector: 'app-loading-screen',
  templateUrl: './loading-screen.component.html',
  styleUrls: ['./loading-screen.component.css']
})
export class LoadingScreenComponent implements AfterViewInit, OnDestroy {

  loading: boolean = false;
  loadingSubscription: Subscription;

  constructor(
    private loadingScreenService: LoadingScreenService,
    private _elmRef: ElementRef,
    private _changeDetectorRef: ChangeDetectorRef
  ) { }

  ngAfterViewInit(): void {
    this._elmRef.nativeElement.style.display = 'none';
    this.loadingSubscription = this.loadingScreenService.loadingStatus.pipe().subscribe(
      (status: boolean) => {
        this._elmRef.nativeElement.style.display = status ? 'block' : 'none';
        this._changeDetectorRef.detectChanges();
      }
    );
  }

  ngOnDestroy() {
    console.log("inside destroy loading component");
    this.loadingSubscription.unsubscribe();
  }

}

loading-screen.component.html

<div id="overlay">
  <mat-spinner class="content"></mat-spinner>
</div>

loading-screen.component.css

  #overlay {
      position: fixed; /* Sit on top of the page content */
      display: block; /* Hidden by default */
      width: 100%; /* Full width (cover the whole page) */
      height: 100%; /* Full height (cover the whole page) */
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(60, 138, 255, 0.1); /* Black background with opacity */
      opacity: 0.5;
      z-index: 2; /* Specify a stack order in case you're using a different order for other elements */
      cursor: progress; /* Add a pointer on hover */
  }

  .content {
      position: absolute;
      top: 50%;
      left: 50%;
      font-size: 50px;
      color: white;
      transform: translate(-50%, -50%);
      -ms-transform: translate(-50%, -50%);
  }

Don't forget to add the component to your root component. In my case, AppComponent

app.component.html

<app-loading-screen></app-loading-screen>

The service that will manage the component: loading-screen.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoadingScreenService {

  constructor() { }

  private _loading: boolean = false;
  loadingStatus: Subject<boolean> = new Subject();

  get loading(): boolean {
    console.log("get loading: " + this._loading);
    return this._loading;
  }

  set loading(value) {
    console.log("get loading: " + value);
    this._loading = value;
    this.loadingStatus.next(value);
  }

  startLoading() {
    console.log("startLoading");
    this.loading = true;
  }

  stopLoading() {
    console.log("stopLoading");
    this.loading = false;
  }
}

Here is the http interceptor, which will show/hide the component, using the previous service.

loading-screen-interceptor.ts

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { LoadingScreenService } from '../services/loading-screen.service';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';

@Injectable()
export class LoadingScreenInterceptor implements HttpInterceptor {

    activeRequests: number = 0;

    constructor(
        private loadingScreenService: LoadingScreenService
    ) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        console.log("inside interceptor");

        if (this.activeRequests === 0) {
            this.loadingScreenService.startLoading();
        }

        this.activeRequests++;

        return next.handle(request).pipe(
            finalize(() => {
                this.activeRequests--;
                if (this.activeRequests === 0) {
                    this.loadingScreenService.stopLoading();
                }
            })
        )
    };
}

And in your app.module.ts, don't forget to config the interceptor

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: LoadingScreenInterceptor,
      multi: true
    }
  ]

get parent's view from a layout

Just write

this.getRootView();

How to select first child with jQuery?

$('div.alldivs :first-child');

Or you can just refer to the id directly:

$('#div1');

As suggested, you might be better of using the child selector:

$('div.alldivs > div:first-child')

If you dont have to use first-child, you could use :first as also suggested, or $('div.alldivs').children(0).

MySQL Select Multiple VALUES

Try this -

 select * from table where id in (3,4) or [name] in ('andy','paul');

How to invert a grep expression

Use command-line option -v or --invert-match,

ls -R |grep -v -E .*[\.exe]$\|.*[\.html]$

How to change fonts in matplotlib (python)?

Say you want Comic Sans for the title and Helvetica for the x label.

csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}

plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()

Java getting the Enum name given the Enum Value

Try, the following code..

    @Override
    public String toString() {
    return this.name();
    }

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

Database rebuild fixed it for me as well. Also had to restore the old database from backup as it got corrupted during power outage... The copy master.mdf procedure did not work for me.

What's the best way to break from nested loops in JavaScript?

If you use Coffeescript, there is a convenient "do" keyword that makes it easier to define and immediately execute an anonymous function:

do ->
  for a in first_loop
    for b in second_loop
      if condition(...)
        return

...so you can simply use "return" to get out of the loops.

How to set underline text on textview?

Use this

tvHide.setPaintFlags(tvHide.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

Kill Attached Screen in Linux

screen -X -S SCREENID kill

alternatively, you can use the following command

screen -S SCREENNAME -p 0 -X quit

You can view the list of the screen sessions by executing screen -ls

How to keep a git branch in sync with master

The accepted answer via git merge will get the job done but leaves a messy commit hisotry, correct way should be 'rebase' via the following steps(assuming you want to keep your feature branch in sycn with develop before you do the final push before PR).

1 git fetch from your feature branch (make sure the feature branch you are working on is update to date)

2 git rebase origin/develop

3 if any conflict shall arise, resolve them one by one

4 use git rebase --continue once all conflicts are dealt with

5 git push --force

How may I sort a list alphabetically using jQuery?

improvement based on Jeetendra Chauhan's answer

$('ul.menu').each(function(){
    $(this).children('li').sort((a,b)=>a.innerText.localeCompare(b.innerText)).appendTo(this);
});

why i consider it an improvement:

  1. using each to support running on more than one ul

  2. using children('li') instead of ('ul li') is important because we only want to process direct children and not descendants

  3. using the arrow function (a,b)=> just looks better (IE not supported)

  4. using vanilla innerText instead of $(a).text() for speed improvement

  5. using vanilla localeCompare improves speed in case of equal elements (rare in real life usage)

  6. using appendTo(this) instead of using another selector will make sure that even if the selector catches more than one ul still nothing breaks

Can I run multiple programs in a Docker container?

If a dedicated script seems like too much overhead, you can spawn separate processes explicitly with sh -c. For example:

CMD sh -c 'mini_httpd -C /my/config -D &' \
 && ./content_computing_loop

Session only cookies with Javascript

For creating session only cookie with java script, you can use the following. This works for me.

document.cookie = "cookiename=value; expires=0; path=/";

then get cookie value as following

 //get cookie 
var cookiename = getCookie("cookiename");
if (cookiename == "value") {
    //write your script
}

//function getCookie        
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

Okay to support IE we can leave "expires" completely and can use this

document.cookie = "mtracker=somevalue; path=/";

Set Radiobuttonlist Selected from Codebehind

You could do:

radio1.SelectedIndex = 1;

But this is the most simple form and would most likely become problematic as your UI grows. Say, for instance, if a team member inserts an item in the RadioButtonList above option2 but doesn't know we use magic numbers in code-behind to select - now the app selects the wrong index!

Maybe you want to look into using FindControl in order to determine the ListItem actually required, by name, and selecting appropriately. For instance:

//omitting possible null reference checks...
var wantedOption = radio1.FindControl("option2").Selected = true;

How to customize message box

MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

T-SQL: Looping through an array of known values

I usually use the following approach

DECLARE @calls TABLE (
    id INT IDENTITY(1,1)
    ,parameter INT
    )

INSERT INTO @calls
select parameter from some_table where some_condition -- here you populate your parameters

declare @i int
declare @n int
declare @myId int
select @i = min(id), @n = max(id) from @calls
while @i <= @n
begin
    select 
        @myId = parameter
    from 
        @calls
    where id = @i

        EXECUTE p_MyInnerProcedure @myId
    set @i = @i+1
end

Convert timestamp long to normal date format

java.time

    ZoneId usersTimeZone = ZoneId.of("Asia/Tashkent");
    Locale usersLocale = Locale.forLanguageTag("ga-IE");
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(usersLocale);

    long microsSince1970 = 1_512_345_678_901_234L;
    long secondsSince1970 = TimeUnit.MICROSECONDS.toSeconds(microsSince1970);
    long remainingMicros = microsSince1970 - TimeUnit.SECONDS.toMicros(secondsSince1970);
    ZonedDateTime dateTime = Instant.ofEpochSecond(secondsSince1970, 
                    TimeUnit.MICROSECONDS.toNanos(remainingMicros))
            .atZone(usersTimeZone);
    String dateTimeInUsersFormat = dateTime.format(formatter);
    System.out.println(dateTimeInUsersFormat);

The above snippet prints:

4 Noll 2017 05:01:18

“Noll” is Gaelic for December, so this should make your user happy. Except there may be very few Gaelic speaking people living in Tashkent, so please specify the user’s correct time zone and locale yourself.

I am taking seriously that you got microseconds from your database. If second precision is fine, you can do without remainingMicros and just use the one-arg Instant.ofEpochSecond(), which will make the code a couple of lines shorter. Since Instant and ZonedDateTime do support nanosecond precision, I found it most correct to keep the full precision of your timestamp. If your timestamp was in milliseconds rather than microseconds (which they often are), you may just use Instant.ofEpochMilli().

The answers using Date, Calendar and/or SimpleDateFormat were fine when this question was asked 7 years ago. Today those classes are all long outdated, and we have so much better in java.time, the modern Java date and time API.

For most uses I recommend you use the built-in localized formats as I do in the code. You may experiment with passing SHORT, LONG or FULL for format style. Yo may even specify format style for the date and for the time of day separately using an overloaded ofLocalizedDateTime method. If a specific format is required (this was asked in a duplicate question), you can have that:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss, dd/MM/uuuu");

Using this formatter instead we get

05:01:18, 04/12/2017

Link: Oracle tutorial: Date Time explaining how to use java.time.

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

How to return a PNG image from Jersey REST service method to the browser

I'm not convinced its a good idea to return image data in a REST service. It ties up your application server's memory and IO bandwidth. Much better to delegate that task to a proper web server that is optimized for this kind of transfer. You can accomplish this by sending a redirect to the image resource (as a HTTP 302 response with the URI of the image). This assumes of course that your images are arranged as web content.

Having said that, if you decide you really need to transfer image data from a web service you can do so with the following (pseudo) code:

@Path("/whatever")
@Produces("image/png")
public Response getFullImage(...) {

    BufferedImage image = ...;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    byte[] imageData = baos.toByteArray();

    // uncomment line below to send non-streamed
    // return Response.ok(imageData).build();

    // uncomment line below to send streamed
    // return Response.ok(new ByteArrayInputStream(imageData)).build();
}

Add in exception handling, etc etc.

In C#, why is String a reference type that behaves like a value type?

It is mainly a performance issue.

Having strings behave LIKE value type helps when writing code, but having it BE a value type would make a huge performance hit.

For an in-depth look, take a peek at a nice article on strings in the .net framework.

Where is the correct location to put Log4j.properties in an Eclipse project?

In general I put it in a special folder "res" or "resources as already said, but after for the web application, I copy the log4j.properties with the ant task to the WEB-INF/classes directory. It is the same like letting the file at the root of the src/ folder but generally I prefer to see it in a dedicated folder.

With Maven, the usual place to put is in the folder src/main/resources as answered in this other post. All resources there will go to your build in the root classpath (e.g. target/classes/)

If you want a powerful logger, you can have also a look to slf4j library which is a logger facade and can use the log4j implementation behind.

hasNext in Python iterators?

Suggested way is StopIteration. Please see Fibonacci example from tutorialspoint

#!usr/bin/python3

import sys
def fibonacci(n): #generator function
   a, b, counter = 0, 1, 0
   while True:
      if (counter > n): 
         return
      yield a
      a, b = b, a + b
      counter += 1
f = fibonacci(5) #f is iterator object

while True:
   try:
      print (next(f), end=" ")
   except StopIteration:
      sys.exit()

Error: "Could Not Find Installable ISAM"

Try putting single quotes around the data source:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb';

The problem tends to be white space which does have meaning to the parser.

If you had other attributes (e.g., Extended Properties), their values may also have to be enclosed in single quotes:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb'; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';

You could equally well use double quotes; however, you'll probably have to escape them, and I find that more of a Pain In The Algorithm than using singles.

How can I change NULL to 0 when getting a single value from a SQL function?

You can use ISNULL().

SELECT ISNULL(SUM(Price), 0) AS TotalPrice 
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

That should do the trick.

Openssl is not recognized as an internal or external command

it's late answer but it will help to lazy people like me.. add this code to your Application class, there is no need to download openssl and no need to set the path.. only need is just copy this code.. and keyHash will generated in log.

import com.facebook.FacebookSdk;
public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
        printKeyHash();
    }

    private void printKeyHash() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    getPackageName(), PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.i("KeyHash:",
                        Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("jk", "Exception(NameNotFoundException) : " + e);
        } catch (NoSuchAlgorithmException e) {
            Log.e("mkm", "Exception(NoSuchAlgorithmException) : " + e);
        }
    }
}

and do not forget add MyApplication class in manifest:

<application
        android:name=".MyApplication"
</application>

Choosing a jQuery datagrid plugin?

You should look here: https://stackoverflow.com/questions/159025/jquery-grid-recommendations

Update

The link above takes to a question that was closed and then deleted. Here are the original suggestions that were on the most voted answer:

What should a JSON service return on failure / error

I would definitely return a 500 error with a JSON object describing the error condition, similar to how an ASP.NET AJAX "ScriptService" error returns. I believe this is fairly standard. It's definitely nice to have that consistency when handling potentially unexpected error conditions.

Aside, why not just use the built in functionality in .NET, if you're writing it in C#? WCF and ASMX services make it easy to serialize data as JSON, without reinventing the wheel.

Send JSON data from Javascript to PHP?

PHP has a built in function called json_decode(). Just pass the JSON string into this function and it will convert it to the PHP equivalent string, array or object.

In order to pass it as a string from Javascript, you can convert it to JSON using

JSON.stringify(object);

or a library such as Prototype

JPA EntityManager: Why use persist() over merge()?

There are some more differences between merge and persist (I will enumerate again those already posted here):

D1. merge does not make the passed entity managed, but rather returns another instance that is managed. persist on the other side will make the passed entity managed:

//MERGE: passedEntity remains unmanaged, but newEntity will be managed
Entity newEntity = em.merge(passedEntity);

//PERSIST: passedEntity will be managed after this
em.persist(passedEntity);

D2. If you remove an entity and then decide to persist the entity back, you may do that only with persist(), because merge will throw an IllegalArgumentException.

D3. If you decided to take care manually of your IDs (e.g by using UUIDs), then a merge operation will trigger subsequent SELECT queries in order to look for existent entities with that ID, while persist may not need those queries.

D4. There are cases when you simply do not trust the code that calls your code, and in order to make sure that no data is updated, but rather is inserted, you must use persist.

Any good, visual HTML5 Editor or IDE?

NetBeans 7 has nice support for HTML5. Previously I was a heavy user of Eclipse, but spend more time with NetBeans to play with HTML5 and Servlet.

How to concatenate two MP4 files using FFmpeg?

Merging all mp4 files from current directory

I personnaly like not creating external file that I have to delete afterwards, so my solution was following which includes files numbering listing (like file_1_name, file_2_name, file_10_name, file_20_name, file_100_name, ...)

#!/bin/bash
filesList=""
for file in $(ls -1v *.mp4);do #lists even numbered file
    filesList="${filesList}${file}|"
done
filesList=${filesList%?} # removes trailing pipe
ffmpeg -i "concat:$filesList" -c copy $(date +%Y%m%d_%H%M%S)_merged.mp4

NullPointerException in Java with no StackTrace

toString() only returns the exception name and the optional message. I would suggest calling

exception.printStackTrace()

to dump the message, or if you need the gory details:

 StackTraceElement[] trace = exception.getStackTrace()

Count Rows in Doctrine QueryBuilder

To count items after some number of items (offset), $qb->setFirstResults() cannot be applied in this case, as it works not as a condition of query, but as an offset of query result for a range of items selected (i. e. setFirstResult cannot be used togather with COUNT at all). So to count items, which are left I simply did the following:

   //in repository class:
   $count = $qb->select('count(p.id)')
      ->from('Products', 'p')
      ->getQuery()
      ->getSingleScalarResult();

    return $count;

    //in controller class:
    $count = $this->em->getRepository('RepositoryBundle')->...

    return $count-$offset;

Anybody knows more clean way to do it?

How does Task<int> become an int?

Does an implicit conversion occur between Task<> and int?

Nope. This is just part of how async/await works.

Any method declared as async has to have a return type of:

  • void (avoid if possible)
  • Task (no result beyond notification of completion/failure)
  • Task<T> (for a logical result of type T in an async manner)

The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length - you can't make the method just return int, as the actual method will return when it hits the first await expression which hasn't already completed. So instead, it returns a Task<int> which will complete when the async method itself completes.

Note that await does the opposite - it unwraps a Task<T> to a T value, which is how this line works:

string urlContents = await getStringTask;

... but of course it unwraps it asynchronously, whereas just using Result would block until the task had completed. (await can unwrap other types which implement the awaitable pattern, but Task<T> is the one you're likely to use most often.)

This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:

public async Task<int> AccessTheWebAndDoubleAsync()
{
    var task = AccessTheWebAsync();
    int result = await task;
    return result * 2;
}

(Or simply return await AccessTheWebAsync() * 2; of course.)

Changing the image source using jQuery

I have the same wonder today, I did on this way :

//<img src="actual.png" alt="myImage" class=myClass>
$('.myClass').attr('src','').promise().done(function() {
$(this).attr('src','img/new.png');  
});

Using OR & AND in COUNTIFS

In a more general case:

N( A union B) = N(A) + N(B) - N(A intersect B) 
= COUNTIFS(A1:A196,"Yes",J1:J196,"Agree")+COUNTIFS(A1:A196,"No",J1:J196,"Agree")-A1:A196,"Yes",A1:A196,"No")

How do you implement a re-try-catch?

Most of these answers are essentially the same. Mine is also, but this is the form I like

boolean completed = false;
Throwable lastException = null;
for (int tryCount=0; tryCount < config.MAX_SOME_OPERATION_RETRIES; tryCount++)
{
    try {
        completed = some_operation();
        break;
    }
    catch (UnlikelyException e) {
        lastException = e;
        fix_the_problem();
    }
}
if (!completed) {
    reportError(lastException);
}

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous FTP usage is covered by RFC 1635: How to Use Anonymous FTP:

What is Anonymous FTP?

Anonymous FTP is a means by which archive sites allow general access to their archives of information. These sites create a special account called "anonymous".

Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address. Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password. Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services.

These are general recommendations, though. Each FTP server may have its own guidelines.

For sample use of the ftp command on anonymous FTP access, see appendix A:

atlas.arc.nasa.gov% ftp naic.nasa.gov
Connected to naic.nasa.gov.
220 naic.nasa.gov FTP server (Wed May 4 12:15:15 PDT 1994) ready.
Name (naic.nasa.gov:amarine): anonymous
331 Guest login ok, send your complete e-mail address as password.
Password:
230-----------------------------------------------------------------
230-Welcome to the NASA Network Applications and Info Center Archive
230-
230-     Access to NAIC's online services is also available through:
230-
230-        Gopher         - naic.nasa.gov (port 70)
230-    World-Wide-Web - http://naic.nasa.gov/naic/naic-home.html
230-
230-        If you experience any problems please send email to
230-
230-                    [email protected]
230-
230-                 or call +1 (800) 858-9947
230-----------------------------------------------------------------
230-
230-Please read the file README
230-  it was last modified on Fri Dec 10 13:06:33 1993 - 165 days ago
230 Guest login ok, access restrictions apply.
ftp> cd files/rfc
250-Please read the file README.rfc
250-  it was last modified on Fri Jul 30 16:47:29 1993 - 298 days ago
250 CWD command successful.
ftp> get rfc959.txt
200 PORT command successful.
150 Opening ASCII mode data connection for rfc959.txt (147316 bytes).
226 Transfer complete.
local: rfc959.txt remote: rfc959.txt
151249 bytes received in 0.9 seconds (1.6e+02 Kbytes/s)
ftp> quit
221 Goodbye.
atlas.arc.nasa.gov%

See also the example session at the University of Edinburgh site.

How to use ScrollView in Android?

As said above you can put it inside a ScrollView... and if you want the Scroll View to be horizontal put it inside HorizontalScrollView... and if you want your component (or layout) to support both put inside both of them like this:

  <HorizontalScrollView>
        <ScrollView>
            <!-- SOME THING -->
        </ScrollView>
    </HorizontalScrollView>

and with setting the layout_width and layout_height ofcourse.

ImportError: No module named Crypto.Cipher

I found the solution. Issue is probably in case sensitivity (on Windows).

Just change the name of the folder:

  • C:\Python27\Lib\site-packages\crypto
  • to: C:\Python27\Lib\site-packages\Crypto

This is how folder was named after installation of pycrypto: enter image description here

I've changed it to: enter image description here

And now the following code works fine: enter image description here

How to use GNU Make on Windows?

You can add the application folder to your path from a command prompt using:

setx PATH "%PATH%;c:\MinGW\bin"

Note that you will probably need to open a new command window for the modified path setting to go into effect.

Add custom message to thrown exception while maintaining stack trace in Java

Following code is a simple example that worked for me.Let me call the function main as parent function and divide as child function.
Basically i am throwing a new exception with my custom message (for the parent's call) if an exception occurs in child function by catching the Exception in the child first.

class Main {
    public static void main(String args[]) {
        try{
            long ans=divide(0);
            System.out.println("answer="+ans);
        }
        catch(Exception e){
            System.out.println("got exception:"+e.getMessage());

        }

    }
    public static long divide(int num) throws Exception{
        long x=-1;
        try {
            x=5/num;
        }
        catch (Exception e){
            throw new Exception("Error occured in divide for number:"+num+"Error:"+e.getMessage());
        }
        return x;
    }
}  

the last line return x will not run if error occurs somewhere in between.

paint() and repaint() in Java

The paint() method supports painting via a Graphics object.

The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

How to require a controller in an angularjs directive

I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".


It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.

Share a Controller

Two directives can use the same controller by passing the same method to two directives, like so:

app.controller( 'MyCtrl', function ( $scope ) {
  // do stuff...
});

app.directive( 'directiveOne', function () {
  return {
    controller: 'MyCtrl'
  };
});

app.directive( 'directiveTwo', function () {
  return {
    controller: 'MyCtrl'
  };
});

Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.

Require a Controller

If you want to share the same instance of a controller, then you use require.

require ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel.

^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.

In either event, you have to use the two directives together for this to work. require is a way of communicating between components.

Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive

How would you make a comma-separated string from a list of strings?

@jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator

from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))

How to resize datagridview control when form resizes

For me, anchoring works only if I set it to all four sides:

Anchoring: Top, Bottom, Left, Right

Setting anchoring just to Left, Bottom moves the whole object when the form is resized in bottom, left side. Setting all four sizes really resizes the object, when parent is resized.

How do you set the document title in React?

Since React 16.8. you can build a custom hook to do so (similar to the solution of @Shortchange):

export function useTitle(title) {
  useEffect(() => {
    const prevTitle = document.title
    document.title = title
    return () => {
      document.title = prevTitle
    }
  })
}

this can be used in any react component, e.g.:

const MyComponent = () => {
  useTitle("New Title")
  return (
    <div>
     ...
    </div>
  )
}

It will update the title as soon as the component mounts and reverts it to the previous title when it unmounts.

Difference Between ViewResult() and ActionResult()

ViewResult is a subclass of ActionResult. The View method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could change the method body to conditionally return a RedirectResult or something else without changing the method definition.

Fastest JavaScript summation

I tried using performance.now() to analyze the performance of the different types of loops. I took a very large array and found the sum of all elements of the array. I ran the code three times every time and found forEach and reduce to be a clear winner.

// For loop

let arr = [...Array(100000).keys()]
function addUsingForLoop(ar){
  let sum = 0;
  for(let i = 0; i < ar.length; i++){
    sum += ar[i];
  }
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingForLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 42.17500000959262 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.41999999107793 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 49.845000030472875 milliseconds"

// While loop

let arr = [...Array(100000).keys()]
function addUsingWhileLoop(ar){
let sum = 0;
let index = 0;
while (index < ar.length) {
  sum += ar[index];
  index++;
}
  console.log(`Sum: ${sum}`)
  return sum;
}
let t1 = performance.now();
addUsingWhileLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 44.2499999771826 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.01999997207895 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 41.71000001952052 milliseconds"

// do-while

let arr = [...Array(100000).keys()]
function addUsingDoWhileLoop(ar){
let sum = 0;
let index = 0;
do {
   sum += index;
   index++;
} while (index < ar.length);
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingDoWhileLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 43.79500000504777 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 43.47500001313165 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 47.535000019706786 milliseconds"

// Reverse loop

let arr = [...Array(100000).keys()]
function addUsingReverseLoop(ar){
   var sum=0;
   for (var i=ar.length; i--;) {
     sum+=arr[i];
   }
   console.log(`Sum: ${sum}`);
   return sum;
}
let t1 = performance.now();
addUsingReverseLoop(arr);
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 46.199999982491136 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.96500000823289 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 43.880000011995435 milliseconds"

// Reverse while loop

let arr = [...Array(100000).keys()]
function addUsingReverseWhileLoop(ar){
    var sum = 0;
    var i = ar.length; 
    while (i--) {
        sum += ar[i];
    }
    console.log(`Sum: ${sum}`);
    return sum;
}
var t1 = performance.now();
addUsingReverseWhileLoop(arr);
var t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 46.26999999163672 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 42.97000000951812 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 44.31500000646338 milliseconds"

// reduce

let arr = [...Array(100000).keys()]
let t1 = performance.now();
sum = arr.reduce((pv, cv) => pv + cv, 0);
console.log(`Sum: ${sum}`)
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 4.654999997001141 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.040000018198043 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 4.835000028833747 milliseconds"

// forEach

let arr = [...Array(100000).keys()]
function addUsingForEach(ar){
  let sum = 0;
  ar.forEach(item => {
    sum += item;
  })
    console.log(`Sum: ${sum}`);
    return sum
}
let t1 = performance.now();
addUsingForEach(arr)
let t2 = performance.now();
console.log(`Time Taken ~ ${(t2 - t1)} milliseconds`)

// "Sum: 4999950000"
// "Time Taken ~ 5.315000016707927 milliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.869999993592501 mienter code herelliseconds"
// "Sum: 4999950000"
// "Time Taken ~ 5.405000003520399 milliseconds"

How do I download the Android SDK without downloading Android Studio?

You can find the command line tools at the downloads page under the "Command line tools only" section.

enter image description here

These are the links provided in the page as of now (version 26.1.1):

Be sure to have read and agreed with the terms of service before downloading any of the command line tools.

The installer version for windows doesn't seem to be available any longer, this is the link for version 24.4.1:

JComboBox Selection Change Listener?

Here is creating a ComboBox adding a listener for item selection change:

JComboBox comboBox = new JComboBox();

comboBox.setBounds(84, 45, 150, 20);
contentPane.add(comboBox);

JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBounds(84, 97, 150, 20);
contentPane.add(comboBox_1);
comboBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent arg0) {
        //Do Something
    }
});

Getting Access Denied when calling the PutObject operation with bucket-level permission

To answer my own question:

The example policy granted PutObject access, but I also had to grant PutObjectAcl access.

I had to change

"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject"

from the example to:

"s3:PutObject",
"s3:PutObjectAcl",
"s3:GetObject",
"s3:GetObjectAcl",
"s3:DeleteObject"

You also need to make sure your bucket is configured for clients to set a public-accessible ACL by unticking these two boxes:

enter image description here

The EntityManager is closed

// first need to reset current manager
$em->resetManager();
// and then get new
$em = $this->getContainer()->get("doctrine");
// or in this way, depending of your environment:
$em = $this->getDoctrine();

Order Bars in ggplot2 bar graph

Using scale_x_discrete (limits = ...) to specify the order of bars.

positions <- c("Goalkeeper", "Defense", "Striker")
p <- ggplot(theTable, aes(x = Position)) + scale_x_discrete(limits = positions)

Data binding to SelectedItem in a WPF Treeview

I know this thread is 10 years old but the problem still exists....

The original question was 'to retrieve' the selected item. I also needed to "get" the selected item in my viewmodel (not set it). Of all the answers in this thread, the one by 'Wes' is the only one that approaches the problem differently: If you can use the 'Selected Item' as a target for databinding use it as a source for databinding. Wes did it to another view property, I will do it to a viewmodel property:

We need two things:

  • Create a dependency property in the viewmodel (in my case of type 'MyObject' as my treeview is bound to object of the 'MyObject' type)
  • Bind from the Treeview.SelectedItem to this property in the View's constructor (yes that is code behind but, it's likely that you will init your datacontext there as well)

Viewmodel:

public static readonly DependencyProperty SelectedTreeViewItemProperty = DependencyProperty.Register("SelectedTreeViewItem", typeof(MyObject), typeof(MyViewModel), new PropertyMetadata(OnSelectedTreeViewItemChanged));

    private static void OnSelectedTreeViewItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        (d as MyViewModel).OnSelectedTreeViewItemChanged(e);
    }

    private void OnSelectedTreeViewItemChanged(DependencyPropertyChangedEventArgs e)
    {
        //do your stuff here
    }

    public MyObject SelectedWorkOrderTreeViewItem
    {
        get { return (MyObject)GetValue(SelectedTreeViewItemProperty); }
        set { SetValue(SelectedTreeViewItemProperty, value); }
    }

View constructor:

Binding binding = new Binding("SelectedItem")
        {
            Source = treeView, //name of tree view in xaml
            Mode = BindingMode.OneWay
        };

        BindingOperations.SetBinding(DataContext, MyViewModel.SelectedTreeViewItemProperty, binding);

JOptionPane Input to int

Simply use:

int ans = Integer.parseInt( JOptionPane.showInputDialog(frame,
        "Text",
        JOptionPane.INFORMATION_MESSAGE,
        null,
        null,
        "[sample text to help input]"));

You cannot cast a String to an int, but you can convert it using Integer.parseInt(string).

Why is the Android emulator so slow? How can we speed up the Android emulator?

Gone were those days, when we used to run projects on slow Android Emulators. Today, Android Emulators are on steroids.. Yeah you heard me. No other emulators are as fast as Android Emulators. You can go to my blog for more details:

http://androidveteran.blogspot.in/2016/01/android-emulator-multi-touch.html

I have explained in details about new Android Emulators. Check it out.

Believe me they are as fast as your real device works.

Using Tempdata in ASP.NET MVC - Best practice

Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.

The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx

Removing time from a Date object?

You can also manually change the time part of date and format in "dd/mm/yyyy" pattern according to your requirement.

  public static Date getZeroTimeDate(Date changeDate){

        Date returnDate=new Date(changeDate.getTime()-(24*60*60*1000));
        return returnDate;
    }

If the return value is not working then check for the context parameter in web.xml. eg.

   <context-param> 
        <param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
        <param-value>true</param-value>
    </context-param>

How to Lock/Unlock screen programmatically?

Edit:

As some folks needs help in Unlocking device after locking programmatically, I came through post Android screen lock/ unlock programatically, please have look, may help you.

Original Answer was:

You need to get Admin permission and you can lock phone screen

please check below simple tutorial to achive this one

Lock Phone Screen Programmtically

also here is the code example..

LockScreenActivity.java

public class LockScreenActivity extends Activity implements OnClickListener {  
 private Button lock;  
 private Button disable;  
 private Button enable;  
 static final int RESULT_ENABLE = 1;  

     DevicePolicyManager deviceManger;  
     ActivityManager activityManager;  
     ComponentName compName;  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  

        deviceManger = (DevicePolicyManager)getSystemService(  
          Context.DEVICE_POLICY_SERVICE);  
        activityManager = (ActivityManager)getSystemService(  
          Context.ACTIVITY_SERVICE);  
        compName = new ComponentName(this, MyAdmin.class);  

        setContentView(R.layout.main);  

        lock =(Button)findViewById(R.id.lock);  
        lock.setOnClickListener(this);  

        disable = (Button)findViewById(R.id.btnDisable);  
        enable =(Button)findViewById(R.id.btnEnable);  
        disable.setOnClickListener(this);  
        enable.setOnClickListener(this);  
    }  

 @Override  
 public void onClick(View v) {  

  if(v == lock){  
    boolean active = deviceManger.isAdminActive(compName);  
             if (active) {  
                 deviceManger.lockNow();  
             }  
  }  

  if(v == enable){  
   Intent intent = new Intent(DevicePolicyManager  
     .ACTION_ADD_DEVICE_ADMIN);  
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,  
                    compName);  
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,  
                    "Additional text explaining why this needs to be added.");  
            startActivityForResult(intent, RESULT_ENABLE);  
  }  

  if(v == disable){  
     deviceManger.removeActiveAdmin(compName);  
              updateButtonStates();  
  }    
 }  

 private void updateButtonStates() {  

        boolean active = deviceManger.isAdminActive(compName);  
        if (active) {  
            enable.setEnabled(false);  
            disable.setEnabled(true);  

        } else {  
            enable.setEnabled(true);  
            disable.setEnabled(false);  
        }      
 }  

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
         switch (requestCode) {  
             case RESULT_ENABLE:  
                 if (resultCode == Activity.RESULT_OK) {  
                     Log.i("DeviceAdminSample", "Admin enabled!");  
                 } else {  
                     Log.i("DeviceAdminSample", "Admin enable FAILED!");  
                 }  
                 return;  
         }  
         super.onActivityResult(requestCode, resultCode, data);  
     }  
}

MyAdmin.java

public class MyAdmin extends DeviceAdminReceiver{  


    static SharedPreferences getSamplePreferences(Context context) {  
        return context.getSharedPreferences(  
          DeviceAdminReceiver.class.getName(), 0);  
    }  

    static String PREF_PASSWORD_QUALITY = "password_quality";  
    static String PREF_PASSWORD_LENGTH = "password_length";  
    static String PREF_MAX_FAILED_PW = "max_failed_pw";  

    void showToast(Context context, CharSequence msg) {  
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();  
    }  

    @Override  
    public void onEnabled(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: enabled");  
    }  

    @Override  
    public CharSequence onDisableRequested(Context context, Intent intent) {  
        return "This is an optional message to warn the user about disabling.";  
    }  

    @Override  
    public void onDisabled(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: disabled");  
    }  

    @Override  
    public void onPasswordChanged(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw changed");  
    }  

    @Override  
    public void onPasswordFailed(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw failed");  
    }  

    @Override  
    public void onPasswordSucceeded(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw succeeded");  
    }  

}

Debugging iframes with Chrome developer tools

Currently evaluation in the console is performed in the context of the main frame in the page and it adheres to the same cross-origin policy as the main frame itself. This means that you cannot access elements in the iframe unless the main frame can. You can still set breakpoints in and debug your code using Scripts panel though.

Update: This is no longer true. See Metagrapher's answer.

Selenium 2.53 not working on Firefox 47

As of September 2016

Firefox 48.0 and selenium==2.53.6 work fine without any errors

To upgrade firefox on Ubuntu 14.04 only

sudo apt-get update
sudo apt-get upgrade firefox

How to match "any character" in regular expression?

There are lots of sophisticated regex testing and development tools, but if you just want a simple test harness in Java, here's one for you to play with:

    String[] tests = {
        "AAA123",
        "ABCDEFGH123",
        "XXXX123",
        "XYZ123ABC",
        "123123",
        "X123",
        "123",
    };
    for (String test : tests) {
        System.out.println(test + " " +test.matches(".+123"));
    }

Now you can easily add new testcases and try new patterns. Have fun exploring regex.

See also

Reading value from console, interactively

The Readline API has changed quite a bit since 12'. The doc's show a useful example to capture user input from a standard stream :

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('What do you think of Node.js? ', (answer) => {
  console.log('Thank you for your valuable feedback:', answer);
  rl.close();
});

More information here.

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

9.5 and newer:

PostgreSQL 9.5 and newer support INSERT ... ON CONFLICT (key) DO UPDATE (and ON CONFLICT (key) DO NOTHING), i.e. upsert.

Comparison with ON DUPLICATE KEY UPDATE.

Quick explanation.

For usage see the manual - specifically the conflict_action clause in the syntax diagram, and the explanatory text.

Unlike the solutions for 9.4 and older that are given below, this feature works with multiple conflicting rows and it doesn't require exclusive locking or a retry loop.

The commit adding the feature is here and the discussion around its development is here.


If you're on 9.5 and don't need to be backward-compatible you can stop reading now.


9.4 and older:

PostgreSQL doesn't have any built-in UPSERT (or MERGE) facility, and doing it efficiently in the face of concurrent use is very difficult.

This article discusses the problem in useful detail.

In general you must choose between two options:

  • Individual insert/update operations in a retry loop; or
  • Locking the table and doing batch merge

Individual row retry loop

Using individual row upserts in a retry loop is the reasonable option if you want many connections concurrently trying to perform inserts.

The PostgreSQL documentation contains a useful procedure that'll let you do this in a loop inside the database. It guards against lost updates and insert races, unlike most naive solutions. It will only work in READ COMMITTED mode and is only safe if it's the only thing you do in the transaction, though. The function won't work correctly if triggers or secondary unique keys cause unique violations.

This strategy is very inefficient. Whenever practical you should queue up work and do a bulk upsert as described below instead.

Many attempted solutions to this problem fail to consider rollbacks, so they result in incomplete updates. Two transactions race with each other; one of them successfully INSERTs; the other gets a duplicate key error and does an UPDATE instead. The UPDATE blocks waiting for the INSERT to rollback or commit. When it rolls back, the UPDATE condition re-check matches zero rows, so even though the UPDATE commits it hasn't actually done the upsert you expected. You have to check the result row counts and re-try where necessary.

Some attempted solutions also fail to consider SELECT races. If you try the obvious and simple:

-- THIS IS WRONG. DO NOT COPY IT. It's an EXAMPLE.

BEGIN;

UPDATE testtable
SET somedata = 'blah'
WHERE id = 2;

-- Remember, this is WRONG. Do NOT COPY IT.

INSERT INTO testtable (id, somedata)
SELECT 2, 'blah'
WHERE NOT EXISTS (SELECT 1 FROM testtable WHERE testtable.id = 2);

COMMIT;

then when two run at once there are several failure modes. One is the already discussed issue with an update re-check. Another is where both UPDATE at the same time, matching zero rows and continuing. Then they both do the EXISTS test, which happens before the INSERT. Both get zero rows, so both do the INSERT. One fails with a duplicate key error.

This is why you need a re-try loop. You might think that you can prevent duplicate key errors or lost updates with clever SQL, but you can't. You need to check row counts or handle duplicate key errors (depending on the chosen approach) and re-try.

Please don't roll your own solution for this. Like with message queuing, it's probably wrong.

Bulk upsert with lock

Sometimes you want to do a bulk upsert, where you have a new data set that you want to merge into an older existing data set. This is vastly more efficient than individual row upserts and should be preferred whenever practical.

In this case, you typically follow the following process:

  • CREATE a TEMPORARY table

  • COPY or bulk-insert the new data into the temp table

  • LOCK the target table IN EXCLUSIVE MODE. This permits other transactions to SELECT, but not make any changes to the table.

  • Do an UPDATE ... FROM of existing records using the values in the temp table;

  • Do an INSERT of rows that don't already exist in the target table;

  • COMMIT, releasing the lock.

For example, for the example given in the question, using multi-valued INSERT to populate the temp table:

BEGIN;

CREATE TEMPORARY TABLE newvals(id integer, somedata text);

INSERT INTO newvals(id, somedata) VALUES (2, 'Joe'), (3, 'Alan');

LOCK TABLE testtable IN EXCLUSIVE MODE;

UPDATE testtable
SET somedata = newvals.somedata
FROM newvals
WHERE newvals.id = testtable.id;

INSERT INTO testtable
SELECT newvals.id, newvals.somedata
FROM newvals
LEFT OUTER JOIN testtable ON (testtable.id = newvals.id)
WHERE testtable.id IS NULL;

COMMIT;

Related reading

What about MERGE?

SQL-standard MERGE actually has poorly defined concurrency semantics and is not suitable for upserting without locking a table first.

It's a really useful OLAP statement for data merging, but it's not actually a useful solution for concurrency-safe upsert. There's lots of advice to people using other DBMSes to use MERGE for upserts, but it's actually wrong.

Other DBs:

Press Keyboard keys using a batch file

Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)

The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.

@if (@CodeSection == @Batch) @then


@echo off

rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"

rem Start the other program in the same Window
start "" /B cmd

%SendKeys% "echo off{ENTER}"

set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"

set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"

set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"

%SendKeys% "exit{ENTER}"

goto :EOF


@end


// JScript section

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));

For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx

For example:

LEFT ARROW    {LEFT}
RIGHT ARROW   {RIGHT}

For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs

Parse query string into an array

If you're having a problem converting a query string to an array because of encoded ampersands

&amp;

then be sure to use html_entity_decode

Example:

// Input string //
$input = 'pg_id=2&amp;parent_id=2&amp;document&amp;video';

// Parse //
parse_str(html_entity_decode($input), $out);

// Output of $out //
array(
  'pg_id' => 2,
  'parent_id' => 2,
  'document' => ,
  'video' =>
)

pip installs packages successfully, but executables not found from command line

Solution

Based on other answers, for linux and mac you can run the following:

echo "export PATH=\"`python3 -m site --user-base`/bin:$PATH\"" >> ~/.bashrc
source ~/.bashrc

instead of python3 you can use any other link to python version: python, python2.7, python3.6, python3.9, etc.

Explanation

In order to know where the user packages are installed in the current OS (win, mac, linux), we run:

python3 -m site --user-base

We know that the scripts go to the bin/ folder where the packages are installed.

So we concatenate the paths:

echo `python3 -m site --user-base`/bin

Then we export that to an environment variable.

export PATH=\"`python3 -m site --user-base`/bin:$PATH\"

Finally, in order to avoid repeating the export command we add it to our .bashrc file and we run source to run the new changes, giving us the suggested solution mentioned at the beginning.

Is it possible to use raw SQL within a Spring Repository

YES, You can do this on bellow ways:

1. By CrudRepository (Projection)

Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons.

Suppose your entity is like this :

    import javax.persistence.*;
    import java.math.BigDecimal;

    @Entity
    @Table(name = "USER_INFO_TEST")
    public class UserInfoTest {
        private int id;
        private String name;
        private String rollNo;

        public UserInfoTest() {
        }

        public UserInfoTest(int id, String name) {
        this.id = id;
        this.name = name;
        }

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "ID", nullable = false, precision = 0)
        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Basic
        @Column(name = "name", nullable = true)
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Basic
        @Column(name = "roll_no", nullable = true)
        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

Now your Projection class is like bellow. It can those fields that you needed.

public interface IUserProjection {
     int getId();
     String getName();
     String getRollNo();
}

And Your Data Access Object(Dao) is like bellow :

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.ArrayList;

public interface UserInfoTestDao extends CrudRepository<UserInfoTest,Integer> {
    @Query(value = "select id,name,roll_no from USER_INFO_TEST where rollNo = ?1", nativeQuery = true)
    ArrayList<IUserProjection> findUserUsingRollNo(String rollNo);
}

Now ArrayList<IUserProjection> findUserUsingRollNo(String rollNo) will give you the list of user.

2. Using EntityManager

Suppose your query is "select id,name from users where roll_no = 1001".

Here query will return a object with id and name column. Your Response class is like bellow:

Your Response class is like:

public class UserObject{
        int id;
        String name;
        String rollNo;

        public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

here UserObject constructor will get a Object Array and set data with object.

public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

Your query executing function is like bellow :

public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {

        String queryStr = "select id,name from users where roll_no = ?1";
        try {
            Query query = entityManager.createNativeQuery(queryStr);
            query.setParameter(1, rollNo);

            return new UserObject((Object[]) query.getSingleResult());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

Here you have to import bellow packages:

import javax.persistence.Query;
import javax.persistence.EntityManager;

Now your main class, you have to call this function. First get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo) function. Calling procedure is given bellow:

Here is the Imports

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

get EntityManager from this way:

@PersistenceContext
private EntityManager entityManager;

UserObject userObject = getUserByRoll(entityManager,"1001");

Now you have data in this userObject.

Note:

query.getSingleResult() return a object array. You have to maintain the column position and data type with query column position.

select id,name from users where roll_no = 1001 

query return a array and it's [0] --> id and [1] -> name.

More info visit this thread and this Thread

Thanks :)

Ascii/Hex convert in bash

jcomeau@aspire:~$ echo -n The quick brown fox jumps over the lazy dog | python -c "print raw_input().encode('hex'),"
54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f67
jcomeau@aspire:~$ echo -n The quick brown fox jumps over the lazy dog | python -c "print raw_input().encode('hex')," | python -c "print raw_input().decode('hex'),"
The quick brown fox jumps over the lazy dog

it could be done with Python3 as well, but differently, and I'm a lazy dog.

Default value for field in Django model

You can also use a callable in the default field, such as:

b = models.CharField(max_length=7, default=foo)

And then define the callable:

def foo():
    return 'bar'

How to iterate through a list of objects in C++

It is also worth to mention, that if you DO NOT intent to modify the values of the list, it is possible (and better) to use the const_iterator, as follows:

for (std::list<Student>::const_iterator it = data.begin(); it != data.end(); ++it){
    // do whatever you wish but don't modify the list elements
    std::cout << it->name;
}

How to center-justify the last line of text in CSS?

There doesn't appear to be a way. You can fake it by using justify and then wrapping the last line of text in a span and setting just that to text align center. It works ok for small blocks of text but is not a useful approach to large quantities of text or dynamic text.

I suggest finding somebody at Adobe who's involved in their W3C work and nagging them to bring up right/left/center justification in their next meeting. If anyone's gonna be able to push for basic typography features in CSS it'd be Adobe.

Better way to Format Currency Input editText?

Use this inputType in your XML

android:inputType="numberSigned|numberDecimal"

Add this nice Kotlin Extension function:

**
 * Use this function from [TextWatcher.afterTextChanged] it will first call [AppCompatEditText.removeTextChangedListener]
 * on the TextWatcher you pass, manipulate the text and then register it again after it call setText.
 *
 * @param fallback The String that we will return if the user is doing illegal adding, like trying to add a third digit after the comma.
 *                  It is best if you will keep the fallback as a member of the class the EditText resides in - and store in it
 * @param textWatcher [TextWatcher] It will be used to unregister before manipulating the text.
 * @param locale The locale that we will pass to [NumberFormat.getCurrencyInstance] - it will affect the currency sign. default is [Locale.US]
 *
 * @return A formatted String to use in [AppCompatEditText.setText]
 *
 */
fun AppCompatEditText.formatCurrency(@NonNull fallback: String, @NonNull textWatcher: TextWatcher,
                                     locale: Locale = Locale.US) {

    removeTextChangedListener(textWatcher)

    var original = text.toString()
    if (original.startsWith(".")) {
        // If the user press on '.-' key on the beginning of the amount - we are getting '.' and we turn it into '-'
        setText(original.replaceFirst(".", "-"))
        addTextChangedListener(textWatcher)
        setSelection(text?.length ?: 0)
        return
    }
    val split = original.split(".")
    when (split.size) {
        0 -> {
            setText(fallback)
            addTextChangedListener(textWatcher)
            setSelection(text?.length ?: 0)
            return
        }
        1 -> {
            if (split[0] == "-") {
                setText("-")
                addTextChangedListener(textWatcher)
                setSelection(text?.length ?: 0)
                return
            }
        }
        2 -> {
            if (split[1].length > 2) {
                setText(fallback)
                addTextChangedListener(textWatcher)
                setSelection(text?.length ?: 0)
                return
            }
        }
    }
    // We store the decimal value in a local variable
    val decimalSplit = original.split(".")
    // flag to indicate that we have a decimal part on the original String.
    val hasDecimal = decimalSplit.size > 1
    if (hasDecimal) {
        original = decimalSplit[0]
    }
    val isNegative = original.startsWith("-")
    val cleanString: String = original.replace("""[$,]""".toRegex(), "")

    val result = if (cleanString.isNotEmpty() && cleanString != "-") {
        val formatString = original.replace("""[-$,.]""".toRegex(), "")
        // Add Commas and Currency symbol.
        var result = NumberFormat.getCurrencyInstance(locale).format(formatString.toDouble())
        result = result.split('.')[0]
        if (isNegative) {
            // If it was negative we must add the minus sign.
            result = "-${result}"
        }
        if (hasDecimal) {
            // after the formatting the decimal is omitted, we need to append it.
            result = "${result}.${decimalSplit[1]}"
        }
        result
    } else {
        original
    }
    setText(result)
    addTextChangedListener(textWatcher)
    setSelection(text?.length ?: 0)
}

And use it like this:

class MyCoolClass{
  
    private var mLastAmount = ""
    ...
    ...

    private fun addTextWatcherToEt() {
            mEtAmount.addTextChangedListener(object : TextWatcher {
    
                override fun afterTextChanged(s: Editable?) {
                    mEtAmount.formatCurrency(mLastAmount, this)
                    mLastAmount = mEtAmount.text.toString()
                    
                    // Do More stuff here if you need...
                }
    
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                }
    
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
    
                }
            })
        }

}

Automatically pass $event with ng-click?

As others said, you can't actually strictly do what you are asking for. That said, all of the tools available to the angular framework are actually available to you as well! What that means is you can actually write your own elements and provide this feature yourself. I wrote one of these up as an example which you can see at the following plunkr (http://plnkr.co/edit/Qrz9zFjc7Ud6KQoNMEI1).

The key parts of this are that I define a "clickable" element (don't do this if you need older IE support). In code that looks like:

<clickable>
  <h1>Hello World!</h1>
</clickable>

Then I defined a directive to take this clickable element and turn it into what I want (something that automatically sets up my click event):

app.directive('clickable', function() {
    return {
        transclude: true,
        restrict: 'E',
        template: '<div ng-transclude ng-click="handleClick($event)"></div>'
    };
});

Finally in my controller I have the click event ready to go:

$scope.handleClick = function($event) {
    var i = 0;
};

Now, its worth stating that this hard codes the name of the method that handles the click event. If you wanted to eliminate this, you should be able to provide the directive with the name of your click handler and "tada" - you have an element (or attribute) that you can use and never have to inject "$event" again.

Hope that helps!

How to make a JFrame button open another JFrame class in Netbeans?

This link works with me: video

The answer posted before didn't work for me until the second click

So what I did is Directly call:

        new NewForm().setVisible(true);

        this.dispose();//to close the current jframe

How to insert &nbsp; in XSLT

One can also do this :

<xsl:text disable-output-escaping="yes"><![CDATA[&nbsp;]]></xsl:text>

T-SQL split string

A recursive cte based solution

declare @T table (iden int identity, col1 varchar(100));
insert into @T(col1) values
       ('ROOT/South America/Lima/Test/Test2')
     , ('ROOT/South America/Peru/Test/Test2')
     , ('ROOT//South America/Venuzuala ')
     , ('RtT/South America / ') 
     , ('ROOT/South Americas// '); 
declare @split char(1) = '/';
select @split as split;
with cte as 
(  select t.iden, case when SUBSTRING(REVERSE(rtrim(t.col1)), 1, 1) = @split then LTRIM(RTRIM(t.col1)) else LTRIM(RTRIM(t.col1)) + @split end  as col1, 0 as pos                             , 1 as cnt
   from @T t
   union all 
   select t.iden, t.col1                                                                                                                              , charindex(@split, t.col1, t.pos + 1), cnt + 1 
   from cte t 
   where charindex(@split, t.col1, t.pos + 1) > 0 
)
select t1.*, t2.pos, t2.cnt
     , ltrim(rtrim(SUBSTRING(t1.col1, t1.pos+1, t2.pos-t1.pos-1))) as bingo
from cte t1 
join cte t2 
  on t2.iden = t1.iden 
 and t2.cnt  = t1.cnt+1
 and t2.pos > t1.pos 
order by t1.iden, t1.cnt;

HTML5 - mp4 video does not play in IE9

If it's still not working here's what may certainly be a solution: encode the mp4 with compression format H.264. If you encode it with format mpeg4 or divx or else it will not work on IE9 and may as well crash Google Chrome. To do that, I use Any Video Converter freeware. But it could be done with any good video tool out there.

I've been trying all solutions listed here and tried other workaround for days but the problem lied in the way I created my mp4. IE9 does not decode other format than H.264.

Hope this helps, Jimmy

CSS media queries for screen sizes

Put it all in one document and use this:

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
  /* Styles */
}

/* iPhone 4 - 5s ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
  /* Styles */
}

/* iPhone 6 ----------- */
@media
only screen and (max-device-width: 667px) 
only screen and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ ----------- */
@media
only screen and (min-device-width : 414px) 
only screen and (-webkit-device-pixel-ratio: 3) {
  /*** You've spent way too much on a phone ***/
}

/* Samsung Galaxy S7 Edge ----------- */
@media only screen
and (-webkit-min-device-pixel-ratio: 3),
and (min-resolution: 192dpi)and (max-width:640px) {
 /* Styles */
}

Source: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

At this point, I would definitely consider using em values instead of pixels. For more information, check this post: https://zellwk.com/blog/media-query-units/.

How to use variables in SQL statement in Python?

Meanwhile there is another way of how to do it with f-strings:

cursor.execute(f"INSERT INTO table VALUES {var1}, {var2}, {var3},")

How to run function of parent window when child window closes?

The answers as they are require you to add code to the spawned window. That is unnecessary coupling.

// In parent window
var pop = open(url);
pop.onunload = function() {
  // Run your code, the popup window is unloading
  // Beware though, this will also fire if the user navigates to a different
  // page within thepopup. If you need to support that, you will have to play around
  // with pop.closed and setTimeouts
}

Twitter Bootstrap hide css class and jQuery

I agree with dfsq if all you want to do is show the button. If you want to switch between hiding and showing the button however, it is easier to use:

$("#buttonEditComment").toggleClass("hide");

Android: ListView elements with multiple clickable buttons

For future readers:

To select manually the buttons with the trackball use:

myListView.setItemsCanFocus(true);

And to disable the focus on the whole list items:

myListView.setFocusable(false);
myListView.setFocusableInTouchMode(false);
myListView.setClickable(false);

It works fine for me, I can click on buttons with touchscreen and also alows focus an click using keypad

Java GC (Allocation Failure)

"Allocation Failure" is a cause of GC cycle to kick in.

"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.

Older JVM were not printing GC cause for minor GC cycles.

"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if +XX:+ScavengeBeforeRemark is enabled).

Can a unit test project load the target application's app.config file?

I couldn't get any of these suggestions to work with nUnit 2.5.10 so I ended up using nUnit's Project -> Edit functionality to specify the config file to target (as others have said it needs to be in the same folder as the .nunit file itself). The positive side of this is that I can give the config file a Test.config name which makes it much clearer what it is and why it is)

What is the difference between i++ and ++i?

The typical answer to this question, unfortunately posted here already, is that one does the increment "before" remaining operations and the other does the increment "after" remaining operations. Though that intuitively gets the idea across, that statement is on the face of it completely wrong. The sequence of events in time is extremely well-defined in C#, and it is emphatically not the case that the prefix (++var) and postfix (var++) versions of ++ do things in a different order with respect to other operations.

It is unsurprising that you'll see a lot of wrong answers to this question. A great many "teach yourself C#" books also get it wrong. Also, the way C# does it is different than how C does it. Many people reason as though C# and C are the same language; they are not. The design of the increment and decrement operators in C# in my opinion avoids the design flaws of these operators in C.

There are two questions that must be answered to determine what exactly the operation of prefix and postfix ++ are in C#. The first question is what is the result? and the second question is when does the side effect of the increment take place?

It is not obvious what the answer to either question is, but it is actually quite simple once you see it. Let me spell out for you precisely what x++ and ++x do for a variable x.

For the prefix form (++x):

  1. x is evaluated to produce the variable
  2. The value of the variable is copied to a temporary location
  3. The temporary value is incremented to produce a new value (not overwriting the temporary!)
  4. The new value is stored in the variable
  5. The result of the operation is the new value (i.e. the incremented value of the temporary)

For the postfix form (x++):

  1. x is evaluated to produce the variable
  2. The value of the variable is copied to a temporary location
  3. The temporary value is incremented to produce a new value (not overwriting the temporary!)
  4. The new value is stored in the variable
  5. The result of the operation is the value of the temporary

Some things to notice:

First, the order of events in time is exactly the same in both cases. Again, it is absolutely not the case that the order of events in time changes between prefix and postfix. It is entirely false to say that the evaluation happens before other evaluations or after other evaluations. The evaluations happen in exactly the same order in both cases as you can see by steps 1 through 4 being identical. The only difference is the last step - whether the result is the value of the temporary, or the new, incremented value.

You can easily demonstrate this with a simple C# console app:

public class Application
{
    public static int currentValue = 0;

    public static void Main()
    {
        Console.WriteLine("Test 1: ++x");
        (++currentValue).TestMethod();

        Console.WriteLine("\nTest 2: x++");
        (currentValue++).TestMethod();

        Console.WriteLine("\nTest 3: ++x");
        (++currentValue).TestMethod();

        Console.ReadKey();
    }
}

public static class ExtensionMethods 
{
    public static void TestMethod(this int passedInValue) 
    {
        Console.WriteLine("Current:{0} Passed-in:{1}",
            Application.currentValue,
            passedInValue);
    }
}

Here are the results...

Test 1: ++x
Current:1 Passed-in:1

Test 2: x++
Current:2 Passed-in:1

Test 3: ++x
Current:3 Passed-in:3

In the first test, you can see that both currentValue and what was passed in to the TestMethod() extension show the same value, as expected.

However, in the second case, people will try to tell you that the increment of currentValue happens after the call to TestMethod(), but as you can see from the results, it happens before the call as indicated by the 'Current:2' result.

In this case, first the value of currentValue is stored in a temporary. Next, an incremented version of that value is stored back in currentValue but without touching the temporary which still stores the original value. Finally that temporary is passed to TestMethod(). If the increment happened after the call to TestMethod() then it would write out the same, non-incremented value twice, but it does not.

It's important to note that the value returned from both the currentValue++ and ++currentValue operations are based on the temporary and not the actual value stored in the variable at the time either operation exits.

Recall in the order of operations above, the first two steps copy the then-current value of the variable into the temporary. That is what's used to calculate the return value; in the case of the prefix version, it's that temporary value incremented while in the case of the suffix version, it's that value directly/non-incremented. The variable itself is not read again after the initial storage into the temporary.

Put more simply, the postfix version returns the value that was read from the variable (i.e. the value of the temporary) while the prefix version returns the value that was written back to the variable (i.e. the incremented value of the temporary). Neither return the variable's value.

This is important to understand because the variable itself could be volatile and have changed on another thread which means the return value of those operations could differ from the current value stored in the variable.

It is surprisingly common for people to get very confused about precedence, associativity, and the order in which side effects are executed, I suspect mostly because it is so confusing in C. C# has been carefully designed to be less confusing in all these regards. For some additional analysis of these issues, including me further demonstrating the falsity of the idea that prefix and postfix operations "move stuff around in time" see:

https://ericlippert.com/2009/08/10/precedence-vs-order-redux/

which led to this SO question:

int[] arr={0}; int value = arr[arr[0]++]; Value = 1?

You might also be interested in my previous articles on the subject:

https://ericlippert.com/2008/05/23/precedence-vs-associativity-vs-order/

and

https://ericlippert.com/2007/08/14/c-and-the-pit-of-despair/

and an interesting case where C makes it hard to reason about correctness:

https://docs.microsoft.com/archive/blogs/ericlippert/bad-recursion-revisited

Also, we run into similar subtle issues when considering other operations that have side effects, such as chained simple assignments:

https://docs.microsoft.com/archive/blogs/ericlippert/chaining-simple-assignments-is-not-so-simple

And here's an interesting post on why the increment operators result in values in C# rather than in variables:

Why can't I do ++i++ in C-like languages?

Table columns, setting both min and max width with css

Tables work differently; sometimes counter-intuitively.

The solution is to use width on the table cells instead of max-width.

Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.

I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.

_x000D_
_x000D_
table {_x000D_
  width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
  border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
  min-width: 10px;_x000D_
  width: 20px;_x000D_
  max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
  min-width: 40px;_x000D_
  width: 45px;_x000D_
  max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td class="a">A</td>_x000D_
    <td class="b">B</td>_x000D_
    <td class="c">C</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to import a class from default package

  1. Create "root" package (folder) in your project, for example.

    package source; (.../path_to_project/source/)

  2. Move YourClass.class into a source folder. (.../path_to_project/source/YourClass.class)

  3. Import like this

    import source.YourClass;

What evaluates to True/False in R?

T and TRUE are True, F and FALSE are False. T and F can be redefined, however, so you should only rely upon TRUE and FALSE. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.

How to check that an element is in a std::set?

You can also check whether an element is in set or not while inserting the element. The single element version return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.

For example: Suppose the set already has 20 as an element.

 std::set<int> myset;
 std::set<int>::iterator it;
 std::pair<std::set<int>::iterator,bool> ret;

 ret=myset.insert(20);
 if(ret.second==false)
 {
     //do nothing

 }
 else
 {
    //do something
 }

 it=ret.first //points to element 20 already in set.

If the element is newly inserted than pair::first will point to the position of new element in set.