Programs & Examples On #Workflow foundation 4

Windows Workflow 4 is Microsoft's framework for declarative composable business logic for .NET.

Angular - POST uploaded file

First, you have to create your own inline TS-Class, since the FormData Class is not well supported at the moment:

var data : {
  name: string;
  file: File;
} = {
  name: "Name",
  file: inputValue.files[0]
  };

Then you send it to the Server with JSON.stringify(data)

let opts: RequestOptions = new RequestOptions();
opts.method = RequestMethods.Post;
opts.headers = headers;
this.http.post(url,JSON.stringify(data),opts);

Replace special characters in a string with _ (underscore)

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g,'_');

How to maintain aspect ratio using HTML IMG tag

With css:

.img {
    display:table-cell;
    max-width:...px;
    max-height:...px;
    width:100%;
}

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

Extending Yoni Gibbs's answer, if you are in an android project using retrofit and configure serialization with Jackson you can do these things in order to deserialization works as expected with kotlin's data class.

In your build gradle import:

implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.11.+"

Then, your implementation of retrofit:

val serverURL = "http://localhost:8080/api/v1"

val objectMapper = ObjectMapper()
objectMapper.registerModule(KotlinModule())
//Only if you are using Java 8's Time API too, require jackson-datatype-jsr310
objectMapper.registerModule(JavaTimeModule())

Retrofit.Builder()
    .baseUrl(serverURL)
    .client(
        OkHttpClient.Builder()
           .readTimeout(1, TimeUnit.MINUTES)//No mandatory
            .connectTimeout(1, TimeUnit.MINUTES)//No mandatory
            .addInterceptor(UnauthorizedHandler())//No mandatory
            .build())
    .addConverterFactory(
                JacksonConverterFactory.create(objectMapper)
            )
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build()

Data class:

@JsonIgnoreProperties(ignoreUnknown = true)
data class Task(val id: Int,
                val name: String,
                @JsonSerialize(using = LocalDateTimeSerializer::class)
                @JsonDeserialize(using = LocalDateTimeDeserializer::class)
                val specificDate: LocalDateTime?,
                var completed: Boolean,
                val archived: Boolean,
                val taskListId: UUID?

Using Excel OleDb to get sheet names IN SHEET ORDER

This worked for me. Stolen from here: How do you get the name of the first page of an excel workbook?

object opt = System.Reflection.Missing.Value;
Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook workbook = app.Workbooks.Open(WorkBookToOpen,
                                         opt, opt, opt, opt, opt, opt, opt,
                                         opt, opt, opt, opt, opt, opt, opt);
Excel.Worksheet worksheet = workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
string firstSheetName = worksheet.Name;

How to do SQL Like % in Linq?

Way late, but I threw this together to be able to do String comparisons using SQL Like style wildcards:

public static class StringLikeExtensions
{
    /// <summary>
    /// Tests a string to be Like another string containing SQL Like style wildcards
    /// </summary>
    /// <param name="value">string to be searched</param>
    /// <param name="searchString">the search string containing wildcards</param>
    /// <returns>value.Like(searchString)</returns>
    /// <example>value.Like("a")</example>
    /// <example>value.Like("a%")</example>
    /// <example>value.Like("%b")</example>
    /// <example>value.Like("a%b")</example>
    /// <example>value.Like("a%b%c")</example>
    /// <remarks>base author -- Ruard van Elburg from StackOverflow, modifications by dvn</remarks>
    /// <remarks>converted to a String extension by sja</remarks>
    /// <seealso cref="https://stackoverflow.com/questions/1040380/wildcard-search-for-linq"/>
    public static bool Like(this String value, string searchString)
    {
        bool result = false;

        var likeParts = searchString.Split(new char[] { '%' });

        for (int i = 0; i < likeParts.Length; i++)
        {
            if (likeParts[i] == String.Empty)
            {
                continue;   // "a%"
            }

            if (i == 0)
            {
                if (likeParts.Length == 1) // "a"
                {
                    result = value.Equals(likeParts[i], StringComparison.OrdinalIgnoreCase);
                }
                else // "a%" or "a%b"
                {
                    result = value.StartsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
                }
            }
            else if (i == likeParts.Length - 1) // "a%b" or "%b"
            {
                result &= value.EndsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
            }
            else // "a%b%c"
            {
                int current = value.IndexOf(likeParts[i], StringComparison.OrdinalIgnoreCase);
                int previous = value.IndexOf(likeParts[i - 1], StringComparison.OrdinalIgnoreCase);
                result &= previous < current;
            }
        }

        return result;
    }

    /// <summary>
    /// Tests a string containing SQL Like style wildcards to be ReverseLike another string 
    /// </summary>
    /// <param name="value">search string containing wildcards</param>
    /// <param name="compareString">string to be compared</param>
    /// <returns>value.ReverseLike(compareString)</returns>
    /// <example>value.ReverseLike("a")</example>
    /// <example>value.ReverseLike("abc")</example>
    /// <example>value.ReverseLike("ab")</example>
    /// <example>value.ReverseLike("axb")</example>
    /// <example>value.ReverseLike("axbyc")</example>
    /// <remarks>reversed logic of Like String extension</remarks>
    public static bool ReverseLike(this String value, string compareString)
    {
        bool result = false;

        var likeParts = value.Split(new char[] {'%'});

        for (int i = 0; i < likeParts.Length; i++)
        {
            if (likeParts[i] == String.Empty)
            {
                continue;   // "a%"
            }

            if (i == 0)
            {
                if (likeParts.Length == 1) // "a"
                {
                    result = compareString.Equals(likeParts[i], StringComparison.OrdinalIgnoreCase);
                }
                else // "a%" or "a%b"
                {
                    result = compareString.StartsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
                }
            }
            else if (i == likeParts.Length - 1) // "a%b" or "%b"
            {
                result &= compareString.EndsWith(likeParts[i], StringComparison.OrdinalIgnoreCase);
            }
            else // "a%b%c"
            {
                int current = compareString.IndexOf(likeParts[i], StringComparison.OrdinalIgnoreCase);
                int previous = compareString.IndexOf(likeParts[i - 1], StringComparison.OrdinalIgnoreCase);
                result &= previous < current;
            }
        }

        return result;
    }
}

Can CSS detect the number of children an element has?

Clarification:

Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.


Original answer:

Incredibly, this is now possible purely in CSS3.

/* one item */
li:first-child:nth-last-child(1) {
/* -or- li:only-child { */
    width: 100%;
}

/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
    width: 50%;
}

/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}

/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
    width: 25%;
}

The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.

Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).

Don't you just love CSS3?

CodePen Example:

Sources:

Counting the number of occurences of characters in a string

Try this:

