Programs & Examples On #Wcf wshttpbinding

get size of json object

you dont need to change your JSON format.

replace:

console.log(data.phones.length);

with:

console.log( Object.keys( data.phones ).length ) ;

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

I've discovered similar problems with the openjdk-6-jre and openjdk-6-jre-headless packages in Ubuntu.

My problem was solved by purging the openjdk-6-jre and openjdk-6-jre-headless packages and re-installing. The alternatives are only updated on a fresh install of the openjdk-6-jre and openjdk-6-jre-headless packages.

Below is a sample of installing after purging:

aptitude purge openjdk-6-jre openjdk-6-jre-headless # to ensure no configuration exists
aptitude install --without-recommends openjdk-6-jre # Installing without some extras
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
  ca-certificates-java{a} java-common{a} libavahi-client3{a} libavahi-common-data{a} libavahi-common3{a} libcups2{a} libflac8{a} libgif4{a} libnspr4-0d{a} libnss3-1d{a} libogg0{a} libpulse0{a} libsndfile1{a} libvorbis0a{a} libvorbisenc2{a} libxi6{a} libxtst6{a}
  openjdk-6-jre openjdk-6-jre-headless{a} openjdk-6-jre-lib{a} tzdata-java{a}
The following packages are RECOMMENDED but will NOT be installed:
  icedtea-6-jre-cacao icedtea-netx ttf-dejavu-extra
0 packages upgraded, 21 newly installed, 0 to remove and 119 not upgraded.
Need to get 0B/34.5MB of archives. After unpacking 97.6MB will be used.
Do you want to continue? [Y/n/?]
Writing extended state information... Done
Selecting previously deselected package openjdk-6-jre-lib.
(Reading database ... 62267 files and directories currently installed.)
Unpacking openjdk-6-jre-lib (from .../openjdk-6-jre-lib_6b24-1.11.5-0ubuntu1~10.04.2_all.deb) ...
...
Processing triggers for man-db ...
Setting up tzdata-java (2012e-0ubuntu0.10.04) ...
...
Setting up openjdk-6-jre-headless (6b24-1.11.5-0ubuntu1~10.04.2) ...
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/java to provide /usr/bin/java (java) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/keytool to provide /usr/bin/keytool (keytool) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/pack200 to provide /usr/bin/pack200 (pack200) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/rmid to provide /usr/bin/rmid (rmid) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/rmiregistry to provide /usr/bin/rmiregistry (rmiregistry) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/unpack200 to provide /usr/bin/unpack200 (unpack200) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/orbd to provide /usr/bin/orbd (orbd) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/servertool to provide /usr/bin/servertool (servertool) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/tnameserv to provide /usr/bin/tnameserv (tnameserv) in auto mode.
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/lib/jexec to provide /usr/bin/jexec (jexec) in auto mode.
Setting up openjdk-6-jre (6b24-1.11.5-0ubuntu1~10.04.2) ...
update-alternatives: using /usr/lib/jvm/java-6-openjdk/jre/bin/policytool to provide /usr/bin/policytool (policytool) in auto mode.
...

You can see above that update-alternatives is run to set up links for the various Java binaries.

After this install, there are also links in /usr/bin, links in /etc/alternatives, and files for each binary in /var/lib/dpkg/alternatives.

ls -l /usr/bin/java /etc/alternatives/java /var/lib/dpkg/alternatives/java
lrwxrwxrwx 1 root root  40 2013-01-16 14:44 /etc/alternatives/java -> /usr/lib/jvm/java-6-openjdk/jre/bin/java
lrwxrwxrwx 1 root root  22 2013-01-16 14:44 /usr/bin/java -> /etc/alternatives/java
-rw-r--r-- 1 root root 158 2013-01-16 14:44 /var/lib/dpkg/alternatives/java

Let's contast this with installing without purging.

aptitude remove openjdk-6-jre
aptitude install --without-recommends openjdk-6-jre
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
  ca-certificates-java{a} java-common{a} libavahi-client3{a} libavahi-common-data{a} libavahi-common3{a} libcups2{a} libflac8{a} libgif4{a} libnspr4-0d{a} libnss3-1d{a} libogg0{a} libpulse0{a} libsndfile1{a} libvorbis0a{a} libvorbisenc2{a} libxi6{a} libxtst6{a}
  openjdk-6-jre openjdk-6-jre-headless{a} openjdk-6-jre-lib{a} tzdata-java{a}
The following packages are RECOMMENDED but will NOT be installed:
  icedtea-6-jre-cacao icedtea-netx ttf-dejavu-extra
0 packages upgraded, 21 newly installed, 0 to remove and 119 not upgraded.
Need to get 0B/34.5MB of archives. After unpacking 97.6MB will be used.
Do you want to continue? [Y/n/?]
Writing extended state information... Done
Selecting previously deselected package openjdk-6-jre-lib.
(Reading database ... 62293 files and directories currently installed.)
Unpacking openjdk-6-jre-lib (from .../openjdk-6-jre-lib_6b24-1.11.5-0ubuntu1~10.04.2_all.deb) ...
...
Processing triggers for man-db ...
...
Setting up openjdk-6-jre-headless (6b24-1.11.5-0ubuntu1~10.04.2) ...

Setting up openjdk-6-jre (6b24-1.11.5-0ubuntu1~10.04.2) ...
...

As you see, update-alternatives is not triggered.

After this install, there are no files for the Java binaries in /var/lib/dpkg/alternatives, no links in /etc/alternatives, and no links in /usr/bin.

The removal of the files in /var/lib/dpkg/alternatives also breaks update-java-alternatives.

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

Remove substring from the string

How about str.gsub("subString", "") Check out the Ruby Doc

Open directory using C

Parameters passed to the C program executable is nothing but an array of string(or character pointer),so memory would have been already allocated for these input parameter before your program access these parameters,so no need to allocate buffer,and that way you can avoid error handling code in your program as well(Reduce chances of segfault :)).

console.log not working in Angular2 Component (Typescript)

The console.log should be wrapped in a function , the "default" function for every class is its constructor so it should be declared there.

import { Component } from '@angular/core';
console.log("Hello1");

 @Component({
  selector: 'hello-console',
})
    export class App {
     s: string = "Hello2";
    constructor(){
     console.log(s); 
    }

}

Delete specific values from column with where condition?

You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.

The general form for this would be an UPDATE statement:

UPDATE <table name>
SET
    ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
    ColumnA = <bad value> /* or any other search conditions */

Getting coordinates of marker in Google Maps API

Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:

            function map_init() {
            var lt=48.451778;
            var lg=31.646305;

            var myLatlng = new google.maps.LatLng(lt,lg);
            var mapOptions = {
                center: new google.maps.LatLng(lt,lg),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('map'),mapOptions);   
            var marker = new google.maps.Marker({
                position:myLatlng,
                map:map,
                draggable:true
            });

            google.maps.event.addListener(
                marker,
                'drag',
                function() {
                    document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
                    document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
                    document.getElementById('zoom').innerHTML = mapObject.getZoom();

                    // Dynamically show it somewhere if needed
                    $(".x").text(marker.position.lat().toFixed(6));
                    $(".y").text(marker.position.lng().toFixed(6));
                    $(".z").text(map.getZoom());

                }
            );                  
            }

JavaScript: How to pass object by value?

Use Object.assign()

Example:

var a = {some: object};
var b = new Object;
Object.assign(b, a);
// b now equals a, but not by association.

A cleaner example that does the same thing:

var a = {some: object};
var b = Object.assign({}, a);
// Once again, b now equals a.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

SQL Logic Operator Precedence: And and Or

I'll add 2 points:

  • "IN" is effectively serial ORs with parentheses around them
  • AND has precedence over OR in every language I know

So, the 2 expressions are simply not equal.

WHERE some_col in (1,2,3,4,5) AND some_other_expr
--to the optimiser is this
WHERE
     (
     some_col = 1 OR
     some_col = 2 OR 
     some_col = 3 OR 
     some_col = 4 OR 
     some_col = 5
     )
     AND
     some_other_expr

So, when you break the IN clause up, you split the serial ORs up, and changed precedence.

How to change the text of a label?

$('#<%= lblVessel.ClientID %>').html('New Text');

ASP.net Label will be rendered as a span in the browser. so user 'html'.

How to convert a ruby hash object to JSON?

Add the following line on the top of your file

require 'json'

Then you can use:

car = {:make => "bmw", :year => "2003"}
car.to_json

Alternatively, you can use:

JSON.generate({:make => "bmw", :year => "2003"})

Best way to generate a random float in C#

One more version... (I think this one is pretty good)

static float NextFloat(Random random)
{
    (float)(float.MaxValue * 2.0 * (rand.NextDouble()-0.5));
}

//inline version
float myVal = (float)(float.MaxValue * 2.0 * (rand.NextDouble()-0.5));

I think this...

  • is the 2nd fastest (see benchmarks)
  • is evenly distributed

And One more version...(not as good but posting anyway)

static float NextFloat(Random random)
{
    return float.MaxValue * ((rand.Next() / 1073741824.0f) - 1.0f);
}

//inline version
float myVal = (float.MaxValue * ((rand.Next() / 1073741824.0f) - 1.0f));

I think this...

  • is the fastest (see benchmarks)
  • is evenly distributed however because Next() is a 31 bit random value it will only return 2^31 values. (50% of the neighbor values will have the same value)

Testing of most of the functions on this page: (i7, release, without debug, 2^28 loops)

 Sunsetquest1: min: 3.402823E+38  max: -3.402823E+38 time: 3096ms
 SimonMourier: min: 3.402823E+38  max: -3.402819E+38 time: 14473ms
 AnthonyPegram:min: 3.402823E+38  max: -3.402823E+38 time: 3191ms
 JonSkeet:     min: 3.402823E+38  max: -3.402823E+38 time: 3186ms
 Sixlettervar: min: 1.701405E+38  max: -1.701410E+38 time: 19653ms
 Sunsetquest2: min: 3.402823E+38  max: -3.402823E+38 time: 2930ms

wget can't download - 404 error

Wget 404 error also always happens if you want to download the pages from Wordpress-website by typing

wget -r http://somewebsite.com

If this website is built using Wordpress you'll get such an error:

ERROR 404: Not Found.

There's no way to mirror Wordpress-website because the website content is stored in the database and wget is not able to grab .php files. That's why you get Wget 404 error.

I know it's not this question's case, because Sam only wants to download a single picture, but it can be helpful for others.

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

if val is not None:
    print(val)
else:
    pass

check wheather particular data is not empty or null.

mkdir -p functionality in Python

import os
import tempfile

path = tempfile.mktemp(dir=path)
os.makedirs(path)
os.rmdir(path)

Check element exists in array

has_key is fast and efficient.

Instead of array use an hash:

valueTo1={"a","b","c"}

if valueTo1.has_key("a"):
        print "Found key in dictionary"

How to read a file in reverse order?

You can also use python module file_read_backwards.

After installing it, via pip install file_read_backwards (v1.2.1), you can read the entire file backwards (line-wise) in a memory efficient manner via:

#!/usr/bin/env python2.7

from file_read_backwards import FileReadBackwards

with FileReadBackwards("/path/to/file", encoding="utf-8") as frb:
    for l in frb:
         print l

It supports "utf-8","latin-1", and "ascii" encodings.

Support is also available for python3. Further documentation can be found at http://file-read-backwards.readthedocs.io/en/latest/readme.html

Does delete on a pointer to a subclass call the base class destructor?

no it will not call destructor for class A, you should call it explicitly (like PoweRoy told), delete line 'delete ptr;' in example to compare ...

  #include <iostream>

  class A
  {
     public:
        A(){};
        ~A();
  };

  A::~A()
  {
     std::cout << "Destructor of A" << std::endl;
  }

  class B
  {
     public:
        B(){ptr = new A();};
        ~B();
     private:
        A* ptr;
  };

  B::~B()
  {
     delete ptr;
     std::cout << "Destructor of B" << std::endl;
  }

  int main()
  {
     B* b = new B();
     delete b;
     return 0;
  }

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

Appending pandas dataframes generated in a for loop

Use pd.concat to merge a list of DataFrame into a single big DataFrame.

appended_data = []
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    # store DataFrame in list
    appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet 
appended_data.to_excel('appended.xlsx')

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

A bit late to the game, but non of the above solutions pointed me in the direction of a pure and simple .NET, no json.net solution. So here it is, ended up being very simple. Below a full running example of how it is done with standard .NET Json serialization, the example has dictionary both in the root object and in the child objects.

The golden bullet is this cat, parse the settings as second parameter to the serializer:

DataContractJsonSerializerSettings settings =
                       new DataContractJsonSerializerSettings();
                    settings.UseSimpleDictionaryFormat = true;

