Programs & Examples On #Qtcpsocket

The QTcpSocket class, part of the Qt framework, provides a TCP socket.

How to create hyperlink to call phone number on mobile devices?

You can also use callto:########### replacing the email code mail with call, at least according to W3Cschool site but I haven't had an opportunity to test it out.

Naming conventions for Java methods that return boolean

is is the one I've come across more than any other. Whatever makes sense in the current situation is the best option though.

Sending simple message body + file attachment using Linux Mailx

Try this it works for me:

(echo "Hello XYX" ; uuencode /export/home/TOTAL_SI_COUNT_10042016.csv TOTAL_SI_COUNT_10042016.csv ) | mailx -s 'Script test' [email protected]

Opening database file from within SQLite command-line shell

The same way you do it in other db system, you can use the name of the db for identifying double named tables. unique tablenames can used directly.

select * from ttt.table_name;

or if table name in all attached databases is unique

select * from my_unique_table_name;

But I think the of of sqlite-shell is only for manual lookup or manual data manipulation and therefor this way is more inconsequential

normally you would use sqlite-command-line in a script

Chrome / Safari not filling 100% height of flex parent

Solution

Use nested flex containers.

Get rid of percentage heights. Get rid of table properties. Get rid of vertical-align. Avoid absolute positioning. Just stick with flexbox all the way through.

Apply display: flex to the flex item (.item), making it a flex container. This automatically sets align-items: stretch, which tells the child (.item-inner) to expand the full height of the parent.

Important: Remove specified heights from flex items for this method to work. If a child has a height specified (e.g. height: 100%), then it will ignore the align-items: stretch coming from the parent. For the stretch default to work, the child's height must compute to auto (full explanation).

Try this (no changes to HTML):

_x000D_
_x000D_
.container {_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    height: 20em;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
.item {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;_x000D_
    border-bottom: 1px solid white;_x000D_
}_x000D_
_x000D_
.item-inner {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
_x000D_
    /* height: 100%;                    <-- remove; unnecessary */_x000D_
    /* width: 100%;                     <-- remove; unnecessary */_x000D_
    /* display: table;                  <-- remove; unnecessary */  _x000D_
}_x000D_
_x000D_
a {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
    align-items: center;                /* new; vertically center text */_x000D_
    background: orange;_x000D_
_x000D_
    /* display: table-cell;             <-- remove; unnecessary */_x000D_
    /* vertical-align: middle;          <-- remove; unnecessary */_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle demo


Explanation

My problem is that .item-inner { height: 100% } is not working in webkit (Chrome).

It's not working because you're using percentage height in a way that doesn't conform with the traditional implementation of the spec.

10.5 Content height: the height property

percentage
Specifies a percentage height. The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly and this element is not absolutely positioned, the value computes to auto.

auto
The height depends on the values of other properties.

In other words, for percentage height to work on an in-flow child, the parent must have a set height.

In your code, the top-level container has a defined height: .container { height: 20em; }

The third-level container has a defined height: .item-inner { height: 100%; }

But between them, the second-level container – .itemdoes not have a defined height. Webkit sees that as a missing link.

.item-inner is telling Chrome: give me height: 100%. Chrome looks to the parent (.item) for reference and responds: 100% of what? I don't see anything (ignoring the flex: 1 rule that is there). As a result, it applies height: auto (content height), in accordance with the spec.

Firefox, on the other hand, now accepts a parent's flex height as a reference for the child's percentage height. IE11 and Edge accept flex heights, as well.

Also, Chrome will accept flex-grow as an adequate parent reference if used in conjunction with flex-basis (any numerical value works (auto won't), including flex-basis: 0). As of this writing, however, this solution fails in Safari.

_x000D_
_x000D_
#outer {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 300px;_x000D_
  background-color: white;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
#middle {_x000D_
  flex-grow: 1;_x000D_
  flex-basis: 1px;_x000D_
  background-color: yellow;_x000D_
}_x000D_
#inner {_x000D_
  height: 100%;_x000D_
  background-color: lightgreen;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="middle">_x000D_
    <div id="inner">_x000D_
      INNER_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Four Solutions

1. Specify a height on all parent elements

A reliable cross-browser solution is to specify a height on all parent elements. This prevents missing links, which Webkit-based browsers consider a violation of the spec.

Note that min-height and max-height are not acceptable. It must be the height property.

More details here: Working with the CSS height property and percentage values

2. CSS Relative & Absolute Positioning

Apply position: relative to the parent and position: absolute to the child.

Size the child with height: 100% and width: 100%, or use the offset properties: top: 0, right: 0, bottom: 0, left: 0.

With absolute positioning, percentage height works without a specified height on the parent.

3. Remove unnecessary HTML containers (recommended)

Is there a need for two containers around button? Why not remove .item or .item-inner, or both? Although button elements sometimes fail as flex containers, they can be flex items. Consider making button a child of .container or .item, and removing gratuitous mark-up.

Here's an example:

_x000D_
_x000D_
.container {_x000D_
    height: 20em;_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
a {_x000D_
    flex: 1;_x000D_
    background: orange;_x000D_
    border-bottom: 1px solid white;_x000D_
    display: flex;                   /* nested flex container (for aligning text) */_x000D_
    align-items: center;             /* center text vertically */_x000D_
    justify-content: center;         /* center text horizontally */_x000D_
}
_x000D_
<div class="container">_x000D_
    <a>Button</a>_x000D_
    <a>Button</a>_x000D_
    <a>Button</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

4. Nested Flex Containers (recommended)

Get rid of percentage heights. Get rid of table properties. Get rid of vertical-align. Avoid absolute positioning. Just stick with flexbox all the way through.

Apply display: flex to the flex item (.item), making it a flex container. This automatically sets align-items: stretch, which tells the child (.item-inner) to expand the full height of the parent.

Important: Remove specified heights from flex items for this method to work. If a child has a height specified (e.g. height: 100%), then it will ignore the align-items: stretch coming from the parent. For the stretch default to work, the child's height must compute to auto (full explanation).

Try this (no changes to HTML):

_x000D_
_x000D_
.container {_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    height: 20em;_x000D_
    border: 5px solid black_x000D_
}_x000D_
_x000D_
.item {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;_x000D_
    border-bottom: 1px solid white;_x000D_
}_x000D_
_x000D_
.item-inner {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
_x000D_
    /* height: 100%;                    <-- remove; unnecessary */_x000D_
    /* width: 100%;                     <-- remove; unnecessary */_x000D_
    /* display: table;                  <-- remove; unnecessary */  _x000D_
}_x000D_
_x000D_
a {_x000D_
    display: flex;                      /* new; nested flex container */_x000D_
    flex: 1;                            /* new */_x000D_
    align-items: center;                /* new; vertically center text */_x000D_
    background: orange;_x000D_
_x000D_
    /* display: table-cell;             <-- remove; unnecessary */_x000D_
    /* vertical-align: middle;          <-- remove; unnecessary */_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div class="item">_x000D_
    <div class="item-inner">_x000D_
      <a>Button</a>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

Android ListView selected item stay highlighted

Simplistic way is,if you are using listview in a xml,use this attributes on your listview,

android:choiceMode="singleChoice"
android:listSelector="#your color code"

if not using xml,by programatically

listview.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listview.setSelector(android.R.color.holo_blue_light);

NoClassDefFoundError in Java: com/google/common/base/Function

I had the same problem, and finally I found that I forgot to add the selenium-server-standalone-version.jar. I had only added the client jar, selenium-java-version.jar.

Hope this helps.

How to add and get Header values in WebApi

Another way using a the TryGetValues method.

public string Postsam([FromBody]object jsonData)
{
    IEnumerable<string> headerValues;

    if (Request.Headers.TryGetValues("Custom", out headerValues))
    {
        string token = headerValues.First();
    }
}   

How to Compare a long value is equal to Long value

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if(a == b.longValue())
    {
        System.out.println("Equals");
    }else{
        System.out.println("not equals");
    }
  }

or:

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if(a == b)
    {
        System.out.println("Equals");
    }else{
        System.out.println("not equals");
    }
  }

How to add spacing between UITableViewCell

Using a bunch of different sections is not needed. The other answers use frame insets and CGRect and layers and... BLAH. Not good; use auto layout and a custom UITableViewCell. In that UITableViewCell, instead of sub viewing your content inside the contentView, make a new containerView (a UIView), subview the container view inside the contentView, then subview all your views inside the container view.

To make the spacing now, simply edit the layout margins of the container view, like so:

class CustomTableViewCell: UITableViewCell {
    let containerView = UIView()
    let imageView = UIImageView()

    required init?(coder aDecoder: NSCoder) {super.init(coder: aDecoder)}

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        containerView.translatesAutoResizingMaskIntoConstraints = false
        imageView.translatesAutoResizingMaskIntoConstraints = false
        contentView.addSubview(containerView)
        containerView.addSubview(imageView)

        contentView.layoutMargins = UIEdgeInsets(top: 15, left: 3, bottom: 15, right: 3)
        containerView.layoutMargins = UIEdgeInsets(top: 15, left: 17, bottom: 15, right: 17) // It isn't really necessary unless you've got an extremely complex table view cell. Otherwise, you could just write e.g. containerView.topAnchor

        let cg = contentView.layoutMarginsGuide
        let lg = containerView.layoutMarginsGuide
        NSLayoutConstraint.activate([
            containerView.topAnchor.constraint(equalTo: cg.topAnchor),
            containerView.leadingAnchor.constraint(equalTo: cg.leadingAnchor),
            containerView.trailingAnchor.constraint(equalTo: cg.trailingAnchor),
            containerView.bottomAnchor.constraint(equalTo: cg.bottomAnchor),
            imageView.topAnchor.constraint(equalTo: lg.topAnchor),
            imageView.leadingAnchor.constraint(equalTo: lg.leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: lg.trailingAnchor),
            imageView.bottomAnchor.constraint(equalTo: lg.bottomAnchor)
        ])
    }
}

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Please ensure that you have following import. Ofcourse other standard imports

import org.springframework.core.io.FileSystemResource


    void uploadzipFiles(String token) {

        RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)

        def zipFile = new File("testdata.zip")
        def Id = "001G00000"
        MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
        form.add("id", id)
        form.add('file',new FileSystemResource(zipFile))
        def urld ='''http://URL''';
        def resp = rest.post(urld) {
            header('X-Auth-Token', clientSecret)
            contentType "multipart/form-data"
            body(form)
        }
        println "resp::"+resp
        println "resp::"+resp.text
        println "resp::"+resp.headers
        println "resp::"+resp.body
        println "resp::"+resp.status
    }

Printing to the console in Google Apps Script?

Answering the OP questions

A) What do I not understand about how the Google Apps Script console works with respect to printing so that I can see if my code is accomplishing what I'd like?

The code on .gs files of a Google Apps Script project run on the server rather than on the web browser. The way to log messages was to use the Class Logger.

B) Is it a problem with the code?

As the error message said, the problem was that console was not defined but nowadays the same code will throw other error:

ReferenceError: "playerArray" is not defined. (line 12, file "Code")

That is because the playerArray is defined as local variable. Moving the line out of the function will solve this.

var playerArray = [];

function addplayerstoArray(numplayers) {
  for (i=0; i<numplayers; i++) {
    playerArray.push(i);
  }
}  

addplayerstoArray(7);

console.log(playerArray[3])

Now that the code executes without throwing errors, instead to look at the browser console we should look at the Stackdriver Logging. From the Google Apps Script editor UI click on View > Stackdriver Logging.

Addendum

On 2017 Google released to all scripts Stackdriver Logging and added the Class Console, so including something like console.log('Hello world!') will not throw an error but the log will be on Google Cloud Platform Stackdriver Logging Service instead of the browser console.

From Google Apps Script Release Notes 2017

June 23, 2017

Stackdriver Logging has been moved out of Early Access. All scripts now have access to Stackdriver logging.

From Logging > Stackdriver logging

The following example shows how to use the console service to log information in Stackdriver.