import java.util.Scanner;

    /* Logic: Consider first character in the string and start counting occurrence of        
              this character in the entire string. Now add this character to a empty
              string "temp" to keep track of the already counted characters.
              Next start counting from next character and start counting the character        
              only if it is not present in the "temp" string( which means only if it is
              not counted already)
public class Counting_Occurences {

    public static void main(String[] args) {


        Scanner input=new Scanner(System.in);
        System.out.println("Enter String");
        String str=input.nextLine();

        int count=0;
        String temp=""; // An empty string to keep track of counted
                                    // characters


        for(int i=0;i<str.length();i++)
        {

            char c=str.charAt(i);  // take one character (c) in string

            for(int j=i;j<str.length();j++)
            {

                char k=str.charAt(j);  
    // take one character (c) and compare with each character (k) in the string
            // also check that character (c) is not already counted.
            // if condition passes then increment the count.
                if(c==k && temp.indexOf(c)==-1)                                                                          
                {

                    count=count+1;

                }

            }

             if(temp.indexOf(c)==-1)  // if it is not already counted
             {


            temp=temp+c; // append the character to the temp indicating
                                         // that you have already counted it.

System.out.println("Character   " + c + "   occurs   " + count + "    times");
             }  
            // reset the counter for next iteration 
              count=0;

        }


    }


}

Error: Unfortunately you can't have non-Gradle Java modules and > Android-Gradle modules in one project

goto .idea folder open modules.xml file and see for yourself what module is there that you are not using in project currently.

awk - concatenate two string variable and assign to a third

You can also concatenate strings from across multiple lines with whitespaces.

$ cat file.txt
apple 10
oranges 22
grapes 7

Example 1:

awk '{aggr=aggr " " $2} END {print aggr}' file.txt
10 22 7

Example 2:

awk '{aggr=aggr ", " $1 ":" $2} END {print aggr}' file.txt
, apple:10, oranges:22, grapes:7

Is there a way to access the "previous row" value in a SELECT statement?

LEFT JOIN the table to itself, with the join condition worked out so the row matched in the joined version of the table is one row previous, for your particular definition of "previous".

Update: At first I was thinking you would want to keep all rows, with NULLs for the condition where there was no previous row. Reading it again you just want that rows culled, so you should an inner join rather than a left join.


Update:

Newer versions of Sql Server also have the LAG and LEAD Windowing functions that can be used for this, too.

How do I get the current location of an iframe?

You can access the src property of the iframe but that will only give you the initially loaded URL. If the user is navigating around in the iframe via you'll need to use an HTA to solve the security problem.

http://msdn.microsoft.com/en-us/library/ms536474(VS.85).aspx

Check out the link, using an HTA and setting the "application" property of an iframe will allow you to access the document.href property and parse out all of the information you want, including DOM elements and their values if you so choose.

How to calculate age (in years) based on Date of Birth and getDate()

you should count years by following way :-

select cast(datediff(DAY, '2000-03-01 10:00:01', '2013-03-01 10:00:00') / (365.23076923074) as int) as 'Age'

it's very easy...

how to loop through json array in jquery?

Your array has default keys(0,1) which store object {'com':'some thing'} use:

var obj = jQuery.parseJSON(response);
$.each(obj, function(key,value) {
  alert(value.com);
}); 

Binding Listbox to List<object> in WinForms

Granted, this isn't going to provide you anything truly meaningful unless the objects have properly overriden ToString() (or you're not really working with a generic list of objects and can bind to specific fields):

List<object> objList = new List<object>();

// Fill the list

someListBox.DataSource = objList;

How can I generate a list of consecutive numbers?

Note :- Certainly in python-3x you need to use Range function It works to generate numbers on demand, standard method to use Range function to make a list of consecutive numbers is

x=list(range(10))
#"list"_will_make_all_numbers_generated_by_range_in_a_list
#number_in_range_(10)_is_an_option_you_can_change_as_you_want
print (x)
#Output_is_ [0,1,2,3,4,5,6,7,8,9]

Also if you want to make an function to generate a list of consecutive numbers by using Range function watch this code !

def  consecutive_numbers(n) :
    list=[i for i in range(n)]
    return (list)
print(consecutive_numbers(10))

Good Luck!

Eclipse doesn't stop at breakpoints

Same Problem!! Easy and Fastest Solution!! Just remove All breakpoints in debug perspective and reapply breakpoint. Works like a charm!!

How can I get the behavior of GNU's readlink -f on a Mac?

A lazy way that works for me,

$ brew install coreutils
$ ln -s /usr/local/bin/greadlink /usr/local/bin/readlink
$ which readlink
/usr/local/bin/readlink
/usr/bin/readlink

How to make a Java Generic method static?

I'll explain it in a simple way.

Generics defined at Class level are completely separate from the generics defined at the (static) method level.

class Greet<T> {

    public static <T> void sayHello(T obj) {
        System.out.println("Hello " + obj);
    }
}

When you see the above code anywhere, please note that the T defined at the class level has nothing to do with the T defined in the static method. The following code is also completely valid and equivalent to the above code.

class Greet<T> {

    public static <E> void sayHello(E obj) {
        System.out.println("Hello " + obj);
    }
}

Why the static method needs to have its own generics separate from those of the Class?

This is because, the static method can be called without even instantiating the Class. So if the Class is not yet instantiated, we do not yet know what is T. This is the reason why the static methods needs to have its own generics.

So, whenever you are calling the static method,

Greet.sayHello("Bob");
Greet.sayHello(123);

JVM interprets it as the following.

Greet.<String>sayHello("Bob");
Greet.<Integer>sayHello(123);

Both giving the same outputs.

Hello Bob
Hello 123

Class constructor type in typescript?

Like that:

class Zoo {
    AnimalClass: typeof Animal;

    constructor(AnimalClass: typeof Animal ) {
        this.AnimalClass = AnimalClass
        let Hector = new AnimalClass();
    }
}

Or just:

class Zoo {
    constructor(public AnimalClass: typeof Animal ) {
        let Hector = new AnimalClass();
    }
}

typeof Class is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.

Here's the relevant part of TypeScript docs. Search for the typeof. As a part of a TypeScript type annotation, it means "give me the type of the symbol called Animal" which is the type of the class constructor function in our case.

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

You can also run ->select('DISTINCT `field`', FALSE) and the second parameter tells CI not to escape the first argument.

With the second parameter as false, the output would be SELECT DISTINCT `field` instead of without the second parameter, SELECT `DISTINCT` `field`

Count textarea characters

This code gets the maximum value from the maxlength attribute of the textarea and decreases the value as the user types.

<DEMO>

_x000D_
_x000D_
var el_t = document.getElementById('textarea');_x000D_
var length = el_t.getAttribute("maxlength");_x000D_
var el_c = document.getElementById('count');_x000D_
el_c.innerHTML = length;_x000D_
el_t.onkeyup = function () {_x000D_
  document.getElementById('count').innerHTML = (length - this.value.length);_x000D_
};
_x000D_
<textarea id="textarea" name="text"_x000D_
 maxlength="500"></textarea>_x000D_
<span id="count"></span>
_x000D_
_x000D_
_x000D_

How do I shut down a python simpleHTTPserver?

if you have started the server with

python -m SimpleHTTPServer 8888 

then you can press ctrl + c to down the server.

But if you have started the server with

python -m SimpleHTTPServer 8888 &

or

python -m SimpleHTTPServer 8888 & disown

you have to see the list first to kill the process,

run command

ps

or

ps aux | less

it will show you some running process like this ..

PID TTY          TIME CMD
7247 pts/3     00:00:00 python
7360 pts/3     00:00:00 ps
23606 pts/3    00:00:00 bash

you can get the PID from here. and kill that process by running this command..

kill -9 7247

here 7247 is the python id.

Also for some reason if the port still open you can shut down the port with this command

fuser -k 8888/tcp

here 8888 is the tcp port opened by python.

Hope its clear now.

Open Form2 from Form1, close Form1 from Form2

if you just want to close form1 from form2 without closing form2 as well in the process, as the title suggests, then you could pass a reference to form 1 along to form 2 when you create it and use that to close form 1

for example you could add a

public class Form2 : Form
{
    Form2(Form1 parentForm):base()
    {
        this.parentForm = parentForm;
    }

    Form1 parentForm;
    .....
}

field and constructor to Form2

if you want to first close form2 and then form1 as the text of the question suggests, I'd go with Justins answer of returning an appropriate result to form1 on upon closing form2

Swipe ListView item From right to left show delete button

you can use this code

holder.img_close.setOnClickListener(new View.OnClickListener() {
      @Override
        public void onClick(View view) {
            holder.swipeRevealLayout.close(true);
            list.remove(position);
            notifyDataSetChanged();
      }});

How do I remove all .pyc files from a project?

Further, people usually want to remove all *.pyc, *.pyo files and __pycache__ directories recursively in the current directory.

Command:

find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf

How do I get a python program to do nothing?

You could use a pass statement:

if condition:
    pass

Python 2.x documentation

Python 3.x documentation

However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the if statement.

If you have something like this:

if condition:        # condition in your case being `num2 == num5`
    pass
else:
    do_something()

You can in general change it to this:

if not condition:
    do_something()

But in this specific case you could (and should) do this:

if num2 != num5:        # != is the not-equal-to operator
    do_something()

jQuery AJAX Call to PHP Script with JSON Return

try to send content type header from server use this just before echoing

header('Content-Type: application/json');

Get type of all variables

R/Rscript doesn't have concrete datatypes.

R interpreter has a duck-typing memory allocation system. There is no builtin method to tell you the datatype of your pointer to memory. Duck typing is done for speed, but turned out to be a bad idea because now statements such as: print(is.integer(5)) returns FALSE and is.integer(as.integer(5)) returns TRUE. Go figure.

The R-manual on basic types: https://cran.r-project.org/doc/manuals/R-lang.html#Basic-types

The best you can hope for is to write your own function to probe your pointer to memory, then use process of elimination to decide if it is suitable for your needs.

If your variable is a global or an object:

Your object() needs to be penetrated with get(...) before you can see inside. Example:

a <- 10
myGlobals <- objects()
for(i in myGlobals){
  typeof(i)         #prints character
  typeof(get(i))    #prints integer
}

typeof(...) probes your variable pointer to memory:

The R function typeof has a bias to give you the type at maximum depth, for example.

library(tibble)

#expression              notes                                  type
#----------------------- -------------------------------------- ----------
typeof(TRUE)             #a single boolean:                     logical
typeof(1L)               #a single numeric with L postfixed:    integer
typeof("foobar")         #A single string in double quotes:     character
typeof(1)                #a single numeric:                     double
typeof(list(5,6,7))      #a list of numeric:                    list
typeof(2i)               #an imaginary number                   complex

typeof(5 + 5L)           #double + integer is coerced:          double
typeof(c())              #an empty vector has no type:          NULL
typeof(!5)               #a bang before a double:               logical
typeof(Inf)              #infinity has a type:                  double
typeof(c(5,6,7))         #a vector containing only doubles:     double
typeof(c(c(TRUE)))       #a vector of vector of logicals:       logical
typeof(matrix(1:10))     #a matrix of doubles has a type:       list

typeof(substr("abc",2,2))#a string at index 2 which is 'b' is:  character
typeof(c(5L,6L,7L))      #a vector containing only integers:    integer
typeof(c(NA,NA,NA))      #a vector containing only NA:          logical
typeof(data.frame())     #a data.frame with nothing in it:      list
typeof(data.frame(c(3))) #a data.frame with a double in it:     list
typeof(c("foobar"))      #a vector containing only strings:     character
typeof(pi)               #builtin expression for pi:            double

typeof(1.66)             #a single numeric with mantissa:       double
typeof(1.66L)            #a double with L postfixed             double
typeof(c("foobar"))      #a vector containing only strings:     character
typeof(c(5L, 6L))        #a vector containing only integers:    integer
typeof(c(1.5, 2.5))      #a vector containing only doubles:     double
typeof(c(1.5, 2.5))      #a vector containing only doubles:     double
typeof(c(TRUE, FALSE))   #a vector containing only logicals:    logical

typeof(factor())         #an empty factor has default type:     integer
typeof(factor(3.14))     #a factor containing doubles:          integer
typeof(factor(T, F))     #a factor containing logicals:         integer
typeof(Sys.Date())       #builtin R dates:                      double
typeof(hms::hms(3600))   #hour minute second timestamp          double
typeof(c(T, F))          #T and F are builtins:                 logical
typeof(1:10)             #a builtin sequence of numerics:       integer
typeof(NA)               #The builtin value not available:      logical

typeof(c(list(T)))       #a vector of lists of logical:         list
typeof(list(c(T)))       #a list of vectors of logical:         list
typeof(c(T, 3.14))       #a vector of logicals and doubles:     double
typeof(c(3.14, "foo"))   #a vector of doubles and characters:   character
typeof(c("foo",list(T))) #a vector of strings and lists:        list
typeof(list("foo",c(T))) #a list of strings and vectors:        list
typeof(TRUE + 5L)        #a logical plus an integer:            integer
typeof(c(TRUE, 5L)[1])   #The true is coerced to 1              integer
typeof(c(c(2i), TRUE)[1])#logical coerced to complex:           complex
typeof(c(NaN, 'batman')) #NaN's in a vector don't dominate:     character
typeof(5 && 4)           #doubles are coerced by order of &&    logical
typeof(8 < 'foobar')     #string and double is coerced          logical
typeof(list(4, T)[[1]])  #a list retains type at every index:   double
typeof(list(4, T)[[2]])  #a list retains type at every index:   logical
typeof(2 ** 5)           #result of exponentiation              double
typeof(0E0)              #exponential lol notation              double
typeof(0x3fade)          #hexidecimal                           double
typeof(paste(3, '3'))    #paste promotes types to string        character
typeof(3 + ?)           #R pukes on unicode                    error
typeof(iconv("a", "latin1", "UTF-8")) #UTF-8 characters         character
typeof(5 == 5)           #result of a comparison:               logical

class(...) probes your variable pointer to memory:

The R function class has a bias to give you the type of container or structure encapsulating your types, for example.

library(tibble)

#expression            notes                                    class
#--------------------- ---------------------------------------- ---------
class(matrix(1:10))     #a matrix of doubles has a class:       matrix
class(factor("hi"))     #factor of items is:                    factor
class(TRUE)             #a single boolean:                      logical
class(1L)               #a single numeric with L postfixed:     integer
class("foobar")         #A single string in double quotes:      character
class(1)                #a single numeric:                      numeric
class(list(5,6,7))      #a list of numeric:                     list
class(2i)               #an imaginary                           complex
class(data.frame())     #a data.frame with nothing in it:       data.frame
class(Sys.Date())       #builtin R dates:                       Date
class(sapply)           #a function is                          function
class(charToRaw("hi"))  #convert string to raw:                 raw
class(array("hi"))      #array of items is:                     array

class(5 + 5L)           #double + integer is coerced:          numeric
class(c())              #an empty vector has no class:         NULL
class(!5)               #a bang before a double:               logical
class(Inf)              #infinity has a class:                 numeric
class(c(5,6,7))         #a vector containing only doubles:     numeric
class(c(c(TRUE)))       #a vector of vector of logicals:       logical

class(substr("abc",2,2))#a string at index 2 which is 'b' is:  character
class(c(5L,6L,7L))      #a vector containing only integers:    integer
class(c(NA,NA,NA))      #a vector containing only NA:          logical
class(data.frame(c(3))) #a data.frame with a double in it:     data.frame
class(c("foobar"))      #a vector containing only strings:     character
class(pi)               #builtin expression for pi:            numeric

class(1.66)             #a single numeric with mantissa:       numeric
class(1.66L)            #a double with L postfixed             numeric
class(c("foobar"))      #a vector containing only strings:     character
class(c(5L, 6L))        #a vector containing only integers:    integer
class(c(1.5, 2.5))      #a vector containing only doubles:     numeric
class(c(TRUE, FALSE))   #a vector containing only logicals:    logical

class(factor())       #an empty factor has default class:      factor
class(factor(3.14))   #a factor containing doubles:            factor
class(factor(T, F))   #a factor containing logicals:           factor
class(hms::hms(3600)) #hour minute second timestamp            hms difftime
class(c(T, F))        #T and F are builtins:                   logical
class(1:10)           #a builtin sequence of numerics:         integer
class(NA)             #The builtin value not available:        logical

class(c(list(T)))       #a vector of lists of logical:         list
class(list(c(T)))       #a list of vectors of logical:         list
class(c(T, 3.14))       #a vector of logicals and doubles:     numeric
class(c(3.14, "foo"))   #a vector of doubles and characters:   character
class(c("foo",list(T))) #a vector of strings and lists:        list
class(list("foo",c(T))) #a list of strings and vectors:        list
class(TRUE + 5L)        #a logical plus an integer:            integer
class(c(TRUE, 5L)[1])   #The true is coerced to 1              integer
class(c(c(2i), TRUE)[1])#logical coerced to complex:           complex
class(c(NaN, 'batman')) #NaN's in a vector don't dominate:     character
class(5 && 4)           #doubles are coerced by order of &&    logical
class(8 < 'foobar')     #string and double is coerced          logical
class(list(4, T)[[1]])  #a list retains class at every index:  numeric
class(list(4, T)[[2]])  #a list retains class at every index:  logical
class(2 ** 5)           #result of exponentiation              numeric
class(0E0)              #exponential lol notation              numeric
class(0x3fade)          #hexidecimal                           numeric
class(paste(3, '3'))     #paste promotes class to string       character
class(3 + ?)           #R pukes on unicode                   error
class(iconv("a", "latin1", "UTF-8")) #UTF-8 characters         character
class(5 == 5)           #result of a comparison:               logical

Get the data storage.mode of your variable:

When an R variable is written to disk, the data layout changes again, and is called the data's storage.mode. The function storage.mode(...) reveals this low level information: see Mode, Class, and Type of R objects. You shouldn't need to worry about R's storage.mode unless you are trying to understand delays caused by round trip casts/coercions that occur when assigning and reading data to and from disk.

Demo: R/Rscript gettype(your_variable):

Run this R code then adapt it for your purposes, it'll make a pretty good guess as to what type it is.

get_type <- function(variable){ 
  sz <- as.integer(length(variable)) #length of your variable 
  tof <- typeof(variable)            #typeof your variable 
  cls <- class(variable)             #class of your variable 
  isc <- is.character(variable)      #what is.character() has to say about it.  
  d <- dim(variable)                 #dimensions of your variable 
  isv <- is.vector(variable) 
  if (is.matrix(variable)){  
    d <- dim(t(variable))             #dimensions of your matrix
  }    
  #observations ----> datatype 
  if (sz>=1 && tof == "logical" && cls == "logical" && isv == TRUE){ return("vector of logical") } 
  if (sz>=1 && tof == "integer" && cls == "integer" ){ return("vector of integer") } 
  if (sz==1 && tof == "double"  && cls == "Date" ){ return("Date") } 
  if (sz>=1 && tof == "raw"     && cls == "raw" ){ return("vector of raw") } 
  if (sz>=1 && tof == "double"  && cls == "numeric" ){ return("vector of double") } 
  if (sz>=1 && tof == "double"  && cls == "array" ){ return("vector of array of double") } 
  if (sz>=1 && tof == "character"  && cls == "array" ){ return("vector of array of character") } 
  if (sz>=0 && tof == "list"       && cls == "data.frame" ){ return("data.frame") } 
  if (sz>=1 && isc == TRUE         && isv == TRUE){ return("vector of character") } 
  if (sz>=1 && tof == "complex"    && cls == "complex" ){ return("vector of complex") } 
  if (sz==0 && tof == "NULL"       && cls == "NULL" ){ return("NULL") } 
  if (sz>=0 && tof == "integer"    && cls == "factor" ){ return("factor") } 
  if (sz>=1 && tof == "double"     && cls == "numeric" && isv == TRUE){ return("vector of double") } 
  if (sz>=1 && tof == "double"     && cls == "matrix"){ return("matrix of double") } 
  if (sz>=1 && tof == "character"  && cls == "matrix"){ return("matrix of character") } 
  if (sz>=1 && tof == "list"       && cls == "list" && isv == TRUE){ return("vector of list") } 
  if (sz>=1 && tof == "closure"    && cls == "function" && isv == FALSE){ return("closure/function") } 
  return("it's pointer to memory, bruh") 
} 
assert <- function(a, b){ 
  if (a == b){ 
    cat("P") 
  } 
  else{ 
    cat("\nFAIL!!!  Sniff test:\n") 
    sz <- as.integer(length(variable))   #length of your variable 
    tof <- typeof(variable)              #typeof your variable 
    cls <- class(variable)               #class of your variable 
    isc <- is.character(variable)        #what is.character() has to say about it. 
    d <- dim(variable)                   #dimensions of your variable 
    isv <- is.vector(variable) 
    if (is.matrix(variable)){  
      d <- dim(t(variable))                   #dimensions of your variable 
    } 
    if (!is.function(variable)){ 
      print(paste("value: '", variable, "'")) 
    } 
    print(paste("get_type said: '", a, "'")) 
    print(paste("supposed to be: '", b, "'")) 
 
    cat("\nYour pointer to memory has properties:\n")  
    print(paste("sz: '", sz, "'")) 
    print(paste("tof: '", tof, "'")) 
    print(paste("cls: '", cls, "'")) 
    print(paste("d: '", d, "'")) 
    print(paste("isc: '", isc, "'")) 
    print(paste("isv: '", isv, "'")) 
    quit() 
  } 
}
#these asserts give a sample for exercising the code. 
assert(get_type(TRUE),      "vector of logical")  #everything is a vector in R by default. 
assert(get_type(c(TRUE)),   "vector of logical")  #c() just casts to vector 
assert(get_type(c(c(TRUE))),"vector of logical")  #casting vector multiple times does nothing 
assert(get_type(!5),        "vector of logical")  #bang inflicts 'not truth-like' 
assert(get_type(1L),              "vector of integer")   #naked integers are still vectors of 1 
assert(get_type(c(1L, 2L)),       "vector of integer")   #Longs are not doubles 
assert(get_type(c(1L, c(2L, 3L))),"vector of integer")   #nested vectors of integers 
assert(get_type(c(1L, c(TRUE))),  "vector of integer")   #logicals coerced to integer 
assert(get_type(c(FALSE, c(1L))), "vector of integer")   #logicals coerced to integer 
assert(get_type("foobar"),        "vector of character")    #character here means 'string' 
assert(get_type(c(1L, "foobar")), "vector of character")    #integers are coerced to string 
assert(get_type(5),           "vector of double") 
assert(get_type(5 + 5L),      "vector of double") 
assert(get_type(Inf),         "vector of double") 
assert(get_type(c(5,6,7)),    "vector of double") 
assert(get_type(NaN),           "vector of double") 
assert(get_type(list(5)),       "vector of list")    #your list is in a vector. 
assert(get_type(list(5,6,7)),   "vector of list") 
assert(get_type(c(list(5,6,7))),"vector of list") 
assert(get_type(list(c(5,6),T)),"vector of list")    #vector of list of vector and logical 
assert(get_type(list(5,6,7)),   "vector of list") 
assert(get_type(2i),            "vector of complex") 
assert(get_type(c(2i, 3i, 4i)), "vector of complex") 
assert(get_type(c()),            "NULL") 
assert(get_type(data.frame()),   "data.frame") 
assert(get_type(data.frame(4,5)),"data.frame") 
assert(get_type(Sys.Date()),     "Date") 
assert(get_type(sapply),         "closure/function") 
assert(get_type(charToRaw("hi")),"vector of raw") 
assert(get_type(c(charToRaw("a"), charToRaw("b"))), "vector of raw") 
assert(get_type(array(4)),       "vector of array of double") 
assert(get_type(array(4,5)),     "vector of array of double") 
assert(get_type(array("hi")),    "vector of array of character") 
assert(get_type(factor()),       "factor") 
assert(get_type(factor(3.14)),   "factor") 
assert(get_type(factor(TRUE)),   "factor") 
assert(get_type(matrix(3,4,5)),  "matrix of double") 
assert(get_type(as.matrix(5)),   "matrix of double") 
assert(get_type(matrix("yatta")),"matrix of character") 

I put in a C++/Java/Python ideology here that gives me the scoop of what the memory most looks like. R triad typing system is like trying to nail spaghetti to the wall, <- and <<- will package your matrix to a list when you least suspect. As the old duck-typing saying goes: If it waddles like a duck and if it quacks like a duck and if it has feathers, then it's a duck.

File Upload without Form

Step 1: Create HTML Page where to place the HTML Code.

Step 2: In the HTML Code Page Bottom(footer)Create Javascript: and put Jquery Code in Script tag.

Step 3: Create PHP File and php code copy past. after Jquery Code in $.ajax Code url apply which one on your php file name.

JS

//$(document).on("change", "#avatar", function() {   // If you want to upload without a submit button 
$(document).on("click", "#upload", function() {
  var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
  var form_data = new FormData(); // Creating object of FormData class
  form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
  form_data.append("user_id", 123) // Adding extra parameters to form_data
  $.ajax({
    url: "/upload_avatar", // Upload Script
    dataType: 'script',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data, // Setting the data attribute of ajax with file_data
    type: 'post',
    success: function(data) {
      // Do something after Ajax completes 
    }
  });
});

HTML

<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />

Php

print_r($_FILES);
print_r($_POST);

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

How to write lists inside a markdown table?

An alternative approach, which I've recently implemented, is to use the div-table plugin with panflute.

This creates a table from a set of fenced divs (standard in the pandoc implementation of markdown), in a similar layout to html:

---
panflute-filters: [div-table]
panflute-path: 'panflute/docs/source'
---

::::: {.divtable}
:::: {.tcaption}
a caption here (optional), only the first paragraph is used.
::::
:::: {.thead}
[Header 1]{width=0.4 align=center}
[Header 2]{width=0.6 align=default}
::::
:::: {.trow}
::: {.tcell}

1. any
2. normal markdown
3. can go in a cell

:::
::: {.tcell}
![](https://pixabay.com/get/e832b60e2cf7043ed1584d05fb0938c9bd22ffd41cb2144894f9c57aae/bird-1771435_1280.png?attachment){width=50%}

some text
:::
::::
:::: {.trow bypara=true}
If bypara=true

Then each paragraph will be treated as a separate column
::::
any text outside a div will be ignored
:::::

Looks like:

enter image description here

How to insert a row in an HTML table body in JavaScript

I have tried this, and this is working for me:

var table = document.getElementById("myTable");
var row = table.insertRow(myTable.rows.length-2);
var cell1 = row.insertCell(0);

How set the android:gravity to TextView from Java side in Android

You should use textView.setGravity(Gravity.CENTER_HORIZONTAL);.

Remember that using

LinearLayout.LayoutParams layoutParams =new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layoutParams2.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;

won't work. This will set the gravity for the widget and not for it's text.

Do the parentheses after the type name make a difference with new?

new Thing(); is explicit that you want a constructor called whereas new Thing; is taken to imply you don't mind if the constructor isn't called.

If used on a struct/class with a user-defined constructor, there is no difference. If called on a trivial struct/class (e.g. struct Thing { int i; };) then new Thing; is like malloc(sizeof(Thing)); whereas new Thing(); is like calloc(sizeof(Thing)); - it gets zero initialized.

The gotcha lies in-between:

struct Thingy {
  ~Thingy(); // No-longer a trivial class
  virtual WaxOn();
  int i;
};

The behavior of new Thingy; vs new Thingy(); in this case changed between C++98 and C++2003. See Michael Burr's explanation for how and why.

UnsatisfiedDependencyException: Error creating bean with name

If you describe a field as criteria in method definition ("findBy"), You must pass that parameter to the method, otherwise you will get "Unsatisfied dependency expressed through method parameter" exception.

public interface ClientRepository extends JpaRepository<Client, Integer> {
       Client findByClientId();                ////WRONG !!!!
       Client findByClientId(int clientId);    /// CORRECT 
}

*I assume that your Client entity has clientId attribute.

Reset select2 value and show placeholder

I know this is kind of an old question, but this works for the select2 version 4.0

 $('#select2-element').val('').trigger('change');

or

$('#select2-element').val('').trigger('change.select2'); 

if you have change events bound to it

Order columns through Bootstrap4

Since column-ordering doesn't work in Bootstrap 4 beta as described in the code provided in the revisited answer above, you would need to use the following (as indicated in the codeply 4 Flexbox order demo - alpha/beta links that were provided in the answer).

<div class="container">
<div class="row">
    <div class="col-3 col-md-6">
        <div class="card card-block">1</div>
    </div>
    <div class="col-6 col-md-12  flex-md-last">
        <div class="card card-block">3</div>
    </div>
    <div class="col-3 col-md-6 ">
        <div class="card card-block">2</div>
    </div>
</div>

Note however that the "Flexbox order demo - beta" goes to an alpha codebase, and changing the codebase to Beta (and running it) results in the divs incorrectly displaying in a single column -- but that looks like a codeply issue since cutting and pasting the code out of codeply works as described.

How to debug Ruby scripts

Well, ruby standard lib has an easy to use gdb-like console debugger: http://ruby-doc.org/stdlib-2.1.0/libdoc/debug/rdoc/DEBUGGER__.html No need to install any extra gems. Rails scripts can be debugged that way too.

e.g.

def say(word)
  require 'debug'
  puts word
end

How to display .svg image using swift

Try this code

var path: String = NSBundle.mainBundle().pathForResource("nameOfFile", ofType: "svg")!

        var url: NSURL = NSURL.fileURLWithPath(path)  //Creating a URL which points towards our path

       //Creating a page request which will load our URL (Which points to our path)
        var request: NSURLRequest = NSURLRequest(URL: url)
       webView.loadRequest(request)  //Telling our webView to load our above request

Round double in two decimal places in C#?

Use an interpolated string, this generates a rounded up string:

var strlen = 6;
$"{48.485:F2}"

Output

"48.49"

How to output loop.counter in python jinja template?

The counter variable inside the loop is called loop.index in jinja2.

>>> from jinja2 import Template

>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4

See http://jinja.pocoo.org/docs/templates/ for more.

Rotation of 3D vector?

I made a fairly complete library of 3D mathematics for Python{2,3}. It still does not use Cython, but relies heavily on the efficiency of numpy. You can find it here with pip:

python[3] -m pip install math3d

Or have a look at my gitweb http://git.automatics.dyndns.dk/?p=pymath3d.git and now also on github: https://github.com/mortlind/pymath3d .

Once installed, in python you may create the orientation object which can rotate vectors, or be part of transform objects. E.g. the following code snippet composes an orientation that represents a rotation of 1 rad around the axis [1,2,3], applies it to the vector [4,5,6], and prints the result:

import math3d as m3d
r = m3d.Orientation.new_axis_angle([1,2,3], 1)
v = m3d.Vector(4,5,6)
print(r * v)

The output would be

<Vector: (2.53727, 6.15234, 5.71935)>

This is more efficient, by a factor of approximately four, as far as I can time it, than the oneliner using scipy posted by B. M. above. However, it requires installation of my math3d package.

How to give a time delay of less than one second in excel vba?

I found this on another site not sure if it works or not.

Application.Wait Now + 1/(24*60*60.0*2)

the numerical value 1 = 1 day

1/24 is one hour

1/(24*60) is one minute

so 1/(24*60*60*2) is 1/2 second

You need to use a decimal point somewhere to force a floating point number

Source

Not sure if this will work worth a shot for milliseconds

Application.Wait (Now + 0.000001) 

How can I make window.showmodaldialog work in chrome 37?

A very good, and working, javascript solution is provided here : https://github.com/niutech/showModalDialog

I personnally used it, works like before for other browser and it creates a new dialog for chrome browser.

Here is an example on how to use it :

function handleReturnValue(returnValue) {
    if (returnValue !== undefined) {
        // do what you want
    }
}

var myCallback = function (returnValue) { // callback for chrome usage
    handleReturnValue(returnValue);
};

var returnValue = window.showModalDialog('someUrl', 'someDialogTitle', 'someDialogParams', myCallback); 
handleReturnValue(returnValue); // for other browsers except Chrome

Which characters need to be escaped in HTML?

The exact answer depends on the context. In general, these characters must not be present (HTML 5.2 §3.2.4.2.5):

Text nodes and attribute values must consist of Unicode characters, must not contain U+0000 characters, must not contain permanently undefined Unicode characters (noncharacters), and must not contain control characters other than space characters. This specification includes extra constraints on the exact value of Text nodes and attribute values depending on their precise context.

For elements in HTML, the constraints of the Text content model also depends on the kind of element. For instance, an "<" inside a textarea element does not need to be escaped in HTML because textarea is an escapable raw text element.

These restrictions are scattered across the specification. E.g., attribute values (§8.1.2.3) must not contain an ambiguous ampersand and be either (i) empty, (ii) within single quotes (and thus must not contain U+0027 APOSTROPHE character '), (iii) within double quotes (must not contain U+0022 QUOTATION MARK character "), or (iv) unquoted — with the following restrictions:

... must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.

How to pass multiple parameters in a querystring

Query_string

(Following is the text of the linked section of the Wikipedia entry.)

Structure

A typical URL containing a query string is as follows:

http://server/path/program?query_string

When a server receives a request for such a page, it runs a program (if configured to do so), passing the query_string unchanged to the program. The question mark is used as a separator and is not part of the query string.

A link in a web page may have a URL that contains a query string, however, HTML defines three ways a web browser can generate the query string:

  • a web form via the ... element
  • a server-side image map via the ?ismap? attribute on the element with a construction
  • an indexed search via the now deprecated element

Web forms

The main use of query strings is to contain the content of an HTML form, also known as web form. In particular, when a form containing the fields field1, field2, field3 is submitted, the content of the fields is encoded as a query string as follows:

field1=value1&field2=value2&field3=value3...

  • The query string is composed of a series of field-value pairs.
  • Within each pair, the field name and value are separated by an equals sign. The equals sign may be omitted if the value is an empty string.
  • The series of pairs is separated by the ampersand, '&' (or semicolon, ';' for URLs embedded in HTML and not generated by a ...; see below). While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field:

field1=value1&field1=value2&field1=value3...

For each field of the form, the query string contains a pair field=value. Web forms may include fields that are not visible to the user; these fields are included in the query string when the form is submitted

This convention is a W3C recommendation. W3C recommends that all web servers support semicolon separators in addition to ampersand separators[6] to allow application/x-www-form-urlencoded query strings in URLs within HTML documents without having to entity escape ampersands.

Technically, the form content is only encoded as a query string when the form submission method is GET. The same encoding is used by default when the submission method is POST, but the result is not sent as a query string, that is, is not added to the action URL of the form. Rather, the string is sent as the body of the HTTP request.

Date difference in years using C#

Use:

int Years(DateTime start, DateTime end)
{
    return (end.Year - start.Year - 1) +
        (((end.Month > start.Month) ||
        ((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0);
}

how to console.log result of this ajax call?

$.ajax({
    type: 'POST',
    url: 'loginCheck',
    data: $(formLogin).serialize(),    
    success: function(result){
        console.log('my message' + result);
    }
});

generating variable names on fly in python

If you really want to create them on the fly you can assign to the dict that is returned by either globals() or locals() depending on what namespace you want to create them in:

globals()['somevar'] = 'someval'
print somevar  # prints 'someval'

But I wouldn't recommend doing that. In general, avoid global variables. Using locals() often just obscures what you are really doing. Instead, create your own dict and assign to it.

mydict = {}
mydict['somevar'] = 'someval'
print mydict['somevar']

Learn the python zen; run this and grok it well:

>>> import this

How to delete a cookie using jQuery?

What you are doing is correct, the problem is somewhere else, e.g. the cookie is being set again somehow on refresh.

How do I make a JAR from a .java file?

Although it is not recommended method but still it works
[7-Zip Software is needed]
Procedure to get jar from java files:

  • place all java files in one folder

  • right click on the folder enter image description here

  • now click on Add to archive you will get something like shown below enter image description here

  • now just change zip to jar and click on ok

How do I display an alert dialog on Android?

I was using this AlertDialog in button onClick method:

button.setOnClickListener(v -> {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater layoutInflaterAndroid = LayoutInflater.from(this);
    View view2 = layoutInflaterAndroid.inflate(R.layout.cancel_dialog, null);
    builder.setView(view2);
    builder.setCancelable(false);
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();

    view2.findViewById(R.id.yesButton).setOnClickListener(v1 -> onBackPressed());
    view2.findViewById(R.id.nobutton).setOnClickListener(v12 -> alertDialog.dismiss());
});

dialog.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/textmain"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:gravity="center"
    android:padding="5dp"
    android:text="@string/warning"
    android:textColor="@android:color/black"
    android:textSize="18sp"
    android:textStyle="bold"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


<TextView
    android:id="@+id/textpart2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:gravity="center"
    android:lines="2"
    android:maxLines="2"
    android:padding="5dp"
    android:singleLine="false"
    android:text="@string/dialog_cancel"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="15sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textmain" />


<TextView
    android:id="@+id/yesButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="40dp"
    android:layout_marginTop="5dp"
    android:layout_marginEnd="40dp"
    android:layout_marginBottom="5dp"
    android:background="#87cefa"
    android:gravity="center"
    android:padding="10dp"
    android:text="@string/yes"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="15sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textpart2" />


<TextView
    android:id="@+id/nobutton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="40dp"
    android:layout_marginTop="5dp"
    android:layout_marginEnd="40dp"
    android:background="#87cefa"
    android:gravity="center"
    android:padding="10dp"
    android:text="@string/no"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="15sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/yesButton" />


<TextView
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:layout_margin="5dp"
    android:padding="10dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/nobutton" />
</androidx.constraintlayout.widget.ConstraintLayout>

Using FileUtils in eclipse

For selenium automation users

  1. Download Library file from http://www.java2s.com/Code/Jar/o/Downloadorgapachecommonsiojar.htm
  2. Extract
  3. Right click on the proj name from the explorer >> Build path >>Config Build Path

Switch role after connecting to database

--create a user that you want to use the database as:

create role neil;

--create the user for the web server to connect as:

create role webgui noinherit login password 's3cr3t';

--let webgui set role to neil:

grant neil to webgui; --this looks backwards but is correct.

webgui is now in the neil group, so webgui can call set role neil . However, webgui did not inherit neil's permissions.

Later, login as webgui:

psql -d some_database -U webgui
(enter s3cr3t as password)

set role neil;

webgui does not need superuser permission for this.

You want to set role at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:

public class SetRoleJdbcInterceptor extends JdbcInterceptor {

    @Override
    public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if(authentication != null) {
            try {

                /* 
                  use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.

                  Or use a whitelist-map approach
                */
                String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());

                Statement statement = pooledConnection.getConnection().createStatement();
                statement.execute("set role \"" + username + "\"");
                statement.close();
            } catch(SQLException exp){
                throw new RuntimeException(exp);
            }
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if("close".equals(method.getName())){
            Statement statement = ((Connection)proxy).createStatement();
            statement.execute("reset role");
            statement.close();
        }

        return super.invoke(proxy, method, args);
    }
}