Full code below:

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

    namespace Kipon.dk
    {
        public class JsonTest
        {
            public const string EXAMPLE = @"{
                ""id"": ""some id"",
                ""children"": {
                ""f1"": {
                    ""name"": ""name 1"",
                    ""subs"": {
                    ""1"": { ""name"": ""first sub"" },
                    ""2"": { ""name"": ""second sub"" }
                    }
                },
                ""f2"": {
                    ""name"": ""name 2"",
                    ""subs"": {
                    ""37"": { ""name"":  ""is 37 in key""}
                    }
                }
                }
            }
            ";

            [DataContract]
            public class Root
            {
                [DataMember(Name ="id")]
                public string Id { get; set; }

                [DataMember(Name = "children")]
                public Dictionary<string,Child> Children { get; set; }
            }

            [DataContract]
            public class Child
            {
                [DataMember(Name = "name")]
                public string Name { get; set; }

                [DataMember(Name = "subs")]
                public Dictionary<int, Sub> Subs { get; set; }
            }

            [DataContract]
            public class Sub
            {
                [DataMember(Name = "name")]
                public string Name { get; set; }
            }

            public static void Test()
            {
                var array = System.Text.Encoding.UTF8.GetBytes(EXAMPLE);
                using (var mem = new System.IO.MemoryStream(array))
                {
                    mem.Seek(0, System.IO.SeekOrigin.Begin);
                    DataContractJsonSerializerSettings settings =
                       new DataContractJsonSerializerSettings();
                    settings.UseSimpleDictionaryFormat = true;

                    var ser = new DataContractJsonSerializer(typeof(Root), settings);
                    var data = (Root)ser.ReadObject(mem);
                    Console.WriteLine(data.Id);
                    foreach (var childKey in data.Children.Keys)
                    {
                        var child = data.Children[childKey];
                        Console.WriteLine(" Child: " + childKey + " " + child.Name);
                        foreach (var subKey in child.Subs.Keys)
                        {
                            var sub = child.Subs[subKey];
                            Console.WriteLine("   Sub: " + subKey + " " + sub.Name);
                        }
                    }
                }
            }
        }
    }

Create a button programmatically and set a background image

Update to Swift 3

let image = UIImage(named: "name")
let button = UIButton(type: .custom)
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.setImage(image, for: .normal)
button.addTarget(self, action: #selector(self.btnAbsRetClicked(_:)), for:.touchUpInside)
self.view.addSubview(button)

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

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

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

Can we have multiple <tbody> in same <table>?

In addition, if you run a HTML document with multiple <tbody> tags through W3C's HTML Validator, with a HTML5 DOCTYPE, it will successfully validate.

Offset a background image from the right using CSS

As proposed here, this is a pretty cross browser solution that works perfectly:

background: url('/img.png') no-repeat right center;
border-right: 10px solid transparent;

I used it since the CSS3 feature of specifying offsets proposed in the answer marked as solving the question is not supported in browsers so well yet. E.g.

How to properly override clone method?

public class MyObject implements Cloneable, Serializable{   

    @Override
    @SuppressWarnings(value = "unchecked")
    protected MyObject clone(){
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            ByteArrayOutputStream bOs = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bOs);
            oos.writeObject(this);
            ois = new ObjectInputStream(new ByteArrayInputStream(bOs.toByteArray()));
            return  (MyObject)ois.readObject();

        } catch (Exception e) {
            //Some seriouse error :< //
            return null;
        }finally {
            if (oos != null)
                try {
                    oos.close();
                } catch (IOException e) {

                }
            if (ois != null)
                try {
                    ois.close();
                } catch (IOException e) {

                }
        }
    }
}

How to get text from EditText?

Put this in your MainActivity:

{
    public EditText bizname, storeno, rcpt, item, price, tax, total;
    public Button click, click2;
    int contentView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main_activity );
        bizname = (EditText) findViewById( R.id.editBizName );
        item = (EditText) findViewById( R.id.editItem );
        price = (EditText) findViewById( R.id.editPrice );
        tax = (EditText) findViewById( R.id.editTax );
        total = (EditText) findViewById( R.id.editTotal );
        click = (Button) findViewById( R.id.button );
    }
}

Put this under a button or something

public void clickBusiness(View view) {
    checkPermsOfStorage( this );

    bizname = (EditText) findViewById( R.id.editBizName );
    item = (EditText) findViewById( R.id.editItem );
    price = (EditText) findViewById( R.id.editPrice );
    tax = (EditText) findViewById( R.id.editTax );
    total = (EditText) findViewById( R.id.editTotal );
    String x = ("\nItem/Price: " + item.getText() + price.getText() + "\nTax/Total" + tax.getText() + total.getText());
    Toast.makeText( this, x, Toast.LENGTH_SHORT ).show();
    try {
        this.WriteBusiness(bizname,storeno,rcpt,item,price,tax,total);
        String vv = tax.getText().toString();
        System.console().printf( "%s", vv );
        //new XMLDivisionWriter(getString(R.string.SDDoc) + "/tax_div_business.xml");
    } catch (ReflectiveOperationException e) {
        e.printStackTrace();
    }
}

There! The debate is settled!

What is the difference between utf8mb4 and utf8 charsets in MySQL?

The utf8mb4 character set is useful because nowadays we need support for storing not only language characters but also symbols, newly introduced emojis, and so on.

A nice read on How to support full Unicode in MySQL databases by Mathias Bynens can also shed some light on this.

The term 'Get-ADUser' is not recognized as the name of a cmdlet

Check here for how to add the activedirectory module if not there by default. This can be done on any machine and then it will allow you to access your active directory "domain control" server.

EDIT

To prevent problems with stale links (I have found MSDN blogs to disappear for no reason in the past), in essence for Windows 7 you need to download and install Remote Server Administration Tools (KB958830). After installing do the following steps:

  • Open Control Panel -> Programs and Features -> Turn On/Off Windows Features
  • Find "Remote Server Administration Tools" and expand it
  • Find "Role Administration Tools" and expand it
  • Find "AD DS And AD LDS Tools" and expand it
  • Check the box next to "Active Directory Module For Windows PowerShell".
  • Click OK and allow Windows to install the feature

Windows server editions should already be OK but if not you need to download and install the Active Directory Management Gateway Service. If any of these links should stop working, you should still be able search for the KB article or download names and find them.

JPA - Returning an auto generated id after persist()

This is how I did it. You can try

    public class ABCService {
    @Resource(name="ABCDao")
    ABCDao abcDao;

    public int addNewABC(ABC abc) {
         ABC.setId(0);
         return abcDao.insertABC(abc);
    }
}

Removing element from array in component state

Here is a simple way to do it:

removeFunction(key){
  const data = {...this.state.data}; //Duplicate state.
  delete data[key];                  //remove Item form stateCopy.
  this.setState({data});             //Set state as the modify one.
}

Hope it Helps!!!

How to execute Ant build in command line

is it still actual?

As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>, then you wrote <target name="build-subprojects"/> (it does nothing). Could it be a reason? Does this <echo message="${ant.project.name}: ${ant.file}"/> print appropriate message? If no then target is not running. Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277

Redirect echo output in shell script to logfile

You can add this line on top of your script:

#!/bin/bash
# redirect stdout/stderr to a file
exec &> logfile.txt

OR else to redirect only stdout use:

exec > logfile.txt

WorksheetFunction.CountA - not working post upgrade to Office 2010

It may be obvious but, by stating the Range and not including which workbook or worksheet then it may be trying to CountA() on a different sheet entirely. I find to fully address these things saves a lot of headaches.

Why is Node.js single threaded?

Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.

At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ

Permission denied on accessing host directory in Docker

I resolved that issue by using a data container, this also has the advantage of isolating the data from the application layer. You could run it like this:

docker run --volumes-from=<container-data-name> ubuntu

This tutorial provides a good explanation on the use of data containers.

How to use Utilities.sleep() function

Serge is right - my workaround:

function mySleep (sec)
{
  SpreadsheetApp.flush();
  Utilities.sleep(sec*1000);
  SpreadsheetApp.flush();
}

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

Related:

Run certain code every n seconds

Here is a simple example compatible with APScheduler 3.00+:

# note that there are many other schedulers available
from apscheduler.schedulers.background import BackgroundScheduler

sched = BackgroundScheduler()

def some_job():
    print('Every 10 seconds')

# seconds can be replaced with minutes, hours, or days
sched.add_job(some_job, 'interval', seconds=10)
sched.start()

...

sched.shutdown()

Alternatively, you can use the following. Unlike many of the alternatives, this timer will execute the desired code every n seconds exactly (irrespective of the time it takes for the code to execute). So this is a great option if you cannot afford any drift.

import time
from threading import Event, Thread

class RepeatedTimer:

    """Repeat `function` every `interval` seconds."""

    def __init__(self, interval, function, *args, **kwargs):
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.start = time.time()
        self.event = Event()
        self.thread = Thread(target=self._target)
        self.thread.start()

    def _target(self):
        while not self.event.wait(self._time):
            self.function(*self.args, **self.kwargs)

    @property
    def _time(self):
        return self.interval - ((time.time() - self.start) % self.interval)

    def stop(self):
        self.event.set()
        self.thread.join()


# start timer
timer = RepeatedTimer(10, print, 'Hello world')

# stop timer
timer.stop()

How can I autoplay a video using the new embed code style for Youtube?

None of yours are solved my problem. But, I found a good solution for me to work properly right now. In between tags write this code:

<div style="position: fixed; z-index: -99; width: 100%; height: 100%">
  <iframe frameborder="0" height="100%" width="100%" 
    src="https://youtube.com/embed/**[CHANGE HERE WITH YOUR YOUTUBE VIDEO ID]**?autoplay=1&controls=0&showinfo=0&autohide=1">
  </iframe>
</div>

Inheriting from a template class in c++

Make Rectangle a template and pass the typename on to Area:

template <typename T>
class Rectangle : public Area<T>
{

};

c# foreach (property in object)... Is there a simple way of doing this?

I couldn't get any of the above ways to work, but this worked. The username and password for DirectoryEntry are optional.

   private List<string> getAnyDirectoryEntryPropertyValue(string userPrincipalName, string propertyToSearchFor)
    {
        List<string> returnValue = new List<string>();
        try
        {
            int index = userPrincipalName.IndexOf("@");
            string originatingServer = userPrincipalName.Remove(0, index + 1);
            string path = "LDAP://" + originatingServer; //+ @"/" + distinguishedName;
            DirectoryEntry objRootDSE = new DirectoryEntry(path, PSUsername, PSPassword);
            var objSearcher = new System.DirectoryServices.DirectorySearcher(objRootDSE);
            objSearcher.Filter = string.Format("(&(UserPrincipalName={0}))", userPrincipalName);
            SearchResultCollection properties = objSearcher.FindAll();

            ResultPropertyValueCollection resPropertyCollection = properties[0].Properties[propertyToSearchFor];
            foreach (string resProperty in resPropertyCollection)
            {
                returnValue.Add(resProperty);
            }
        }
        catch (Exception ex)
        {
            returnValue.Add(ex.Message);
            throw;
        }

        return returnValue;
    }

No == operator found while comparing structs in C++

C++20 introduced default comparisons, aka the "spaceship" operator<=>, which allows you to request compiler-generated </<=/==/!=/>=/ and/or > operators with the obvious/naive(?) implementation...

auto operator<=>(const MyClass&) const = default;

...but you can customise that for more complicated situations (discussed below). See here for the language proposal, which contains justifications and discussion. This answer remains relevant for C++17 and earlier, and for insight in to when you should customise the implementation of operator<=>....

It may seem a bit unhelpful of C++ not to have already Standardised this earlier, but often structs/classes have some data members to exclude from comparison (e.g. counters, cached results, container capacity, last operation success/error code, cursors), as well as decisions to make about myriad things including but not limited to:

  • which fields to compare first, e.g. comparing a particular int member might eliminate 99% of unequal objects very quickly, while a map<string,string> member might often have identical entries and be relatively expensive to compare - if the values are loaded at runtime, the programmer may have insights the compiler can't possibly
  • in comparing strings: case sensitivity, equivalence of whitespace and separators, escaping conventions...
  • precision when comparing floats/doubles
  • whether NaN floating point values should be considered equal
  • comparing pointers or pointed-to-data (and if the latter, how to know how whether the pointers are to arrays and of how many objects/bytes needing comparison)
  • whether order matters when comparing unsorted containers (e.g. vector, list), and if so whether it's ok to sort them in-place before comparing vs. using extra memory to sort temporaries each time a comparison is done
  • how many array elements currently hold valid values that should be compared (is there a size somewhere or a sentinel?)
  • which member of a union to compare
  • normalisation: for example, date types may allow out-of-range day-of-month or month-of-year, or a rational/fraction object may have 6/8ths while another has 3/4ers, which for performance reasons they correct lazily with a separate normalisation step; you may have to decide whether to trigger a normalisation before comparison
  • what to do when weak pointers aren't valid
  • how to handle members and bases that don't implement operator== themselves (but might have compare() or operator< or str() or getters...)
  • what locks must be taken while reading/comparing data that other threads may want to update

So, it's kind of nice to have an error until you've explicitly thought about what comparison should mean for your specific structure, rather than letting it compile but not give you a meaningful result at run-time.

All that said, it'd be good if C++ let you say bool operator==() const = default; when you'd decided a "naive" member-by-member == test was ok. Same for !=. Given multiple members/bases, "default" <, <=, >, and >= implementations seem hopeless though - cascading on the basis of order of declaration's possible but very unlikely to be what's wanted, given conflicting imperatives for member ordering (bases being necessarily before members, grouping by accessibility, construction/destruction before dependent use). To be more widely useful, C++ would need a new data member/base annotation system to guide choices - that would be a great thing to have in the Standard though, ideally coupled with AST-based user-defined code generation... I expect it'll happen one day.