function measuringExecutionTime() {
  // A simple INFO log message, using sprintf() formatting.
  console.info('Timing the %s function (%d arguments)', 'myFunction', 1);

  // Log a JSON object at a DEBUG level. The log is labeled
  // with the message string in the log viewer, and the JSON content
  // is displayed in the expanded log structure under "structPayload".
  var parameters = {
      isValid: true,
      content: 'some string',
      timestamp: new Date()
  };
  console.log({message: 'Function Input', initialData: parameters});

  var label = 'myFunction() time';  // Labels the timing log entry.
  console.time(label);              // Starts the timer.
  try {
    myFunction(parameters);         // Function to time.
  } catch (e) {
    // Logs an ERROR message.
    console.error('myFunction() yielded an error: ' + e);
  }
  console.timeEnd(label);      // Stops the timer, logs execution duration.
}

super() in Java

Source article: Java: Calling super()


Yes. super(...) will invoke the constructor of the super-class.

Illustration:

enter image description here


Stand alone example:

class Animal {
    public Animal(String arg) {
        System.out.println("Constructing an animal: " + arg);
    }
}

class Dog extends Animal {
    public Dog() {
        super("From Dog constructor");
        System.out.println("Constructing a dog.");
    }
}

public class Test {
    public static void main(String[] a) {
        new Dog();
    }
}

Prints:

Constructing an animal: From Dog constructor
Constructing a dog.

How to get json key and value in javascript?

you have parse that Json string using JSON.parse()

..
}).done(function(data){
    obj = JSON.parse(data);
    alert(obj.jobtitel);
});

Using Cookie in Asp.Net Mvc 4

We are using Response.SetCookie() for update the old one cookies and Response.Cookies.Add() are use to add the new cookies. Here below code CompanyId is update in old cookie[OldCookieName].

HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

In my case, because I had reinstalled iis, I needed to register iis with dot net 4 using this command:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

sqlalchemy filter multiple columns

You can simply call filter multiple times:

query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
                                 filter(User.lastname.like(searchVar2))

Changing Underline color

You can wrap your <span> with a <a> and use this little JQuery plugin to color the underline. You can modify the color by passing a parameter to the plugin.

    (function ($) {
        $.fn.useful = function (params) {

            var aCSS = {
                'color' : '#d43',
                'text-decoration' : 'underline'
            };

            $.extend(aCSS, params);

            this.wrap('<a></a>');
            var element = this.closest('a');
            element.css(aCSS);
            return element;
        };
    })(jQuery);

Then you call by writing this :

    $("span.name").useful({color:'red'});

_x000D_
_x000D_
$(function () {_x000D_
_x000D_
        var spanCSS = {_x000D_
            'color' : '#000',_x000D_
            'text-decoration': 'none'_x000D_
        };_x000D_
        _x000D_
        $.fn.useful = function (params) {_x000D_
            _x000D_
            var aCSS = {_x000D_
                'color' : '#d43',_x000D_
                'text-decoration' : 'underline'_x000D_
            };_x000D_
_x000D_
            $.extend(aCSS, params);_x000D_
            this.wrap('<a></a>');_x000D_
            this.closest('a').css(aCSS);_x000D_
        };_x000D_
_x000D_
        // Use example:_x000D_
        $("span.name").css(spanCSS).useful({color:'red'});_x000D_
_x000D_
_x000D_
_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<section class="container">_x000D_
_x000D_
    <div class="user important">_x000D_
        <span class="name">Bob</span>_x000D_
        -_x000D_
        <span class="location">Bali</span>_x000D_
    </div>_x000D_
_x000D_
    <div class="user">_x000D_
        <span class="name">Dude</span>_x000D_
        -_x000D_
        <span class="location">Los Angeles</span>_x000D_
    </div>_x000D_
_x000D_
_x000D_
    <div class="user">_x000D_
        <span class="name">Gérard</span>_x000D_
        -_x000D_
        <span class="location">Paris</span>_x000D_
    </div>_x000D_
_x000D_
</section>
_x000D_
_x000D_
_x000D_

How to calculate mean, median, mode and range from a set of numbers

If you only care about unimodal distributions, consider sth. like this.

public static Optional<Integer> mode(Stream<Integer> stream) {
    Map<Integer, Long> frequencies = stream
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    return frequencies.entrySet().stream()
        .max(Comparator.comparingLong(Map.Entry::getValue))
        .map(Map.Entry::getKey);
}

What does the keyword Set actually do in VBA?

Off the top of my head, Set is used to assign COM objects to variables. By doing a Set I suspect that under the hood it's doing an AddRef() call on the object to manage it's lifetime.

error: expected declaration or statement at end of input in c

Try to place a

return 0;

on the end of your code or just erase the

void

from your main function I hope that I helped

JavaScript check if variable exists (is defined/initialized)

You want the typeof operator. Specifically:

if (typeof variable !== 'undefined') {
    // the variable is defined
}

Use SELECT inside an UPDATE query

I had a similar problem. I wanted to find a string in one column and put that value in another column in the same table. The select statement below finds the text inside the parens.

When I created the query in Access I selected all fields. On the SQL view for that query, I replaced the mytable.myfield for the field I wanted to have the value from inside the parens with

SELECT Left(Right(OtherField,Len(OtherField)-InStr((OtherField),"(")), 
            Len(Right(OtherField,Len(OtherField)-InStr((OtherField),"(")))-1) 

I ran a make table query. The make table query has all the fields with the above substitution and ends with INTO NameofNewTable FROM mytable

Connecting to SQL Server with Visual Studio Express Editions

You should be able to choose the SQL Server Database file option to get the right kind of database (the system.data.SqlClient provider), and then manually correct the connection string to point to your db.

I think the reasoning behind those db choices probably goes something like this:

  • If you're using the Express Edition, and you're not using Visual Web Developer, you're probably building a desktop program.
  • If you're building a desktop program, and you're using the express edition, you're probably a hobbyist or uISV-er working at home rather than doing development for a corporation.
  • If you're not developing for a corporation, your app is probably destined for the end-user and your data store is probably going on their local machine.
  • You really shouldn't be deploying server-class databases to end-user desktops. An in-process db like Sql Server Compact or MS Access is much more appropriate.

However, this logic doesn't quite hold. Even if each of those 4 points is true 90% of the time, by the time you apply all four of them it only applies to ~65% of your audience, which means up to 35% of the express market might legitimately want to talk to a server-class db, and that's a significant group. And so, the simplified (greedy) version:

  • A real db server (and the hardware to run it) costs real money. If you have access to that, you ought to be able to afford at least the standard edition of visual studio.

Convert int (number) to string with leading zeros? (4 digits)

Use the formatting options available to you, use the Decimal format string. It is far more flexible and requires little to no maintenance compared to direct string manipulation.

To get the string representation using at least 4 digits:

int length = 4;
int number = 50;
string asString = number.ToString("D" + length); //"0050"

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.

The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.

What is the difference between connection and read timeout for sockets?

  1. What is the difference between connection and read timeout for sockets?

The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.

  1. What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?

It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt() call may also do the trick ... not sure.)

  1. What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?

It means that a call to read on the socket stream may block for ever. Once again there is no infinite loop, but the read can be unblocked by a Thread.interrupt() call, closing the socket, and (of course) the other end sending data or closing the connection.


1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.

Basic text editor in command prompt?

You can install vim/vi for windows and set windows PATH variable and open it in command line.

Passing arguments to JavaScript function from code-behind

Response.Write("<scrip" + "t>test(" + x + "," + y + ");</script>");

breaking up the script keyword because VStudio / asp.net compiler doesn't like it

Print ArrayList

From what I understand you are trying to print an ArrayList of arrays and one way to display that would be

System.out.println(Arrays.deepToString(list.toArray()));

How to compare DateTime without time via LINQ?

Try this code

var today = DateTime.Today;
var q = db.Games.Where(t => DbFunctions.TruncateTime(t.StartDate) <= today);

How to auto adjust table td width from the content

Use this style attribute for no word wrapping:

white-space: nowrap;

Compare two DataFrames and output their differences side-by-side

pandas >= 1.1: DataFrame.compare

With pandas 1.1, you could essentially replicate Ted Petrou's output with a single function call. Example taken from the docs:

pd.__version__
# '1.1.0'

df1.compare(df2)

  score       isEnrolled       Comment             
   self other       self other    self        other
1  1.11  1.21        NaN   NaN     NaN          NaN
2   NaN   NaN        1.0   0.0     NaN  On vacation

Here, "self" refers to the LHS dataFrame, while "other" is the RHS DataFrame. By default, equal values are replaced with NaNs so you can focus on just the diffs. If you want to show values that are equal as well, use

df1.compare(df2, keep_equal=True, keep_shape=True) 

  score       isEnrolled           Comment             
   self other       self  other       self        other
1  1.11  1.21      False  False  Graduated    Graduated
2  4.12  4.12       True  False        NaN  On vacation

You can also change the axis of comparison using align_axis:

df1.compare(df2, align_axis='index')

         score  isEnrolled      Comment
1 self    1.11         NaN          NaN
  other   1.21         NaN          NaN
2 self     NaN         1.0          NaN
  other    NaN         0.0  On vacation

This compares values row-wise, instead of column-wise.

Checkbox angular material checked by default

Set this in HTML:

    <div class="modal-body " [formGroup]="Form">
        <div class="">
            <mat-checkbox formControlName="a" [disabled]="true"> Display 1</mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="b"  [disabled]="true">  Display 2 </mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="c"  [disabled]="true">  Display 3 </mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="d"  [disabled]="true">  Display 4</mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="e"  [disabled]="true"> Display 5 </mat-checkbox>
        </div>
    </div>

Changes in Ts file

this.Form = this.formBuilder.group({
a: false,
b: false,
c: false,
d: false,
e: false,
});

Conditionvalidation in Ur Business logic

if(true){
this.Form.patch(a: true);
}

How to configure port for a Spring Boot application

This worked for me :

Added a custom container class :

@Component
public class CustomContainer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
       configurableEmbeddedServletContainer.setPort(8888);
    }

}

But this was still not using port 8888.

Then I set "scanBasePackages" property like this on "@SpringBootApplication" class on my main method: (scanBasePackages = {"custom container package"})

@SpringBootApplication(scanBasePackages = {"com.javabrains.util"})
public class CourseApiApp {

    public static void main (String args []) {
        SpringApplication.run(CourseApiApp.class, args);
    }
}

And it started picking up port set in Custom Container.

Spring Security with roles and permissions

To implement that, it seems that you have to:

  1. Create your model (user, role, permissions) and a way to retrieve permissions for a given user;
  2. Define your own org.springframework.security.authentication.ProviderManager and configure it (set its providers) to a custom org.springframework.security.authentication.AuthenticationProvider. This last one should return on its authenticate method a Authentication, which should be setted with the org.springframework.security.core.GrantedAuthority, in your case, all the permissions for the given user.

The trick in that article is to have roles assigned to users, but, to set the permissions for those roles in the Authentication.authorities object.

For that I advise you to read the API, and see if you can extend some basic ProviderManager and AuthenticationProvider instead of implementing everything. I've done that with org.springframework.security.ldap.authentication.LdapAuthenticationProvider setting a custom LdapAuthoritiesPopulator, that would retrieve the correct roles for the user.

Hope this time I got what you are looking for. Good luck.

how to convert java string to Date object

var startDate = "06/27/2007";
startDate = new Date(startDate);

console.log(startDate);

git push: permission denied (public key)

I am running Ubuntu 16.04

Removing the remote origin using

git remote rm origin

setting the http url using

git remote add origin https://github.com/<<Entire Path of the new Repo>>

git push origin master

Above steps successfully added code to repo.

Uncaught TypeError: Cannot read property 'appendChild' of null

Use querySelector insted of getElementById();

var c = document.querySelector('#mainContent');
    c.appendChild(document.createElement('div'));

How can I add the sqlite3 module to Python?

if you have error in Sqlite built in python you can use Conda to solve this conflict

conda install sqlite

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

My solution based on the ideas above.

function pageLoad() {
    var element = document.querySelector('table[id*=_fixedTable] > tbody > tr:last-child > td:last-child > div');
    if (element) {
        element.style.overflow = "visible";
    } 
}

It's not limited to a certain id plus you don't need to include any other library such as jQuery.

How to exit in Node.js

If you're in Windows, go to Task Manager, then go to Processes, look for a process called "node", then click on it with the right button of your mouse and then click the "End Process" option.

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

This problem also arises when you have mockito-all on your class path, which is already deprecated.

If possible just include mockito-core.

Maven config for mixing junit, mockito and hamcrest:

<dependencies>
  <dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-core</artifactId>
    <version>1.3</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.9.5</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>