Python copy files to a new directory and rename if file name already exists

I would say you have an indentation problem, at least as you wrote it here:

while not os.path.exists(file + "_" + str(i) + extension):
   i+=1
   print "Already 2x exists..."
   print "Renaming"
   shutil.copy(path, file + "_" + str(i) + extension)

should be:

while os.path.exists(file + "_" + str(i) + extension):
    i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)

Check this out, please!

git clone through ssh

Easy way to do this issue
try this.

Step 1:

ls -al ~/.ssh

enter image description here

Step 2:

ssh-keygen 

(using enter key for default value) enter image description here Step 3: To setup config file

vim /c/Users/Willie/.ssh/config

Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_rsa

Step 4:

git clone [email protected]:<username>/test2.git

enter image description here

Step 5:
When you finished Step 4
1.the test2.git file will be download done
2.you will get the new file(known_hosts) in the ~/.ssh
enter image description here

PS: I create the id_rsa and id_rsa.ub by meself and I deliver it to the Gitlab server. using both keys to any client-sides(windows and Linux).

Npm install cannot find module 'semver'

Having just encountered this on Arch Linux 4.13.3, I solved the issue by simply reinstalling semver:

pacman -S semver

How to set image to fit width of the page using jsPDF?

A better solution is to set the doc width/height using the aspect ratio of your image.