Typical implementation of equality operators

A plausible implementation

It's likely that a reasonable and efficient implementation would be:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return lhs.my_struct2 == rhs.my_struct2 &&
           lhs.an_int     == rhs.an_int;
}

Note that this needs an operator== for MyStruct2 too.

Implications of this implementation, and alternatives, are discussed under the heading Discussion of specifics of your MyStruct1 below.

A consistent approach to ==, <, > <= etc

It's easy to leverage std::tuple's comparison operators to compare your own class instances - just use std::tie to create tuples of references to fields in the desired order of comparison. Generalising my example from here:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return std::tie(lhs.my_struct2, lhs.an_int) ==
           std::tie(rhs.my_struct2, rhs.an_int);
}

inline bool operator<(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return std::tie(lhs.my_struct2, lhs.an_int) <
           std::tie(rhs.my_struct2, rhs.an_int);
}

// ...etc...

When you "own" (i.e. can edit, a factor with corporate and 3rd party libs) the class you want to compare, and especially with C++14's preparedness to deduce function return type from the return statement, it's often nicer to add a "tie" member function to the class you want to be able to compare:

auto tie() const { return std::tie(my_struct1, an_int); }

Then the comparisons above simplify to:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return lhs.tie() == rhs.tie();
}

If you want a fuller set of comparison operators, I suggest boost operators (search for less_than_comparable). If it's unsuitable for some reason, you may or may not like the idea of support macros (online):

#define TIED_OP(STRUCT, OP, GET_FIELDS) \
    inline bool operator OP(const STRUCT& lhs, const STRUCT& rhs) \
    { \
        return std::tie(GET_FIELDS(lhs)) OP std::tie(GET_FIELDS(rhs)); \
    }

#define TIED_COMPARISONS(STRUCT, GET_FIELDS) \
    TIED_OP(STRUCT, ==, GET_FIELDS) \
    TIED_OP(STRUCT, !=, GET_FIELDS) \
    TIED_OP(STRUCT, <, GET_FIELDS) \
    TIED_OP(STRUCT, <=, GET_FIELDS) \
    TIED_OP(STRUCT, >=, GET_FIELDS) \
    TIED_OP(STRUCT, >, GET_FIELDS)

...that can then be used a la...

#define MY_STRUCT_FIELDS(X) X.my_struct2, X.an_int
TIED_COMPARISONS(MyStruct1, MY_STRUCT_FIELDS)

(C++14 member-tie version here)

Discussion of specifics of your MyStruct1

There are implications to the choice to provide a free-standing versus member operator==()...

Freestanding implementation

You have an interesting decision to make. As your class can be implicitly constructed from a MyStruct2, a free-standing / non-member bool operator==(const MyStruct2& lhs, const MyStruct2& rhs) function would support...

my_MyStruct2 == my_MyStruct1

...by first creating a temporary MyStruct1 from my_myStruct2, then doing the comparison. This would definitely leave MyStruct1::an_int set to the constructor's default parameter value of -1. Depending on whether you include an_int comparison in the implementation of your operator==, a MyStruct1 might or might not compare equal to a MyStruct2 that itself compares equal to the MyStruct1's my_struct_2 member! Further, creating a temporary MyStruct1 can be a very inefficient operation, as it involves copying the existing my_struct2 member to a temporary, only to throw it away after the comparison. (Of course, you could prevent this implicit construction of MyStruct1s for comparison by making that constructor explicit or removing the default value for an_int.)

Member implementation

If you want to avoid implicit construction of a MyStruct1 from a MyStruct2, make the comparison operator a member function:

struct MyStruct1
{
    ...
    bool operator==(const MyStruct1& rhs) const
    {
        return tie() == rhs.tie(); // or another approach as above
    }
};

Note the const keyword - only needed for the member implementation - advises the compiler that comparing objects doesn't modify them, so can be allowed on const objects.

Comparing the visible representations

Sometimes the easiest way to get the kind of comparison you want can be...

    return lhs.to_string() == rhs.to_string();

...which is often very expensive too - those strings painfully created just to be thrown away! For types with floating point values, comparing visible representations means the number of displayed digits determines the tolerance within which nearly-equal values are treated as equal during comparison.

Replace non-ASCII characters with a single space

As a native and efficient approach, you don't need to use ord or any loop over the characters. Just encode with ascii and ignore the errors.

The following will just remove the non-ascii characters:

new_string = old_string.encode('ascii',errors='ignore')

Now if you want to replace the deleted characters just do the following:

final_string = new_string + b' ' * (len(old_string) - len(new_string))

How to "add existing frameworks" in Xcode 4?

Xcode 12

Just drag it into the Frameworks, Libraries, and Embedded Content of the General section of the Target:

enter image description here Done!

Note that Xcode 11 and 10 have a very similar flow too.

How do I install a color theme for IntelliJ IDEA 7.0.x

Go to Settings => Plugins => Search Plugins in Marketplace

Search by material theme and download and restart it. it is a good theme.

In the market place, you can also search by theme and it will list all the themes and you can download any themes. You no need to find themes and download and import it. You can also remove the theme very easily. thanks

How do I set a textbox's text to bold at run time?

The bold property of the font itself is read only, but the actual font property of the text box is not. You can change the font of the textbox to bold as follows:

  textBox1.Font = new Font(textBox1.Font, FontStyle.Bold);

And then back again:

  textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);

What is base 64 encoding used for?

It's used for converting arbitrary binary data to ASCII text.

For example, e-mail attachments are sent this way.

Android draw a Horizontal line between views

You should use the new lightweight View Space to draw dividers. Your layout will load faster if you will use Space instead of View.

Horizontal divider:

<android.support.v4.widget.Space
        android:layout_height="1dp"
        android:layout_width="match_parent" /> 

Vertical divider:

<android.support.v4.widget.Space
        android:layout_height="match_parent"
        android:layout_width="1dp" />

You can also add a background:

<android.support.v4.widget.Space
        android:layout_height="match_parent"
        android:layout_width="1dp"
        android:background="?android:attr/listDivider"/>

Usage example:

....
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="One"/>

<android.support.v4.widget.Space
    android:layout_height="match_parent"
    android:layout_width="1dp"
    android:background="?android:attr/listDivider"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Two"/>

<android.support.v4.widget.Space
    android:layout_height="match_parent"
    android:layout_width="1dp"
    android:background="?android:attr/listDivider"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Three"/>
....

In order to use Space you should add the dependency in your build.gradle:

dependencies {
    compile 'com.android.support:support-v4:22.1.+'
}

Documentation https://developer.android.com/reference/android/support/v4/widget/Space.html

php: loop through json array

Use json_decode to convert the JSON string to a PHP array, then use normal PHP array functions on it.

$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$data = json_decode($json);

var_dump($data[0]['var1']); // outputs '9'

Setting up MySQL and importing dump within Dockerfile

I used docker-entrypoint-initdb.d approach (Thanks to @Kuhess) But in my case I want to create my DB based on some parameters I defined in .env file so I did these

1) First I define .env file something like this in my docker root project directory

MYSQL_DATABASE=my_db_name
MYSQL_USER=user_test
MYSQL_PASSWORD=test
MYSQL_ROOT_PASSWORD=test
MYSQL_PORT=3306

2) Then I define my docker-compose.yml file. So I used the args directive to define my environment variables and I set them from .env file

version: '2'
services:
### MySQL Container
    mysql:
        build:
            context: ./mysql
            args:
                - MYSQL_DATABASE=${MYSQL_DATABASE}
                - MYSQL_USER=${MYSQL_USER}
                - MYSQL_PASSWORD=${MYSQL_PASSWORD}
                - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
        ports:
            - "${MYSQL_PORT}:3306"

3) Then I define a mysql folder that includes a Dockerfile. So the Dockerfile is this

FROM mysql:5.7
RUN chown -R mysql:root /var/lib/mysql/

ARG MYSQL_DATABASE
ARG MYSQL_USER
ARG MYSQL_PASSWORD
ARG MYSQL_ROOT_PASSWORD

ENV MYSQL_DATABASE=$MYSQL_DATABASE
ENV MYSQL_USER=$MYSQL_USER
ENV MYSQL_PASSWORD=$MYSQL_PASSWORD
ENV MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD

ADD data.sql /etc/mysql/data.sql
RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql
RUN cp /etc/mysql/data.sql /docker-entrypoint-initdb.d

EXPOSE 3306

4) Now I use mysqldump to dump my db and put the data.sql inside mysql folder

mysqldump -h <server name> -u<user> -p <db name> > data.sql

The file is just a normal sql dump file but I add 2 lines at the beginning so the file would look like this

--
-- Create a database using `MYSQL_DATABASE` placeholder
--
CREATE DATABASE IF NOT EXISTS `MYSQL_DATABASE`;
USE `MYSQL_DATABASE`;

-- Rest of queries
DROP TABLE IF EXISTS `x`;
CREATE TABLE `x` (..)
LOCK TABLES `x` WRITE;
INSERT INTO `x` VALUES ...;
...
...
...

So what happening is that I used "RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql" command to replace the MYSQL_DATABASE placeholder with the name of my DB that I have set it in .env file.

|- docker-compose.yml
|- .env
|- mysql
     |- Dockerfile
     |- data.sql

Now you are ready to build and run your container

converting Java bitmap to byte array

Ted Hopp is correct, from the API Documentation :

public void copyPixelsToBuffer (Buffer dst)

"... After this method returns, the current position of the buffer is updated: the position is incremented by the number of elements written in the buffer. "

and

public ByteBuffer get (byte[] dst, int dstOffset, int byteCount)

"Reads bytes from the current position into the specified byte array, starting at the specified offset, and increases the position by the number of bytes read."

Why do people hate SQL cursors so much?

The answers above have not emphasized enough the importance of locking. I'm not a big fan of cursors because they often result in table level locks.

Active Directory LDAP Query by sAMAccountName and Domain

You have to perform your search in the domain:

http://msdn.microsoft.com/en-us/library/ms677934(VS.85).aspx So, basically your should bind to a domain in order to search inside this domain.

Pip freeze vs. pip list

The main difference is that the output of pip freeze can be dumped into a requirements.txt file and used later to re-construct the "frozen" environment.

In other words you can run: pip freeze > frozen-requirements.txt on one machine and then later on a different machine or on a clean environment you can do: pip install -r frozen-requirements.txt and you'll get the an identical environment with the exact same dependencies installed as you had in the original environment where you generated the frozen-requirements.txt.

Finding an element in an array in Java

Use a for loop. There's nothing built into array. Or switch to a java.util Collection class.

twitter bootstrap text-center when in xs mode

Css Part is:

CSS:

@media (max-width: 767px) {

  // Align text to center.
  .text-xs-center {
    text-align: center;
  } 
}

And the HTML part will be ( this text center work only below 767px width )

HTML:

 <div class="col-xs-12 col-sm-6 text-right text-xs-center">
        <p>
            <a href="#"><i class="fa fa-facebook"></i></a> 
            <a href="#"><i class="fa fa-twitter"></i></a> 
            <a href="#"><i class="fa fa-google-plus"></i></a>
        </p>
 </div>

Location for session files in Apache/PHP

The only surefire option to find the current session.save_path value is always to check with phpinfo() in exactly the environment where you want to find out the session storage directory.

Reason: there can be all sorts of things that change session.save_path, either by overriding the php.ini value or by setting it at runtime with ini_set('session.save_path','/path/to/folder');. For example, web server management panels like ISPConfig, Plesk etc. often adapt this to give each website its own directory with session files.

Getting the filenames of all files in a folder

Here's how to look in the documentation.

First, you're dealing with IO, so look in the java.io package.

There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles() method in the File class. And the documentation for that method says:

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

Scrolling up in the File JavaDoc, I see the constructors. And that's really all I need to be able to create a File instance and call listFiles() on it. Scrolling still further, I can see some information about how files are named in different operating systems.

MIN and MAX in C

The simplest way is to define it as a global function in a .h file, and call it whenever you want, if your program is modular with lots of files. If not, double MIN(a,b){return (a<b?a:b)} is the simplest way.

"Undefined reference to" template class constructor

You will have to define the functions inside your header file.
You cannot separate definition of template functions in to the source file and declarations in to header file.

When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared.

Reference:
C++03 standard, § 14.7.2.4:

The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.

EDIT:
To clarify the discussion on the comments:
Technically, there are three ways to get around this linking problem:

  • To move the definition to the .h file
  • Add explicit instantiations in the .cpp file.
  • #include the .cpp file defining the template at the .cpp file using the template.

Each of them have their pros and cons,

Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure.

Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance.

While including cpp files is confusing at the same time shares the problems of both above approaches.

I find first method the easiest to follow and implement and hence advocte using it.

alternative to "!is.null()" in R

To handle undefined variables as well as nulls, you can use substitute with deparse:

nullSafe <- function(x) {
  if (!exists(deparse(substitute(x))) || is.null(x)) {
    return(NA)
  } else {
    return(x)
  }
}