</dependencies>

Proper way to return JSON using node or Express

You can just prettify it using pipe and one of many processor. Your app should always response with as small load as possible.

$ curl -i -X GET http://echo.jsontest.com/key/value/anotherKey/anotherValue | underscore print

https://github.com/ddopson/underscore-cli

Changing width property of a :before css selector using JQuery

As Boltclock states in his answer to Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery

Although they are rendered by browsers through CSS as if they were like other real DOM elements, pseudo-elements themselves are not part of the DOM, and thus you can't select and manipulate them with jQuery.

Might just be best to set the style with jQuery instead of using the pseudo CSS selector.

Iterating over each line of ls -l output

As already mentioned, awk is the right tool for this. If you don't want to use awk, instead of parsing output of "ls -l" line by line, you could iterate over all files and do an "ls -l" for each individual file like this:

for x in * ; do echo `ls -ld $x` ; done

What is the default database path for MongoDB?

For a Windows machine start the mongod process by specifying the dbpath:

mongod --dbpath \mongodb\data

Reference: Manage mongod Processes

CSV in Python adding an extra carriage return, on Windows

Note that if you use DictWriter, you will have a new line from the open function and a new line from the writerow function. You can use newline='' within the open function to remove the extra newline.

Return multiple values to a method caller

Now that C# 7 has been released, you can use the new included Tuples syntax

(string, string, string) LookupName(long id) // tuple return type
{
    ... // retrieve first, middle and last from data storage
    return (first, middle, last); // tuple literal
}

which could then be used like this:

var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");

You can also provide names to your elements (so they are not "Item1", "Item2" etc). You can do it by adding a name to the signature or the return methods:

(string first, string middle, string last) LookupName(long id) // tuple elements have names

or

return (first: first, middle: middle, last: last); // named tuple elements in a literal

They can also be deconstructed, which is a pretty nice new feature:

(string first, string middle, string last) = LookupName(id1); // deconstructing declaration

Check out this link to see more examples on what can be done :)

How do I use itertools.groupby()?

A neato trick with groupby is to run length encoding in one line:

[(c,len(list(cgen))) for c,cgen in groupby(some_string)]

will give you a list of 2-tuples where the first element is the char and the 2nd is the number of repetitions.

Edit: Note that this is what separates itertools.groupby from the SQL GROUP BY semantics: itertools doesn't (and in general can't) sort the iterator in advance, so groups with the same "key" aren't merged.

How to extract epoch from LocalDate and LocalDateTime?

'Millis since unix epoch' represents an instant, so you should use the Instant class:

private long toEpochMilli(LocalDateTime localDateTime)
{
  return localDateTime.atZone(ZoneId.systemDefault())
    .toInstant().toEpochMilli();
}

adb command for getting ip address assigned by operator

To get all IPs (WIFI and data SIM) even on a non-rooted phone in 2019 use:

adb shell ip -o a

The output looks like:

1: lo    inet 127.0.0.1/8 scope host lo\       valid_lft forever preferred_lft forever
1: lo    inet6 ::1/128 scope host \       valid_lft forever preferred_lft forever
3: dummy0    inet6 fe80::489c:2ff:fe4a:00005/64 scope link \       valid_lft forever preferred_lft forever
11: rmnet_data1    inet6 fe80::735d:50fb:2e2:0000/64 scope link \       valid_lft forever preferred_lft forever
21: r_rmnet_data0    inet6 fe80::e38:ce2a:523a:0000/64 scope link \       valid_lft forever preferred_lft forever
30: wlan0    inet 192.168.178.0/24 brd 192.168.178.255 scope global wlan0\       valid_lft forever preferred_lft forever
30: wlan0    inet6 fe80::c2ee:fbff:fe4a:0000/64 scope link \       valid_lft forever preferred_lft forever

You can connect either through adb shell or run the comman ip -o a directly in a terminal emulator. Again, no root required.

'Missing contentDescription attribute on image' in XML

Add android:contentDescription="@string/description" (static or dynamic) to your ImageView. Please do not ignore nor filter the message, because it is helpfull for people using alternative input methods because of their disability (Like TalkBack, Tecla Access Shield etc etc).

Find the number of employees in each department - SQL Oracle

select  d.dname
       ,count(e.empno) as count 
from dept d 
left outer join emp e 
  on e.deptno=d.deptno 
group by d.dname;

Amazon products API - Looking for basic overview and information

I agree that Amazon appears to be intentionally obfuscating even how to find the API documentation, as well as use it. I'm just speculating though.

Renaming the services from "ECS" to "Product Advertising API" was probably also not the best move, it essentially invalidated all that Google mojo they had built up over time.

It took me quite a while to 'discover' this updated link for the Product Advertising API. I don't remember being able to easily discover it through the typical 'Developer' link on the Amazon webpage. This documentation appears to valid and what I've worked from recently.

The change to authentication procedures also seems to add further complexity, but I'm sure they have a reason for it.

I use SOAP via C# to communicate with Amazon Product API.

With the REST API you have to encrypt the whole URL in a fairly specific way. The params have to be sorted, etc. There is just more to do. With the SOAP API, you just encrypt the operation+timestamp, and thats it.

Adam O'Neil's post here, How to get album, dvd, and blueray cover art from Amazon, walks through the SOAP with C# method. Its not the original sample I pulled down, and contrary to his comment, it was not an official Amazon sample I stumbled on, though the code looks identical. However, Adam does a good job at presenting all the necessary steps. I wish I could credit the original author.

Custom Date Format for Bootstrap-DatePicker

var type={
      format:"DD, d MM, yy"
};
$('.classname').datepicker(type.format);

insert multiple rows into DB2 database

UPDATE - Even less wordy version

INSERT INTO tableName (col1, col2, col3, col4, col5) 
VALUES ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5')

The following also works for DB2 and is slightly less wordy

INSERT INTO tableName (col1, col2, col3, col4, col5) 
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5')

Executable directory where application is running from?

You could use the static StartupPath property of the Application class.

Number input type that takes only integers?

var valKeyDown;
var valKeyUp;


function integerOnly(e) {
    e = e || window.event;
    var code = e.which || e.keyCode;
    if (!e.ctrlKey) {
        var arrIntCodes1 = new Array(96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 8, 9, 116);   // 96 TO 105 - 0 TO 9 (Numpad)
        if (!e.shiftKey) {                          //48 to 57 - 0 to 9 
            arrIntCodes1.push(48);                  //These keys will be allowed only if shift key is NOT pressed
            arrIntCodes1.push(49);                  //Because, with shift key (48 to 57) events will print chars like @,#,$,%,^, etc.
            arrIntCodes1.push(50);
            arrIntCodes1.push(51);
            arrIntCodes1.push(52);
            arrIntCodes1.push(53);
            arrIntCodes1.push(54);
            arrIntCodes1.push(55);
            arrIntCodes1.push(56);
            arrIntCodes1.push(57);
        }
        var arrIntCodes2 = new Array(35, 36, 37, 38, 39, 40, 46);
        if ($.inArray(e.keyCode, arrIntCodes2) != -1) {
            arrIntCodes1.push(e.keyCode);
        }
        if ($.inArray(code, arrIntCodes1) == -1) {
            return false;
        }
    }
    return true;
}

$('.integerOnly').keydown(function (event) {
    valKeyDown = this.value;
    return integerOnly(event);
});

$('.integerOnly').keyup(function (event) {          //This is to protect if user copy-pastes some character value ,..
    valKeyUp = this.value;                          //In that case, pasted text is replaced with old value,
    if (!new RegExp('^[0-9]*$').test(valKeyUp)) {   //which is stored in 'valKeyDown' at keydown event.
        $(this).val(valKeyDown);                    //It is not possible to check this inside 'integerOnly' function as,
    }                                               //one cannot get the text printed by keydown event 
});                                                 //(that's why, this is checked on keyup)

$('.integerOnly').bind('input propertychange', function(e) {    //if user copy-pastes some character value using mouse
    valKeyUp = this.value;
    if (!new RegExp('^[0-9]*$').test(valKeyUp)) {
        $(this).val(valKeyDown);
    }
});

how to specify local modules as npm package dependencies

After struggling much with the npm link command (suggested solution for developing local modules without publishing them to a registry or maintaining a separate copy in the node_modules folder), I built a small npm module to help with this issue.

The fix requires two easy steps.

First:

npm install lib-manager --save-dev

Second, add this to your package.json:

{  
  "name": "yourModuleName",  
  // ...
  "scripts": {
    "postinstall": "./node_modules/.bin/local-link"
  }
}

More details at https://www.npmjs.com/package/lib-manager. Hope it helps someone.

Checking something isEmpty in Javascript?

This should cover all cases:

function empty( val ) {

    // test results
    //---------------
    // []        true, empty array
    // {}        true, empty object
    // null      true
    // undefined true
    // ""        true, empty string
    // ''        true, empty string
    // 0         false, number
    // true      false, boolean
    // false     false, boolean
    // Date      false
    // function  false

        if (val === undefined)
        return true;

    if (typeof (val) == 'function' || typeof (val) == 'number' || typeof (val) == 'boolean' || Object.prototype.toString.call(val) === '[object Date]')
        return false;

    if (val == null || val.length === 0)        // null or 0 length array
        return true;

    if (typeof (val) == "object") {
        // empty object

        var r = true;

        for (var f in val)
            r = false;

        return r;
    }

    return false;
}

What is the difference between supervised learning and unsupervised learning?

In supervised learning, the input x is provided with the expected outcome y (i.e., the output the model is supposed to produce when the input is x), which is often called the "class" (or "label") of the corresponding input x.

In unsupervised learning, the "class" of an example x is not provided. So, unsupervised learning can be thought of as finding "hidden structure" in unlabelled data set.

Approaches to supervised learning include:

  • Classification (1R, Naive Bayes, decision tree learning algorithm, such as ID3 CART, and so on)

  • Numeric Value Prediction

Approaches to unsupervised learning include:

  • Clustering (K-means, hierarchical clustering)

  • Association Rule Learning

Inserting records into a MySQL table using Java

no that cannot work(not with real data):

String sql = "INSERT INTO course " +
        "VALUES (course_code, course_desc, course_chair)";
    stmt.executeUpdate(sql);

change it to:

String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
        "VALUES (?, ?, ?)";

Create a PreparedStatment with that sql and insert the values with index:

PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate(); 

Peak detection in a 2D array

Here is an idea: you calculate the (discrete) Laplacian of the image. I would expect it to be (negative and) large at maxima, in a way that is more dramatic than in the original images. Thus, maxima could be easier to find.

Here is another idea: if you know the typical size of the high-pressure spots, you can first smooth your image by convoluting it with a Gaussian of the same size. This may give you simpler images to process.

How do I compare two hashes?

You can compare hashes directly for equality:

hash1 = {'a' => 1, 'b' => 2}
hash2 = {'a' => 1, 'b' => 2}
hash3 = {'a' => 1, 'b' => 2, 'c' => 3}

hash1 == hash2 # => true
hash1 == hash3 # => false

hash1.to_a == hash2.to_a # => true
hash1.to_a == hash3.to_a # => false


You can convert the hashes to arrays, then get their difference:

hash3.to_a - hash1.to_a # => [["c", 3]]

if (hash3.size > hash1.size)
  difference = hash3.to_a - hash1.to_a
else
  difference = hash1.to_a - hash3.to_a
end
Hash[*difference.flatten] # => {"c"=>3}

Simplifying further:

Assigning difference via a ternary structure:

  difference = (hash3.size > hash1.size) \
                ? hash3.to_a - hash1.to_a \
                : hash1.to_a - hash3.to_a
=> [["c", 3]]
  Hash[*difference.flatten] 
=> {"c"=>3}

Doing it all in one operation and getting rid of the difference variable:

  Hash[*(
  (hash3.size > hash1.size)    \
      ? hash3.to_a - hash1.to_a \
      : hash1.to_a - hash3.to_a
  ).flatten] 
=> {"c"=>3}

JavaScript "cannot read property "bar" of undefined

If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

if (thing && thing.foo)
   alert(thing.foo.bar);

I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

function someFunc(parameterName) {
   if (parameterName && parameterName.foo)
       alert(parameterName.foo.bar);
}

PostgreSQL: How to change PostgreSQL user password?

You can and should have the users's password encrypted:

ALTER USER username WITH ENCRYPTED PASSWORD 'password';

What is the usefulness of PUT and DELETE HTTP request methods?

Using HTTP Request verb such as GET, POST, DELETE, PUT etc... enables you to build RESTful web applications. Read about it here: http://en.wikipedia.org/wiki/Representational_state_transfer

The easiest way to see benefits from this is to look at this example. Every MVC framework has a Router/Dispatcher that maps URL-s to actionControllers. So URL like this: /blog/article/1 would invoke blogController::articleAction($id); Now this Router is only aware of the URL or /blog/article/1/

But if that Router would be aware of whole HTTP Request object instead of just URL, he could have access HTTP Request verb (GET, POST, PUT, DELETE...), and many other useful stuff about current HTTP Request.

That would enable you to configure application so it can accept the same URL and map it to different actionControllers depending on the HTTP Request verb.

For example:

if you want to retrive article 1 you can do this:

GET /blog/article/1 HTTP/1.1

but if you want to delete article 1 you will do this:

DELETE /blog/article/1 HTTP/1.1

Notice that both HTTP Requests have the same URI, /blog/article/1, the only difference is the HTTP Request verb. And based on that verb your router can call different actionController. This enables you to build neat URL-s.

Read this two articles, they might help you:

Symfony 2 - HTTP Fundamentals

Symfony 2 - Routing

These articles are about Symfony 2 framework, but they can help you to figure out how does HTTP Requests and Responses work.

Hope this helps!

How do I extract value from Json

Use a JSON parser. There are plenty of JSON parsers written in Java.

http://www.json.org/

Look under the Java section and find one you like.

What is Activity.finish() method doing exactly?

onDestroy() is meant for final cleanup - freeing up resources that you can on your own,closing open connections,readers,writers,etc. If you don't override it, the system does what it has to.

on the other hand, finish() just lets the system know that the programmer wants the current Activity to be finished. And hence, it calls up onDestroy() after that.

Something to note:

it isn't necessary that only a call to finish() triggers a call to onDestroy(). No. As we know, the android system is free to kill activities if it feels that there are resources needed by the current Activity that are needed to be freed.

How to evaluate a boolean variable in an if block in bash?

Note that the if $myVar; then ... ;fi construct has a security problem you might want to avoid with

case $myvar in
  (true)    echo "is true";;
  (false)   echo "is false";;
  (rm -rf*) echo "I just dodged a bullet";;
esac

You might also want to rethink why if [ "$myvar" = "true" ] appears awkward to you. It's a shell string comparison that beats possibly forking a process just to obtain an exit status. A fork is a heavy and expensive operation, while a string comparison is dead cheap. Think a few CPU cycles versus several thousand. My case solution is also handled without forks.

How to connect to Oracle 11g database remotely

First. It is necessary add static IP address for Computer A AND B. For example in my case Computer A (172.20.14.13) and B (172.20.14.78).

Second. In Computer A with Net Manager add for Listener new address (172.20.14.13) or manually add new record in listener.ora

# listener.ora Network Configuration File: E:\app\user\product\11.2.0\dbhome_1\NETWORK\ADMIN\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = E:\app\user\product\11.2.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:E:\app\user\product\11.2.0\dbhome_1\bin\oraclr11.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
  )

ADR_BASE_LISTENER = E:\app\user

Third. With Net Manager create Service Naming with IP address computer B (172.20.14.78) or manually add new record in tnsnames.ora

# tnsnames.ora Network Configuration File: E:\app\user\product\11.2.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora
# Generated by Oracle configuration tools.

ALINADB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

LISTENER_ALINADB =
  (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))


LOCAL =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

ORACLR_CONNECTION_DATA =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
    (CONNECT_DATA =
      (SID = CLRExtProc)
      (PRESENTATION = RO)
    )
  )

ORCL =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.78)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

Fourth. In computer B (172.20.14.78) install win64_11gR2_client (For example it is for me in Windows 10 Pro 64 bit )

Five. Create with Net Configuration Assistant listener (localhost) or manually add record in listener.ora

# listener.ora Network Configuration File: F:\app\alinasoft\product\11.2.0\client_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

    LISTENER =
      (DESCRIPTION_LIST =
        (DESCRIPTION =
          (ADDRESS = (PROTOCOL = TCP)(HOST = myserver)(PORT = 1521))
          (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
        )
      )

    ADR_BASE_LISTENER = F:\app\alinasoft

Six. With Net Manager create Service Naming with IP address computer A (172.20.14.13) or manually add new record in tnsnames.ora.

SERVER-DB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 172.20.14.13)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = alinadb)
    )
  )

Seven (Computer A - (172.20.14.13)) for database operations and connectivity from remote clients, the following executables must be added to the Windows Firewall exception list: (see image) Oracle_home\bin\oracle.exe - Oracle Database executable Oracle_home\bin\tnslsnr.exe - Oracle Listener

Eight Allow connections for port 1158 (Computer A - (172.20.14.13)) for Oracle Enterprise Manager (https://172.20.14.13:1158/em/console/logon/logon)

Ninth Allow connections for port 1521 ( in and out) (Computer A - (172.20.14.17))

Tenth In computer B 172.20.14.78 sqlplus /NOLOG CONNECT system/oracle@//172.20.14.13:1521/alinadb

If uses Toad, in my case is enter image description here

Write to .txt file?

FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
    printf("Error opening file!\n");
    exit(1);
}

/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);

/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);

/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);

fclose(f);

How does DHT in torrents work?

DHT nodes have unique identifiers, termed, Node ID. Node IDs are chosen at random from the same 160-bit space as BitTorrent info-hashes. Closeness is measured by comparing Node ID's routing tables, the closer the Node, the more detailed, resulting in optimal

What then makes them more optimal than it's predecessor "Kademlia" which used simple unsigned integers: distance(A,B) = |A xor B| Smaller values are closer. XOR. Besides not being secure, its logic was flawed.

If your client supports DHT, there are 8-bytes reserved in which contains 0x09 followed by a 2-byte payload with the UDP Port and DHT node. If the handshake is successful the above will continue.

How to send post request to the below post method using postman rest client

I had same issue . I passed my data as key->value in "Body" section by choosing "form-data" option and it worked fine.

Why functional languages?

I'm always skeptical about the Next Big Thing. Lots of times the Next Big Thing is pure accident of history, being there in the right place at the right time no matter whether the technology is good or not. Examples: C++, Tcl/Tk, Perl. All flawed technologies, all wildly successful because they were perceived either to solve the problems of the day or to be nearly identical to entrenched standards, or both. Functional programming may indeed be great, but that doesn't mean it will be adopted.

But I can tell you why people are excited about functional programming: many, many programmers have had a kind of "conversion experience" in which they discover that using a functional language makes them twice as productive (or maybe ten times as productive) while producing code that is more resilient to change and has fewer bugs. These people think of functional programming as a secret weapon; a good example of this mindset is Paul Graham's Beating the Averages. Oh, and his application? E-commerce web apps.

Since early 2006 there has also been some buzz about functional programming and parallelism. Since people like Simon Peyton Jones have been worrying about parallelism off and on since at least 1984, I'm not holding my breath until functional languages solve the multicore problem. But it does explain some of the additional buzz right about now.

In general, American universities are doing a poor job teaching functional programming. There's a strong core of support for teaching intro programming using Scheme, and Haskell also enjoys some support there, but there's very little in the way of teaching advanced technique for functional programmer. I've taught such a course at Harvard and will do so again this spring at Tufts. Benjamin Pierce has taught such a course at Penn. I don't know if Paul Hudak has done anything at Yale. The European universities are doing a much better job; for example, functional programming is emphasized in important places in Denmark, the Netherlands, Sweden, and the UK. I have less of a sense of what's happening in Australasia.

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

var functionName = function() {} vs function functionName() {}

Both are different ways of defining a function. The difference is how the browser interprets and loads them into an execution context.

The first case is of function expressions which loads only when the interpreter reaches that line of code. So if you do it like the following, you will get an error that the functionOne is not a function.

functionOne();
var functionOne = function() {
    // Some code
};

The reason is that on the first line no value is assigned to functionOne, and hence it is undefined. We are trying to call it as a function, and hence we are getting an error.

On the second line we are assigning the reference of an anonymous function to functionOne.

The second case is of function declarations that loads before any code is executed. So if you do like the following you won't get any error as the declaration loads before code execution.

functionOne();
function functionOne() {
   // Some code
}

Lombok annotations do not compile under Intellij idea

For me, both lombok plugin and annotation processing enable needed, no else. No need to Use Eclipse and additional -javaagent:lombok.jar options.

  • Idea 14.1.3, build 141.1010
  • Lombok plugin[Preference->plugins->browse repositories->search 'lombok'->install and restart idea.
  • Preference ->search 'annotation'->enter annotation processor ->enable annotation processing.

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

I ran into this problem and tried a number of solutions on my Mac without any success. I finally got to work with the commands below:

$ rm -rf ~/.android
$ killall adb
$ adb devices

Note that rm -rf ~/.android will remove any AVDs that you have configured, so don't take this step lightly. Personally I had to though and I'm not sure why. Hopefully this helps someone.

Static variable inside of a function in C

6 7

x is a global variable that is visible only from foo(). 5 is its initial value, as stored in the .data section of the code. Any subsequent modification overwrite previous value. There is no assignment code generated in the function body.

jQuery - setting the selected value of a select control via its text description

 $("#Test").find("option:contains('two')").each(function(){
     if( $(this).text() == 'two' ) {
        $(this).attr("selected","selected");
     }
 });

The if statement does a exact match with "two" and "two three" will not be matched

Add multiple items to already initialized arraylist in java

What is the "source" of those integer? If it is something that you need to hard code in your source code, you may do

arList.addAll(Arrays.asList(1,1,2,3,5,8,13,21));

How do we count rows using older versions of Hibernate (~2009)?

This works in Hibernate 4(Tested).

String hql="select count(*) from  Book";
Query query= getCurrentSession().createQuery(hql);
Long count=(Long) query.uniqueResult();
return count;

Where getCurrentSession() is:

@Autowired
private SessionFactory sessionFactory;


private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}

Linux command-line call not returning what it should from os.system?

What gets returned is the return value of executing this command. What you see in while executing it directly is the output of the command in stdout. That 0 is returned means, there was no error in execution.

Use popen etc for capturing the output .

Some thing along this line:

import subprocess as sub
p = sub.Popen(['your command', 'arg1', 'arg2', ...],stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
print output

or

import os
p = os.popen('command',"r")
while 1:
    line = p.readline()
    if not line: break
    print line

ON SO : Popen and python

Removing the fragment identifier from AngularJS urls (# symbol)

If you are in .NET stack with MVC with AngularJS, this is what you have to do to remove the '#' from url:

  1. Set up your base href in your _Layout page: <head> <base href="/"> </head>

  2. Then, add following in your angular app config : $locationProvider.html5Mode(true)

  3. Above will remove '#' from url but page refresh won't work e.g. if you are in "yoursite.com/about" page refreash will give you a 404. This is because MVC does not know about angular routing and by MVC pattern it will look for a MVC page for 'about' which does not exists in MVC routing path. Workaround for this is to send all MVC page request to a single MVC view and you can do that by adding a route that catches all

url:

routes.MapRoute(
    name: "App",
    url: "{*url}",
    defaults: new {
        controller = "Home", action = "Index"
    }
);

How to create a density plot in matplotlib?

The density plot can also be created by using matplotlib: The function plt.hist(data) returns the y and x values necessary for the density plot (see the documentation https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html). Resultingly, the following code creates a density plot by using the matplotlib library:

import matplotlib.pyplot as plt
dat=[-1,2,1,4,-5,3,6,1,2,1,2,5,6,5,6,2,2,2]
a=plt.hist(dat,density=True)
plt.close()
plt.figure()
plt.plot(a[1][1:],a[0])      

This code returns the following density plot

enter image description here

Java - Create a new String instance with specified length and filled with specific character. Best solution?

using Dollar is simple:

String filled = $("=").repeat(10).toString(); // produces "=========="

Importing a GitHub project into Eclipse

I think you need to create a branch before you can import into your local Eclipse, otherwise, there is an error leading to incapable of importing repository from Github or Bitbucket.

Where is the user's Subversion config file stored on the major operating systems?

In windows 7, 8, and 10 you can find at the following location

C:\Users\<user>\AppData\Roaming\Subversion

If you enter the following in the Windows Explorer address bar, it will take you right there.

%appdata%\Subversion

how to fetch data from database in Hibernate

Let me quote this:

Hibernate created a new language named Hibernate Query Language (HQL), the syntax is quite similar to database SQL language. The main difference between is HQL uses class name instead of table name, and property names instead of column name.

As far as I can see you are using the table name.

So it should be like this:

Query query = session.createQuery("from Employee");

Understanding repr( ) function in Python

>>> x = 'foo'
>>> x
'foo'

So the name x is attached to 'foo' string. When you call for example repr(x) the interpreter puts 'foo' instead of x and then calls repr('foo').

>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"

repr actually calls a magic method __repr__ of x, which gives the string containing the representation of the value 'foo' assigned to x. So it returns 'foo' inside the string "" resulting in "'foo'". The idea of repr is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to repr.

>>> eval("'foo'")
'foo'

When we call eval("'foo'"), it's the same as we type 'foo' in the interpreter. It's as we directly type the contents of the outer string "" in the interpreter.

>>> eval('foo')

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    eval('foo')
  File "<string>", line 1, in <module>
NameError: name 'foo' is not defined

If we call eval('foo'), it's the same as we type foo in the interpreter. But there is no foo variable available and an exception is raised.

>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>> 

str is just the string representation of the object (remember, x variable refers to 'foo'), so this function returns string.

>>> str(5)
'5'

String representation of integer 5 is '5'.

>>> str('foo')
'foo'

And string representation of string 'foo' is the same string 'foo'.

Java AES encryption and decryption

Here is the implementation that was mentioned above:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;

try
{
    String passEncrypt = "my password";
    byte[] saltEncrypt = "choose a better salt".getBytes();
    int iterationsEncrypt = 10000;
    SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory
            .getInstance("PBKDF2WithHmacSHA1");
    SecretKey tmp = factoryKeyEncrypt.generateSecret(new PBEKeySpec(
            passEncrypt.toCharArray(), saltEncrypt, iterationsEncrypt,
            128));
    SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(),
            "AES");

    Cipher aesCipherEncrypt = Cipher
            .getInstance("AES/ECB/PKCS5Padding");
    aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey);

    // get the bytes
    byte[] bytes = StringUtils.getBytesUtf8(toEncodeEncryptString);

    // encrypt the bytes
    byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes);

    // encode 64 the encrypted bytes
    String encoded = Base64.encodeBase64URLSafeString(encryptBytes);

    System.out.println("e: " + encoded);

    // assume some transport happens here

    // create a new string, to make sure we are not pointing to the same
    // string as the one above
    String encodedEncrypted = new String(encoded);

    //we recreate the same salt/encrypt as if its a separate system
    String passDecrypt = "my password";
    byte[] saltDecrypt = "choose a better salt".getBytes();
    int iterationsDecrypt = 10000;
    SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory
            .getInstance("PBKDF2WithHmacSHA1");
    SecretKey tmp2 = factoryKeyDecrypt.generateSecret(new PBEKeySpec(passDecrypt
            .toCharArray(), saltDecrypt, iterationsDecrypt, 128));
    SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), "AES");

    Cipher aesCipherDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
            aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);

    //basically we reverse the process we did earlier

    // get the bytes from encodedEncrypted string
    byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);

    // decode 64, now the bytes should be encrypted
    byte[] eBytes = Base64.decodeBase64(e64bytes);

    // decrypt the bytes
    byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);

    // to string
    String decoded = StringUtils.newStringUtf8(cipherDecode);

    System.out.println("d: " + decoded);

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

How to pass parameters to a partial view in ASP.NET MVC?

You need to create a view model. Something like this should do...

public class FullNameViewModel
{
     public string FirstName { get; set; }
     public string LastName { get; set; }

     public FullNameViewModel() { } 

     public FullNameViewModel(string firstName, string lastName)
     {
          this.FirstName = firstName;
          this.LastName = lastName;
     }

}

then from your action result pass the model

return View("FullName", new FullNameViewModel("John", "Doe"));

and you will be able to access @Model.FirstName and @Model.LastName accordingly.

Storing Images in PostgreSQL

Re jcoby's answer:

bytea being a "normal" column also means the value being read completely into memory when you fetch it. Blobs, in contrast, you can stream into stdout. That helps in reducing the server memory footprint. Especially, when you store 4-6 MPix images.

No problem with backing up blobs. pg_dump provides "-b" option to include the large objects into the backup.

So, I prefer using pg_lo_*, you may guess.

Re Kris Erickson's answer:

I'd say the opposite :). When images are not the only data you store, don't store them on the file system unless you absolutely have to. It's such a benefit to be always sure about your data consistency, and to have the data "in one piece" (the DB). BTW, PostgreSQL is great in preserving consistency.

However, true, reality is often too performance-demanding ;-), and it pushes you to serve the binary files from the file system. But even then I tend to use the DB as the "master" storage for binaries, with all the other relations consistently linked, while providing some file system-based caching mechanism for performance optimization.

Recyclerview and handling different type of row inflation

The trick is to create subclasses of ViewHolder and then cast them.

public class GroupViewHolder extends RecyclerView.ViewHolder {
    TextView mTitle;
    TextView mContent;
    public GroupViewHolder(View itemView) {
        super (itemView);
        // init views...
    }
}

public class ImageViewHolder extends RecyclerView.ViewHolder {
    ImageView mImage;
    public ImageViewHolder(View itemView) {
        super (itemView);
        // init views...
    }
}

private static final int TYPE_IMAGE = 1;
private static final int TYPE_GROUP = 2;  

And then, at runtime do something like this:

@Override
public int getItemViewType(int position) {
    // here your custom logic to choose the view type
    return position == 0 ? TYPE_IMAGE : TYPE_GROUP;
}

@Override
public void onBindViewHolder (ViewHolder viewHolder, int i) {

    switch (viewHolder.getItemViewType()) {

        case TYPE_IMAGE:
            ImageViewHolder imageViewHolder = (ImageViewHolder) viewHolder;
            imageViewHolder.mImage.setImageResource(...);
            break;

        case TYPE_GROUP:
            GroupViewHolder groupViewHolder = (GroupViewHolder) viewHolder;
            groupViewHolder.mContent.setText(...)
            groupViewHolder.mTitle.setText(...);
            break;
    }
}

Hope it helps.

(change) vs (ngModelChange) in angular

In Angular 7, the (ngModelChange)="eventHandler()" will fire before the value bound to [(ngModel)]="value" is changed while the (change)="eventHandler()" will fire after the value bound to [(ngModel)]="value" is changed.

Updating property value in properties file without deleting other values

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

How to run PowerShell in CMD

I'd like to add the following to Shay Levy's correct answer: You can make your life easier if you create a little batch script run.cmd to launch your powershell script:

@echo off & setlocal
set batchPath=%~dp0
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" "MY-PC"

Put it in the same path as SQLExecutor.ps1 and from now on you can run it by simply double-clicking on run.cmd.


Note:

  • If you require command line arguments inside the run.cmd batch, simply pass them as %1 ... %9 (or use %* to pass all parameters) to the powershell script, i.e.
    powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*

  • The variable batchPath contains the executing path of the batch file itself (this is what the expression %~dp0 is used for). So you just put the powershell script in the same path as the calling batch file.

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

You probably have a syntax error in the css you are using.

Run this command

$ bundle exec rake assets:precompile RAILS_ENV=development --trace

It will give the exception, fixed that and you are all done.

Thanks

How do I set headers using python's urllib?

For multiple headers do as follow:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()

adding a datatable in a dataset

you have to set the tableName you want to your dtimage that is for instance

dtImage.TableName="mydtimage";


if(!ds.Tables.Contains(dtImage.TableName))
        ds.Tables.Add(dtImage);

it will be reflected in dataset because dataset is a container of your datatable dtimage and you have a reference on your dtimage

Java: parse int value from a char

Using binary AND with 0b1111:

String element = "el5";

char c = element.charAt(2);

System.out.println(c & 0b1111); // => '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5

// '0' & 0b1111 => 0b0011_0000 & 0b0000_1111 => 0
// '1' & 0b1111 => 0b0011_0001 & 0b0000_1111 => 1
// '2' & 0b1111 => 0b0011_0010 & 0b0000_1111 => 2
// '3' & 0b1111 => 0b0011_0011 & 0b0000_1111 => 3
// '4' & 0b1111 => 0b0011_0100 & 0b0000_1111 => 4
// '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
// '6' & 0b1111 => 0b0011_0110 & 0b0000_1111 => 6
// '7' & 0b1111 => 0b0011_0111 & 0b0000_1111 => 7
// '8' & 0b1111 => 0b0011_1000 & 0b0000_1111 => 8
// '9' & 0b1111 => 0b0011_1001 & 0b0000_1111 => 9

Enter key in textarea

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

Error in installation a R package

After using the wrong quotation mark characters in install.packages(), correcting the quote marks yielded the "cannot remove prior installation" error. Closing and restarting R worked.

Setting selected option in laravel form

Everybody talking about you go using {!! Form::select() !!} but, if all you need is to use plain simple HTML.. here is another way to do it.

<select name="myselect">
@foreach ($options as $key => $value)
    <option value="{{ $key }}"
    @if ($key == old('myselect', $model->option))
        selected="selected"
    @endif
    >{{ $value }}</option>
@endforeach
</select>

the old() function is useful when you submit the form and the validation fails. So that, old() returns the previously selected value.

.htaccess rewrite to redirect root URL to subdirectory

Try this:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
RewriteRule ^$ store [L]

If you want an external redirect (which cause the visiting browser to show the redirected URL), set the R flag there as well:

RewriteRule ^$ /store [L,R=301]

Read/Write String from/to a File in Android

Hope this might be useful to you.

Write File:

private void writeToFile(String data,Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

Read File:

private String readFromFile(Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput("config.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

Concat all strings inside a List<string> using LINQ

I think that if you define the logic in an extension method the code will be much more readable:

public static class EnumerableExtensions { 
  public static string Join<T>(this IEnumerable<T> self, string separator) {  
    return String.Join(separator, self.Select(e => e.ToString()).ToArray()); 
  } 
} 

public class Person {  
  public string FirstName { get; set; }  
  public string LastName { get; set; }  
  public override string ToString() {
    return string.Format("{0} {1}", FirstName, LastName);
  }
}  

// ...

List<Person> people = new List<Person>();
// ...
string fullNames = people.Join(", ");
string lastNames = people.Select(p => p.LastName).Join(", ");

Dynamically changing font size of UILabel

Single line- There are two ways, you can simply change.

1- Pragmatically (Swift 3)

Just add the following code

    yourLabel.numberOfLines = 1;
    yourLabel.minimumScaleFactor = 0.7;
    yourLabel.adjustsFontSizeToFitWidth = true;

2 - Using UILabel Attributes inspector

i- Select your label- Set number of lines 1.
ii- Autoshrink-  Select Minimum Font Scale from drop down
iii- Set Minimum Font Scale value as you wish , I have set 0.7 as in below image. (default is 0.5)

enter image description here

Sorting a vector in descending order

According to my machine, sorting a long long vector of [1..3000000] using the first method takes around 4 seconds, while using the second takes about twice the time. That says something, obviously, but I don't understand why either. Just think this would be helpful.

Same thing reported here.

As said by Xeo, with -O3 they use about the same time to finish.

How to stop console from closing on exit?

Yes, in VS2010 they changed this behavior somewhy.
Open your project and navigate to the following menu: Project -> YourProjectName Properties -> Configuration Properties -> Linker -> System. There in the field SubSystem use the drop-down to select Console (/SUBSYSTEM:CONSOLE) and apply the change.
"Start without debugging" should do the right thing now.

Or, if you write in C++ or in C, put

system("pause");

at the end of your program, then you'll get "Press any key to continue..." even when running in debug mode.

Adding delay between execution of two following lines

You can use the NSThread method:

[NSThread sleepForTimeInterval: delay];

However, if you do this on the main thread you'll block the app, so only do this on a background thread.


or in Swift

NSThread.sleepForTimeInterval(delay)

in Swift 3

Thread.sleep(forTimeInterval: delay)

HTML Upload MAX_FILE_SIZE does not appear to work

It's only supposed to send the information to the server. The reason that it must preceed the file field is that it has to come before the file payload in the request for the server to be able to use it to check the size of the upload.

How the value is used on the server depends on what you use to take care of the upload. The code is supposedly intended for a specific upload component that specifically looks for that value.

It seems that the built in upload support in PHP is one to use this field value.

How to delete all data from solr and hbase

If you're using Cloudera 5.x, Here in this documentation is mentioned that Lily maintains the Real time updations and deletions also.

Configuring the Lily HBase NRT Indexer Service for Use with Cloudera Search

As HBase applies inserts, updates, and deletes to HBase table cells, the indexer keeps Solr consistent with the HBase table contents, using standard HBase replication.

Not sure iftruncate 'hTable' is also supported in the same.

Else you create a Trigger or Service to clear up your data from both Solr and HBase on a particular Event or anything.

How can I get the last character in a string?

Since in Javascript a string is a char array, you can access the last character by the length of the string.

var lastChar = myString[myString.length -1];

How to override application.properties during production in Spring-Boot?

I am not sure you can dynamically change profiles.

Why not just have an internal properties file with the spring.config.location property set to your desired outside location, and the properties file at that location (outside the jar) have the spring.profiles.active property set?

Better yet, have an internal properties file, specific to dev profile (has spring.profiles.active=dev) and leave it like that, and when you want to deploy in production, specify a new location for your properties file, which has spring.profiles.active=prod:

java -jar myjar.jar --spring.config.location=D:\wherever\application.properties

What's the best way to add a drop shadow to my UIView

The trick is defining the masksToBounds property of your view's layer properly:

view.layer.masksToBounds = NO;

and it should work.

(Source)

How can you find out which process is listening on a TCP or UDP port on Windows?

The -b switch mentioned in most answers requires you to have administrative privileges on the machine. You don't really need elevated rights to get the process name!

Find the pid of the process running in the port number (e.g., 8080)

netstat -ano | findStr "8080"

Find the process name by pid

tasklist /fi "pid eq 2216"

find process by TCP/IP port

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I had this problem, and on a hunch I removed the Qt Configs from my environment. I.e.,

rm -rf ~/.config/Qt*

Then I started qtcreator and it reconfigured itself with the existing state of the machine. It no longer remembered where my projects were, but that just meant I had to browse to them "for the first time" again.

But more importantly it built itself a coherent set of library paths, so I could rebuild and run my project executables again without the xcb or qxcb libraries going missing.

Invoking a jQuery function after .each() has completed

Ok, this might be a little after the fact, but .promise() should also achieve what you're after.

Promise documentation

An example from a project i'm working on:

$( '.panel' )
    .fadeOut( 'slow')
    .promise()
    .done( function() {
        $( '#' + target_panel ).fadeIn( 'slow', function() {});
    });

:)

Explode PHP string by new line

Try "\n\r" (double quotes) or just "\n".

If you're not sure which type of EOL you have, run a str_replace before your explode, replacing "\n\r" with "\n".

How can I remove the outline around hyperlinks images?

For Remove outline for anchor tag

a {outline : none;}

Remove outline from image link

a img {outline : none;}

Remove border from image link

img {border : 0;}

How to get text in QlineEdit when QpushButton is pressed in a string?

My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.

Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.

A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit and see the there is a text method.

To answer your specific question:

To make your GUI elements available to the rest of the object, preface them with self.

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect") 

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print shost


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

This IP, site or mobile application is not authorized to use this API key

Also the corresponding API should be enabled for the given project

https://console.developers.google.com/apis/library?project=projectnamehere

Closing database connections in Java

When you are done with using your Connection, you need to explicitly close it by calling its close() method in order to release any other database resources (cursors, handles, etc.) the connection may be holding on to.

Actually, the safe pattern in Java is to close your ResultSet, Statement, and Connection (in that order) in a finally block when you are done with them. Something like this:

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
    // Do stuff
    ...

} catch (SQLException ex) {
    // Exception handling stuff
    ...
} finally {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) { /* Ignored */}
    }
    if (ps != null) {
        try {
            ps.close();
        } catch (SQLException e) { /* Ignored */}
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) { /* Ignored */}
    }
}

The finally block can be slightly improved into (to avoid the null check):

} finally {
    try { rs.close(); } catch (Exception e) { /* Ignored */ }
    try { ps.close(); } catch (Exception e) { /* Ignored */ }
    try { conn.close(); } catch (Exception e) { /* Ignored */ }
}

But, still, this is extremely verbose so you generally end up using an helper class to close the objects in null-safe helper methods and the finally block becomes something like this:

} finally {
    DbUtils.closeQuietly(rs);
    DbUtils.closeQuietly(ps);
    DbUtils.closeQuietly(conn);
}

And, actually, the Apache Commons DbUtils has a DbUtils class which is precisely doing that, so there isn't any need to write your own.

How can I bind a background color in WPF/XAML?

The Background property expects a Brush object, not a string. Change the type of the property to Brush and initialize it thus:

Background = new SolidColorBrush(Colors.Red);

Detecting superfluous #includes in C/C++?

Gimpel Software's PC Lint can report on when an include file has been included more than once in a compilation unit, but it can't find include files which are not needed in the way you are looking for.

Edit: It can. See itsmatt's answer

Parse string to DateTime in C#

Put the value of a human-readable string into a .NET DateTime with code like this:

DateTime.ParseExact("April 16, 2011 4:27 pm", "MMMM d, yyyy h:mm tt", null);

How to block calls in android

OMG!!! YES, WE CAN DO THAT!!! I was going to kill myself after severe 24 hours of investigating and discovering... But I've found "fresh" solution!

// "cheat" with Java reflection to gain access to TelephonyManager's
// ITelephony getter
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony)m.invoke(tm);

all all all of hundreds of people who wants to develop their call-control software visit this start point

there is a project. and there are important comments (and credits)

briefly: copy aidl file, add permissions to manifest, copy-paste source for telephony management )))

Some more info for you. AT commands you can send only if you are rooted. Than you can kill system process and send commands but you will need a reboot to allow your phone to receive and send calls =)))

I'm very hapy =) Now my Shake2MuteCall will get an update !

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

I resolved this problem. I think it happened maybe because of https but I am not very sure. You can Switch remote URLs from HTTPS to SSH.

1.Pls refer to this link for details:https://help.github.com/articles/changing-a-remote-s-url/

Also I had to config the ssh key.

2.Follow this:https://help.github.com/articles/generating-ssh-keys/

I came across this problem because I replaced my mac, but I do the transfer of data,I think it is probably because the key reasons.

How to identify numpy types in python?

Use the builtin type function to get the type, then you can use the __module__ property to find out where it was defined:

>>> import numpy as np
a = np.array([1, 2, 3])
>>> type(a)
<type 'numpy.ndarray'>
>>> type(a).__module__
'numpy'
>>> type(a).__module__ == np.__name__
True

Angular2 module has no exported member

This error can also occur if your interface name is different than the file it is contained in. Read about ES6 modules for details. If the SignInComponent was an interface, as was in my case, then

SignInComponent

should be in a file named SignInComponent.ts.

Convert command line argument to string

Because all attempts to print the argument I placed in my variable failed, here my 2 bytes for this question:

std::string dump_name;

(stuff..)

if(argc>2)
{
    dump_name.assign(argv[2]);
    fprintf(stdout, "ARGUMENT %s", dump_name.c_str());
}

Note the use of assign, and also the need for the c_str() function call.

Jquery Ajax beforeSend and success,error & complete

Maybe you can try the following :

var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
        i++;
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        i--;
        if (i <= 0) {
            $(placeholder).removeClass('loading');
        }
    },
    dataType: 'html'
});
}

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

Importing CSV with line breaks in Excel 2007

Excel (at least in Office 2007 on XP) can behave differently depending on whether a CSV file is imported by opening it from the File->Open menu or by double-clicking on the file in Explorer.

I have a CSV file that is in UTF-8 encoding and contains newlines in some cells. If I open this file from Excel's File->Open menu, the "import CSV" wizard pops up and the file cannot be correctly imported: the newlines start a new row even when quoted. If I open this file by double-clicking on it in an Explorer window, then it opens correctly without the intervention of the wizard.

how to set select element as readonly ('disabled' doesnt pass select value on server)

without disabling the selected value on submitting..

$('#selectID option:not(:selected)').prop('disabled', true);

If you use Jquery version lesser than 1.7
$('#selectID option:not(:selected)').attr('disabled', true);

It works for me..

MISCONF Redis is configured to save RDB snapshots

Thanks everyone for checking the problem, apparently the error was produced during bgsave.

For me, typing config set stop-writes-on-bgsave-error no in a shell and restarting Redis solved the problem.

Inner Joining three tables

Just do the same thing agin but then for TableC

SELECT *
FROM dbo.tableA A 
INNER JOIN dbo.TableB B ON A.common = B.common
INNER JOIN dbo.TableC C ON A.common = C.common

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

How to fix error Base table or view not found: 1146 Table laravel relationship table?

You can add this in Post Model,

public function categories()
{
 return $this->belongsToMany('App\Category','category_post','post_id','category_id');                 
}

category_post indicate the table you want to use.
post_id indicate the column where you want to store the posts id.
category_id indicate the column where you want to store the categories id.

Apache HttpClient Interim Error: NoHttpResponseException

Most likely persistent connections that are kept alive by the connection manager become stale. That is, the target server shuts down the connection on its end without HttpClient being able to react to that event, while the connection is being idle, thus rendering the connection half-closed or 'stale'. Usually this is not a problem. HttpClient employs several techniques to verify connection validity upon its lease from the pool. Even if the stale connection check is disabled and a stale connection is used to transmit a request message the request execution usually fails in the write operation with SocketException and gets automatically retried. However under some circumstances the write operation can terminate without an exception and the subsequent read operation returns -1 (end of stream). In this case HttpClient has no other choice but to assume the request succeeded but the server failed to respond most likely due to an unexpected error on the server side.

The simplest way to remedy the situation is to evict expired connections and connections that have been idle longer than, say, 1 minute from the pool after a period of inactivity. For details please see this section of the HttpClient tutorial.

how to return index of a sorted list?

How about

l1 = [2,3,1,4,5]
l2 = [l1.index(x) for x in sorted(l1)]

How to insert a character in a string at a certain position?

As mentioned in comments, a StringBuilder is probably a faster implementation than using a StringBuffer. As mentioned in the Java docs:

This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Usage :

String str = Integer.toString(j);
str = new StringBuilder(str).insert(str.length()-2, ".").toString();

Or if you need synchronization use the StringBuffer with similar usage :

String str = Integer.toString(j);
str = new StringBuffer(str).insert(str.length()-2, ".").toString();

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

Change priorityQueue to max priorityqueue

PriorityQueue<Integer> pq = new PriorityQueue<Integer> (
  new Comparator<Integer> () {
    public int compare(Integer a, Integer b) {
       return b - a;
    }
  }
);

How to resolve the "ADB server didn't ACK" error?

On my Mac, I wrote this code in my Terminal:

xxx-MacBook-Pro:~ xxx$ cd /Users/xxx/Documents/0_Software/adt20140702/sdk/platform-tools/

xxx-MacBook-Pro:platform-tools xxx$ ./adb kill-server

xxx-MacBook-Pro:platform-tools xxx$ ./adb start-server

  • daemon not running. starting it now on port 5037 *
  • daemon started successfully *

xxx-MacBook-Pro:platform-tools tuananh$

Hope this help.

Could not find any resources appropriate for the specified culture or the neutral culture

For me the problem was copying .resx files and associated .cs files from one project to another. Both projects had the same namespace so that wasn't the problem.

Finally solved it when I noticed in Solution Explorer that in the original project the .resx files were dependent on the .cs files:

MyResource.cs
|_ MyResource.resx

While in the copied project the .cs files was dependent on the .resx files:

MyResource.resx
|_ MyResource.cs

It turned out that in the second project somehow the .resx files had been set to auto-generate the .cs files. The auto-generated .cs files were overwriting the .cs files copied from the original project.

To fix the problem edit the properties of each .resx file in the copied project. The Custom Tool property will be set to something like ResXFileCodeGenerator. Clear the Custom Tool property of the .resx file. You will need to re-copy the .cs file from the original project as it will have been overwritten by the auto-generated file.