_x000D_
_x000D_
var ExportModule = {_x000D_
  // Member method to convert pixels to mm._x000D_
  pxTomm: function(px) {_x000D_
    return Math.floor(px / $('#my_mm').height());_x000D_
  },_x000D_
  ExportToPDF: function() {_x000D_
    var myCanvas = document.getElementById("exportToPDF");_x000D_
_x000D_
    html2canvas(myCanvas, {_x000D_
      onrendered: function(canvas) {_x000D_
        var imgData = canvas.toDataURL(_x000D_
          'image/jpeg', 1.0);_x000D_
        //Get the original size of canvas/image_x000D_
        var img_w = canvas.width;_x000D_
        var img_h = canvas.height;_x000D_
_x000D_
        //Convert to mm_x000D_
        var doc_w = ExportModule.pxTomm(img_w);_x000D_
        var doc_h = ExportModule.pxTomm(img_h);_x000D_
        //Set doc size_x000D_
        var doc = new jsPDF('l', 'mm', [doc_w, doc_h]);_x000D_
_x000D_
        //set image height similar to doc size_x000D_
        doc.addImage(imgData, 'JPG', 0, 0, doc_w, doc_h);_x000D_
        var currentTime = new Date();_x000D_
        doc.save('Dashboard_' + currentTime + '.pdf');_x000D_
_x000D_
      }_x000D_
    });_x000D_
  },_x000D_
}
_x000D_
<script src="Scripts/html2canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/jsPDF.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/addimage.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/fileSaver.js"></script>_x000D_
<div id="my_mm" style="height: 1mm; display: none"></div>_x000D_
_x000D_
<div id="exportToPDF">_x000D_
  Your html here._x000D_
</div>_x000D_
_x000D_
<button id="export_btn" onclick="ExportModule.ExportToPDF();">Export</button>
_x000D_
_x000D_
_x000D_

javax.net.ssl.SSLException: Received fatal alert: protocol_version

This seems like a protocol version mismatch, this exception normally happens when there is a mismatch between SSL protocol version used by the client and the server. your clients should use a proctocol version supported by the server.

How to open a web page automatically in full screen mode

view full size page large (function () { var viewFullScreen = document.getElementById("view-fullscreen"); if (viewFullScreen) { viewFullScreen.addEventListener("click", function () { var docElm = document.documentElement; if (docElm.requestFullscreen) { docElm.requestFullscreen(); } else if (docElm.mozRequestFullScreen) { docElm.mozRequestFullScreen(); } else if (docElm.webkitRequestFullScreen) { docElm.webkitRequestFullScreen(); } }, false); } })();

_x000D_
_x000D_
<div class="container">      _x000D_
            <section class="main-content">_x000D_
                                    <center><a href="#"><button id="view-fullscreen">view full size page large</button></a><center>_x000D_
                                           <script>(function () {_x000D_
    var viewFullScreen = document.getElementById("view-fullscreen");_x000D_
    if (viewFullScreen) {_x000D_
        viewFullScreen.addEventListener("click", function () {_x000D_
            var docElm = document.documentElement;_x000D_
            if (docElm.requestFullscreen) {_x000D_
                docElm.requestFullscreen();_x000D_
            }_x000D_
            else if (docElm.mozRequestFullScreen) {_x000D_
                docElm.mozRequestFullScreen();_x000D_
            }_x000D_
            else if (docElm.webkitRequestFullScreen) {_x000D_
                docElm.webkitRequestFullScreen();_x000D_
            }_x000D_
        }, false);_x000D_
    }_x000D_
    })();</script>_x000D_
                                           </section>_x000D_
</div>
_x000D_
_x000D_
_x000D_

for view demo clcik here demo of click to open page in fullscreen

Error "File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it"

for people coming here from the firebase codelabs tutorial step 3:go to page 4.

Apparently, if google says You should now have the android-start project open in Android Studio. ,She means it,and not You should now have the android-start project open in Android Studio, without any build-errors .
As the instruction says there, you have to get a configuration file from firebase. i.e , create a new project in your firebase acc with name 'friendly chat and in the next page , add its package name and SHA1 KEY.
after downloading the json file,add it to your project>app folder, and Rebuild project.

Twitter bootstrap scrollable modal

How about the below solution? It worked for me. Try this:

.modal .modal-body {
    max-height: 420px;
    overflow-y: auto;
}

Details:

  1. remove overflow-y: auto; or overflow: auto; from .modal class (important)
  2. remove max-height: 400px; from .modal class (important)
  3. Add max-height: 400px; to .modal .modal-body (or what ever, can be 420px or less, but would not go more than 450px)
  4. Add overflow-y: auto; to .modal .modal-body

Done, only body will scroll.

Getting a POST variable

Use this for GET values:

Request.QueryString["key"]

And this for POST values

Request.Form["key"]

Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:

Request["key"]

Another thing to note (if you need it) is you can check the type of request by using:

Request.RequestType

Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.

Run Jquery function on window events: load, resize, and scroll?

You can bind listeners to one common functions -

$(window).bind("load resize scroll",function(e){
  // do stuff
});

Or another way -