nullSafe(my.nonexistent.var)

Replace words in a string - Ruby

You can try using this way :

sentence ["Robert"] = "Roger"

Then the sentence will become :

sentence = "My name is Roger" # Robert is replaced with Roger

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

The following has worked for me very well:

$("#button").attr('disabled', 'disabled');

Xcode 6: Keyboard does not show up in simulator

If keyboard do not shown up automatically in simulator, just press [Command+K]

or Hardware -> Keyboard -> Toggle Software Keyboard

How to count TRUE values in a logical vector

There's also a package called bit that is specifically designed for fast boolean operations. It's especially useful if you have large vectors or need to do many boolean operations.

z <- sample(c(TRUE, FALSE), 1e8, rep = TRUE)

system.time({
  sum(z) # 0.170s
})

system.time({
  bit::sum.bit(z) # 0.021s, ~10x improvement in speed
})

How to iterate over a column vector in Matlab?

with many functions in matlab, you don't need to iterate at all.

for example, to multiply by it's position in the list:

m = [1:numel(list)]';
elm = list.*m;

vectorized algorithms in matlab are in general much faster.

sorting integers in order lowest to highest java

Well, if you want to do it using an algorithm. There are a plethora of sorting algorithms out there. If you aren't concerned too much about efficiency and more about readability and understandability. I recommend Insertion Sort. Here is the psudo code, it is trivial to translate this into java.

begin
    for i := 1 to length(A)-1 do
    begin
        value := A[i];
        j := i - 1;
        done := false;
        repeat
            { To sort in descending order simply reverse
              the operator i.e. A[j] < value }
            if A[j] > value then
            begin
                A[j + 1] := A[j];
                j := j - 1;
                if j < 0 then
                    done := true;
            end
            else
                done := true;
        until done;
        A[j + 1] := value;
    end;
end;

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

You should probably set all of the cookie properties not just the value of it. setPath(), setDomain() ... etc

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

Suppress the @JoinColumn(name="categoria") on the ID field of the Categoria class and I think it will work.

MySQL Check if username and password matches in Database

Instead of selecting all the columns in count count(*) you can limit count for one column count(UserName).

You can limit the whole search to one row by using Limit 0,1

SELECT COUNT(UserName)
  FROM TableName
 WHERE UserName = 'User' AND
       Password = 'Pass'
 LIMIT 0, 1

How to store standard error in a variable

If you want to bypass the use of a temporary file you may be able to use process substitution. I haven't quite gotten it to work yet. This was my first attempt:

$ .useless.sh 2> >( ERROR=$(<) )
-bash: command substitution: line 42: syntax error near unexpected token `)'
-bash: command substitution: line 42: `<)'

Then I tried

$ ./useless.sh 2> >( ERROR=$( cat <() )  )
This Is Output
$ echo $ERROR   # $ERROR is empty

However

$ ./useless.sh 2> >( cat <() > asdf.txt )
This Is Output
$ cat asdf.txt
This Is Error

So the process substitution is doing generally the right thing... unfortunately, whenever I wrap STDIN inside >( ) with something in $() in an attempt to capture that to a variable, I lose the contents of $(). I think that this is because $() launches a sub process which no longer has access to the file descriptor in /dev/fd which is owned by the parent process.

Process substitution has bought me the ability to work with a data stream which is no longer in STDERR, unfortunately I don't seem to be able to manipulate it the way that I want.

Cannot import XSSF in Apache POI

I added below contents in app "build.gradle"

implementation 'org.apache.poi:poi:4.0.0'
implementation 'org.apache.poi:poi-ooxml:4.0.0'

In Angular, how to redirect with $location.path as $http.post success callback

it's very easy code .. but hard to fined..

detailsApp.controller("SchoolCtrl", function ($scope, $location) { 
      $scope.addSchool = function () {

        location.href='/ManageSchool/TeacherProfile?ID=' + $scope.TeacherID;
      }
});

Maven Out of Memory Build Failure

Answering late to mention yet another option rather than the common MAVEN_OPTS environment variable to pass to the Maven build the required JVM options.

Since Maven 3.3.1, you could have an .mvn folder as part of the concerned project and a jvm.config file as perfect place for such an option.

two new optional configuration files .mvn/jvm.config and .mvn/maven.config, located at the base directory of project source tree. If present, these files will provide default jvm and maven options. Because these files are part of the project source tree, they will be present in all project checkouts and will be automatically used every time the project is build.

As part of the official release notes

In Maven it is not simple to define JVM configuration on a per project base. The existing mechanism based on an environment variable MAVEN_OPTS and the usage of ${user.home}/.mavenrc is an other option with the drawback of not being part of the project.

Starting with this release you can define JVM configuration via ${maven.projectBasedir}/.mvn/jvm.config file which means you can define the options for your build on a per project base. This file will become part of your project and will be checked in along with your project. So no need anymore for MAVEN_OPTS, .mavenrc files. So for example if you put the following JVM options into the ${maven.projectBasedir}/.mvn/jvm.config file:

-Xmx2048m -Xms1024m -XX:MaxPermSize=512m -Djava.awt.headless=true

The main advantage of this approach is that the configuration is isolated to the concerned project and applied to the whole build as well, and less fragile than MAVEN_OPTS for other developers working on the same project (forgetting to setting it).
Moreover, the options will be applied to all modules in case of a multi-module project.

How to animate the change of image in an UIImageView?

Vladimir's answer is perfect, but anyone like me who is looking for swift solution

This Solution is Worked for swift version 4.2

var i = 0
    func animation(){
        let name = (i % 2 == 0) ? "1.png" : "2.png"
        myImageView.image = UIImage.init(named: name)
        let transition: CATransition = CATransition.init()
        transition.duration = 1.0
        transition.timingFunction = CAMediaTimingFunction.init(name: .easeInEaseOut)
        transition.type = .fade
        myImageView.layer.add(transition, forKey: nil)
        i += 1
    }

You can call this method from anywhere. It will change the image to next one(image) with animation.

For Swift Version 4.0 Use bellow solution

var i = 0
    func animationVersion4(){
        let name = (i % 2 == 0) ? "1.png" : "2.png"
        uiImage.image = UIImage.init(named: name)
        let transition: CATransition = CATransition.init()
        transition.duration = 1.0
        transition.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)
        transition.type = kCATransitionFade
        uiImage.layer.add(transition, forKey: nil)
        i += 1
    }

REST API 404: Bad URI, or Missing Resource?

The Uniform Resource Identifier is a unique pointer to the resource. A poorly form URI doesn't point to the resource and therefore performing a GET on it will not return a resource. 404 means The server has not found anything matching the Request-URI. If you put in the wrong URI or bad URI that is your problem and the reason you didn't get to a resource whether a HTML page or IMG.

WCF Service , how to increase the timeout?

Got the same error recently but was able to fixed it by ensuring to close every wcf client call. eg.

WCFServiceClient client = new WCFServiceClient ();
//More codes here
// Always close the client.
client.Close();

or

using(WCFServiceClient client = new WCFServiceClient ())
{ 
    //More codes here 
}

How do I find out which DOM element has the focus?

By itself, document.activeElement can still return an element if the document isn't focused (and thus nothing in the document is focused!)

You may want that behavior, or it may not matter (e.g. within a keydown event), but if you need to know something is actually focused, you can additionally check document.hasFocus().

The following will give you the focused element if there is one, or else null.

var focused_element = null;
if (
    document.hasFocus() &&
    document.activeElement !== document.body &&
    document.activeElement !== document.documentElement
) {
    focused_element = document.activeElement;
}

To check whether a specific element has focus, it's simpler:

var input_focused = document.activeElement === input && document.hasFocus();

To check whether anything is focused, it's more complex again:

var anything_is_focused = (
    document.hasFocus() &&
    document.activeElement !== null &&
    document.activeElement !== document.body &&
    document.activeElement !== document.documentElement
);

Robustness Note: In the code where it the checks against document.body and document.documentElement, this is because some browsers return one of these or null when nothing is focused.

It doesn't account for if the <body> (or maybe <html>) had a tabIndex attribute and thus could actually be focused. If you're writing a library or something and want it to be robust, you should probably handle that somehow.


Here's a (heavy airquotes) "one-liner" version of getting the focused element, which is conceptually more complicated because you have to know about short-circuiting, and y'know, it obviously doesn't fit on one line, assuming you want it to be readable.
I'm not gonna recommend this one. But if you're a 1337 hax0r, idk... it's there.
You could also remove the || null part if you don't mind getting false in some cases. (You could still get null if document.activeElement is null):

var focused_element = (
    document.hasFocus() &&
    document.activeElement !== document.body &&
    document.activeElement !== document.documentElement &&
    document.activeElement
) || null;

For checking if a specific element is focused, alternatively you could use events, but this way requires setup (and potentially teardown), and importantly, assumes an initial state:

var input_focused = false;
input.addEventListener("focus", function() {
    input_focused = true;
});
input.addEventListener("blur", function() {
    input_focused = false;
});

You could fix the initial state assumption by using the non-evented way, but then you might as well just use that instead.

error: strcpy was not declared in this scope

This error sometimes occurs in a situation like this:

#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif

static void init_random(uint32_t initseed=0)
{
    if (initseed==0)
    {
        struct timeval tv;
        gettimeofday(&tv, NULL);
        seed=(uint32_t) (4223517*getpid()*tv.tv_sec*tv.tv_usec);
    }
    else
        seed=initseed;
#if !defined(CYGWIN) && !defined(__INTERIX)
    //seed=42
    //SG_SPRINT("initializing random number generator with %d (seed size %d)\n", seed, RNG_SEED_SIZE)
    initstate(seed, CMath::rand_state, RNG_SEED_SIZE);
#endif
}

If the following code lines not run in the run-time:

#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif

you will face with an error in your code like something as follows; because initstate is placed in the stdlib.h file and it's not included:

In file included from ../../shogun/features/SubsetStack.h:14:0, 
                 from ../../shogun/features/Features.h:21, 
                 from ../../shogun/ui/SGInterface.h:7, 
                 from MatlabInterface.h:15, 
                 from matlabInterface.cpp:7: 
../../shogun/mathematics/Math.h: In static member function 'static void shogun::CMath::init_random(uint32_t)': 
../../shogun/mathematics/Math.h:459:52: error: 'initstate' was not declared in this scope

Vertically aligning CSS :before and :after content

Messing around with the line-height attribute should do the trick. I haven't tested this, so the exact value may not be right, but start with 1.5em, and tweak it in 0.1 increments until it lines up.

.pdf{ line-height:1.5em; }

How do I refresh the page in ASP.NET? (Let it reload itself by code)

The only correct way that I could do page refresh was through JavaScript, many of top .NET answers failed for me.

Response.Write("<script type='text/javascript'> setTimeout('location.reload(true); ', timeout);</script>");

Put the above code in button click event or anywhere you want to force page refresh.

Should functions return null or an empty object?

I tend to

  • return null if the object id doesn't exist when it's not known beforehand whether it should exist.
  • throw if the object id doesn't exist when it should exist.

I differentiate these two scenarios with these three types of methods. First:

Boolean TryGetSomeObjectById(Int32 id, out SomeObject o)
{
    if (InternalIdExists(id))
    {
        o = InternalGetSomeObject(id);

        return true;
    }
    else
    {
        return false;
    }
}

Second:

SomeObject FindSomeObjectById(Int32 id)
{
    SomeObject o;

    return TryGetObjectById(id, out o) ? o : null;
}

Third:

SomeObject GetSomeObjectById(Int32 id)
{
    SomeObject o;

    if (!TryGetObjectById(id, out o))
    {
        throw new SomeAppropriateException();
    }

    return o;
}

How to make join queries using Sequelize on Node.js

Model1.belongsTo(Model2, { as: 'alias' })

Model1.findAll({include: [{model: Model2  , as: 'alias'  }]},{raw: true}).success(onSuccess).error(onError);

how to print a string to console in c++

yes it's possible to print a string to the console.

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string strMytestString("hello world");
    cout << strMytestString;
    return 0;
}

stdafx.h isn't pertinent to the solution, everything else is.

How to remove leading zeros using C#

Regex rx = new Regex(@"^0+(\d+)$");
rx.Replace("0001234", @"$1"); // => "1234"
rx.Replace("0001234000", @"$1"); // => "1234000"
rx.Replace("000", @"$1"); // => "0" (TrimStart will convert this to "")

// usage
var outString = rx.Replace(inputString, @"$1");

SQL Insert Query Using C#

I assume you have a connection to your database and you can not do the insert parameters using c #.

You are not adding the parameters in your query. It should look like:

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";

SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id","abc");
command.Parameters.Add("@username","abc");
command.Parameters.Add("@password","abc");
command.Parameters.Add("@email","abc");

command.ExecuteNonQuery();

Updated:

using(SqlConnection connection = new SqlConnection(_connectionString))
{
    String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";

    using(SqlCommand command = new SqlCommand(query, connection))
    {
        command.Parameters.AddWithValue("@id", "abc");
        command.Parameters.AddWithValue("@username", "abc");
        command.Parameters.AddWithValue("@password", "abc");
        command.Parameters.AddWithValue("@email", "abc");

        connection.Open();
        int result = command.ExecuteNonQuery();

        // Check Error
        if(result < 0)
            Console.WriteLine("Error inserting data into Database!");
    }
}