Invalid hook call. Hooks can only be called inside of the body of a function component

I had this issue when I used npm link to install my local library, which I've built using cra. I found the answer here. Which literally says:

This problem can also come up when you use npm link or an equivalent. In that case, your bundler might “see” two Reacts — one in application folder and one in your library folder. Assuming 'myapp' and 'mylib' are sibling folders, one possible fix is to run 'npm link ../myapp/node_modules/react' from 'mylib'. This should make the library use the application’s React copy.

Thus, running the command: npm link ../../libraries/core/decipher/node_modules/react from my project folder has fixed the issue.

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

When you put empty action then some security filtration consider it malicious or phishing. Hence they can block your page. So its advisable not to keep action= blank.

How to use goto statement correctly

The Java keyword list specifies the goto keyword, but it is marked as "not used".

This was probably done in case it were to be added to a later version of Java.

If goto weren't on the list, and it were added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etcetera) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.

Python 2.7.10 error "from urllib.request import urlopen" no module named request

Instead of using urllib.request.urlopen() remove request for python 2.

urllib.urlopen() you do not have to request in python 2.x for what you are trying to do. Hope it works for you. This was tested using python 2.7 I was receiving the same error message and this resolved it.

ERROR 1067 (42000): Invalid default value for 'created_at'

Try and run the following command:

ALTER TABLE `investments` 
MODIFY created_at TIMESTAMP 
DEFAULT CURRENT_TIMESTAMP 
NOT NULL;

and

ALTER TABLE `investments` 
MODIFY updated_at TIMESTAMP 
DEFAULT CURRENT_TIMESTAMP 
NOT NULL;

The reason you are getting this error is because you are not setting a default value for the created_at and updated_at fields. MySQL is not accepting your command since the values for these columns cannot be null.

Multi-statement Table Valued Function vs Inline Table Valued Function

Your examples, I think, answer the question very well. The first function can be done as a single select, and is a good reason to use the inline style. The second could probably be done as a single statement (using a sub-query to get the max date), but some coders may find it easier to read or more natural to do it in multiple statements as you have done. Some functions just plain can't get done in one statement, and so require the multi-statement version.

I suggest using the simplest (inline) whenever possible, and using multi-statements when necessary (obviously) or when personal preference/readability makes it wirth the extra typing.

What is the difference between static_cast<> and C style casting?

struct A {};
struct B : A {};
struct C {}; 

int main()
{
    A* a = new A;    

    int i = 10;

    a = (A*) (&i); // NO ERROR! FAIL!

    //a = static_cast<A*>(&i); ERROR! SMART!

    A* b = new B;

    B* b2 = static_cast<B*>(b); // NO ERROR! SMART!

    C* c = (C*)(b); // NO ERROR! FAIL!

    //C* c = static_cast<C*>(b); ERROR! SMART!
}

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

If you want to use them as in swift 2, you can use these funcs:

For CGRectMake:

func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
    return CGRect(x: x, y: y, width: width, height: height)
}

For CGPointMake:

func CGPointMake(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
    return CGPoint(x: x, y: y)
}

For CGSizeMake:

func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize {
    return CGSize(width: width, height: height)
}

Just put them outside any class and it should work. (Works for me at least)

Java out.println() how is this possible?

@sfussenegger's answer explains how to make this work. But I'd say don't do it!

Experienced Java programmers use, and expect to see

        System.out.println(...);

and not

        out.println(...);

A static import of System.out or System.err is (IMO) bad style because:

  • it breaks the accepted idiom, and
  • it makes it harder to track down unwanted trace prints that were added during testing and not removed.

If you find yourself doing lots of output to System.out or System.err, I think it is a better to abstract the streams into attributes, local variables or methods. This will make your application more reusable.

How do I append a node to an existing XML file in java

The following complete example will read an existing server.xml file from the current directory, append a new Server and re-write the file to server.xml. It does not work without an existing .xml file, so you will need to modify the code to handle that case.

import java.util.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;

public class AddXmlNode {
    public static void main(String[] args) throws Exception {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse("server.xml");
        Element root = document.getDocumentElement();

        Collection<Server> servers = new ArrayList<Server>();
        servers.add(new Server());

        for (Server server : servers) {
            // server elements
            Element newServer = document.createElement("server");

            Element name = document.createElement("name");
            name.appendChild(document.createTextNode(server.getName()));
            newServer.appendChild(name);

            Element port = document.createElement("port");
            port.appendChild(document.createTextNode(Integer.toString(server.getPort())));
            newServer.appendChild(port);

            root.appendChild(newServer);
        }

        DOMSource source = new DOMSource(document);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        StreamResult result = new StreamResult("server.xml");
        transformer.transform(source, result);
    }

    public static class Server {
        public String getName() { return "foo"; }
        public Integer getPort() { return 12345; }
    }
}

Example server.xml file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Servers>
  <server>
    <name>something</name>
    <port>port</port>
  </server>
</Servers>

The main change to your code is not creating a new "root" element. The above example just uses the current root node from the existing server.xml and then just appends a new Server element and re-writes the file.

Ruby String to Date Conversion

You can try https://rubygems.org/gems/dates_from_string:

Find date in structure:

text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)

=> ["2015-02-02 23:00:10"]

What are the main performance differences between varchar and nvarchar SQL Server data types?

Why, in all this discussion, has there been no mention of UTF-8? Being able to store the full unicode span of characters does not mean one has to always allocate two-bytes-per-character (or "code point" to use the UNICODE term). All of ASCII is UTF-8. Does SQL Server check for VARCHAR() fields that the text is strict ASCII (i.e. top byte bit zero)? I would hope not.

If then you want to store unicode and want compatibility with older ASCII-only applications, I would think using VARCHAR() and UTF-8 would be the magic bullet: It only uses more space when it needs to.

For those of you unfamiliar with UTF-8, might I recommend a primer.

How to edit a JavaScript alert box title?

Override the javascript window.alert() function.

window.alert = function(title, message){
    var myElementToShow = document.getElementById("someElementId");
    myElementToShow.innerHTML = title + "</br>" + message; 
}

With this you can create your own alert() function. Create a new 'cool' looking dialog (from some div elements).

Tested working in chrome and webkit, not sure of others.

SQL Server Error : String or binary data would be truncated

This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.

I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.

ImportError: No module named Crypto.Cipher

I've had the same problem 'ImportError: No module named Crypto.Cipher', since using GoogleAppEngineLauncher (version > 1.8.X) with GAE Boilerplate on OSX 10.8.5 (Mountain Lion). In Google App Engine SDK with python 2.7 runtime, pyCrypto 2.6 is the suggested version. The solution that worked for me was...

1) Download pycrypto2.6 source extract it somewhere(~/Downloads/pycrypto26)

e.g., git clone https://github.com/dlitz/pycrypto.git

2) cd (cd ~/Downloads/pycrypto26) then

3) Execute the following terminal command inside the previous folder in order to install pyCrypto 2.6 manually in GAE folder.

sudo python setup.py install --install-lib /Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

There isn't direct support for COUNT(DISTINCT {x})), but you can simulate it from an IGrouping<,> (i.e. what group by returns); I'm afraid I only "do" C#, so you'll have to translate to VB...

 select new
 {
     Foo= grp.Key,
     Bar= grp.Select(x => x.SomeField).Distinct().Count()
 };

Here's a Northwind example:

    using(var ctx = new DataClasses1DataContext())
    {
        ctx.Log = Console.Out; // log TSQL to console
        var qry = from cust in ctx.Customers
                  where cust.CustomerID != ""
                  group cust by cust.Country
                  into grp
                  select new
                  {
                      Country = grp.Key,
                      Count = grp.Select(x => x.City).Distinct().Count()
                  };

        foreach(var row in qry.OrderBy(x=>x.Country))
        {
            Console.WriteLine("{0}: {1}", row.Country, row.Count);
        }
    }

The TSQL isn't quite what we'd like, but it does the job:

SELECT [t1].[Country], (
    SELECT COUNT(*)
    FROM (
        SELECT DISTINCT [t2].[City]
        FROM [dbo].[Customers] AS [t2]
        WHERE ((([t1].[Country] IS NULL) AND ([t2].[Country] IS NULL)) OR (([t1]
.[Country] IS NOT NULL) AND ([t2].[Country] IS NOT NULL) AND ([t1].[Country] = [
t2].[Country]))) AND ([t2].[CustomerID] <> @p0)
        ) AS [t3]
    ) AS [Count]
FROM (
    SELECT [t0].[Country]
    FROM [dbo].[Customers] AS [t0]
    WHERE [t0].[CustomerID] <> @p0
    GROUP BY [t0].[Country]
    ) AS [t1]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

The results, however, are correct- verifyable by running it manually:

        const string sql = @"
SELECT c.Country, COUNT(DISTINCT c.City) AS [Count]
FROM Customers c
WHERE c.CustomerID != ''
GROUP BY c.Country
ORDER BY c.Country";
        var qry2 = ctx.ExecuteQuery<QueryResult>(sql);
        foreach(var row in qry2)
        {
            Console.WriteLine("{0}: {1}", row.Country, row.Count);
        }

With definition:

class QueryResult
{
    public string Country { get; set; }
    public int Count { get; set; }
}

How to make a HTML list appear horizontally instead of vertically using CSS only?

Using display: inline-flex

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  display: inline-flex_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using display: inline-block

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
#menu li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I use $rootScope in Angular to store variables?

Variables set at the root-scope are available to the controller scope via prototypical inheritance.

Here is a modified version of @Nitish's demo that shows the relationship a bit clearer: http://jsfiddle.net/TmPk5/6/

Notice that the rootScope's variable is set when the module initializes, and then each of the inherited scope's get their own copy which can be set independently (the change function). Also, the rootScope's value can be updated too (the changeRs function in myCtrl2)

angular.module('myApp', [])
.run(function($rootScope) {
    $rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
  $scope.change = function() {
        $scope.test = new Date();
    };

    $scope.getOrig = function() {
        return $rootScope.test;
    };
})
.controller('myCtrl2', function($scope, $rootScope) {
    $scope.change = function() {
        $scope.test = new Date();
    };

    $scope.changeRs = function() {
        $rootScope.test = new Date();
    };

    $scope.getOrig = function() {
        return $rootScope.test;
    };
});

Marquee text in Android

Xml code

 <TextView
            android:id="@+id/txtTicker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal"
            android:ellipsize="marquee"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:freezesText="true"
            android:gravity="center_horizontal"
            android:marqueeRepeatLimit="marquee_forever"
            android:paddingLeft="5dip"
            android:paddingRight="5dip"
            android:scrollHorizontally="true"
            android:shadowColor="#FF0000"
            android:shadowDx="1.5"
            android:shadowDy="1.3"
            android:shadowRadius="1.6"
            android:singleLine="true"
            android:textColor="@android:color/white"
            android:textSize="20sp"
            android:textStyle="bold" >
        </TextView>

Java

txtEventName.setSelected(true);

if text is small then add space before and after text

txtEventName.setText("\t \t \t \t \t \t"+eventName+"\t \t \t \t \t \t");

Return the most recent record from ElasticSearch index

For information purpose, _timestamp is now deprecated since 2.0.0-beta2. Use date type in your mapping.

A simple date mapping JSON from date datatype doc:

{
  "mappings": {
     "my_type": {
        "properties": {
          "date": {
          "type": "date" 
        }
      }
    }
  }
}

You can also add a format field in date:

{
  "mappings": {
    "my_type": {
      "properties": {
        "date": {
          "type":   "date",
          "format": "yyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
        }
      }
    }
  }
}

Replace multiple whitespaces with single whitespace in JavaScript string

I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:

  • I want to replace multiple occurences of whitespace inside the string with a single space
  • ...and... I do not want whitespaces in the beginnin or end of the string (trim)

For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):

s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');

The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.

Angular 2 Scroll to bottom (Chat style)

Vivek's answer has worked for me, but resulted in an expression has changed after it was checked error. None of the comments worked for me, but what I did was change the change detection strategy.

import {  Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'page1',
  templateUrl: 'page1.html',
})

AngularJS : The correct way of binding to a service properties

To bind any data,which sends service is not a good idea (architecture),but if you need it anymore I suggest you 2 ways to do that

1) you can get the data not inside you service.You can get data inside your controller/directive and you will not have a problem to bind it anywhere