$(window).bind({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Alternatively, instead of using .bind() you can use .on() as bind directly maps to on(). And maybe .bind() won't be there in future jquery versions.

$(window).on({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Spring data JPA query with parameter properties

This link will help you: Spring Data JPA M1 with SpEL expressions supported. The similar example would be:

@Query("select u from User u where u.firstname = :#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);

https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions

npm not working after clearing cache

I solved this issue by running cmd as an administrator. before that, I was trying to run in vs code.

run it in Power Shell or Cmd with administrative privilege. I hope that it will help.

npm install –g @angular/cli@latest

How to convert an object to JSON correctly in Angular 2 with TypeScript

Tested and working in Angular 9.0

If you're getting the data using API

array: [];

ngOnInit()    {
this.service.method()
.subscribe(
    data=>
  {
    this.array = JSON.parse(JSON.stringify(data.object));
  }
)

}

You can use that array to print your results from API data in html template.

Like

<p>{{array['something']}}</p>

Why is using "for...in" for array iteration a bad idea?

The reason is that one construct:

_x000D_
_x000D_
var a = []; // Create a new empty array._x000D_
a[5] = 5;   // Perfectly legal JavaScript that resizes the array._x000D_
_x000D_
for (var i = 0; i < a.length; i++) {_x000D_
    // Iterate over numeric indexes from 0 to 5, as everyone expects._x000D_
    console.log(a[i]);_x000D_
}_x000D_
_x000D_
/* Will display:_x000D_
   undefined_x000D_
   undefined_x000D_
   undefined_x000D_
   undefined_x000D_
   undefined_x000D_
   5_x000D_
*/
_x000D_
_x000D_
_x000D_

can sometimes be totally different from the other:

_x000D_
_x000D_
var a = [];_x000D_
a[5] = 5;_x000D_
for (var x in a) {_x000D_
    // Shows only the explicitly set index of "5", and ignores 0-4_x000D_
    console.log(x);_x000D_
}_x000D_
_x000D_
/* Will display:_x000D_
   5_x000D_
*/
_x000D_
_x000D_
_x000D_

Also consider that JavaScript libraries might do things like this, which will affect any array you create:

_x000D_
_x000D_
// Somewhere deep in your JavaScript library..._x000D_
Array.prototype.foo = 1;_x000D_
_x000D_
// Now you have no idea what the below code will do._x000D_
var a = [1, 2, 3, 4, 5];_x000D_
for (var x in a){_x000D_
    // Now foo is a part of EVERY array and _x000D_
    // will show up here as a value of 'x'._x000D_
    console.log(x);_x000D_
}_x000D_
_x000D_
/* Will display:_x000D_
   0_x000D_
   1_x000D_
   2_x000D_
   3_x000D_
   4_x000D_
   foo_x000D_
*/
_x000D_
_x000D_
_x000D_

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Type

netsh wlan set hostednetwork mode=allow ssid=hotspotname key=123456789

perform all steps in proper order.. for more detail with image ,have a look..this might help to setup hotspot correctly.

http://www.infogeekers.com/turn-windows-8-into-wifi-hotspot/

How can I profile C++ code running on Linux?

You can use Valgrind with the following options

valgrind --tool=callgrind ./(Your binary)

It will generate a file called callgrind.out.x. You can then use kcachegrind tool to read this file. It will give you a graphical analysis of things with results like which lines cost how much.

Why can I not push_back a unique_ptr into a vector?

std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.

error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
 std::unique_ptr<int>]'

The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

The following works with the new emplace calls.

std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );

See using unique_ptr with standard library containers for further reading.

How to install Java SDK on CentOS?

I have written a shell script to install/uninstall java on centos. You can get it done by just run the shell. The core of this shell is :

1.download the jdk rpm(RedHat Package Manager) package.
2.install java using rpm.

You can see more detail here: https://github.com/daikaixian/WaterShell/tree/master/program_installer

Hope it works for you.

Ruby - ignore "exit" in code

One hackish way to define an exit method in context:

class Bar; def exit; end; end 

This works because exit in the initializer will be resolved as self.exit1. In addition, this approach allows using the object after it has been created, as in: b = B.new.

But really, one shouldn't be doing this: don't have exit (or even puts) there to begin with.

(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)


1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit normally resolves to Object#exit. However, this can be changed by introducing an overridden method as shown - nothing fancy.

How to get the browser to navigate to URL in JavaScript

This works in all browsers:

window.location.href = '...';

If you wanted to change the page without it reflecting in the browser back history, you can do:

window.location.replace('...');

Colorizing text in the console with C++

I'm not sure what you really want to do, but my guess is you want your C++ program to output colored text in the console, right ? Don't know about Windows, but on all Unices (including Mac OS X), you'd simply use ANSI escape sequences for that.

Deleting multiple elements from a list

For some reason I don't like any of the answers here. Yes, they work, but strictly speaking most of them aren't deleting elements in a list, are they? (But making a copy and then replacing the original one with the edited copy).

Why not just delete the higher index first?

Is there a reason for this? I would just do:

for i in sorted(indices, reverse=True):
    del somelist[i]

If you really don't want to delete items backwards, then I guess you should just deincrement the indices values which are greater than the last deleted index (can't really use the same index since you're having a different list) or use a copy of the list (which wouldn't be 'deleting' but replacing the original with an edited copy).

Am I missing something here, any reason to NOT delete in the reverse order?

UIBarButtonItem in navigation bar programmatically?

This is a crazy thing of apple. When you say self.navigationItem.rightBarButtonItem.title then it will say nil while on the GUI it shows Edit or Save. Fresher likes me will take a lot of time to debug this behavior.

There is a requirement that the Item will show Edit in the firt load then user taps on it It will change to Save title. To archive this, i did as below.

//view did load will say Edit title

private func loadRightBarItem() {
    let logoutBarButtonItem = UIBarButtonItem(title: "Edit", style: .done, target: self, action: #selector(handleEditBtn))
    self.navigationItem.rightBarButtonItem  = logoutBarButtonItem
}

// tap Edit item will change to Save title

@objc private func handleEditBtn() {
    print("clicked on Edit btn")
    let logoutBarButtonItem = UIBarButtonItem(title: "Save", style: .done, target: self, action: #selector(handleSaveBtn))
    self.navigationItem.rightBarButtonItem  = logoutBarButtonItem
    blockEditTable(isBlock: false)
}

//tap Save item will display Edit title

@objc private func handleSaveBtn(){
    print("clicked on Save btn")
    let logoutBarButtonItem = UIBarButtonItem(title: "Edit", style: .done, target: self, action: #selector(handleEditBtn))
    self.navigationItem.rightBarButtonItem  = logoutBarButtonItem

    saveInvitation()
    blockEditTable(isBlock: true)

}

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

Git keeps prompting me for a password

I had this issue. A repo was requiring me to input credentials every time. All my other repos were not asking for my credentials. They were even set up to track GitLab using HTTPS under the same account credentials, so it was weird that they all worked fine except one.

Comparing the .git/config files, I found that there were 2 key differences in the URLs which was causing the issue:

Does ask for credentials:

https://gitlab.com/myaccount/myproject

Does not ask for credentials:

https://[email protected]/myaccount/myproject.git 

So adding the "myaccount@" and ".git" resolved the issue in my case.

How do you follow an HTTP Redirect in Node.js?

If you have https server, change your url to use https:// protocol.

I got into similar issue with this one. My url has http:// protocol and I want to make a POST request, but the server wants to redirect it to https. What happen is that, turns out to be node http behavior sends the redirect request (next) in GET method which is not the case.

What I did is to change my url to https:// protocol and it works.

High Quality Image Scaling Library

You can try dotImage, one of my company's products, which includes an object for resampling images that has 18 filter types for various levels of quality.

Typical usage is:

// BiCubic is one technique available in PhotoShop
ResampleCommand resampler = new ResampleCommand(newSize, ResampleMethod.BiCubic);
AtalaImage newImage = resampler.Apply(oldImage).Image;

in addition, dotImage includes 140 some odd image processing commands including many filters similar to those in PhotoShop, if that's what you're looking for.

npm install error from the terminal

I had this problem when trying to run 'npm install' in a Terminal window which had been opened before installing Node.js.

Opening a new Terminal window (i.e. bash session) worked. (Presumably this provided the correct environment variables for npm to run correctly.)

Append integer to beginning of list in Python

Another way of doing the same,

list[0:0] = [a]

JSON formatter in C#?

I was very impressed by compact JSON formatter by Vince Panuccio.
Here is an improved version I now use:

public static string FormatJson(string json, string indent = "  ")
{
    var indentation = 0;
    var quoteCount = 0;
    var escapeCount = 0;

    var result =
        from ch in json ?? string.Empty
        let escaped = (ch == '\\' ? escapeCount++ : escapeCount > 0 ? escapeCount-- : escapeCount) > 0
        let quotes = ch == '"' && !escaped ? quoteCount++ : quoteCount
        let unquoted = quotes % 2 == 0
        let colon = ch == ':' && unquoted ? ": " : null
        let nospace = char.IsWhiteSpace(ch) && unquoted ? string.Empty : null
        let lineBreak = ch == ',' && unquoted ? ch + Environment.NewLine + string.Concat(Enumerable.Repeat(indent, indentation)) : null
        let openChar = (ch == '{' || ch == '[') && unquoted ? ch + Environment.NewLine + string.Concat(Enumerable.Repeat(indent, ++indentation)) : ch.ToString()
        let closeChar = (ch == '}' || ch == ']') && unquoted ? Environment.NewLine + string.Concat(Enumerable.Repeat(indent, --indentation)) + ch : ch.ToString()
        select colon ?? nospace ?? lineBreak ?? (
            openChar.Length > 1 ? openChar : closeChar
        );

    return string.Concat(result);
}

It fixes the following issues:

  1. Escape sequences inside strings
  2. Missing spaces after colon
  3. Extra spaces after commas (or elsewhere)
  4. Square and curly braces inside strings
  5. Doesn't fail on null input

Outputs:

{
  "status": "OK",
  "results": [
    {
      "types": [
        "locality",
        "political"
      ],
      "formatted_address": "New York, NY, USA",
      "address_components": [
        {
          "long_name": "New York",
          "short_name": "New York",
          "types": [
            "locality",
            "political"
          ]
        },
        {
          "long_name": "New York",
          "short_name": "New York",
          "types": [
            "administrative_area_level_2",
            "political"
          ]
        },
        {
          "long_name": "New York",
          "short_name": "NY",
          "types": [
            "administrative_area_level_1",
            "political"
          ]
        },
        {
          "long_name": "United States",
          "short_name": "US",
          "types": [
            "country",
            "political"
          ]
        }
      ],
      "geometry": {
        "location": {
          "lat": 40.7143528,
          "lng": -74.0059731
        },
        "location_type": "APPROXIMATE",
        "viewport": {
          "southwest": {
            "lat": 40.5788964,
            "lng": -74.2620919
          },
          "northeast": {
            "lat": 40.8495342,
            "lng": -73.7498543
          }
        },
        "bounds": {
          "southwest": {
            "lat": 40.4773990,
            "lng": -74.2590900
          },
          "northeast": {
            "lat": 40.9175770,
            "lng": -73.7002720
          }
        }
      }
    }
  ]
}

Converts scss to css

Install Ruby-sass using below command
sudo apt-get -y update
sudo apt-get -y install ruby-full
sudo apt install ruby-sass
gem install bundler

Example
sass SCSS_FILE_PATH:CSS_FILE_PATH;

e.g sass mda/at-md-black.scss:css/at-md-black.css;

How do I solve the INSTALL_FAILED_DEXOPT error?

If you are using Android Studio, try clean your project:

Build > Clean Project

How to store custom objects in NSUserDefaults

I create a library RMMapper (https://github.com/roomorama/RMMapper) to help save custom object into NSUserDefaults easier and more convenient, because implementing encodeWithCoder and initWithCoder is super boring!

To mark a class as archivable, just use: #import "NSObject+RMArchivable.h"

To save a custom object into NSUserDefaults:

#import "NSUserDefaults+RMSaveCustomObject.h"
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults rm_setCustomObject:user forKey:@"SAVED_DATA"];

To get custom obj from NSUserDefaults:

user = [defaults rm_customObjectForKey:@"SAVED_DATA"]; 

Python locale error: unsupported locale setting

In trying to get python to spit out names in specific locale I landed here with same problem.

In pursuing the answer, things got a little mystical I find.

I found that python code.

import locale
print locale.getdefaultlocale()
>> ('en_DK', 'UTF-8')

And indeed locale.setlocale(locale.LC_TIME, 'en_DK.UTF-8') works

Using tips here I tested further to see what is available using python code

import locale
loc_list = [(a,b) for a,b in locale.locale_alias.items() ]
loc_size = len(loc_list)
print loc_size,'entries'

for loc in loc_list:
    try:
        locale.setlocale(locale.LC_TIME, loc[1])
        print 'SUCCES set {:12} ({})'.format(loc[1],loc[0])
    except:
        pass

which yields

858 entries
SUCCES set en_US.UTF-8  (univ)
SUCCES set C            (c.ascii)
SUCCES set C            (c.en)
SUCCES set C            (posix-utf2)
SUCCES set C            (c)
SUCCES set C            (c_c)
SUCCES set C            (c_c.c)
SUCCES set en_IE.UTF-8  (en_ie.utf8@euro)
SUCCES set en_US.UTF-8  (universal.utf8@ucs4)
SUCCES set C            (posix)
SUCCES set C            (english_united-states.437)
SUCCES set en_US.UTF-8  (universal)

Of which only above is working! But the en_DK.UTF-8 is not in this list, though it works!?!? What?? And the python generated locale list do contain a lot of combos of da and DK, which I am looking for, but again no UTF-8 for da/DK...

I am on a Point Linux distro (Debian based), and here locale says amongst other LC_TIME="en_DK.UTF-8", which I know works, but not the locale I need.

locale -a says

C
C.UTF-8
en_DK.utf8
en_US.utf8
POSIX

So definitely need to install other locale, which i did by editing /etc/locale.gen, uncomment needed line da_DK.UTF-8 UTF-8 and run command locale-gen

Now locale.setlocale(locale.LC_TIME, 'da_DK.UTF-8') works too, and I can get my localized day and month names.

My Conclision:

Python : locale.locale_alias is not at all helpfull in finding available locales!!!

Linux : It is quite easy to get locale list and install new locale. A lot of help available.

Windows : I have been investigating a little, but nothing conclusive. There are though posts leading to answers, but I have not felt the urge to pursue it.

How should I make my VBA code compatible with 64-bit Windows?

Actually, the correct way of checking for 32 bit or 64 bit platform is to use the Win64 constant which is defined in all versions of VBA (16 bit, 32 bit, and 64 bit versions).

#If Win64 Then 
' Win64=true, Win32=true, Win16= false 
#ElseIf Win32 Then 
' Win32=true, Win16=false 
#Else 
' Win16=true 
#End If

Source: VBA help on compiler constants

Jupyter/IPython Notebooks: Shortcut for "run all"?

I've been trying to do this in Jupyter Lab so thought it might be useful to post the answer here. You can find the shortcuts in settings and also add your own, where a full list of the possible shortcuts can be found here.

For example, I added my own shortcut to run all cells. In Jupyter Lab, under Settings > Advanced Settings, select Keyboard Shortcuts, then add the following code to 'User Overrides':

{
    "notebook:run-all-cells": {
      "command": "notebook:run-all-cells",
      "keys": [
        "Shift Backspace"
      ],
      "selector": ".jp-Notebook.jp-mod-editMode"
    }
}

Here, Shift + Backspace will run all cells in the notebook.

How does a Breadth-First Search work when looking for Shortest Path?

Based on acheron55 answer I posted a possible implementation here.
Here is a brief summery of it:

All you have to do, is to keep track of the path through which the target has been reached. A simple way to do it, is to push into the Queue the whole path used to reach a node, rather than the node itself.
The benefit of doing so is that when the target has been reached the queue holds the path used to reach it.
This is also applicable to cyclic graphs, where a node can have more than one parent.

How to check if a string starts with "_" in PHP?

$variable[0] != "_"

How does it work?

In PHP you can get particular character of a string with array index notation. $variable[0] is the first character of a string (if $variable is a string).

Converting std::__cxx11::string to std::string

I had a similar issue recently while trying to link with the pre-built binaries of hdf5 version 1.10.5 on Ubuntu 16.04. None of the solutions suggested here worked for me, and I was using g++ version 9.1. I found that the best solution is to build the hdf5 library from source. Do not use the pre-built binaries since these were built using gcc 4.9! Instead, download the source code archives from the hdf website for your particular distribution and build the library. It is very easy.

You will also need the compression libraries zlib and szip from here and here, respectively, if you do not already have them on your system.

Importing csv file into R - numeric values read as characters

In read.table (and its relatives) it is the na.strings argument which specifies which strings are to be interpreted as missing values NA. The default value is na.strings = "NA"

If missing values in an otherwise numeric variable column are coded as something else than "NA", e.g. "." or "N/A", these rows will be interpreted as character, and then the whole column is converted to character.

Thus, if your missing values are some else than "NA", you need to specify them in na.strings.

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

I had the same problem, but it was because in my buttons layout_width/height I forgot to put dp at the end when editing them. Added dp and problem fixed :/

New line in Sql Query

-- Access: 
SELECT CHR(13) & CHR(10) 

-- SQL Server: 
SELECT CHAR(13) + CHAR(10)

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

For that you need to enter one command that is missing from bitbucket commands

Please try git init.

Using GitLab token to clone without authentication

You can use the runners token for CI/CD Pipelines of your GitLab repo.

git clone https://gitlab-ci-token:<runners token>@git.example.com/myuser/myrepo.git

Where <runners token> can be obtained from:

git.example.com/myuser/myrepo/pipelines/settings

or by clicking on the Settings icon -> CI/CD Pipeline and look for Runners Token on the page

Screenshot of the runners token location: Screenshot of the runners token location

Install python 2.6 in CentOS

When I've run into similar situations, I generally avoid the package manager, especially if it would be embarrassing to break something, i.e. a production server. Instead, I would go to Activestate and download their binary package:

https://www.activestate.com/activepython/downloads/

This is installed by running a script which places everything into a folder and does not touch any system files. In fact, you don't even need root permissions to set it up. Then I change the name of the binary to something like apy26, add that folder to the end of the PATH and start coding. If you install packages with apy26 setup.py installor if you use virtualenv and easyinstall, then you have just as flexible a python environment as you need without touching the system standard python.

Edits... Recently I've done some work to build a portable Python binary for Linux that should run on any distro with no external dependencies. This means that any binary shared libraries needed by the portable Python module are part of the build, included in the tarball and installed in Python's private directory structure. This way you can install Python for your application without interfering with the system installed Python.

My github site has a build script which has been thoroughly tested on Ubuntu Lucid 10.04 LTS both 32 and 64 bit installs. I've also built it on Debian Etch but that was a while ago and I can't guarantee that I haven't changed something. The easiest way to do this is you just put your choice of Ubuntu Lucid in a virtual machine, checkout the script with git clone git://github.com/wavetossed/pybuild.git and then run the script.

Once you have it built, use the tarball on any recent Linux distro. There is one little wrinkle with moving it to a directory other than /data1/packages/python272 which is that you have to run the included patchelf to set the interpreter path BEFORE you move the directory. This affects any binaries in /data1/packages/python272/bin

All of this is based on building with RUNPATH and copying the dependent shared libraries. Even though the script is in several files, it is effectively one long shell script arranged in the style of /etc/rc.d directories.

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

You must use the column names and then set the values to insert (both ? marks):

//insert 1st row            
String inserting = "INSERT INTO employee(emp_name ,emp_address) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.executeUpdate();

Limit characters displayed in span

use js:

 $(document).ready(function ()
   { $(".class-span").each(function(i){
        var len=$(this).text().trim().length;
        if(len>100)
        {
            $(this).text($(this).text().substr(0,100)+'...');
        }
    });
 });

How to access /storage/emulated/0/

Also you can use Android Debug Bridge (adb) to copy your file from Android device to folder on your PC:

adb pull /storage/emulated/0/AudioRecorder/1436854479696.mp4 <folder_on_your_PC_e.g. c:/temp>

And you can copy from device whole AudioRecorder folder:

adb pull /storage/emulated/0/AudioRecorder <folder_on_your_PC_e.g. c:/temp>

Best way to structure a tkinter application?

Organizing your application using class make it easy to you and others who work with you to debug problems and improve the app easily.

You can easily organize your application like this:

class hello(Tk):
    def __init__(self):
        super(hello, self).__init__()
        self.btn = Button(text = "Click me", command=close)
        self.btn.pack()
    def close():
        self.destroy()

app = hello()
app.mainloop()

round a single column in pandas

If you are doing machine learning and use tensorflow, many float are of 'float32', not 'float64', and none of the methods mentioned in this thread likely to work. You will have to first convert to float64 first.

x.astype('float')

before round(...).

How to ensure that there is a delay before a service is started in systemd?

You can run the sleep command before your ExecStart with ExecStartPre :

[Service]
ExecStartPre=/bin/sleep 30

Uncaught SyntaxError: Unexpected token with JSON.parse

Let's say you know it's valid JSON but your are still getting this...

In that case it's likely that there are hidden/special characters in the string from whatever source your getting them. When you paste into a validator, they are lost - but in the string they are still there. Those chars, while invisible, will break JSON.parse()

If s is your raw JSON, then clean it up with:

// preserve newlines, etc - use valid JSON
s = s.replace(/\\n/g, "\\n")  
               .replace(/\\'/g, "\\'")
               .replace(/\\"/g, '\\"')
               .replace(/\\&/g, "\\&")
               .replace(/\\r/g, "\\r")
               .replace(/\\t/g, "\\t")
               .replace(/\\b/g, "\\b")
               .replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
s = s.replace(/[\u0000-\u0019]+/g,""); 
var o = JSON.parse(s);

Java error: Only a type can be imported. XYZ resolves to a package

My bet is that you have a package called org.ivec.eresearch.knowledgeportal.model.category (small c) and are running on a non-case sensitive filesystem like Windows or Mac. It seems that the compiler gets confused when a class and package exist.

You can either renamed the class "Category" or the package "category" and this error will go away. Unfortunately I'm not sure if this is a Tomcat or ECJ bug.

SQL select statements with multiple tables

select P.*,
A.Street,
A.City,
A.State
from Preson P
inner join Address A on P.id=A.Person_id
where A.Zip=97229
Order by A.Street,A.City,A.State

restart mysql server on windows 7

In order to prevent 'Access Denied' error:

Start -> search 'Services' -> right click -> Run as admistrator

Changing text color of menu item in navigation drawer

In Future if anyone comes here using, Navigation Drawer Activity (provided by Studio in Activity Prompt window)

The answer is -

Use this before OnCreate() in MainActivity

int[][] state = new int[][] {
        new int[] {android.R.attr.state_checked}, // checked
        new int[] {-android.R.attr.state_checked}
};

int[] color = new int[] {
        Color.rgb(255,46,84),
        (Color.BLACK)
};

ColorStateList csl = new ColorStateList(state, color);

int[][] state2 = new int[][] {
        new int[] {android.R.attr.state_checked}, // checked
        new int[] {-android.R.attr.state_checked}
};

int[] color2 = new int[] {
        Color.rgb(255,46,84),
        (Color.GRAY)
};

ColorStateList csl2 = new ColorStateList(state2, color2);

and use this in onNavigationItemSelected() in MainActivity (you dont need to Write this function if you use Navigation Drawer activity, it will be added in MainActivity).

 NavigationView nav = (NavigationView) findViewById(R.id.nav_view);
    nav.setItemTextColor(csl);
    nav.setItemIconTintList(csl2);
    nav.setItemBackgroundResource(R.color.white);

Tip - add this code before If else Condition in onNavigationItemSelected()

How to convert JSON string into List of Java object?

use below simple code, no need to use any library

String list = "your_json_string";
Gson gson = new Gson();                         
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);

How do ports work with IPv6?

They work almost the same as today. However, be sure you include [] around your IP.

For example : http://[1fff:0:a88:85a3::ac1f]:8001/index.html

Wikipedia has a pretty good article about IPv6: http://en.wikipedia.org/wiki/IPv6#Addressing

PHP If Statement with Multiple Conditions

An elegant way is building an array on the fly and using in_array():

if (in_array($var, array("abc", "def", "ghi")))

The switch statement is also an alternative:

switch ($var) {
case "abc":
case "def":
case "hij":
    echo "yes";
    break;
default:
    echo "no";
}

How do I get a div to float to the bottom of its container?

Pretty old question, but still ... You can float a div to the bottom of the page like this:

div{
  position: absolute; 
  height: 100px; 
  top: 100%; 
  margin-top:-100px; 
}

You can see where the magic happens. I think you could do the same for floating it to the bottom of a parent div.

Update row with data from another row in the same table

UPDATE financialyear
   SET firstsemfrom = dt2.firstsemfrom,
       firstsemto = dt2.firstsemto,
       secondsemfrom = dt2.secondsemfrom,
       secondsemto = dt2.secondsemto
  from financialyear dt2
 WHERE financialyear.financialyearkey = 141
   AND dt2.financialyearkey = 140

Printing a java map Map<String, Object> - How?

You may use Map.entrySet() method:

for (Map.Entry entry : objectSet.entrySet())
{
    System.out.println("key: " + entry.getKey() + "; value: " + entry.getValue());
}

Initializing a dictionary in python with a key value and no corresponding values

You can initialize the values as empty strings and fill them in later as they are found.

dictionary = {'one':'','two':''}
dictionary['one']=1
dictionary['two']=2

Conda command not found

If you're using zsh and it has not been set up to read .bashrc, you need to add the Miniconda directory to the zsh shell PATH environment variable. Add this to your .zshrc:

export PATH="/home/username/miniconda/bin:$PATH"

Make sure to replace /home/username/miniconda with your actual path.

Save, exit the terminal and then reopen the terminal. conda command should work.

PHP, Get tomorrows date from date

$date = '2013-01-22';
$time = strtotime($date) + 86400;
echo date('Y-m-d', $time);

Where 86400 is the # of seconds in a day.

Adding an HTTP Header to the request in a servlet filter

You'll have to use an HttpServletRequestWrapper:

public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
        @Override
        public String getHeader(String name) {
            final String value = request.getParameter(name);
            if (value != null) {
                return value;
            }
            return super.getHeader(name);
        }
    };
    chain.doFilter(wrapper, response);
}

Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.

How do I write the 'cd' command in a makefile?

What do you want it to do once it gets there? Each command is executed in a subshell, so the subshell changes directory, but the end result is that the next command is still in the current directory.

With GNU make, you can do something like:

BIN=/bin
foo:
    $(shell cd $(BIN); ls)

Getting the last element of a split string array

You can also consider to reverse your array and take the first element. That way you don't have to know about the length, but it brings no real benefits and the disadvantage that the reverse operation might take longer with big arrays:

array1.split(",").reverse()[0]

It's easy though, but also modifies the original array in question. That might or might not be a problem.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

Probably you might want to use this though:

array1.split(",").pop()

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

That usually means a null is being posted to the query instead of your desired value, you might try to run the SQL Profiler to see exactly what is getting passed to SQL Server from linq.

Installing PHP Zip Extension

You may have several php.ini files, one for CLI and one for apache. Run php --ini to see where the CLI ini location is.

Can the Android layout folder contain subfolders?

Not possible, but the layout folder is sorted by name. So, I prepend the layout file names with my package names. E.g. for the two packages "buying" and "playing":

buying_bought_tracks.xml
buying_buy_tracks.xml
playing_edit_playlist.xml
playing_play_playlist.xml
playing_show_playlists.xml

How to format a numeric column as phone number in SQL

You can also try this:

CREATE  function [dbo].[fn_FormatPhone](@Phone varchar(30)) 
returns varchar(30)
As
Begin
declare @FormattedPhone varchar(30)

set     @Phone = replace(@Phone, '.', '-') --alot of entries use periods instead of dashes
set @FormattedPhone =
    Case
      When isNumeric(@Phone) = 1 Then
        case
          when len(@Phone) = 10 then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 4, 3)+ '-' +substring(@Phone, 7, 4)
          when len(@Phone) = 7  then substring(@Phone, 1, 3)+ '-' +substring(@Phone, 4, 4)
          else @Phone
        end
      When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 8, 4)
      When @phone like '[0-9][0-9][0-9] [0-9][0-9][0-9] [0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
      When @phone like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' Then '('+substring(@Phone, 1, 3)+')'+ ' ' +substring(@Phone, 5, 3)+ '-' +substring(@Phone, 9, 4)
      Else @Phone
    End
return  @FormattedPhone

end

use on it select

(SELECT [dbo].[fn_FormatPhone](f.coffphone)) as 'Phone'

Output will be

enter image description here

Composer Warning: openssl extension is missing. How to enable in WAMP

I had the same problem even though openssl was enabled. The issue was that the Composer installer was looking at this config file:

C:\wamp\bin\php\php5.4.3\php.ini

But the config file that's loaded is actually here:

C:\wamp\bin\apache\apache2.2.22\bin\php.ini

So I just had to uncomment it in the first php.ini file and that did the trick. This is how WAMP was installed on my machine by default. I didn't go changing anything, so this will probably happen to others as well. This is basically the same as Augie Gardner's answer above, but I just wanted to point out that you might have two php.ini files.

check if variable empty

here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also

<?php
    $val = 0;
    //evaluates to true because $var is empty
    if (empty($val)) {
        echo '$val is either 0, empty, or not set at all';
    }
    //evaluates to true because $VAR IS SET
    if (isset($val)) {
        echo '$val is set even though it is empty';
    }
    ?>

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

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

Finding square root without using sqrt function?

if you need to find square root without using sqrt(),use root=pow(x,0.5).

Where x is value whose square root you need to find.

Determining if Swift dictionary contains key and obtaining any of its values

if dictionayTemp["quantity"] != nil
    {

  //write your code
    }

Gradients on UIView and UILabels On iPhone

You could also use a graphic image one pixel wide as the gradient, and set the view property to expand the graphic to fill the view (assuming you are thinking of a simple linear gradient and not some kind of radial graphic).

Getting a machine's external IP address with Python

Linux only solution.

On Linux Systems, you can use Python to execute a command on the shell. I think it might help someone.

Something like this, (assuming 'dig/drill' is working on the os)

import os 
command = "dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | awk -F\'\"\' '{print $2}' " 
ip = os.system(command)

For Arch users, please replace 'dig' with 'drill'.

parsing JSONP $http.jsonp() response in angular.js

for me the above solutions worked only once i added "format=jsonp" to the request parameters.

PHP string "contains"

You can use these string functions,

strstr — Find the first occurrence of a string

stristr — Case-insensitive strstr()

strrchr — Find the last occurrence of a character in a string

strpos — Find the position of the first occurrence of a substring in a string

strpbrk — Search a string for any of a set of characters

If that doesn't help then you should use preg regular expression

preg_match — Perform a regular expression match

How to make --no-ri --no-rdoc the default for gem install?

On Windows XP the path to the .gemrc file is

c:\Documents and Settings\All Users\Application Data\gemrc 

and this file is not created by default, you should create it yourself.

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

If you have a JPA dependency in your pom.xml then just remove it. This solution worked for me.

How to download folder from putty using ssh client

You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.

Please see the following link on how to download a file/folder: https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html

Auto highlight text in a textbox control

If you need to do this for a large number of textboxes (in Silverlight or WPF), then you can use the technique used in the blog post: http://dnchannel.blogspot.com/2010/01/silverlight-3-auto-select-text-in.html. It uses Attached Properties and Routed Events.

How to initialize HashSet values by construction?

Using Java 8 we can create HashSet as:

Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));