How to print a string at a fixed width?

>>> print(f"{'123':<4}56789")
123 56789

Jupyter notebook not running code. Stuck on In [*]

I had the same problem, and the little star means that the kernel is still working. So the program is trapped in an endless while loop. So you only have to the rewrite the code

milliseconds to time in javascript

Simplest Way

let getTime = (Time)=>{
    let Hours = Time.getHours();
    let Min = Time.getMinutes();
    let Sec = Time.getSeconds();

    return `Current time ${Hours} : ${Min} : ${Sec}`;
}

console.log(getTime(new Date()));

PHP 7 simpleXML

For Ubuntu 18.04 and php7.3, install php7.3-xml sudo apt-get install php7.3-xml

this will installl the required simplexml

Calculating how many days are between two dates in DB2?

It seems like one closing brace is missing at ,right(a2.chdlm,2)))) from sysibm.sysdummy1 a1,

So your Query will be

select days(current date) - days(date(select concat(concat(concat(concat(left(a2.chdlm,4),'-'),substr(a2.chdlm,4,2)),'-'),right(a2.chdlm,2)))) from sysibm.sysdummy1 a1, chcart00 a2 where chstat = '05';

Position an element relative to its container

Absolute positioning positions an element relative to its nearest positioned ancestor. So put position: relative on the container, then for child elements, top and left will be relative to the top-left of the container so long as the child elements have position: absolute. More information is available in the CSS 2.1 specification.

Is it possible to use JS to open an HTML select to show its option list?

I use this... but it requires the user to click on the select box...

Here are the 2 javascript functions

function expand(obj)
{
    obj.size = 5;
}
function unexpand(obj)
{
    obj.size = 1;
}

then i create the select box

<select id="test" multiple="multiple" name="foo" onFocus="expand(this)" onBlur="unexpand(this)">
<option >option1</option>
<option >option2</option>
<option >option3</option>
<option >option4</option>
<option >option5</option>
</select> 

I know this code is a little late, but i hope it helps someone who had the same problem as me.

ps/fyi i have not tested the code above (i create my select box dynamically), and the code i did write was only tested in FireFox.

Pressed <button> selector

You can do this if you use an <a> tag instead of a button. I know it's not exactly what you asked for, but it might give you some other options if you cannot find a solution to this:

Borrowing from a demo from another answer here I produced this:

_x000D_
_x000D_
a {_x000D_
  display: block;_x000D_
  font-size: 18px;_x000D_
  border: 2px solid gray;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  text-align: center;_x000D_
  line-height: 100px;_x000D_
}_x000D_
_x000D_
a:active {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid green;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
a:target {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid red;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<a id="btn" href="#btn">Demo</a>
_x000D_
_x000D_
_x000D_

Notice the use of :target; this will be the style applied when the element is targeted via the hash. Which also means your HTML will need to be this: <a id="btn" href="#btn">Demo</a> a link targeting itself. and the demo http://jsfiddle.net/rlemon/Awdq5/4/

Thanks to @BenjaminGruenbaum here is a better demo: http://jsfiddle.net/agzVt/

Also, as a footnote: this should really be done with JavaScript and applying / removing CSS classes from the element. It would be much less convoluted.

Set formula to a range of cells

Use this

            Sub calc()


            Range("C1:C10").FormulaR1C1 = "=(R10C1+R10C2)"


            End Sub

PHP: Get key from array?

Try this

foreach(array_keys($array) as $nmkey)
    {
        echo $nmkey;
    }

use localStorage across subdomains

this kind of solution causes many problems like this. for consistency and SEO considerations redirect on the main domain is the best solution.

do it redirection at the server level

How To Redirect www to Non-www with Nginx

https://www.digitalocean.com/community/tutorials/how-to-redirect-www-to-non-www-with-nginx-on-centos-7

or any other level like route 53 if are using

Handling a timeout error in python sockets

I had enough success just catchig socket.timeout and socket.error; although socket.error can be raised for lots of reasons. Be careful.

import socket
import logging

hostname='google.com'
port=443

try:
    sock = socket.create_connection((hostname, port), timeout=3)

except socket.timeout as err:
    logging.error(err)

except socket.error as err:
    logging.error(err)

Angular2 disable button

I tried using disabled along with click event. Below is the snippet , the accepted answer also worked perfectly fine , I am adding this answer to give an example how it can be used with disabled and click properties.

<button (click)="!planNextDisabled && planNext()" [disabled]="planNextDisabled"></button>

Build tree array from flat array in javascript

My solution:

  • Allows bi-directional mapping (root to leaves and leaves to root)
  • Returns all nodes, roots, and leaves
  • One data pass and very fast performance
  • Vanilla Javascript
/**
 * 
 * @param data items array
 * @param idKey item's id key (e.g., item.id)
 * @param parentIdKey item's key that points to parent (e.g., item.parentId)
 * @param noParentValue item's parent value when root (e.g., item.parentId === noParentValue => item is root)
 * @param bidirectional should parent reference be added
 */
function flatToTree(data, idKey, parentIdKey, noParentValue = null, bidirectional = true) {
  const nodes = {}, roots = {}, leaves = {};

  // iterate over all data items
  for (const i of data) {

    // add item as a node and possibly as a leaf
    if (nodes[i[idKey]]) { // already seen this item when child was found first
      // add all of the item's data and found children
      nodes[i[idKey]] = Object.assign(nodes[i[idKey]], i);
    } else { // never seen this item
      // add to the nodes map
      nodes[i[idKey]] = Object.assign({ $children: []}, i);
      // assume it's a leaf for now
      leaves[i[idKey]] = nodes[i[idKey]];
    }

    // put the item as a child in parent item and possibly as a root
    if (i[parentIdKey] !== noParentValue) { // item has a parent
      if (nodes[i[parentIdKey]]) { // parent already exist as a node
        // add as a child
        (nodes[i[parentIdKey]].$children || []).push( nodes[i[idKey]] );
      } else { // parent wasn't seen yet
        // add a "dummy" parent to the nodes map and put the item as its child
        nodes[i[parentIdKey]] = { $children: [ nodes[i[idKey]] ] };
      }
      if (bidirectional) {
        // link to the parent
        nodes[i[idKey]].$parent = nodes[i[parentIdKey]];
      }
      // item is definitely not a leaf
      delete leaves[i[parentIdKey]];
    } else { // this is a root item
      roots[i[idKey]] = nodes[i[idKey]];
    }
  }
  return {roots, nodes, leaves};
}

Usage example:

const data = [{id: 2, parentId: 0}, {id: 1, parentId: 2} /*, ... */];
const { nodes, roots, leaves } = flatToTree(data, 'id', 'parentId', 0);

Sorting arraylist in alphabetical order (case insensitive)

You need to use custom comparator which will use compareToIgnoreCase, not compareTo.

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

How are you running the application? Are you just hitting the website or are you building and running from within Visual Studio? If you are building and running you may want to tell it to use the local IIS web server. This would make sure it is using the App Pool you have set up to run with v4.0/integrated.

I am guessing that it is using the Visual Studio Development Server when running. This server is probably trying to run with the 2.0 framework. This then causes your error to be thrown.

Edit: To note, I normally just build my website application and then I attach to process w3wp when I want to debug. I do not use the publishing tool. Of course this means my local working directory is within the web root.

start MySQL server from command line on Mac OS Lion

If you have MySQL installed through Homebrew these commands will help you:

# For starting
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

# For stoping
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

What is the difference between encode/decode?

To represent a unicode string as a string of bytes is known as encoding. Use u'...'.encode(encoding).

Example:

    >>> u'æøå'.encode('utf8')
    '\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5'
    >>> u'æøå'.encode('latin1')
    '\xc3\xa6\xc3\xb8\xc3\xa5'
    >>> u'æøå'.encode('ascii')
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: 
    ordinal not in range(128)

You typically encode a unicode string whenever you need to use it for IO, for instance transfer it over the network, or save it to a disk file.

To convert a string of bytes to a unicode string is known as decoding. Use unicode('...', encoding) or '...'.decode(encoding).

Example:

   >>> u'æøå'
   u'\xc3\xa6\xc3\xb8\xc3\xa5' # the interpreter prints the unicode object like so
   >>> unicode('\xc3\xa6\xc3\xb8\xc3\xa5', 'latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'
   >>> '\xc3\xa6\xc3\xb8\xc3\xa5'.decode('latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'

You typically decode a string of bytes whenever you receive string data from the network or from a disk file.

I believe there are some changes in unicode handling in python 3, so the above is probably not correct for python 3.

Some good links:

Change size of text in text input tag?

In your CSS stylesheet, try adding:

input[type="text"] {
    font-size:25px;
}

See this jsFiddle example

Convert normal date to unix timestamp

convert timestamp to unix timestamp.

const date = 1513787412; const unixDate = new Date(date * 1000);// Dec 20 2020 (object)

to get the timeStamp after conversion const TimeStamp = new Date(date*1000).getTime(); //1513787412000

MySQL duplicate entry error even though there is no duplicate entry

In case this helps anyone besides the OP, I had a similar problem using InnoDB.

For me, what was really going on was a foreign key constraint failure. I was referencing a foreign key that did not exist.

In other words, the error was completely off. The primary key was fine, and inserting the foreign key first fixed the problem. No idea why MySQL got this wrong suddenly.

Your password does not satisfy the current policy requirements

The problem is that your password wont match the password validation rules. You can simple follow below steps to solve your problem.

You can simply see password validation configuration matrix by typing below code.

mysql-> SHOW VARIABLES LIKE 'validate_password%';

Then in your matrix you can find below variables with corresponding values and in there you have to check validate_password_length , validate_password_number_count and validate_password_policy.

Check the values used for those variables. Make sure your validate_password_length should not be greater than 6. You can set that to 6 by using below code.

SET GLOBAL validate_password_length = 6;

And after that you need to set validate_password_number_count to 0. Do it by using below code.

SET GLOBAL validate_password_number_count = 0;

Finally you have to set you validate_password_policy to low. Having that as Medium or High wont allow your less secure passwords. Set that to low by below code.

SET GLOBAL validate_password_policy=LOW;

How to setup Tomcat server in Netbeans?

If TomCat is install. Perhaps it is not installed Java EE. Services-> plug-ins-> additional plug-ins-> in the search dial tomcat. and install the module java ee. then in the services, servers, add the tomcat server.

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.

That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.

public class PlusEquals {
    public static void main(String[] args) {
        byte a = 1;
        byte b = 2;
        a = a + b;
        System.out.println(a);
    }
}

What does this program print?

Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.

But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

Better way to check variable for null or empty string?

When you want to check if a value is provided for a field, that field may be a string , an array, or undifined. So, the following is enough

function isSet($param)
{
    return (is_array($param) && count($param)) || trim($param) !== '';
}

Send raw ZPL to Zebra printer via USB

Install an share your printer: \localhost\zebra Send ZPL as text, try with copy first:

copy file.zpl \localhost\zebra

very simple, almost no coding.

count (non-blank) lines-of-code in bash

cat foo.c | sed '/^\s*$/d' | wc -l

And if you consider comments blank lines:

cat foo.pl | sed '/^\s*#/d;/^\s*$/d' | wc -l

Although, that's language dependent.

CSS3 Rotate Animation

Here is a demo. The correct animation CSS:

_x000D_
_x000D_
.image {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    width: 120px;_x000D_
    height: 120px;_x000D_
    margin:-60px 0 0 -60px;_x000D_
    -webkit-animation:spin 4s linear infinite;_x000D_
    -moz-animation:spin 4s linear infinite;_x000D_
    animation:spin 4s linear infinite;_x000D_
}_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
_x000D_
<img class="image" src="http://i.stack.imgur.com/pC1Tv.jpg" alt="" width="120" height="120">
_x000D_
_x000D_
_x000D_


Some notes on your code:

  1. You've nested the keyframes inside the .image rule, and that's incorrect
  2. float:left won't work on absolutely positioned elements
  3. Have a look at caniuse: IE10 doesn't need the -ms- prefix

Cut Java String at a number of character

StringUtils.abbreviate("abcdefg", 6);

This will give you the following result: abc...

Where 6 is the needed length, and "abcdefg" is the string that needs to be abbrevieted.

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

Vue template or render function not defined yet I am using neither?

I had this script in app.js in laravel which automatically adds all components in the component folder.

const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key)))

To make it work just add default

const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Binding ConverterParameter

The ConverterParameter property can not be bound because it is not a dependency property.

Since Binding is not derived from DependencyObject none of its properties can be dependency properties. As a consequence, a Binding can never be the target object of another Binding.

There is however an alternative solution. You could use a MultiBinding with a multi-value converter instead of a normal Binding:

<Style TargetType="FrameworkElement">
    <Setter Property="Visibility">
        <Setter.Value>
            <MultiBinding Converter="{StaticResource AccessLevelToVisibilityConverter}">
                <Binding Path="Tag" RelativeSource="{RelativeSource Mode=FindAncestor,
                                                     AncestorType=UserControl}"/>
                <Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}"/>
            </MultiBinding>
        </Setter.Value>
    </Setter>