2) you can use angularjs events.Whenever you want,you can send a signal(from $rootScope) and catch it wherever you want.You can even send a data on that eventName.

Maybe this can help you. If you need more with examples,here is the link

http://www.w3docs.com/snippets/angularjs/bind-value-between-service-and-controller-directive.html

JOptionPane Input to int

String String_firstNumber = JOptionPane.showInputDialog("Input  Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);

Now your Int_firstnumber contains integer value of String_fristNumber.

hope it helped

Android Starting Service at Boot Time , How to restart service class after device Reboot?

First register a receiver in your manifest.xml file:

    <receiver android:name="com.mileagelog.service.Broadcast_PowerUp" >
        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
        </intent-filter>
    </receiver>

and then write a broadcast for this receiver like:

public class Broadcast_PowerUp extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
        Toast.makeText(context, "Service_PowerUp Started",
                Toast.LENGTH_LONG).show();


    } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {



        Toast.makeText(context, "Service_PowerUp Stoped", Toast.LENGTH_LONG)
        .show();
    }
  }
}

Cheap way to search a large text file for a string

I'm surprised no one mentioned mapping the file into memory: mmap

With this you can access the file as if it were already loaded into memory and the OS will take care of mapping it in and out as possible. Also, if you do this from 2 independent processes and they map the file "shared", they will share the underlying memory.

Once mapped, it will behave like a bytearray. You can use regular expressions, find or any of the other common methods.

Beware that this approach is a little OS specific. It will not be automatically portable.

How can I recover the return value of a function passed to multiprocessing.Process?

I think the approach suggested by @sega_sai is the better one. But it really needs a code example, so here goes:

import multiprocessing
from os import getpid

def worker(procnum):
    print('I am number %d in process %d' % (procnum, getpid()))
    return getpid()

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes = 3)
    print(pool.map(worker, range(5)))

Which will print the return values:

I am number 0 in process 19139
I am number 1 in process 19138
I am number 2 in process 19140
I am number 3 in process 19139
I am number 4 in process 19140
[19139, 19138, 19140, 19139, 19140]

If you are familiar with map (the Python 2 built-in) this should not be too challenging. Otherwise have a look at sega_Sai's link.

Note how little code is needed. (Also note how processes are re-used).

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

As of February 27, 2014, npm no longer supports its self-signed certificates. The following options, as recommended by npm, is to do one of the following:

Upgrade your version of npm

npm install npm -g --ca=""

-- OR --

Tell your current version of npm to use known registrars

npm config set ca ""

Update: npm has posted More help with SELF_SIGNED_CERT_IN_CHAIN and npm with more solutions particular to different environments



You may or may not need to prepend sudo to the recommendations.


Other options

It seems that people are having issues using npm's recommendations, so here are some other potential solutions.

Upgrade Node itself
Receiving this error may suggest you have an older version of node, which naturally comes with an older version of npm. One solution is to upgrade your version of Node. This is likely the best option as it brings you up to date and fixes existing bugs and vulnerabilities.

The process here depends on how you've installed Node, your operating system, and otherwise.

Update npm
Being that you probably got here while trying to install a package, it is possible that npm install npm -g might fail with the same error. If this is the case, use update instead. As suggested by Nisanth Sojan:

npm update npm -g

Update npm alternative
One way around the underlying issue is to use known registrars, install, and then stop using known registrars. As suggested by jnylen:

npm config set ca ""
npm install npm -g
npm config delete ca

Is there an opposite to display:none?

The best answer for display: none is

display:inline

or

display:normal

How do I run a Python program?

What I just did, to open a simple python script by double clicking. I just added a batch file to the directory containing the script:

@echo off
python exercise.py
pause>nul

(I have the python executable on my system path. If not one would need include its complete path of course.)

Then I just can double click on the batch file to run the script. The third line keeps the cmd window from being dismissed as soon as the script ends, so you can see the results. :) When you're done just close the command window.

Spring,Request method 'POST' not supported

For information i removed the action attribute and i got this error when i call an ajax post..Even though my action attribute in the form looks like this action="javascript://;"

I thought I had it from the ajax call and serializing the form but I added the dummy action attribute to the form back again and it worked.

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Drawing an SVG file on a HTML5 canvas

EDIT Dec 16th, 2019

Path2D is supported by all major browsers now

EDIT November 5th, 2014

You can now use ctx.drawImage to draw HTMLImageElements that have a .svg source in some but not all browsers. Chrome, IE11, and Safari work, Firefox works with some bugs (but nightly has fixed them).

var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";

Live example here. You should see a green square in the canvas. The second green square on the page is the same <svg> element inserted into the DOM for reference.

You can also use the new Path2D objects to draw SVG (string) paths. In other words, you can write:

var path = new Path2D('M 100,100 h 50 v 50 h 50');
ctx.stroke(path);

Live example of that here.


Old posterity answer:

There's nothing native that allows you to natively use SVG paths in canvas. You must convert yourself or use a library to do it for you.

I'd suggest looking in to canvg:

http://code.google.com/p/canvg/

http://canvg.googlecode.com/svn/trunk/examples/index.htm

Difference between $(window).load() and $(document).ready() functions

$(document).ready happens when all the elements are present in the DOM, but not necessarily all content.

$(document).ready(function() {
    alert("document is ready");
});

window.onload or $(window).load() happens after all the content resources (images, etc) have been loaded.

$(window).load(function() {
    alert("window is loaded");
});

What is the default access specifier in Java?

the default access specifier is package.Classes can access the members of other classes in the same package.but outside the package it appears as private

How to create a folder with name as current date in batch (.bat) files

echo var D = new Date() > tmp.js 
echo D = (D.getFullYear()*100+D.getMonth()+1)*100+D.getDate() >> tmp.js 
echo WScript.Echo( 'set YYYYMMDD='+D ) >> tmp.js 
echo @echo off > tmp.bat 
cscript //nologo tmp.js >> tmp.bat 
call tmp.bat
mkdir %YYYYMMDD%

Renaming files in a folder to sequential numbers

If your rename doesn't support -N, you can do something like this:

ls -1 --color=never -c | xargs rename -n 's/.*/our $i; sprintf("%04d.jpg", $i++)/e'

Edit To start with a given number, you can use the (somewhat ugly-looking) code below, just replace 123 with the number you want:

ls -1 --color=never  -c | xargs rename -n 's/.*/our $i; if(!$i) { $i=123; } sprintf("%04d.jpg", $i++)/e'

This lists files in order by creation time (newest first, add -r to ls to reverse sort), then sends this list of files to rename. Rename uses perl code in the regex to format and increment counter.

However, if you're dealing with JPEG images with EXIF information, I'd recommend exiftool

This is from the exiftool documentation, under "Renaming Examples"

   exiftool '-FileName<CreateDate' -d %Y%m%d_%H%M%S%%-c.%%e dir

   Rename all images in "dir" according to the "CreateDate" date and time, adding a copy number with leading '-' if the file already exists ("%-c"), and
   preserving the original file extension (%e).  Note the extra '%' necessary to escape the filename codes (%c and %e) in the date format string.

Disable developer mode extensions pop up in Chrome

Unfortunately I cant automate setting it to developer mode because of restrictions in width using the browser in iphone mode. I have found a dangerous workaround for now, install the dev channel version of chrome. It does not have the warning message, but im sure it will cause me more problems in the long run when problems are introduced. Still will hopefully give me a few days to find a workaround.

Custom fonts and XML layouts (Android)

Peter's answer is the best, but it can be improved by using the styles.xml from Android to customize your fonts for all textviews in your app.

My code is here

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

How can I get the DateTime for the start of the week?

Did it for Monday but similar logic for Sunday.

public static DateTime GetStartOfWeekDate()
{
    // Get today's date
    DateTime today = DateTime.Today;
    // Get the value for today. DayOfWeek is an enum with 0 being Sunday, 1 Monday, etc
    var todayDayOfWeek = (int)today.DayOfWeek;

    var dateStartOfWeek = today;
    // If today is not Monday, then get the date for Monday
    if (todayDayOfWeek != 1)
    {
        // How many days to get back to Monday from today
        var daysToStartOfWeek = (todayDayOfWeek - 1);
        // Subtract from today's date the number of days to get to Monday
        dateStartOfWeek = today.AddDays(-daysToStartOfWeek);
    }

    return dateStartOfWeek;

}

Class method differences in Python: bound, unbound and static

method_two won't work because you're defining a member function but not telling it what the function is a member of. If you execute the last line you'll get:

>>> a_test.method_two()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)

If you're defining member functions for a class the first argument must always be 'self'.

How can I see the raw SQL queries Django is running?

I developed an extension for this purpose, so you can easily put a decorator on your view function and see how many queries are executed.

To install:

$ pip install django-print-sql

To use as context manager:

from django_print_sql import print_sql

# set `count_only` to `True` will print the number of executed SQL statements only
with print_sql(count_only=False):

  # write the code you want to analyze in here,
  # e.g. some complex foreign key lookup,
  # or analyzing a DRF serializer's performance

  for user in User.objects.all()[:10]:
      user.groups.first()

To use as decorator:

from django_print_sql import print_sql_decorator


@print_sql_decorator(count_only=False)  # this works on class-based views as well
def get(request):
    # your view code here

Github: https://github.com/rabbit-aaron/django-print-sql

Get number of digits with JavaScript

You can use in this trick:

(''+number).length

Print a list in reverse order with range()?

[9-i for i in range(10)]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

How to remove \n from a list element?

You could do -

DELIMITER = '\t'
lines = list()
for line in open('file.txt'):
    lines.append(line.strip().split(DELIMITER))

The lines has got all the contents of your file.

One could also use list comprehensions to make this more compact.

lines = [ line.strip().split(DELIMITER) for line in open('file.txt')]

How to hide a button programmatically?

You can use the following code:

playButton = (Button) findViewById(R.id.play);
playButton.setVisibility(View.VISIBLE);
playButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        //when play is clicked show stop button and hide play button
        playButton.setVisibility(View.GONE);
        stopButton.setVisibility(View.VISIBLE);
    }
});

How to create a directory using Ansible

You can use the statement

- name: webfolder - Creates web folder
  file: path=/srv/www state=directory owner=www-data group=www-data mode=0775`

When should I use a trailing slash in my URL?

Other answers here seem to favor omitting the trailing slash. There is one case in which a trailing slash will help with search engine optimization (SEO). That is the case that your document has what appears to be a file extension that is not .html. This becomes an issue with sites that are rating websites. They might choose between these two urls:

  • http://mysite.example.com/rated.example.com
  • http://mysite.example.com/rated.example.com/

In such a case, I would choose the one with the trailing slash. That is because the .com extension is an extension for Windows executable command files. Search engines and virus checkers often dislike URLs that appear that they may contain malware distributed through such mechanisms. The trailing slash seems to mitigate any concerns, allowing the page to rank in search engines and get by virus checkers.

If your URLs have no . in the file portion, then I would recommend omitting the trailing slash for simplicity.

PHP append one array to another (not array_push or +)

Following on from answer's by bstoney and Snark I did some tests on the various methods:

// Test 1 (array_merge)
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
$array1 = array_merge($array1, $array2);
echo sprintf("Test 1: %.06f\n", microtime(true) - $start);

// Test2 (foreach)
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
foreach ($array2 as $v) {
    $array1[] = $v;
}
echo sprintf("Test 2: %.06f\n", microtime(true) - $start);

// Test 3 (... token)
// PHP 5.6+ and produces error if $array2 is empty
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
array_push($array1, ...$array2);
echo sprintf("Test 3: %.06f\n", microtime(true) - $start);

Which produces:

Test 1: 0.002717 
Test 2: 0.006922 
Test 3: 0.004744

ORIGINAL: I believe as of PHP 7, method 3 is a significantly better alternative due to the way foreach loops now act, which is to make a copy of the array being iterated over.

Whilst method 3 isn't strictly an answer to the criteria of 'not array_push' in the question, it is one line and the most high performance in all respects, I think the question was asked before the ... syntax was an option.

UPDATE 25/03/2020: I've updated the test which was flawed as the variables weren't reset. Interestingly (or confusingly) the results now show as test 1 being the fastest, where it was the slowest, having gone from 0.008392 to 0.002717! This can only be down to PHP updates, as this wouldn't have been affected by the testing flaw.

So, the saga continues, I will start using array_merge from now on!