And if we want unmodifiable set we can create a utility method as :

public static <T, A extends Set<T>> Collector<T, A, Set<T>> toImmutableSet(Supplier<A> supplier) {
        return Collector.of(
                supplier,
                Set::add, (left, right) -> {
                    left.addAll(right);
                    return left;
                }, Collections::unmodifiableSet);
    }

This method can be used as :

 Stream.of("A", "B", "C", "D").collect(toImmutableSet(HashSet::new));

In a URL, should spaces be encoded using %20 or +?

It shouldn't matter, any more than if you encoded the letter A as %41.

However, if you're dealing with a system that doesn't recognize one form, it seems like you're just going to have to give it what it expects regardless of what the "spec" says.

Is it correct to use alt tag for an anchor link?

You should use the title attribute for anchor tags if you wish to apply descriptive information similarly as you would for an alt attribute. The title attribute is valid on anchor tags and is serves no other purpose than providing information about the linked page.

W3C recommends that the value of the title attribute should match the value of the title of the linked document but it's not mandatory.

http://www.w3.org/MarkUp/1995-archive/Elements/A.html


Alternatively, and likely to be more beneficial, you can use the ARIA accessibility attribute aria-label (not to be confused with aria-labeledby). aria-label serves the same function as the alt attribute does for images but for non-image elements and includes some measure of optimization since your optimizing for screen readers.