</Style>

The multi-value converter gets an array of source values as input:

public class AccessLevelToVisibilityConverter : IMultiValueConverter
{
    public object Convert(
        object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values.All(v => (v is bool && (bool)v))
            ? Visibility.Visible
            : Visibility.Hidden;
    }

    public object[] ConvertBack(
        object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

How to set Google Chrome in WebDriver

Aditya,

As you said in your last comment that you are trying to access chrome of some other system so based on that you should keep your chrome driver in that system itself.

for example: if you are trying to access linux chrome from windows then you need to put your chrome driver in linux at some place and give permission as 777 and use below code at your windows system.

System.setProperty("webdriver.chrome.driver", "\\var\\www\\Jar\\chromedriver");
Capability= DesiredCapabilities.chrome();   Capability.setPlatform(org.openqa.selenium.Platform.ANY);
browser=new RemoteWebDriver(new URL(nodeURL),Capability);

This is working code of my system.

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

If your project already uses commons-lang, StringUtils provide a nice method for this purpose:

String filename = "abc.def.ghi";

String start = StringUtils.substringBefore(filename, "."); // returns "abc"

see javadoc [2.6] [3.1]

What is the default value for enum variable?

I think it's quite dangerous to rely on the order of the values in a enum and to assume that the first is always the default. This would be good practice if you are concerned about protecting the default value.

enum E
{
    Foo = 0, Bar, Baz, Quux
}

Otherwise, all it takes is a careless refactor of the order and you've got a completely different default.

MongoDB via Mongoose JS - What is findByID?

I'm the maintainer of Mongoose. findById() is a built-in method on Mongoose models. findById(id) is equivalent to findOne({ _id: id }), with one caveat: findById() with 0 params is equivalent to findOne({ _id: null }).

You can read more about findById() on the Mongoose docs and this findById() tutorial.

How to find char in string and get all the indexes?

x = "abcdabcdabcd"
print(x)
l = -1
while True:
    l = x.find("a", l+1)
    if l == -1:
        break
    print(l)

Total memory used by Python process?

For Unix based systems (Linux, Mac OS X, Solaris), you can use the getrusage() function from the standard library module resource. The resulting object has the attribute ru_maxrss, which gives the peak memory usage for the calling process:

>>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
2656  # peak memory usage (kilobytes on Linux, bytes on OS X)

The Python docs don't make note of the units. Refer to your specific system's man getrusage.2 page to check the unit for the value. On Ubuntu 18.04, the unit is noted as kilobytes. On Mac OS X, it's bytes.

The getrusage() function can also be given resource.RUSAGE_CHILDREN to get the usage for child processes, and (on some systems) resource.RUSAGE_BOTH for total (self and child) process usage.

If you care only about Linux, you can alternatively read the /proc/self/status or /proc/self/statm file as described in other answers for this question and this one too.

The source was not found, but some or all event logs could not be searched

For me this error was due to the command prompt, which was not running under administrator privileges. You need to right click on the command prompt and say "Run as administrator".

You need administrator role to install or uninstall a service.

How to programmatically round corners and set random background colors

Instead of setBackgroundColor, retrieve the background drawable and set its color:

v.setBackgroundResource(R.drawable.tags_rounded_corners);

GradientDrawable drawable = (GradientDrawable) v.getBackground();
if (i % 2 == 0) {
  drawable.setColor(Color.RED);
} else {
  drawable.setColor(Color.BLUE);
}

Also, you can define the padding within your tags_rounded_corners.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <corners android:radius="4dp" />
  <padding
    android:top="2dp"
    android:left="2dp"
    android:bottom="2dp"
    android:right="2dp" />
</shape> 

Ant: How to execute a command for each file in directory?

An approach without ant-contrib is suggested by Tassilo Horn (the original target is here)

Basicly, as there is no extension of <java> (yet?) in the same way that <apply> extends <exec>, he suggests to use <apply> (which can of course also run a java programm in a command line)

Here some examples:

  <apply executable="java"> 
    <arg value="-cp"/> 
    <arg pathref="classpath"/> 
    <arg value="-f"/> 
    <srcfile/> 
    <arg line="-o ${output.dir}"/> 

    <fileset dir="${input.dir}" includes="*.txt"/> 
  </apply> 

How do I make a matrix from a list of vectors in R?

simplify2array is a base function that is fairly intuitive. However, since R's default is to fill in data by columns first, you will need to transpose the output. (sapply uses simplify2array, as documented in help(sapply).)

> t(simplify2array(a))
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

How to get first element in a list of tuples?

do you mean something like this?

new_list = [ seq[0] for seq in yourlist ]

What you actually have is a list of tuple objects, not a list of sets (as your original question implied). If it is actually a list of sets, then there is no first element because sets have no order.

Here I've created a flat list because generally that seems more useful than creating a list of 1 element tuples. However, you can easily create a list of 1 element tuples by just replacing seq[0] with (seq[0],).

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

Appending HTML string to the DOM

Performance

AppendChild (E) is more than 2x faster than other solutions on chrome and safari, insertAdjacentHTML(F) is fastest on firefox. The innerHTML= (B) (do not confuse with += (A)) is second fast solution on all browsers and it is much more handy than E and F.

Details

Set up environment (2019.07.10) MacOs High Sierra 10.13.4 on Chrome 75.0.3770 (64-bit), Safari 11.1.0 (13604.5.6), Firefox 67.0.0 (64-bit)

enter image description here

  • on Chrome E (140k operations per second) is fastest, B (47k) and F (46k) are second, A (332) is slowest
  • on firefox F (94k) is fastest, then B(80k), D (73k), E(64k), C (21k) slowest is A(466)
  • on Safari E(207k) is fastest, then B(89k), F(88k), D(83k), C (25k), slowest is A(509)

You can replay test in your machine here

_x000D_
_x000D_
function A() {    _x000D_
  container.innerHTML += '<p>A: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function B() {    _x000D_
  container.innerHTML = '<p>B: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function C() {    _x000D_
  $('#container').append('<p>C: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
function D() {_x000D_
  var p = document.createElement("p");_x000D_
  p.innerHTML = 'D: Just some <span>text</span> here';_x000D_
  container.appendChild(p);_x000D_
}_x000D_
_x000D_
function E() {    _x000D_
  var p = document.createElement("p");_x000D_
  var s = document.createElement("span"); _x000D_
  s.appendChild( document.createTextNode("text ") );_x000D_
  p.appendChild( document.createTextNode("E: Just some ") );_x000D_
  p.appendChild( s );_x000D_
  p.appendChild( document.createTextNode(" here") );_x000D_
  container.appendChild(p);_x000D_
}_x000D_
_x000D_
function F() {    _x000D_
  container.insertAdjacentHTML('beforeend', '<p>F: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
This snippet only for show code used in test (in jsperf.com) - it not perform test itself. _x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

Is <img> element block level or inline level?

<img> is a replaced element; it has a display value of inline by default, but its default dimensions are defined by the embedded image's intrinsic values, like it were inline-block. You can set properties like border/border-radius, padding/margin, width, height, etc. on an image.

Replaced elements : They're elements whose contents are not affected by the current document's styles. The position of the replaced element can be affected using CSS, but not the contents of the replaced element itself.

Referenece : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

ExecuteNonQuery doesn't return results

if you want to run an update, delete, or insert statement, you should use the ExecuteNonQuery. ExecuteNonQuery returns the number of rows affected by the statement.

How to Set Count On

How to find the Windows version from the PowerShell command line

$OSVersion = [Version](Get-ItemProperty -Path "$($Env:Windir)\System32\hal.dll" -ErrorAction SilentlyContinue).VersionInfo.FileVersion.Split()[0]

On Windows 10 returns: 10.0.10586.420

You can then use the variable to access properties for granular comparison

$OSVersion.Major equals 10
$OSVersion.Minor equals 0
$OSVersion.Build equals 10586
$OSVersion.Revision equals 420

Additionally, you can compare operating system versions using the following

If ([Version]$OSVersion -ge [Version]"6.1")
   {
       #Do Something
   }

Recyclerview and handling different type of row inflation

You can use the library: https://github.com/vivchar/RendererRecyclerViewAdapter

mRecyclerViewAdapter = new RendererRecyclerViewAdapter(); /* included from library */
mRecyclerViewAdapter.registerRenderer(new SomeViewRenderer(SomeModel.TYPE, this));
mRecyclerViewAdapter.registerRenderer(...); /* you can use several types of cells */

For each item, you should to implement a ViewRenderer, ViewHolder, SomeModel:

ViewHolder - it is a simple view holder of recycler view.

SomeModel - it is your model with ItemModel interface

public class SomeViewRenderer extends ViewRenderer<SomeModel, SomeViewHolder> {

    public SomeViewRenderer(final int type, final Context context) {
        super(type, context);
    }

    @Override
    public void bindView(@NonNull final SomeModel model, @NonNull final SomeViewHolder holder) {
       holder.mTitle.setText(model.getTitle());
    }

    @NonNull
    @Override
    public SomeViewHolder createViewHolder(@Nullable final ViewGroup parent) {
        return new SomeViewHolder(LayoutInflater.from(getContext()).inflate(R.layout.some_item, parent, false));
    }
}

For more details you can look documentations.

how to save canvas as png image?

FileSaver.js should be able to help you here.

var canvas = document.getElementById("my-canvas");
// draw to canvas...
canvas.toBlob(function(blob) {
    saveAs(blob, "pretty image.png");
});

Add Foreign Key to existing table

How to fix Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150) in mysql.

  1. alter your table and add an index to it..

    ALTER TABLE users ADD INDEX index_name (index_column)
    
  2. Now add the constraint

    ALTER TABLE foreign_key_table
    ADD CONSTRAINT foreign_key_name FOREIGN KEY (foreign_key_column)
    REFERENCES primary_key_table (primary_key_column) ON DELETE NO ACTION
    ON UPDATE CASCADE;
    

Note if you don't add an index it wont work.

After battling with it for about 6 hours I came up with the solution I hope this save a soul.

Defining custom attrs

Currently the best documentation is the source. You can take a look at it here (attrs.xml).

You can define attributes in the top <resources> element or inside of a <declare-styleable> element. If I'm going to use an attr in more than one place I put it in the root element. Note, all attributes share the same global namespace. That means that even if you create a new attribute inside of a <declare-styleable> element it can be used outside of it and you cannot create another attribute with the same name of a different type.

An <attr> element has two xml attributes name and format. name lets you call it something and this is how you end up referring to it in code, e.g., R.attr.my_attribute. The format attribute can have different values depending on the 'type' of attribute you want.

  • reference - if it references another resource id (e.g, "@color/my_color", "@layout/my_layout")
  • color
  • boolean
  • dimension
  • float
  • integer
  • string
  • fraction
  • enum - normally implicitly defined
  • flag - normally implicitly defined

You can set the format to multiple types by using |, e.g., format="reference|color".

enum attributes can be defined as follows:

<attr name="my_enum_attr">
  <enum name="value1" value="1" />
  <enum name="value2" value="2" />
</attr>

flag attributes are similar except the values need to be defined so they can be bit ored together:

<attr name="my_flag_attr">
  <flag name="fuzzy" value="0x01" />
  <flag name="cold" value="0x02" />
</attr>

In addition to attributes there is the <declare-styleable> element. This allows you to define attributes a custom view can use. You do this by specifying an <attr> element, if it was previously defined you do not specify the format. If you wish to reuse an android attr, for example, android:gravity, then you can do that in the name, as follows.

An example of a custom view <declare-styleable>:

<declare-styleable name="MyCustomView">
  <attr name="my_custom_attribute" />
  <attr name="android:gravity" />
</declare-styleable>

When defining your custom attributes in XML on your custom view you need to do a few things. First you must declare a namespace to find your attributes. You do this on the root layout element. Normally there is only xmlns:android="http://schemas.android.com/apk/res/android". You must now also add xmlns:whatever="http://schemas.android.com/apk/res-auto".

Example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:whatever="http://schemas.android.com/apk/res-auto"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

    <org.example.mypackage.MyCustomView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      whatever:my_custom_attribute="Hello, world!" />
</LinearLayout>

Finally, to access that custom attribute you normally do so in the constructor of your custom view as follows.

public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);

  TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0);

  String str = a.getString(R.styleable.MyCustomView_my_custom_attribute);

  //do something with str

  a.recycle();
}

The end. :)

How might I convert a double to the nearest integer value?

For Unity, use Mathf.RoundToInt.

using UnityEngine;

public class ExampleScript : MonoBehaviour
{
    void Start()
    {
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.0f));
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.2f));
        // Prints 11
        Debug.Log(Mathf.RoundToInt(10.7f));
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.5f));
        // Prints 12
        Debug.Log(Mathf.RoundToInt(11.5f));

        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.0f));
        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.2f));
        // Prints -11
        Debug.Log(Mathf.RoundToInt(-10.7f));
        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.5f));
        // Prints -12
        Debug.Log(Mathf.RoundToInt(-11.5f));
    }
}

Source

public static int RoundToInt(float f) { return (int)Math.Round(f); }

MySQL combine two columns and add into a new column

Are you sure you want to do this? In essence, you're duplicating the data that is in the three original columns. From that point on, you'll need to make sure that the data in the combined field matches the data in the first three columns. This is more overhead for your application, and other processes that update the system will need to understand the relationship.

If you need the data, why not select in when you need it? The SQL for selecting what would be in that field would be:

SELECT CONCAT(zipcode, ' - ', city, ', ', state) FROM Table;

This way, if the data in the fields changes, you don't have to update your combined field.

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Check your short_open_tag setting (use <?php phpinfo() ?> to see its current setting).

Print debugging info from stored procedure in MySQL

This is the way how I will debug:

CREATE PROCEDURE procedure_name() 
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        SHOW ERRORS;  --this is the only one which you need
        ROLLBACK;   
    END; 
    START TRANSACTION;
        --query 1
        --query 2
        --query 3
    COMMIT;
END 

If query 1, 2 or 3 will throw an error, HANDLER will catch the SQLEXCEPTION and SHOW ERRORS will show errors for us. Note: SHOW ERRORS should be the first statement in the HANDLER.

disable textbox using jquery?

get radio buttons value and matches with each if it is 3 then disabled checkbox and textbox.

_x000D_
_x000D_
$("#radiobutt input[type=radio]").click(function () {_x000D_
    $(this).each(function(index){_x000D_
    //console.log($(this).val());_x000D_
        if($(this).val()==3) { //get radio buttons value and matched if 3 then disabled._x000D_
            $("#textbox_field").attr("disabled", "disabled"); _x000D_
            $("#checkbox_field").attr("disabled", "disabled"); _x000D_
        }_x000D_
        else {_x000D_
            $("#textbox_field").removeAttr("disabled"); _x000D_
            $("#checkbox_field").removeAttr("disabled"); _x000D_
        }_x000D_
      });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<span id="radiobutt">_x000D_
  <input type="radio" name="groupname" value="1" />_x000D_
  <input type="radio" name="groupname" value="2" />_x000D_
  <input type="radio" name="groupname" value="3" />_x000D_
</span>_x000D_
<div>_x000D_
  <input type="text" id="textbox_field" />_x000D_
  <input type="checkbox" id="checkbox_field" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

What is the most efficient/elegant way to parse a flat table into a tree?

Think about using nosql tools like neo4j for hierarchial structures. e.g a networked application like linkedin uses couchbase (another nosql solution)

But use nosql only for data-mart level queries and not to store / maintain transactions

Set Focus After Last Character in Text Box

This works fine for me . [Ref: the very nice plug in by Gavin G]

(function($){
    $.fn.focusTextToEnd = function(){
        this.focus();
        var $thisVal = this.val();
        this.val('').val($thisVal);
        return this;
    }
}(jQuery));

$('#mytext').focusTextToEnd();

Setting attribute disabled on a SPAN element does not prevent click events

The disabled attribute is not global and is only allowed on form controls. What you could do is set a custom data attribute (perhaps data-disabled) and check for that attribute when you handle the click event.

How can I use MS Visual Studio for Android Development?

I suppose you can open Java files in Visual Studio and just use the command line tools directly. I don't think you'd get syntax highlighting or autocompletion though.

Eclipse is really not all that different from Visual Studio, and there are a lot of tools that are designed to make Android development more comfortable that work from within Eclipse.

Disable beep of Linux Bash on Windows 10

Find the location of the .bash_profile file and enter the following into the file:

setterm -blength 0

Which will set the amount of time the beep happens to 0 and thus no beep.

How do you use subprocess.check_output() in Python?

The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])

To demonstrate, here are my two programs:

py2.py:

import sys
print sys.argv

py3.py:

import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])

First, str('python py2.py') is exactly the same thing as 'python py2.py'—you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python py2.py can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py. Which you're not; you're trying to run, say, /usr/bin/python with first argument py2.py. So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".

Also:

-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

How to reference a local XML Schema file correctly?

Add one more slash after file:// in the value of xsi:schemaLocation. (You have two; you need three. Think protocol://host/path where protocol is 'file' and host is empty here, yielding three slashes in a row.) You can also eliminate the double slashes along the path. I believe that the double slashes help with file systems that allow spaces in file and directory names, but you wisely avoided that complication in your path naming.

xsi:schemaLocation="http://www.w3schools.com file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd"

Still not working? I suggest that you carefully copy the full file specification for the XSD into the address bar of Chrome or Firefox:

file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd

If the XSD does not display in the browser, delete all but the last component of the path (email.xsd) and see if you can't display the parent directory. Continue in this manner, walking up the directory structure until you discover where the path diverges from the reality of your local filesystem.

If the XSD does displayed in the browser, state what XML processor you're using, and be prepared to hear that it's broken or that you must work around some limitation. I can tell you that the above fix will work with my Xerces-J-based validator.

How can I get a list of locally installed Python modules?

Here is a python code solution that will return a list of modules installed. One can easily modify the code to include version numbers.

import subprocess
import sys
from pprint import pprint

installed_packages = reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']).decode('utf-8')
installed_packages = installed_packages.split('\r\n')
installed_packages = [pkg.split('==')[0] for pkg in installed_packages if pkg != '']
pprint(installed_packages)

HTTP POST and GET using cURL in Linux

*nix provides a nice little command which makes our lives a lot easier.

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:

For JSON:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file

or

curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h

How to embed an autoplaying YouTube video in an iframe?

<iframe width="560" height="315" 
        src="https://www.youtube.com/embed/9IILMHo4RCQ?rel=0&amp;controls=0&amp;showinfo=0&amp;autoplay=1" 
        frameborder="0" allowfullscreen></iframe>

What is the significance of 1/1/1753 in SQL Server?

1752 was the year of Britain switching from the Julian to the Gregorian calendar. I believe two weeks in September 1752 never happened as a result, which has implications for dates in that general area.

An explanation: http://uneasysilence.com/archive/2007/08/12008/ (Internet Archive version)

What is an MvcHtmlString and when should I use it?

You would use an MvcHtmlString if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

How can I get column names from a table in SQL Server?

You can try this.This gives all the column names with their respective data types.

desc <TABLE NAME> ;

How to convert int to Integer

I had a similar problem . For this you can use a Hashmap which takes "string" and "object" as shown in code below:

/** stores the image database icons */
public static int[] imageIconDatabase = { R.drawable.ball,
        R.drawable.catmouse, R.drawable.cube, R.drawable.fresh,
        R.drawable.guitar, R.drawable.orange, R.drawable.teapot,
        R.drawable.india, R.drawable.thailand, R.drawable.netherlands,
        R.drawable.srilanka, R.drawable.pakistan,

};
private void initializeImageList() {
    // TODO Auto-generated method stub
    for (int i = 0; i < imageIconDatabase.length; i++) {
        map = new HashMap<String, Object>();

        map.put("Name", imageNameDatabase[i]);
        map.put("Icon", imageIconDatabase[i]);
    }

}

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

Why are primes important in cryptography?

It's not so much the prime numbers themselves that are important, but the algorithms that work with primes. In particular, finding the factors of a number (any number).

As you know, any number has at least two factors. Prime numbers have the unique property in that they have exactly two factors: 1 and themselves.

The reason factoring is so important is mathematicians and computer scientists don't know how to factor a number without simply trying every possible combination. That is, first try dividing by 2, then by 3, then by 4, and so forth. If you try to factor a prime number--especially a very large one--you'll have to try (essentially) every possible number between 2 and that large prime number. Even on the fastest computers, it will take years (even centuries) to factor the kinds of prime numbers used in cryptography.

It is the fact that we don't know how to efficiently factor a large number that gives cryptographic algorithms their strength. If, one day, someone figures out how to do it, all the cryptographic algorithms we currently use will become obsolete. This remains an open area of research.

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Deleting this line fixes it, but the problem is the boostrap files are in bower_components and not checked into source control.

So, every developer on the team will get the css file with the map reference when they pull the repo and do bower install (which is part of using a new repo).

The file should not have the reference to a map that is not there.

Entity Framework Join 3 Tables

This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.

var fullEntries = dbContext.tbl_EntryPoint
    .Join(
        dbContext.tbl_Entry,
        entryPoint => entryPoint.EID,
        entry => entry.EID,
        (entryPoint, entry) => new { entryPoint, entry }
    )
    .Join(
        dbContext.tbl_Title,
        combinedEntry => combinedEntry.entry.TID,
        title => title.TID,
        (combinedEntry, title) => new 
        {
            UID = combinedEntry.entry.OwnerUID,
            TID = combinedEntry.entry.TID,
            EID = combinedEntry.entryPoint.EID,
            Title = title.Title
        }
    )
    .Where(fullEntry => fullEntry.UID == user.UID)
    .Take(10);

MySQL: Insert record if not exists in table

I had a similar problem and I needed to insert multiple if not existing. So from the examples above I came to this combination... it's here just in case somebody would need it.

Notice: I had to define name everywhere as MSSQL required it... MySQL works with * too.

INSERT INTO names (name)
SELECT name
FROM
(
  SELECT name
  FROM
  (
     SELECT 'Test 4' as name
  ) AS tmp_single
  WHERE NOT EXISTS
  (
     SELECT name FROM names WHERE name = 'Test 4'
  )
  UNION ALL
  SELECT name
  FROM
  (
     SELECT 'Test 5' as name
  ) AS tmp_single
  WHERE NOT EXISTS
  (
     SELECT name FROM names WHERE name = 'Test 5'
  )
) tmp_all;

MySQL: CREATE TABLE names ( OID int(11) NOT NULL AUTO_INCREMENT, name varchar(32) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (OID), UNIQUE KEY name_UNIQUE (name) ) ENGINE=InnoDB AUTO_INCREMENT=1;

or

MSSQL: CREATE TABLE [names] ( [OID] INT IDENTITY (1, 1) NOT NULL, [name] NVARCHAR (32) NOT NULL, PRIMARY KEY CLUSTERED ([OID] ASC) ); CREATE UNIQUE NONCLUSTERED INDEX [Index_Names_Name] ON [names]([name] ASC);

Pandas How to filter a Series

In [5]:

import pandas as pd

test = {
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
}

s = pd.Series(test)
s = s[s != 1]
s
Out[0]:
383    3.000000
737    9.000000
833    8.166667
dtype: float64

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

This errors occurs when we use same method name for Jaxb2Marshaller for exemple:

    @Bean
    public Jaxb2Marshaller marshallerClient() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        // this package must match the package in the <generatePackage> specified in
        // pom.xml
        marshaller.setContextPath("library.io.github.walterwhites.loans");

        return marshaller;
    }

And on other file

    @Bean
    public Jaxb2Marshaller marshallerClient() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        // this package must match the package in the <generatePackage> specified in
        // pom.xml
        marshaller.setContextPath("library.io.github.walterwhites.client");

        return marshaller;
    }

Even It's different class, you should named them differently

Serialize Property as Xml Attribute in Element

You will need wrapper classes:

public class SomeIntInfo
{
    [XmlAttribute]
    public int Value { get; set; }
}

public class SomeStringInfo
{
    [XmlAttribute]
    public string Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeStringInfo SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeIntInfo SomeInfo { get; set; }
}

or a more generic approach if you prefer:

public class SomeInfo<T>
{
    [XmlAttribute]
    public T Value { get; set; }
}

public class SomeModel
{
    [XmlElement("SomeStringElementName")]
    public SomeInfo<string> SomeString { get; set; }

    [XmlElement("SomeInfoElementName")]
    public SomeInfo<int> SomeInfo { get; set; }
}

And then:

class Program
{
    static void Main()
    {
        var model = new SomeModel
        {
            SomeString = new SomeInfo<string> { Value = "testData" },
            SomeInfo = new SomeInfo<int> { Value = 5 }
        };
        var serializer = new XmlSerializer(model.GetType());
        serializer.Serialize(Console.Out, model);
    }
}

will produce:

<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SomeStringElementName Value="testData" />
  <SomeInfoElementName Value="5" />
</SomeModel>

Redirect From Action Filter Attribute

Alternatively to a redirect, if it is calling your own code, you could use this:

actionContext.Result = new RedirectToRouteResult(
    new RouteValueDictionary(new { controller = "Home", action = "Error" })
);

actionContext.Result.ExecuteResult(actionContext.Controller.ControllerContext);

It is not a pure redirect but gives a similar result without unnecessary overhead.

UITableView example for Swift

The example below is an adaptation and simplification of a longer post from We ? Swift. This is what it will look like:

enter image description here

Create a New Project

It can be just the usual Single View Application.

Add the Code

Replace the ViewController.swift code with the following:

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    // Data model: These strings will be the data for the table view cells
    let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    
    // cell reuse id (cells that scroll out of view can be reused)
    let cellReuseIdentifier = "cell"
    
    // don't forget to hook this up from the storyboard
    @IBOutlet var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Register the table view cell class and its reuse id
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        
        // (optional) include this line if you want to remove the extra empty cell divider lines
        // self.tableView.tableFooterView = UIView()

        // This view controller itself will provide the delegate methods and row data for the table view.
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    // number of rows in table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.animals.count
    }
    
    // create a cell for each table view row
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // create a new cell if needed or reuse an old one
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
        
        // set the text from the data model
        cell.textLabel?.text = self.animals[indexPath.row]
        
        return cell
    }
    
    // method to run when table view cell is tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }
}