http://www.w3.org/WAI/GL/wiki/Using_aria-label_to_provide_labels_for_objects


If you want to describe an anchor tag though, it's usually appropriate to use the rel or rev tag but your limited to specific values, they should not be used for human readable descriptions.

Rel serves to describe the relationship of the linked page to the current page. (e.g. if the linked page is next in a logical series it would be rel=next)

The rev attribute is essentially the reverse relationship of the rel attribute. Rev describes the relationship of the current page to the linked page.

You can find a list of valid values here: http://microformats.org/wiki/existing-rel-values

Change text from "Submit" on input tag

The value attribute is used to determine the rendered label of a submit input.

<input type="submit" class="like" value="Like" />

Note that if the control is successful (this one won't be as it has no name) this will also be the submitted value for it.

To have a different submitted value and label you need to use a button element, in which the textNode inside the element determines the label. You can include other elements (including <img> here).

<button type="submit" class="like" name="foo" value="bar">Like</button>

Note that support for <button> is dodgy in older versions of Internet Explorer.

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

How to get number of rows inserted by a transaction

I found the answer to may previous post. Here it is.

CREATE TABLE #TempTable (id int) 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 1,2 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 3,4 

SELECT * FROM #TempTable --this select will chage @@ROWCOUNT value

How to delete history of last 10 commands in shell?

to delete last 10 entries (based on your example) :

history -d 511 520

How to change a DIV padding without affecting the width/height ?

try this trick

div{
 -webkit-box-sizing: border-box; 
 -moz-box-sizing: border-box;    
 box-sizing: border-box;      
}

this will force the browser to calculate the width acording to the "outer"-width of the div, it means the padding will be substracted from the width.

How to vertically align text inside a flexbox?

It's depend on your li height just call one more thing line height

_x000D_
_x000D_
* {
  padding: 0;
  margin: 0;
}

html,
body {
  height: 100%;
}

ul {
  height: 100%;
}

li {
  display: flex;
  justify-content: center;
  align-self: center;
  background: silver;
  width: 100%;
  height:50px;line-height:50px;
}
_x000D_
<ul>
  <li>This is the text</li>
</ul>
_x000D_
_x000D_
_x000D_

Fast and simple String encrypt/decrypt in JAVA

Java - encrypt / decrypt user name and password from a configuration file

Code from above link

DESKeySpec keySpec = new DESKeySpec("Your secret Key phrase".getBytes("UTF8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
sun.misc.BASE64Encoder base64encoder = new BASE64Encoder();
sun.misc.BASE64Decoder base64decoder = new BASE64Decoder();
.........

// ENCODE plainTextPassword String
byte[] cleartext = plainTextPassword.getBytes("UTF8");      

Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
cipher.init(Cipher.ENCRYPT_MODE, key);
String encryptedPwd = base64encoder.encode(cipher.doFinal(cleartext));
// now you can store it 
......

// DECODE encryptedPwd String
byte[] encrypedPwdBytes = base64decoder.decodeBuffer(encryptedPwd);

Cipher cipher = Cipher.getInstance("DES");// cipher is not thread safe
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));

How to convert color code into media.brush?

Sorry to be so late to the party! I came across a similar issue, in WinRT. I'm not sure whether you're using WPF or WinRT, but they do differ in some ways (some better than others). Hopefully this will help people across the board, whichever situation they're in.

You could always use the code from the converter class I created to re-use and do in your C# code-behind, or wherever you're using it, to be honest:

I made it with the intention that a 6-digit (RGB), or an 8-digit (ARGB) Hex value could be used either way.

So I created a converter class:

public class StringToSolidColorBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var hexString = (value as string).Replace("#", "");

        if (string.IsNullOrWhiteSpace(hexString)) throw new FormatException();
        if (hexString.Length != 6 || hexString.Length != 8) throw new FormatException();

        try
        {
            var a = hexString.Length == 8 ? hexString.Substring(0, 2) : "255";
            var r = hexString.Length == 8 ? hexString.Substring(2, 2) : hexString.Substring(0, 2);
            var g = hexString.Length == 8 ? hexString.Substring(4, 2) : hexString.Substring(2, 2);
            var b = hexString.Length == 8 ? hexString.Substring(6, 2) : hexString.Substring(4, 2);

            return new SolidColorBrush(ColorHelper.FromArgb(
                byte.Parse(a, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(r, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(g, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(b, System.Globalization.NumberStyles.HexNumber)));
        }
        catch
        {
            throw new FormatException();
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

Added it into my App.xaml:

<ResourceDictionary>
    ...
    <converters:StringToSolidColorBrushConverter x:Key="StringToSolidColorBrushConverter" />
    ...
</ResourceDictionary>

And used it in my View's Xaml:

<Grid>
    <Rectangle Fill="{Binding RectangleColour,
               Converter={StaticResource StringToSolidColorBrushConverter}}"
               Height="20" Width="20" />
</Grid>

Works a charm!

Side note... Unfortunately, WinRT hasn't got the System.Windows.Media.BrushConverter that H.B. suggested; so I needed another way, otherwise I would have made a VM property that returned a SolidColorBrush (or similar) from the RectangleColour string property.

How do I iterate over an NSArray?

For OS X 10.4.x and previous:

 int i;
 for (i = 0; i < [myArray count]; i++) {
   id myArrayElement = [myArray objectAtIndex:i];
   ...do something useful with myArrayElement
 }

For OS X 10.5.x (or iPhone) and beyond:

for (id myArrayElement in myArray) {
   ...do something useful with myArrayElement
}

How do I install a pip package globally instead of locally?

Why don't you try sudo with the H flag? This should do the trick.

sudo -H pip install flake8

A regular sudo pip install flake8 will try to use your own home directory. The -H instructs it to use the system's home directory. More info at https://stackoverflow.com/a/43623102/

Console.log not working at all

Now in modern browsers, console.log() can be used by pressing F12 key. The picture will be helpful to understand the concept clearly. Console.log() and document.write()

How to display a JSON representation and not [Object Object] on the screen

If you want to see what you you have inside an object in your web app, then use the json pipe in a component HTML template, for example:

<li *ngFor="let obj of myArray">{{obj | json}}</li>

Tested and valid using Angular 4.3.2.

The difference between sys.stdout.write and print?

print is just a thin wrapper that formats the inputs (modifiable, but by default with a space between args and newline at the end) and calls the write function of a given object. By default this object is sys.stdout, but you can pass a file using the "chevron" form. For example:

print >> open('file.txt', 'w'), 'Hello', 'World', 2+3

See: https://docs.python.org/2/reference/simple_stmts.html?highlight=print#the-print-statement


In Python 3.x, print becomes a function, but it is still possible to pass something other than sys.stdout thanks to the fileargument.

print('Hello', 'World', 2+3, file=open('file.txt', 'w'))

See https://docs.python.org/3/library/functions.html#print


In Python 2.6+, print is still a statement, but it can be used as a function with

from __future__ import print_function

Update: Bakuriu commented to point out that there is a small difference between the print function and the print statement (and more generally between a function and a statement).

In case of an error when evaluating arguments:

print "something", 1/0, "other" #prints only something because 1/0 raise an Exception

print("something", 1/0, "other") #doesn't print anything. The function is not called

Identifying country by IP address

I think what you're looking for is an IP Geolocation database or service provider. There are many out there and some are free (get what you pay for).

Although I haven't used this service before, it claims to be in real-time. https://kickfire.com/kf-api

Here's another IP geo location API from Abstract API - https://www.abstractapi.com/ip-geolocation-api

But just do a google search on IP geo and you'll get more results than you need.

Only Add Unique Item To List

If your requirements are to have no duplicates, you should be using a HashSet.

HashSet.Add will return false when the item already exists (if that even matters to you).

You can use the constructor that @pstrjds links to below (or here) to define the equality operator or you'll need to implement the equality methods in RemoteDevice (GetHashCode & Equals).

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

In my case, I was in my office proxy which was skipping some of the packages. When I came out of my office proxy and tried to do npm install it worked. Maybe this helps for someone.

But it took me several hours to identify that was the reason.

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

or

TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

Google Drive as FTP Server

What about running the google-drive-ftp-adapter application in your local pc and then connect your filezilla client to that application? The google-drive-ftp-adapter application is not an online service, but its an alternative solution to connect to google drive through ftp.

The google-drive-ftp-adapter is an open source application hosted in github and it is a kind of standalone ftp-server java application that connects to your google drive in behalf of you, acting as a bridge (or adapter) between your ftp client and the google drive service. Once you have running the google-drive-ftp adapter, you can connect your preferred FTP client to the google-drive-ftp-adapter ftp server in your localhost (or wherever the app is running, like in a remote machine) to manage your files.

I use it in conjunction with beyond compare to synchronize my local files against the ones I have in the google drive and it serves well for the purpose.

This is the current github link hosting the google-drive-ftp-adapter repository: https://github.com/andresoviedo/google-drive-ftp-adapter

Get page title with Selenium WebDriver using Java

You can do it easily by Assertion using Selenium Testng framework.

Steps:

1.Create Firefox browser session

2.Initialize expected title name.

3.Navigate to "www.google.com" [As per you requirement, you can change] and wait for some time (15 seconds) to load the page completely.

4.Get the actual title name using "driver.getTitle()" and store it in String variable.

5.Apply the Assertion like below, Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle ),"Page title name not matched or Problem in loading grid");

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.myapplication.Utilty;

public class PageTitleVerification
{   
private static WebDriver driver = new FirefoxDriver();

@Test
public void test01_GooglePageTitleVerify()
{               
driver.navigate().to("https://www.google.com/");
String expectedGooglePageTitle = "Google";      
Utility.waitForElementInDOM(driver, "Google Search", 15);   
//Get page title
String actualGooglePageTitlte=driver.getTitle();
System.out.println("Google page title" + actualGooglePageTitlte);   
//Verify expected page title and actual page title is same  
Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle 
),"Page title not matched or Problem in loading url page");     
}
}

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Utility {

/*Wait for an element to be present in DOM before specified time (in seconds ) has 
elapsed */
public static void waitForElementInDOM(WebDriver driver,String elementIdentifier, 
long timeOutInSeconds) 
{       
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds );
try
{
//this will wait for element to be visible for 15 seconds        
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
(elementIdentifier))); 
}
catch(NoSuchElementException e)
{           
e.printStackTrace();
}           
}
}