Read the in-code comments to see what is happening. The highlights are

  • The view controller adopts the UITableViewDelegate and UITableViewDataSource protocols.
  • The numberOfRowsInSection method determines how many rows there will be in the table view.
  • The cellForRowAtIndexPath method sets up each row.
  • The didSelectRowAtIndexPath method is called every time a row is tapped.

Add a Table View to the Storyboard

Drag a UITableView onto your View Controller. Use auto layout to pin the four sides.

enter image description here

Hook up the Outlets

Control drag from the Table View in IB to the tableView outlet in the code.

Finished

That's all. You should be able run your app now.

This answer was tested with Xcode 9 and Swift 4


Variations

Row Deletion

You only have to add a single method to the basic project above if you want to enable users to delete rows. See this basic example to learn how.

enter image description here

Row Spacing

If you would like to have spacing between your rows, see this supplemental example.

enter image description here

Custom cells

The default layout for the table view cells may not be what you need. Check out this example to help get you started making your own custom cells.

enter image description here

Dynamic Cell Height

Sometimes you don't want every cell to be the same height. Starting with iOS 8 it is easy to automatically set the height depending on the cell content. See this example for everything you need to get you started.

enter image description here

Further Reading

How do I ALTER a PostgreSQL table and make a column unique?

Or, have the DB automatically assign a constraint name using:

ALTER TABLE foo ADD UNIQUE (thecolumn);

How to run VBScript from command line without Cscript/Wscript

You may follow the following steps:

  • Open your CMD(Command Prompt)
  • Type 'D:' and hit Enter. Example: C:\Users\[Your User Name]>D:
  • Type 'CD VBS' and hit Enter. Example: D:>CD VBS
  • Type 'Converter.vbs' or 'start Converter.vbs' and hit Enter. Example: D:\VBS>Converter.vbs Or D:\VBS>start Converter.vbs

Should you use .htm or .html file extension? What is the difference, and which file is correct?

I guess it's a little too late now however the only time it does make a difference is when you set up HTML signatures on MS Outlook (even 2010). It's just not able to handle .html extensions, only .htm

How to enable/disable bluetooth programmatically in android

Here is a bit more robust way of doing this, also handling the return values of enable()\disable() methods:

public static boolean setBluetooth(boolean enable) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean isEnabled = bluetoothAdapter.isEnabled();
    if (enable && !isEnabled) {
        return bluetoothAdapter.enable(); 
    }
    else if(!enable && isEnabled) {
        return bluetoothAdapter.disable();
    }
    // No need to change bluetooth state
    return true;
}

And add the following permissions into your manifest file:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

But remember these important points:

This is an asynchronous call: it will return immediately, and clients should listen for ACTION_STATE_CHANGED to be notified of subsequent adapter state changes. If this call returns true, then the adapter state will immediately transition from STATE_OFF to STATE_TURNING_ON, and some time later transition to either STATE_OFF or STATE_ON. If this call returns false then there was an immediate problem that will prevent the adapter from being turned on - such as Airplane mode, or the adapter is already turned on.

UPDATE:

Ok, so how to implement bluetooth listener?:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                                 BluetoothAdapter.ERROR);
            switch (state) {
            case BluetoothAdapter.STATE_OFF:
                // Bluetooth has been turned off;
                break;
            case BluetoothAdapter.STATE_TURNING_OFF:
                // Bluetooth is turning off;
                break;
            case BluetoothAdapter.STATE_ON:
                // Bluetooth is on
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                // Bluetooth is turning on
                break;
            }
        }
    }
};

And how to register/unregister the receiver? (In your Activity class)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ...

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, filter);
}

@Override
public void onStop() {
    super.onStop();

     // ...

    // Unregister broadcast listeners
    unregisterReceiver(mReceiver);
}

Flexbox and Internet Explorer 11 (display:flex in <html>?)

According to http://caniuse.com/#feat=flexbox:

"IE10 and IE11 default values for flex are 0 0 auto rather than 0 1 auto, as per the draft spec, as of September 2013"

So in plain words, if somewhere in your CSS you have something like this: flex:1 , that is not translated the same way in all browsers. Try changing it to 1 0 0 and I believe you will immediately see that it -kinda- works.

The problem is that this solution will probably mess up firefox, but then you can use some hacks to target only Mozilla and change it back:

@-moz-document url-prefix() {
 #flexible-content{
      flex: 1;
    }
}

Since flexbox is a W3C Candidate and not official, browsers tend to give different results, but I guess that will change in the immediate future.

If someone has a better answer I would like to know!

Reset all the items in a form

You can create the form again and dispose the old one.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnReset_Click(object sender, EventArgs e)
    {
        Form1 NewForm = new Form1();           
        NewForm.Show();
        this.Dispose(false);
    }
}

React Native absolute positioning horizontal centre

If you want to center one element itself you could use alignSelf:

logoImg: {
    position: 'absolute',
    alignSelf: 'center',
    bottom: '-5%'
}

This is an example (Note the logo parent is a view with position: relative)

enter image description here

More elegant way of declaring multiple variables at the same time

Use a list/dictionary or define your own class to encapsulate the stuff you're defining, but if you need all those variables you can do:

a = b = c = d = e = g = h = i = j = True
f = False

Set maxlength in Html Textarea

<p>
   <textarea id="msgc" onkeyup="cnt(event)" rows="1" cols="1"></textarea> 
</p> 
<p id="valmess2" style="color:red" ></p>

function cnt(event)
{ 
 document.getElementById("valmess2").innerHTML=""; // init and clear if b < max     
allowed character 

 a = document.getElementById("msgc").value; 
 b = a.length; 
 if (b > 400)
  { 
   document.getElementById("valmess2").innerHTML="the max length of 400 characters is 
reached, you typed in  " + b + "characters"; 
  } 
}

maxlength is only valid for HTML5. For HTML/XHTML you have to use JavaScript and/or PHP. With PHP you can use strlen for example.This example indicates only the max length, it's NOT blocking the input.

SOAP-UI - How to pass xml inside parameter

Either encode the needed XML entities or use CDATA.

<arg0>
    <!--Optional:-->
    <parameter1>&lt;test>like this&lt;/test></parameter1>
    <!--Optional:-->
    <parameter2><![CDATA[<test>or like this</test>]]></parameter2>
 </arg0>

PHP cURL, extract an XML response

<?php
function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);          
    curl_close($ch);
    return $retValue;
}

$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);

foreach($oXML->entry as $oEntry){
    echo $oEntry->title . "\n";
}

Reset par to the default values at startup

Every time a new device is opened par() will reset, so another option is simply do dev.off() and continue.

HttpGet with HTTPS : SSLPeerUnverifiedException

This answer follows on to owlstead and Mat's responses. It applies to SE/EE installations, not ME/mobile/Android SSL.

Since no one has yet mentioned it, I'll mention the "production way" to fix this: Follow the steps from the AuthSSLProtocolSocketFactory class in HttpClient to update your trust store & key stores.

  1. Import a trusted certificate and generate a truststore file

keytool -import -alias "my server cert" -file server.crt -keystore my.truststore

  1. Generate a new key (use the same password as the truststore)

keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore

  1. Issue a certificate signing request (CSR)

keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore

  1. (self-sign or get your cert signed)

  2. Import the trusted CA root certificate

keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore

  1. Import the PKCS#7 file containg the complete certificate chain

keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore

  1. Verify the resultant keystore file's contents

keytool -list -v -keystore my.keystore

If you don't have a server certificate, generate one in JKS format, then export it as a CRT file. Source: keytool documentation

keytool -genkey -alias server-alias -keyalg RSA -keypass changeit
    -storepass changeit -keystore my.keystore

keytool -export -alias server-alias -storepass changeit
    -file server.crt -keystore my.keystore

Google Maps API 3 - Custom marker color for default (dot) marker

If you use Google Maps API v3 you can use setIcon e.g.

marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')

Or as part of marker init:

marker = new google.maps.Marker({
    icon: 'http://...'
});

Other colours:

Use the following piece of code to update default markers with different colors.

(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)

Apache POI Excel - how to configure columns to be expanded?

If you know the count of your columns (f.e. it's equal to a collection list). You can simply use this one liner to adjust all columns of one sheet (if you use at least java 8):

IntStream.range(0, columnCount).forEach((columnIndex) -> sheet.autoSizeColumn(columnIndex));

List of All Folders and Sub-folders

As well as find listed in other answers, better shells allow both recurvsive globs and filtering of glob matches, so in zsh for example...

ls -lad **/*(/)

...lists all directories while keeping all the "-l" details that you want, which you'd otherwise need to recreate using something like...

find . -type d -exec ls -ld {} \;

(not quite as easy as the other answers suggest)

The benefit of find is that it's more independent of the shell - more portable, even for system() calls from within a C/C++ program etc..

C#: Assign same value to multiple variables in single statement

It is simple.

int num1,num2;
num1 = num2 = 5;

Selenium using Python - Geckodriver executable needs to be in PATH

Some additional input/clarification for future readers of this thread:

The following suffices as a resolution for Windows 7, Python 3.6, and Selenium 3.11:

dsalaj's note for another answer for Unix is applicable to Windows as well; tinkering with the PATH environment variable at the Windows level and restart of the Windows system can be avoided.

(1) Download geckodriver (as described in this thread earlier) and place the (unzipped) geckdriver.exe at X:\Folder\of\your\choice

(2) Python code sample:

import os;
os.environ["PATH"] += os.pathsep + r'X:\Folder\of\your\choice';

from selenium import webdriver;
browser = webdriver.Firefox();
browser.get('http://localhost:8000')
assert 'Django' in browser.title

Notes: (1) It may take about 10 seconds for the above code to open up the Firefox browser for the specified URL. (2) The Python console would show the following error if there's no server already running at the specified URL or serving a page with the title containing the string 'Django': selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=connectionFailure&u=http%3A//localhost%3A8000/&c=UTF-8&f=regular&d=Firefox%20can%E2%80%9

PostgreSQL: insert from another table

You could use coalesce:

insert into destination select coalesce(field1,'somedata'),... from source;

jQuery exclude elements with certain class in selector

use this..

$(".content_box a:not('.button')")

Change working directory in my current shell context when running Node script

Short answer: no (easy?) way, but you can do something that serves your purpose.

I've done a similar tool (a small command that, given a description of a project, sets environment, paths, directories, etc.). What I do is set-up everything and then spawn a shell with:

spawn('bash', ['-i'], {
  cwd: new_cwd,
  env: new_env,
  stdio: 'inherit'
});

After execution, you'll be on a shell with the new directory (and, in my case, environment). Of course you can change bash for whatever shell you prefer. The main differences with what you originally asked for are:

  • There is an additional process, so...
  • you have to write 'exit' to come back, and then...
  • after existing, all changes are undone.

However, for me, that differences are desirable.

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

For whom is using GitLab runners:

  • Be sure to run the runner with an account that you can logon to: ./gitlab-runner.exe install --user ".\ENTER-YOUR-USERNAME" --password "ENTER-YOUR-PASSWORD" (I had to stop and uninstall first)
  • follow this guide to grant the build user permission to login as a service
  • logon with such build user
  • use the command suggested in other answers: sn -i certificate.pfx VS_KEY_C***6

the container name is suggested in the failed Job output on GitLab (msbuild output) enter image description here

Best way to handle multiple constructors in Java

Some general constructor tips:

  • Try to focus all initialization in a single constructor and call it from the other constructors
    • This works well if multiple constructors exist to simulate default parameters
  • Never call a non-final method from a constructor
    • Private methods are final by definition
    • Polymorphism can kill you here; you can end up calling a subclass implementation before the subclass has been initialized
    • If you need "helper" methods, be sure to make them private or final
  • Be explicit in your calls to super()
    • You would be surprised at how many Java programmers don't realize that super() is called even if you don't explicitly write it (assuming you don't have a call to this(...) )
  • Know the order of initialization rules for constructors. It's basically:

    1. this(...) if present (just move to another constructor)
    2. call super(...) [if not explicit, call super() implicitly]
    3. (construct superclass using these rules recursively)
    4. initialize fields via their declarations
    5. run body of current constructor
    6. return to previous constructors (if you had encountered this(...) calls)

The overall flow ends up being:

  • move all the way up the superclass hierarchy to Object
  • while not done
    • init fields
    • run constructor bodies
    • drop down to subclass

For a nice example of evil, try figuring out what the following will print, then run it

package com.javadude.sample;

/** THIS IS REALLY EVIL CODE! BEWARE!!! */
class A {
    private int x = 10;
    public A() {
        init();
    }
    protected void init() {
        x = 20;
    }
    public int getX() {
        return x;
    }
}

class B extends A {
    private int y = 42;
    protected void init() {
        y = getX();
    }
    public int getY() {
        return y;
    }
}

public class Test {
    public static void main(String[] args) {
        B b = new B();
        System.out.println("x=" + b.getX());
        System.out.println("y=" + b.getY());
    }
}

I'll add comments describing why the above works as it does... Some of it may be obvious; some is not...