Get viewport/window height in ReactJS

// just use (useEffect). every change will be logged with current value
import React, { useEffect } from "react";

export function () {
  useEffect(() => {
    window.addEventListener('resize', () => {
      const myWidth  = window.innerWidth;
      console.log('my width :::', myWidth)
   })
  },[window])

  return (
    <>
      enter code here
   </>
  )
}

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

As @Sean said, fcntl() is largely standardized, and therefore available across platforms. The ioctl() function predates fcntl() in Unix, but is not standardized at all. That the ioctl() worked for you across all the platforms of relevance to you is fortunate, but not guaranteed. In particular, the names used for the second argument are arcane and not reliable across platforms. Indeed, they are often unique to the particular device driver that the file descriptor references. (The ioctl() calls used for a bit-mapped graphics device running on an ICL Perq running PNX (Perq Unix) of twenty years ago never translated to anything else anywhere else, for example.)

Are complex expressions possible in ng-hide / ng-show?

I generally try to avoid expressions with ng-show and ng-hide as they were designed as booleans, not conditionals. If I need both conditional and boolean logic, I prefer to put in the conditional logic using ng-if as the first check, then add in an additional check for the boolean logic with ng-show and ng-hide

Howerver, if you want to use a conditional for ng-show or ng-hide, here is a link with some examples: Conditional Display using ng-if, ng-show, ng-hide, ng-include, ng-switch

CSS3 transform: rotate; in IE9

Try this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
    margin-left: 50px;
    margin-top: 50px;
    margin-right: 50px;
    margin-bottom: 50px;
}
.rotate {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;
}
</style>
</head>

<body>
<div class="rotate">Alpesh</div>
</body>
</html>

JavaScript global event mechanism

You listen to the onerror event by assigning a function to window.onerror:

 window.onerror = function (msg, url, lineNo, columnNo, error) {
        var string = msg.toLowerCase();
        var substring = "script error";
        if (string.indexOf(substring) > -1){
            alert('Script Error: See Browser Console for Detail');
        } else {
            alert(msg, url, lineNo, columnNo, error);
        }   
      return false; 
  };

How to get base64 encoded data from html image

You can also use the FileReader class :

    var reader = new FileReader();
    reader.onload = function (e) {
        var data = this.result;
    }
    reader.readAsDataURL( file );

Creating a .p12 file

I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.

I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!

  1. Generate 2048-bit RSA private key:

    openssl genrsa -out key.pem 2048

  2. Generate a Certificate Signing Request:

    openssl req -new -sha256 -key key.pem -out csr.csr

  3. Generate a self-signed x509 certificate suitable for use on web servers.

    openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem

  4. Create SSL identity file in PKCS12 as mentioned here

    openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem

Cannot issue data manipulation statements with executeQuery()

This code works for me: I set values whit an INSERT and get the LAST_INSERT_ID() of this value whit a SELECT; I use java NetBeans 8.1, MySql and java.JDBC.driver

                try {

        String Query = "INSERT INTO `stock`(`stock`, `min_stock`,   
                `id_stock`) VALUES ("

                + "\"" + p.get_Stock().getStock() + "\", "
                + "\"" + p.get_Stock().getStockMinimo() + "\","
                + "" + "null" + ")";

        Statement st = miConexion.createStatement();
        st.executeUpdate(Query);

        java.sql.ResultSet rs;
        rs = st.executeQuery("Select LAST_INSERT_ID() from stock limit 1");                
        rs.next(); //para posicionar el puntero en la primer fila
        ultimo_id = rs.getInt("LAST_INSERT_ID()");
        } catch (SqlException ex) { ex.printTrace;}

How to specify jdk path in eclipse.ini on windows 8 when path contains space

Even if your %JAVA_HOME% contains spaces, you can directly put entire string over there.

-vm
C:\Program Files (x86)\Java\jdk1.8.0_162\bin

Also, you don't have to specify javaw.exe in the path, just mention it till bin it will find javaw.exe in bin folder by itself. Just keep one thing in mind that the jdk version you provide should match with the eclipse version you are using.

If you are using a 64 bit java then download 64 bit Eclipse. If you are using a 32 bit java then download 32 bit Eclipse.

How to make an Asynchronous Method return a value?

Probably the simplest way to do it is to create a delegate and then BeginInvoke, followed by a wait at some time in the future, and an EndInvoke.

public bool Foo(){
    Thread.Sleep(100000); // Do work
    return true;
}

public SomeMethod()
{
    var fooCaller = new Func<bool>(Foo);
    // Call the method asynchronously
    var asyncResult = fooCaller.BeginInvoke(null, null);

    // Potentially do other work while the asynchronous method is executing.

    // Finally, wait for result
    asyncResult.AsyncWaitHandle.WaitOne();
    bool fooResult = fooCaller.EndInvoke(asyncResult);

    Console.WriteLine("Foo returned {0}", fooResult);
}

How to embed fonts in CSS?

Go through http://www.w3.org/TR/css3-fonts/

Try this:

  @font-face {
        font-family: 'EntezareZohoor2';
        src: url('EntezareZohoor2.eot');
        src: local('EntezareZohoor2'), local('EntezareZohoor2'), url('EntezareZohoor2.ttf') format('svg');
       font-weight: normal;
       font-style: normal;
    }

Is there a php echo/print equivalent in javascript

You can use

function echo(content) {  
    var e = document.createElement("p");
    e.innerHTML = content;
    document.currentScript.parentElement.replaceChild(document.currentScript, e);
}

which will replace the currently executing script who called the echo function with the text in the content argument.

Create a folder if it doesn't already exist

Try this, using mkdir:

if (!file_exists('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
}

Note that 0777 is already the default mode for directories and may still be modified by the current umask.

Simple way to measure cell execution time in ipython notebook

import time
start = time.time()
"the code you want to test stays here"
end = time.time()
print(end - start)

In PowerShell, how do I test whether or not a specific variable exists in global scope?

There's an even easier way:

if ($variable)
{
    Write-Host "bar exist"
}
else
{
    Write-Host "bar does not exists"
}

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Please check the permissions on the the ca certificates installed on server.

add created_at and updated_at fields to mongoose schemas

Use the built-in timestamps option for your Schema.

var ItemSchema = new Schema({
    name: { type: String, required: true, trim: true }
},
{
    timestamps: true
});

This will automatically add createdAt and updatedAt fields to your schema.

http://mongoosejs.com/docs/guide.html#timestamps

CSS: How to align vertically a "label" and "input" inside a "div"?

Use padding on the div (top and bottom) and vertical-align:middle on the label and input.

example at http://jsfiddle.net/VLFeV/1/

Can I get JSON to load into an OrderedDict?

Some great news! Since version 3.6 the cPython implementation has preserved the insertion order of dictionaries (https://mail.python.org/pipermail/python-dev/2016-September/146327.html). This means that the json library is now order preserving by default. Observe the difference in behaviour between python 3.5 and 3.6. The code:

import json
data = json.loads('{"foo":1, "bar":2, "fiddle":{"bar":2, "foo":1}}')
print(json.dumps(data, indent=4))

In py3.5 the resulting order is undefined:

{
    "fiddle": {
        "bar": 2,
        "foo": 1
    },
    "bar": 2,
    "foo": 1
}

In the cPython implementation of python 3.6:

{
    "foo": 1,
    "bar": 2,
    "fiddle": {
        "bar": 2,
        "foo": 1
    }
}

The really great news is that this has become a language specification as of python 3.7 (as opposed to an implementation detail of cPython 3.6+): https://mail.python.org/pipermail/python-dev/2017-December/151283.html

So the answer to your question now becomes: upgrade to python 3.6! :)

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

This project should be helpful - maps touch events to click events in a way that allows jQuery UI to work on iPad and iPhone without any changes. Just add the JS to any existing project.

http://code.google.com/p/jquery-ui-for-ipad-and-iphone/

How do I escape double and single quotes in sed?

The s/// command in sed allows you to use other characters instead of / as the delimiter, as in

sed 's#"http://www\.fubar\.com"#URL_FUBAR#g'

or

sed 's,"http://www\.fubar\.com",URL_FUBAR,g'

The double quotes are not a problem. For matching single quotes, switch the two types of quotes around. Note that a single quoted string may not contain single quotes (not even escaped ones).

The dots need to be escaped if sed is to interpret them as literal dots and not as the regular expression pattern . which matches any one character.

Datetime in where clause

Use a convert function to get all entries for a particular day.

Select * from tblErrorLog where convert(date,errorDate,101) = '12/20/2008'

See CAST and CONVERT for more info

How do I select an entire row which has the largest ID in the table?

One can always go for analytical functions as well which will give you more control

select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1

If you face issue with rank() function depending on the type of data then one can choose from row_number() or dense_rank() too.

Get div's offsetTop positions in React

You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.

Check the John Resig's post describing how helpful this method is.

Java double comparison epsilon

Yes. Java doubles will hold their precision better than your given epsilon of 0.00001.

Any rounding error that occurs due to the storage of floating point values will occur smaller than 0.00001. I regularly use 1E-6 or 0.000001 for a double epsilon in Java with no trouble.

On a related note, I like the format of epsilon = 1E-5; because I feel it is more readable (1E-5 in Java = 1 x 10^-5). 1E-6 is easy to distinguish from 1E-5 when reading code whereas 0.00001 and 0.000001 look so similar when glancing at code I think they are the same value.

How do I compare two variables containing strings in JavaScript?

I used below function to compare two strings and It is working good.

function CompareUserId (first, second)
{

   var regex = new RegExp('^' + first+ '$', 'i');
   if (regex.test(second)) 
   {
        return true;
   }
   else 
   {
        return false;
   }
   return false;
}

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Perhaps the error message is somewhat misleading, but the gist is that X_train is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:

out_images = np.array(X_train)[indices.astype(int)]

Can't connect to Postgresql on port 5432

Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf and postgres.conf files I finally found out that my firewall was overriding everything and therefore blocking connections

Adding sheets to end of workbook in Excel (normal method not working?)

A common mistake is

mainWB.Sheets.Add(After:=Sheets.Count)

which leads to Error 1004. Although it is not clear at all from the official documentation, it turns out that the 'After' parameter cannot be an integer, it must be a reference to a sheet in the same workbook.

PHP Regex to check date is in YYYY-MM-DD format

Format 1 : $format1 = "2012-12-31";

Format 2 : $format2 = "31-12-2012";

if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$format1)) {
    return true;
} else {
    return false;
}

if (preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-[0-9]{4}$/",$format2)) {
    return true;
} else {
    return false;
}

How to cancel a Task in await?

I just want to add to the already accepted answer. I was stuck on this, but I was going a different route on handling the complete event. Rather than running await, I add a completed handler to the task.

Comments.AsAsyncAction().Completed += new AsyncActionCompletedHandler(CommentLoadComplete);

Where the event handler looks like this

private void CommentLoadComplete(IAsyncAction sender, AsyncStatus status )
{
    if (status == AsyncStatus.Canceled)
    {
        return;
    }
    CommentsItemsControl.ItemsSource = Comments.Result;
    CommentScrollViewer.ScrollToVerticalOffset(0);
    CommentScrollViewer.Visibility = Visibility.Visible;
    CommentProgressRing.Visibility = Visibility.Collapsed;
}

With this route, all the handling is already done for you, when the task is cancelled it just triggers the event handler and you can see if it was cancelled there.

Get protocol + host name from URL

You can simply use urljoin with relative root '/' as second argument:

import urllib.parse


url = 'https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url'
root_url = urllib.parse.urljoin(url, '/')
print(root_url)

Describe table structure

In MySQL you can use DESCRIBE <table_name>

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

Or try adding this...

$code = @"
[DllImport("kernel32.dll")]
public static extern int GetExitCodeProcess(IntPtr hProcess, out Int32 exitcode);
"@
$type = Add-Type -MemberDefinition $code -Name "Win32" -Namespace Win32 -PassThru
[Int32]$exitCode = 0
$type::GetExitCodeProcess($process.Handle, [ref]$exitCode)

By using this code, you can still let PowerShell take care of managing redirected output/error streams, which you cannot do using System.Diagnostics.Process.Start() directly.

php stdClass to array

use this function to get a standard array back of the type you are after...

return get_object_vars($booking);