Programs & Examples On #Fuzzing

Testing software by presenting it with invalid input to find errors in input validation and handling.

How to set the context path of a web application in Tomcat 7.0

I faced this problem for one month,Putting context tag inside server.xml is not safe it affect context elements deploying for all other host ,for big apps it take connection errors also not good isolation for example you may access other sites by folder name domain2.com/domain1Folder !! also database session connections loaded twice ! the other way is put ROOT.xml file that has context tag with full path such :

 <Context path="" docBase="/var/lib/tomcat7/webapps/ROOT" />

in conf/catalina/webappsfoldername and deploy war file as ROOT.war inside webappsfoldername and also specify host such

 <Host name="domianname"  appBase="webapps2" unpackWARs="true"  autoDeploy="true"  xmlValidation="false" xmlNamespaceAware="false" >

        <Logger className="org.apache.catalina.logger.FileLogger"
               directory="logs"  prefix="localhost_log." suffix=".txt"
          timestamp="true"/>
</Host>

In this approach also for same type apps user sessions has not good isolation ! you may inside app1 if app1 same as app2 you may after login by server side session automatically can login to app2 ?! So you have to keep users session in client side cache and not with jsessionid ! we may change engine name from localhost to solve it. but let say playing with tomcat need more time than play with other cats!

Practical uses for AtomicInteger

The absolute simplest example I can think of is to make incrementing an atomic operation.

With standard ints:

private volatile int counter;

public int getNextUniqueIndex() {
    return counter++; // Not atomic, multiple threads could get the same result
}

With AtomicInteger:

private AtomicInteger counter;

public int getNextUniqueIndex() {
    return counter.getAndIncrement();
}

The latter is a very simple way to perform simple mutations effects (especially counting, or unique-indexing), without having to resort to synchronizing all access.

More complex synchronization-free logic can be employed by using compareAndSet() as a type of optimistic locking - get the current value, compute result based on this, set this result iff value is still the input used to do the calculation, else start again - but the counting examples are very useful, and I'll often use AtomicIntegers for counting and VM-wide unique generators if there's any hint of multiple threads being involved, because they're so easy to work with I'd almost consider it premature optimisation to use plain ints.

While you can almost always achieve the same synchronization guarantees with ints and appropriate synchronized declarations, the beauty of AtomicInteger is that the thread-safety is built into the actual object itself, rather than you needing to worry about the possible interleavings, and monitors held, of every method that happens to access the int value. It's much harder to accidentally violate threadsafety when calling getAndIncrement() than when returning i++ and remembering (or not) to acquire the correct set of monitors beforehand.

Using Tempdata in ASP.NET MVC - Best practice

Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek method. I would recommend reading this cool article:

MVC Tempdata , Peek and Keep confusion

How to filter rows in pandas by regex

Use contains instead:

In [10]: df.b.str.contains('^f')
Out[10]: 
0    False
1     True
2     True
3    False
Name: b, dtype: bool

How to Replace dot (.) in a string in Java

return sentence.replaceAll("\s",".");

filter items in a python dictionary where keys contain a specific string

Jonathon gave you an approach using dict comprehensions in his answer. Here is an approach that deals with your do something part.

If you want to do something with the values of the dictionary, you don't need a dictionary comprehension at all:

I'm using iteritems() since you tagged your question with

results = map(some_function, [(k,v) for k,v in a_dict.iteritems() if 'foo' in k])

Now the result will be in a list with some_function applied to each key/value pair of the dictionary, that has foo in its key.

If you just want to deal with the values and ignore the keys, just change the list comprehension:

results = map(some_function, [v for k,v in a_dict.iteritems() if 'foo' in k])

some_function can be any callable, so a lambda would work as well:

results = map(lambda x: x*2, [v for k,v in a_dict.iteritems() if 'foo' in k])

The inner list is actually not required, as you can pass a generator expression to map as well:

>>> map(lambda a: a[0]*a[1], ((k,v) for k,v in {2:2, 3:2}.iteritems() if k == 2))
[4]

SyntaxError: missing ; before statement

I got this error, hope this will help someone:

const firstName = 'Joe';
const lastName = 'Blogs';
const wholeName = firstName + ' ' lastName + '.';

The problem was that I was missing a plus (+) between the empty space and lastName. This is a super simplified example: I was concatenating about 9 different parts so it was hard to spot the error.

Summa summarum: if you get "SyntaxError: missing ; before statement", don't look at what is wrong with the the semicolon (;) symbols in your code, look for an error in syntax on that line.

Characters allowed in GET parameter

All of the rules concerning the encoding of URIs (which contains URNs and URLs) are specified in the RFC1738 and the RFC3986, here's a TL;DR of these long and boring documents:

Percent-encoding, also known as URL encoding, is a mechanism for encoding information in a URI under certain circumstances. The characters allowed in a URI are either reserved or unreserved. Reserved characters are those characters that sometimes have special meaning, but they are not the only characters that needs encoding.

There are 66 unreserved characters that doesn't need any encoding: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~

There are 18 reserved characters which needs to be encoded: !*'();:@&=+$,/?#[], and all the other characters must be encoded.

To percent-encode a character, simply concatenate "%" and its ASCII value in hexadecimal. The php functions "urlencode" and "rawurlencode" do this job for you.

What is the difference between Task.Run() and Task.Factory.StartNew()

Apart from the similarities i.e. Task.Run() being a shorthand for Task.Factory.StartNew(), there is a minute difference between their behaviour in case of sync and async delegates.

Suppose there are following two methods:

public async Task<int> GetIntAsync()
{
    return Task.FromResult(1);
}

public int GetInt()
{
    return 1;
}

Now consider the following code.

var sync1 = Task.Run(() => GetInt());
var sync2 = Task.Factory.StartNew(() => GetInt());

Here both sync1 and sync2 are of type Task<int>

However, difference comes in case of async methods.

var async1 = Task.Run(() => GetIntAsync());
var async2 = Task.Factory.StartNew(() => GetIntAsync());

In this scenario, async1 is of type Task<int>, however async2 is of type Task<Task<int>>

What causes a TCP/IP reset (RST) flag to be sent?

This is because there is another process in the network sending RST to your TCP connection.

Normally RST would be sent in the following case

  • A process close the socket when socket using SO_LINGER option is enabled
  • OS is doing the resource cleanup when your process exit without closing socket.

In your case, it sounds like a process is connecting your connection(IP + port) and keeps sending RST after establish the connection.

Get variable from PHP to JavaScript

You can print the PHP variable into your javascript while your page is created.

<script type="text/javascript">
    var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
    var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
</script>

Of course this is for simple variables and not objects.

What does this thread join code mean?

Hope it helps!

package join;

public class ThreadJoinApp {

    Thread th = new Thread("Thread 1") {
        public void run() {
            System.out.println("Current thread execution - " + Thread.currentThread().getName());
            for (int i = 0; i < 10; i++) {
                System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
            }
        }
    };

    Thread th2 = new Thread("Thread 2") {
        public void run() {
            System.out.println("Current thread execution - " + Thread.currentThread().getName());

            //Thread 2 waits until the thread 1 successfully completes.
            try {
            th.join();
            } catch( InterruptedException ex) {
                System.out.println("Exception has been caught");
            }

            for (int i = 0; i < 10; i++) {
                System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
            }
        }
    };

    public static void main(String[] args) {
        ThreadJoinApp threadJoinApp = new ThreadJoinApp();
        threadJoinApp.th.start();
        threadJoinApp.th2.start();
    }

    //Happy coding -- Parthasarathy S
}

Django development IDE

Geany

It is GTK2 based, fast, lightweight, available for Linux and Windows.

How can I convert integer into float in Java?

You just need to transfer the first value to float, before it gets involved in further computations:

float z = x * 1.0 / y;

Phone: numeric keyboard for text input

I couldn't find a type that worked best for me in all situations: I needed to default to numeric entry (entry of "7.5" for example) but also at certain times allow text ("pass" for example). Users wanted a numeric keypad (entry of 7.5 for example) but occasional text entry was required ("pass" for example).

Rather what I did was to add a checkbox to the form and allow the user to toggle my input (id="inputSresult") between type="number" and type="text".

<input type="number" id="result"... >
<label><input id="cbAllowTextResults" type="checkbox" ...>Allow entry of text results.</label>

Then I wired a click handler to the checkbox that toggles the type between text and number based on whether the checkbox above is checked:

$(document).ready(function () {
    var cb = document.getElementById('cbAllowTextResults');
    cb.onclick = function (event) {
        if ($("#cbAllowTextResults").is(":checked"))
            $("#result").attr("type", "text");
        else
            $("#result").attr("type", "number");

    }
});

This worked out well for us.

Detect browser or tab closing

Try to use it:

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

$(function () {
    $("a").not('#lnkLogOut').click(function () {
        window.onbeforeunload = null;
    });
    $(".btn").click(function () {
        window.onbeforeunload = null;
});
});

Calculate distance between two points in google maps V3

Example using GPS latitude/longitude of 2 points.

var latitude1 = 39.46;
var longitude1 = -0.36;
var latitude2 = 40.40;
var longitude2 = -3.68;

var distance = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(latitude1, longitude1), new google.maps.LatLng(latitude2, longitude2));       

Changing java platform on which netbeans runs

In my Windows 7 box I found netbeans.conf in <Drive>:\<Program Files folder>\<NetBeans installation folder>\etc . Thanks all.

Specifying Style and Weight for Google Fonts

you can use the weight value specified in the Google Fonts.

body{
 font-family: 'Heebo', sans-serif;
 font-weight: 100;
}

Convert form data to JavaScript object with jQuery

This function returns all values converted to the right type;

bool/string/(integer/floats) possible

Tho you kinda need jQuery for this, but since serializeArray is jQuery too, so no big deal imho.

/**
 * serialized a form to a json object
 *
 * @usage: $("#myform").jsonSerialize();
 *
 */

(function($) {
    "use strict";
    $.fn.jsonSerialize = function() {
        var json = {};
        var array = $(this).serializeArray();
        $.each(array, function(key, obj) {
            var value = (obj.value == "") ? false : obj.value;
            if(value) {
                // check if we have a number
                var isNum = /^\d+$/.test(value);
                if(isNum) value = parseFloat(value);
                // check if we have a boolean
                var isBool = /^(false|true)+$/.test(value);
                if(isBool) value = (value!=="false");
            }
            json[obj.name] = value;
        });
        return json;
    }
})(jQuery);

This project references NuGet package(s) that are missing on this computer

I had the same issue. In my case installing the Microsoft.Bcl.Build package fixed the problem.

How to get the indices list of all NaN value in numpy array?

You can use np.where to match the boolean conditions corresponding to Nan values of the array and map each outcome to generate a list of tuples.

>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]

How can I change the remote/target repository URL on Windows?

The easiest way to tweak this in my opinion (imho) is to edit the .git/config file in your repository. Look for the entry you messed up and just tweak the URL.

On my machine in a repo I regularly use it looks like this:

KidA% cat .git/config 
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    autocflg = true
[remote "origin"]
    url = ssh://localhost:8888/opt/local/var/git/project.git
    #url = ssh://xxx.xxx.xxx.xxx:80/opt/local/var/git/project.git
    fetch = +refs/heads/*:refs/remotes/origin/*

The line you see commented out is an alternative address for the repository that I sometimes switch to simply by changing which line is commented out.

This is the file that is getting manipulated under-the-hood when you run something like git remote rm or git remote add but in this case since its only a typo you made it might make sense to correct it this way.

How to get all table names from a database?

In your example problem is passed table name pattern in getTables function of DatabaseMetaData.

Some database supports Uppercase identifier, some support lower case identifiers. For example oracle fetches the table name in upper case, while postgreSQL fetch it in lower case.

DatabaseMetaDeta provides a method to determine how the database stores identifiers, can be mixed case, uppercase, lowercase see:http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()

From below example, you can get all tables and view of providing table name pattern, if you want only tables then remove "VIEW" from TYPES array.

public class DBUtility {
    private static final String[] TYPES = {"TABLE", "VIEW"};
    public static void getTableMetadata(Connection jdbcConnection, String tableNamePattern, String schema, String catalog, boolean isQuoted) throws HibernateException {
            try {
                DatabaseMetaData meta = jdbcConnection.getMetaData();
                ResultSet rs = null;
                try {
                    if ( (isQuoted && meta.storesMixedCaseQuotedIdentifiers())) {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    } else if ( (isQuoted && meta.storesUpperCaseQuotedIdentifiers())
                        || (!isQuoted && meta.storesUpperCaseIdentifiers() )) {
                        rs = meta.getTables(
                                StringHelper.toUpperCase(catalog),
                                StringHelper.toUpperCase(schema),
                                StringHelper.toUpperCase(tableNamePattern),
                                TYPES
                            );
                    }
                    else if ( (isQuoted && meta.storesLowerCaseQuotedIdentifiers())
                            || (!isQuoted && meta.storesLowerCaseIdentifiers() )) {
                        rs = meta.getTables( 
                                StringHelper.toLowerCase( catalog ),
                                StringHelper.toLowerCase(schema), 
                                StringHelper.toLowerCase(tableNamePattern), 
                                TYPES 
                            );
                    }
                    else {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    }

                    while ( rs.next() ) {
                        String tableName = rs.getString("TABLE_NAME");
                        System.out.println("table = " + tableName);
                    }



                }
                finally {
                    if (rs!=null) rs.close();
                }
            }
            catch (SQLException sqlException) {
                // TODO 
                sqlException.printStackTrace();
            }

    }

    public static void main(String[] args) {
        Connection jdbcConnection;
        try {
            jdbcConnection = DriverManager.getConnection("", "", "");
            getTableMetadata(jdbcConnection, "tbl%", null, null, false);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

How do you copy the contents of an array to a std::vector in C++ without looping?

Yet another answer, since the person said "I don't know how many times my function will be called", you could use the vector insert method like so to append arrays of values to the end of the vector:

vector<int> x;

void AddValues(int* values, size_t size)
{
   x.insert(x.end(), values, values+size);
}

I like this way because the implementation of the vector should be able to optimize for the best way to insert the values based on the iterator type and the type itself. You are somewhat replying on the implementation of stl.

If you need to guarantee the fastest speed and you know your type is a POD type then I would recommend the resize method in Thomas's answer:

vector<int> x;

void AddValues(int* values, size_t size)
{
   size_t old_size(x.size());
   x.resize(old_size + size, 0);
   memcpy(&x[old_size], values, size * sizeof(int));
}

How to connect to SQL Server from another computer?

I'll edit my previous answer based on further info supplied. You can clearely ping the remote computer as you can use terminal services.

I've a feeling that port 1433 is being blocked by a firewall, hence your trouble. See TCP Ports Needed for Communication to SQL Server Through a Firewall by Microsoft.

Try using this application to ping your servers ip address and port 1433.

tcping your.server.ip.address 1433

And see if you get a "Port is open" response from tcping.

Ok, next to try is to check SQL Server. RDP onto the SQL Server computer. Start SSMS. Connect to the database. In object explorer (usually docked on the left) right click on the server and click properties.

alt text http://www.hicrest.net/server_prop_menu.jpg

Goto the Connections settings and make sure "Allow remote connections to this server" is ticket.

alt text http://www.hicrest.net/server_properties.jpg

Stop MySQL service windows

To successfully stop MySQL Service on Windows

  1. Check on services the name of the service for MySQL
  2. Run as administrator : net stop [MySQL Service name]

'ssh' is not recognized as an internal or external command

For Windows, first install the git base from here: https://git-scm.com/downloads

Next, set the environment variable:

  1. Press Windows+R and type sysdm.cpl
  2. Select advance -> Environment variable
  3. Select path-> edit the path and paste the below line:
C:\Program Files\Git\git-bash.exe

To test it, open the command window: press Windows+R, type cmd and then type ssh.

Trying to add adb to PATH variable OSX

If anyone can't seem to get there .bash_profile file to take any new Paths AND you have other commands in that file (like alias commands) then try moving the PATH statements to the top of the file.

That is the only thing that worked for me. The reason it worked was because I had some typos in my alias commands and apparently this file throws an error and exits if it runs into a problem. So that is why my PATH statements weren't being run. Moving it to the top just let it run first.

Use Fieldset Legend with bootstrap

I had a different approach , used bootstrap panel to show it little more rich. Just to help someone and improve the answer.

_x000D_
_x000D_
.text-on-pannel {_x000D_
  background: #fff none repeat scroll 0 0;_x000D_
  height: auto;_x000D_
  margin-left: 20px;_x000D_
  padding: 3px 5px;_x000D_
  position: absolute;_x000D_
  margin-top: -47px;_x000D_
  border: 1px solid #337ab7;_x000D_
  border-radius: 8px;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
  /* for text on pannel */_x000D_
  margin-top: 27px !important;_x000D_
}_x000D_
_x000D_
.panel-body {_x000D_
  padding-top: 30px !important;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="container">_x000D_
  <div class="panel panel-primary">_x000D_
    <div class="panel-body">_x000D_
      <h3 class="text-on-pannel text-primary"><strong class="text-uppercase"> Title </strong></h3>_x000D_
      <p> Your Code </p>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div>
_x000D_
_x000D_
_x000D_

This will give below look. enter image description here

Note: We need to change the styles in order to use different header size.

pandas get column average/mean

You can simply go for: df.describe() that will provide you with all the relevant details you need, but to find the min, max or average value of a particular column (say 'weights' in your case), use:

    df['weights'].mean(): For average value
    df['weights'].max(): For maximum value
    df['weights'].min(): For minimum value

Java for loop syntax: "for (T obj : objects)"

public class ForEachLoopExample {

    public static void main(String[] args) {

        System.out.println("For Each Loop Example: ");

        int[] intArray = { 1,2,3,4,5 };

        //Here iteration starts from index 0 to last index
        for(int i : intArray)
            System.out.println(i);
    }

}

Win32Exception (0x80004005): The wait operation timed out

In our case we were able to narrow the cause down to a number of views which had WITH SCHEMABINDING on them. Although this is supposed to improve performance it was resulting in an awful query plan (doing a single record update on a table which was being referenced by these views was taking nearly 2 seconds of elapsed time). Removing WITH SCHEMABINDING has meant all is running smoothly again and the "wait operation timed out" errors have gone.

The server committed a protocol violation. Section=ResponseStatusLine ERROR

Many solutions talk about a workaround, but not about the actual cause of the error.

One possible cause of this error is if the webserver uses an encoding other than ASCII or ISO-8859-1 to output the header response section. The reason to use ISO-8859-1 would be if the Response-Phrase contains extended Latin characters.

Another possible cause of this error is if a webserver uses UTF-8 that outputs the byte-order-marker (BOM). For example, the default constant Encoding.UTF8 outputs the BOM, and it's easy to forget this. The webpages will work correctly in Firefox and Chrome, but HttpWebRequest will bomb :). A quick fix is to change the webserver to use the UTF-8 encoding that doesn't output the BOM, e.g. new UTF8Encoding(false) (which is OK as long as the Response-Phrase only contains ASCII characters, but really it should use ASCII or ISO-8859-1 for the headers, and then UTF-8 or some other encoding for the response).

SVN - Checksum mismatch while updating

1.'update to reversion' check 'only this item' under the directory 2.update again check 'Fully recursive'

Is it possible to use JavaScript to change the meta-tags of the page?

You can use more simpler and lighter solution:

document.head.querySelector('meta[name="description"]').content = _desc

How to find the minimum value in an ArrayList, along with the index number? (Java)

This should do it using built in functions.

public static int minIndex (ArrayList<Float> list) {
  return list.indexOf (Collections.min(list)); }

How to add a WiX custom action that happens only on uninstall (via MSI)?

EDIT: Perhaps look at the answer currently immediately below.


This topic has been a headache for long time. I finally figured it out. There are some solutions online, but none of them really works. And of course there is no documentation. So in the chart below there are several properties that are suggested to use and the values they have for various installation scenarios:

alt text

So in my case I wanted a CA that will run only on uninstalls - not upgrades, not repairs or modifies. According to the table above I had to use

<Custom Action='CA_ID' Before='other_CA_ID'>
        (NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")</Custom>

And it worked!

How to SELECT by MAX(date)?

Workaround but working solution

Only if ID is autoincrement, you can search for the maximum id instead of the max date. So, by the ID you can find all others fields.

select *
from table
where id IN ( 
              select max(id)
              from table
              group by #MY_FIELD#
              )

MySQL - DATE_ADD month interval

Well, for me this is the expected result; adding six months to Jan. 1st July.

mysql> SELECT DATE_ADD( '2011-01-01', INTERVAL 6 month );
+--------------------------------------------+
| DATE_ADD( '2011-01-01', INTERVAL 6 month ) |
+--------------------------------------------+
| 2011-07-01                                 | 
+--------------------------------------------+

Pass arguments to Constructor in VBA

Why not this way:

  1. In a class module »myClass« use Public Sub Init(myArguments) instead of Private Sub Class_Initialize()
  2. Instancing: Dim myInstance As New myClass: myInstance.Init myArguments

Capitalize only first character of string and leave others alone? (Rails)

An even shorter version could be:

s = "i'm from New York..."
s[0] = s.capitalize[0]

Java, "Variable name" cannot be resolved to a variable

I've noticed bizarre behavior with Eclipse version 4.2.1 delivering me this error:

String cannot be resolved to a variable

With this Java code:

if (true)
    String my_variable = "somevalue";
    System.out.println("foobar");

You would think this code is very straight forward, the conditional is true, we set my_variable to somevalue. And it should print foobar. Right?

Wrong, you get the above mentioned compile time error. Eclipse is trying to prevent you from making a mistake by assuming that both statements are within the if statement.

If you put braces around the conditional block like this:

if (true){
    String my_variable = "somevalue"; }
    System.out.println("foobar");

Then it compiles and runs fine. Apparently poorly bracketed conditionals are fair game for generating compile time errors now.

unsigned APK can not be installed

You can test the unsigned-apk only on Emulator. And as its step of application deployment and distribution, you should read this article atleast once, i suggest: http://developer.android.com/guide/publishing/app-signing.html.

For your question, you can find the below line in above article:

All applications must be signed. The system will not install an application that is not signed.

so you have to have signed-apk before the distribution of your application.

To generate Signed-apk of your application, there is a simple wizard procedure, click on File -> Export -> Android -> Export Android application.

enter image description here

What size do you use for varchar(MAX) in your parameter declaration?

For those of us who did not see -1 by Michal Chaniewski, the complete line of code:

cmd.Parameters.Add("@blah",SqlDbType.VarChar,-1).Value = "some large text";

og:type and valid values : constantly being parsed as og:type=website

Make sure your article:author data is a Facebook author URL. Unfortunately, that conflicts with what Pinterest is expecting. It's the best thing about standards, there are so many ways to implement them!

<meta property="article:author" content="https://www.facebook.com/mpatnode76">

But Pinterest wants to see something like this:

<meta property="article:author" content="Mike Patnode">

We ended up swapping the formats depending upon the user agent. Hopefully, that doesn't screw up your page cache. That fixed it for us.

Full disclosure. Found this here: https://surniaulula.com/2014/03/01/pinterest-articleauthor-incompatible-with-open-graph/

Display string multiple times

The accepted answer is short and sweet, but here is an alternate syntax allowing to provide a separator in Python 3.x.

print(*3*('-',), sep='_')

When should we implement Serializable interface?

  1. From What's this "serialization" thing all about?:

    It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).

    Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."

    So, implement the Serializable interface when you need to store a copy of the object, send them to another process which runs on the same system or over the network.

  2. Because you want to store or send an object.

  3. It makes storing and sending objects easy. It has nothing to do with security.

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

In my case, I got this while overloading

ostream & operator << (ostream &out, const MyClass &obj)

and forgot to return out. In other systems this just generates a warning, but on macos it also generated an error (although it seems to print correctly).

The error was resolved by adding the correct return value. In my case, adding the -mmacosx-version-min flag had no effect.

Malformed String ValueError ast.literal_eval() with String representation of Tuple

I know this is an old question, but I think found a very simple answer, in case anybody needs it.

If you put string quotes inside your string ("'hello'"), ast_literaleval() will understand it perfectly.

You can use a simple function:

    def doubleStringify(a):
        b = "\'" + a + "\'"
        return b

Or probably more suitable for this example:

    def perfectEval(anonstring):
        try:
            ev = ast.literal_eval(anonstring)
            return ev
        except ValueError:
            corrected = "\'" + anonstring + "\'"
            ev = ast.literal_eval(corrected)
            return ev

How to capture UIView to UIImage without loss of quality on retina display

- (UIImage*)screenshotForView:(UIView *)view
{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // hack, helps w/ our colors when blurring
    NSData *imageData = UIImageJPEGRepresentation(image, 1); // convert to jpeg
    image = [UIImage imageWithData:imageData];

    return image;
}

How to delete object from array inside foreach loop?

I'm not much of a php programmer, but I can say that in C# you cannot modify an array while iterating through it. You may want to try using your foreach loop to identify the index of the element, or elements to remove, then delete the elements after the loop.

Regex: Check if string contains at least one digit

If anybody falls here from google, this is how to check if string contains at least one digit in C#:

With Regex

if (Regex.IsMatch(myString, @"\d"))
{
  // do something
}

Info: necessary to add using System.Text.RegularExpressions

With linq:

if (myString.Any(c => Char.IsDigit(c)))
{
  // do something
}

Info: necessary to add using System.Linq

Virtual member call in a constructor

One important aspect of this question which other answers have not yet addressed is that it is safe for a base-class to call virtual members from within its constructor if that is what the derived classes are expecting it to do. In such cases, the designer of the derived class is responsible for ensuring that any methods which are run before construction is complete will behave as sensibly as they can under the circumstances. For example, in C++/CLI, constructors are wrapped in code which will call Dispose on the partially-constructed object if construction fails. Calling Dispose in such cases is often necessary to prevent resource leaks, but Dispose methods must be prepared for the possibility that the object upon which they are run may not have been fully constructed.

How to get Python requests to trust a self signed SSL certificate?

Incase anyone happens to land here (like I did) looking to add a CA (in my case Charles Proxy) for httplib2, it looks like you can append it to the cacerts.txt file included with the python package.

For example:

cat ~/Desktop/charles-ssl-proxying-certificate.pem >> /usr/local/google-cloud-sdk/lib/third_party/httplib2/cacerts.txt

The environment variables referenced in other solutions appear to be requests-specific and were not picked up by httplib2 in my testing.

How do I make XAML DataGridColumns fill the entire DataGrid?

set ONE column's width to any value, i.e. width="*"

How to mark a build unstable in Jenkins when running shell scripts

Modern Jenkins versions (since 2.26, October 2016) solved this: it's just an advanced option for the Execute shell build step!

exit code for build

You can just choose and set an arbitrary exit value; if it matches, the build will be unstable. Just pick a value which is unlikely to be launched by a real process in your build.

How do I view the Explain Plan in Oracle Sql developer?

Explain only shows how the optimizer thinks the query will execute.

To show the real plan, you will need to run the sql once. Then use the same session run the following:

@yoursql 
select * from table(dbms_xplan.display_cursor()) 

This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".

HttpServletRequest - how to obtain the referring URL?

The URLs are passed in the request: request.getRequestURL().

If you mean other sites that are linking to you? You want to capture the HTTP Referrer, which you can do by calling:

request.getHeader("referer");

Can I write into the console in a unit test? If yes, why doesn't the console window open?

You could use this line to write to Output Window of the Visual Studio:

System.Diagnostics.Debug.WriteLine("Matrix has you...");

Must run in Debug mode.

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

In order to update your project to the latest version of java available in your environment, follow these steps:

  1. Open your pom.xml file
  2. Switch your view to Effective POM tab
  3. Open Find Dialog (ctrl + F) to search for maven-compiler-plugin
  4. Copy the the following lines

_x000D_
_x000D_
<plugin>_x000D_
 <artifactId>maven-compiler-plugin</artifactId>_x000D_
 <version>3.1</version>
_x000D_
_x000D_
_x000D_

  1. Click on pom.xml tab to open your project pom configuration
  2. Inside your <build> ... </build> configuration section, paste the configuration copied and modify it as...

_x000D_
_x000D_
        <plugins>_x000D_
     <plugin>_x000D_
      <artifactId>maven-compiler-plugin</artifactId>_x000D_
      <version>3.1</version>_x000D_
    _x000D_
      <configuration>_x000D_
       <source>1.8</source>_x000D_
       <target>1.8</target>_x000D_
      </configuration>_x000D_
     </plugin>_x000D_
    </plugins>
_x000D_
_x000D_
_x000D_

  1. save your configuration
  2. Right Click in your project Click on [Maven -> Update Project] and Click on OK in the displayed update dialog box.

Done!

How to put labels over geom_bar in R with ggplot2

As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:

dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))

So that the x variable matches the corresponding variable in df, and so on. Then you simply include it using geom_text:

ggplot(df) + geom_bar(aes(x,fill=x)) + 
    geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
    opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),legend.title=theme_blank(),
        axis.title.y=theme_blank())

This example will plot just the percentages, but you can paste together the counts as well via something like this:

dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")

Note that in the current version of ggplot2, opts is deprecated, so we would use theme and element_blank now.

Add params to given URL in Python

There are a couple of quirks with the urllib and urlparse modules. Here's a working example:

try:
    import urlparse
    from urllib import urlencode
except: # For Python 3
    import urllib.parse as urlparse
    from urllib.parse import urlencode

url = "http://stackoverflow.com/search?q=question"
params = {'lang':'en','tag':'python'}

url_parts = list(urlparse.urlparse(url))
query = dict(urlparse.parse_qsl(url_parts[4]))
query.update(params)

url_parts[4] = urlencode(query)

print(urlparse.urlunparse(url_parts))

ParseResult, the result of urlparse(), is read-only and we need to convert it to a list before we can attempt to modify its data.

Error message Strict standards: Non-static method should not be called statically in php

Your methods are missing the static keyword. Change

function getInstanceByName($name=''){

to

public static function getInstanceByName($name=''){

if you want to call them statically.

Note that static methods (and Singletons) are death to testability.

Also note that you are doing way too much work in the constructor, especially all that querying shouldn't be in there. All your constructor is supposed to do is set the object into a valid state. If you have to have data from outside the class to do that consider injecting it instead of pulling it. Also note that constructors cannot return anything. They will always return void so all these return false statements do nothing but end the construction.

How do I use FileSystemObject in VBA?

After adding the reference, I had to use

Dim fso As New Scripting.FileSystemObject

How to use regex in XPath "contains" function

XPath 1.0 doesn't handle regex natively, you could try something like

//*[starts-with(@id, 'sometext') and ends-with(@id, '_text')]

(as pointed out by paul t, //*[boolean(number(substring-before(substring-after(@id, "sometext"), "_text")))] could be used to perform the same check your original regex does, if you need to check for middle digits as well)

In XPath 2.0, try

//*[matches(@id, 'sometext\d+_text')]

Resize Cross Domain Iframe Height

If you have access to manipulate the code of the site you are loading, the following should provide a comprehensive method to updating the height of the iframe container anytime the height of the framed content changes.

Add the following code to the pages you are loading (perhaps in a header). This code sends a message containing the height of the HTML container any time the DOM is updated (if you're lazy loading) or the window is resized (when the user modifies the browser).

window.addEventListener("load", function(){
    if(window.self === window.top) return; // if w.self === w.top, we are not in an iframe 
    send_height_to_parent_function = function(){
        var height = document.getElementsByTagName("html")[0].clientHeight;
        //console.log("Sending height as " + height + "px");
        parent.postMessage({"height" : height }, "*");
    }
    // send message to parent about height updates
    send_height_to_parent_function(); //whenever the page is loaded
    window.addEventListener("resize", send_height_to_parent_function); // whenever the page is resized
    var observer = new MutationObserver(send_height_to_parent_function);           // whenever DOM changes PT1
    var config = { attributes: true, childList: true, characterData: true, subtree:true}; // PT2
    observer.observe(window.document, config);                                            // PT3 
});

Add the following code to the page that the iframe is stored on. This will update the height of the iframe, given that the message came from the page that that iframe loads.

<script>
window.addEventListener("message", function(e){
    var this_frame = document.getElementById("healthy_behavior_iframe");
    if (this_frame.contentWindow === e.source) {
        this_frame.height = e.data.height + "px";
        this_frame.style.height = e.data.height + "px";
    }
})
</script>

Convert string to JSON array

Input String

[
   {
      "userName": "sandeep",
      "age": 30
   }, 
   {
      "userName": "vivan",
      "age": 5
   }
]

Simple Way to Convert String to JSON

public class Test
{

    public static void main(String[] args) throws JSONException
    {
        String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}]  ";
        JSONArray jsonArr = new JSONArray(data);

        for (int i = 0; i < jsonArr.length(); i++)
        {
            JSONObject jsonObj = jsonArr.getJSONObject(i);

            System.out.println(jsonObj);
        }

    }
}

Output

{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}

How to check whether a string contains a substring in JavaScript?

There is a String.prototype.includes in ES6:

"potato".includes("to");
> true

Note that this does not work in Internet Explorer or some other old browsers with no or incomplete ES6 support. To make it work in old browsers, you may wish to use a transpiler like Babel, a shim library like es6-shim, or this polyfill from MDN:

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }

    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

Note about bug of MySQL Connector/C on macOS (my current version is 10.13.2), fix the mysql_config and reinstall mysqlclient or MySQL-python, here is the detail

Replacing characters in Ant property

Here is the solution without scripting and no external jars like ant-conrib:

The trick is to use ANT's resources:

  • There is one resource type called "propertyresource" which is like a source file, but provides an stream from the string value of this resource. So you can load it and use it in any task like "copy" that accepts files
  • There is also the task "loadresource" that can load any resource to a property (e.g., a file), but this one could also load our propertyresource. This task allows for filtering the input by applying some token transformations. Finally the following will do what you want:
<loadresource property="propB">
  <propertyresource name="propA"/>
  <filterchain>
    <tokenfilter>
      <filetokenizer/>
      <replacestring from=" " to="_"/>
    </tokenfilter>
  </filterchain>
</loadresource>

This one will replace all " " in propA by "_" and place the result in propB. "filetokenizer" treats the whole input stream (our property) as one token and appies the string replacement on it.

You can do other fancy transformations using other tokenfilters: http://ant.apache.org/manual/Types/filterchain.html

Scroll / Jump to id without jQuery

on anchor tag use href and not onclick

<a href="#target1">asdf<a>

And div:

<div id="target1">some content</div>

Shortcut to open file in Vim

Use tabs, they work when inputting file paths in vim escape mode!

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

java.lang.NoClassDefFoundError in junit

The same problem can occur if you have downloaded JUnit jar from the JUnit website, but forgotten to download the Hamcrest jar - both are required (the instructions say to download both, but I skipped ahead! Oops)

c++ array - expression must have a constant value

C++ doesn't allow non-constant values for the size of an array. That's just the way it was designed.

C99 allows the size of an array to be a variable, but I'm not sure it is allowed for two dimensions. Some C++ compilers (gcc) will allow this as an extension, but you may need to turn on a compiler option to allow it.

And I almost missed it - you need to declare a variable name, not just the array dimensions.

AngularJS directive does not update on scope variable changes

I needed a solution for this issue as well and I used the answers in this thread to come up with the following:

.directive('tpReport', ['$parse', '$http', '$compile', '$templateCache', function($parse, $http, $compile, $templateCache)
    {
        var getTemplateUrl = function(type)
        {
            var templateUrl = '';

            switch (type)
            {
                case 1: // Table
                    templateUrl = 'modules/tpReport/directives/table-report.tpl.html';
                    break;
                case 0:
                    templateUrl = 'modules/tpReport/directives/default.tpl.html';
                    break;
                default:
                    templateUrl = '';
                    console.log("Type not defined for tpReport");
                    break;
            }

            return templateUrl;
        };

        var linker = function (scope, element, attrs)
        {

            scope.$watch('data', function(){
                var templateUrl = getTemplateUrl(scope.data[0].typeID);
                var data = $templateCache.get(templateUrl);
                element.html(data);
                $compile(element.contents())(scope);

            });



        };

        return {
            controller: 'tpReportCtrl',
            template: '<div>{{data}}</div>',
            // Remove all existing content of the directive.
            transclude: true,
            restrict: "E",
            scope: {
                data: '='
            },
            link: linker
        };
    }])
    ;

Include in your html:

<tp-report data='data'></tp-report>

This directive is used for dynamically loading report templates based on the dataset retrieved from the server.

It sets a watch on the scope.data property and whenever this gets updated (when the users requests a new dataset from the server) it loads the corresponding directive to show the data.

php form action php self

If you want to be secure use this:<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

How can I reverse the order of lines in a file?

at the end of your command put: | tac

tac does exactly what you're asking for, it "Write each FILE to standard output, last line first."

tac is the opposite of cat :-).

How do I run a file on localhost?

Localhost is the computer you're using right now. You run things by typing commands at the command prompt and pressing Enter. If you're asking how to run things from your programming environment, then the answer depends on which environment you're using. Most languages have commands with names like system or exec for running external programs. You need to be more specific about what you're actually looking to do, and what obstacles you've encountered while trying to achieve it.

How to scroll to an element inside a div?

Native JS, Cross Browser, Smooth Scroll (Update 2020)

Setting ScrollTop does give the desired result but the scroll is very abrupt. Using jquery to have smooth scroll was not an option. So here's a native way to get the job done that supports all major browsers. Reference - caniuse

// get the "Div" inside which you wish to scroll (i.e. the container element)
const El = document.getElementById('xyz');

// Lets say you wish to scroll by 100px, 
El.scrollTo({top: 100, behavior: 'smooth'});

// If you wish to scroll until the end of the container
El.scrollTo({top: El.scrollHeight, behavior: 'smooth'});

That's it!


And here's a working snippet for the doubtful -

_x000D_
_x000D_
document.getElementById('btn').addEventListener('click', e => {
  e.preventDefault();
  // smooth scroll
  document.getElementById('container').scrollTo({top: 175, behavior: 'smooth'});
});
_x000D_
/* just some styling for you to ignore */
.scrollContainer {
  overflow-y: auto;
  max-height: 100px;
  position: relative;
  border: 1px solid red;
  width: 120px;
}

body {
  padding: 10px;
}

.box {
  margin: 5px;
  background-color: yellow;
  height: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
}

#goose {
  background-color: lime;
}
_x000D_
<!-- Dummy html to be ignored -->
<div id="container" class="scrollContainer">
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div id="goose" class="box">goose</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
  <div class="box">duck</div>
</div>

<button id="btn">goose</button>
_x000D_
_x000D_
_x000D_

Update: As you can perceive in the comments, it seems that Element.scrollTo() is not supported in IE11. So if you don't care about IE11 (you really shouldn't), feel free to use this in all your projects. Note that support exists for Edge! So you're not really leaving your Edge/Windows users behind ;)

Reference

Using Bootstrap Tooltip with AngularJS

easiest way , add $("[data-toggle=tooltip]").tooltip(); to the concerned controller.

Can't install APK from browser downloads

It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.

A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?

Settings > Applications > Unknown sources...

Edit

Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive

How to get the ASCII value of a character

Note that ord() doesn't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it's in. Therefore the result of ord('ä') can be 228 if you're using Latin-1, or it can raise a TypeError if you're using UTF-8. It can even return the Unicode codepoint instead if you pass it a unicode:

>>> ord(u'?')
12354

Difference between map, applymap and apply methods in Pandas

Quick Summary

  • DataFrame.apply operates on entire rows or columns at a time.

  • DataFrame.applymap, Series.apply, and Series.map operate on one element at time.

Series.apply and Series.map are similar and often interchangeable. Some of their slight differences are discussed in osa's answer below.

Git: How to pull a single file from a server repository in Git?

git fetch --all
git checkout origin/master -- <your_file_path>
git add <your_file_path>
git commit -m "<your_file_name> updated"

This is assuming you are pulling the file from origin/master.

Showing an image from an array of images - Javascript

Also, when checking for the last image, you must compare with imgArray.length-1 because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:

if(i == imgArray.length-1)

Get Character value from KeyCode in JavaScript... then trim

For those of you who came here looking for the actual Unicode character values for a keycode, like I did, here is a function for that. For instance, given the right arrow unicode keycode this will output the visible string \u001B\u005B\u0043

function toUnicode(theString) {
    var unicodeString = '';
    for (var i = 0; i < theString.length; i++) {
        var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
        while (theUnicode.length < 4) {
            theUnicode = '0' + theUnicode;
        }
        theUnicode = '\\u' + theUnicode;
        unicodeString += theUnicode;
    }
    return unicodeString;
}

Java stack overflow error - how to increase the stack size in Eclipse?

When the argument -Xss doesn't do the job try deleting the temporary files from:

c:\Users\{user}\AppData\Local\Temp\.

This did the trick for me.

How do I create a ListView with rounded corners in Android?

@kris-van-bael

For those having issues with selection highlight for the top and bottom row where the background rectangle shows up on selection you need to set the selector for your listview to transparent color.

listView.setSelector(R.color.transparent);

In color.xml just add the following -

<color name="transparent">#00000000</color>

How to dock "Tool Options" to "Toolbox"?

In the detached 'Tool Options' window, click on the red 'X' in the upper right corner to get rid of the window. Then on the main Gimp screen, click on 'Windows,' then 'Dockable Dialogs.' The first entry on its list will be 'Tool Options,' so click on that. Then, Tool Options will appear as a tab in the window on the right side of the screen, along with layers and undo history. Click and drag that tab over to the toolbox window on hte left and drop it inside. The tool options will again be docked in the toolbox.

pypi UserWarning: Unknown distribution option: 'install_requires'

This is a warning from distutils, and is a sign that you do not have setuptools installed. Installing it from http://pypi.python.org/pypi/setuptools will remove the warning.

How to initialize an array's length in JavaScript?

I'm surprised there hasn't been a functional solution suggested that allows you to set the length in one line. The following is based on UnderscoreJS:

var test = _.map(_.range(4), function () { return undefined; });
console.log(test.length);

For reasons mentioned above, I'd avoid doing this unless I wanted to initialize the array to a specific value. It's interesting to note there are other libraries that implement range including Lo-dash and Lazy, which may have different performance characteristics.

Angular 5 ngHide ngShow [hidden] not working

If you want to just toggle visibility and still keep the input in DOM:

<input class="txt" type="password" [(ngModel)]="input_pw" 
 [style.visibility]="isHidden? 'hidden': 'visible'">

The other way around is as per answer by rrd, which is to use HTML hidden attribute. In an HTML element if hidden attribute is set to true browsers are supposed to hide the element from display, but the problem is that this behavior is overridden if the element has an explicit display style mentioned.

_x000D_
_x000D_
.hasDisplay {_x000D_
  display: block;_x000D_
}
_x000D_
<input class="hasDisplay" hidden value="shown" />_x000D_
<input hidden value="not shown">
_x000D_
_x000D_
_x000D_

To overcome this you can opt to use an explicit css for [hidden] that overrides the display;

[hidden] {
  display: none !important;
}

Yet another way is to have a is-hidden class and do:

<input [class.is-hidden]="isHidden"/>

.is-hidden {
      display: none;
 }

If you use display: none the element will be skipped from the static flow and no space will be allocated for the element, if you use visibility: hidden it will be included in the flow and a space will be allocated but it will be blank space.

The important thing is to use one way across an application rather than mixing different ways thereby making the code less maintainable.

If you want to remove it from DOM

<input class="txt" type="password" [(ngModel)]="input_pw" *ngIf="!isHidden">

How to write a Python module/package?

Since nobody did cover this question of the OP yet:

What I wanted to do:

Make a python module install-able with "pip install ..."

Here is an absolute minimal example, showing the basic steps of preparing and uploading your package to PyPI using setuptools and twine.

This is by no means a substitute for reading at least the tutorial, there is much more to it than covered in this very basic example.

Creating the package itself is already covered by other answers here, so let us assume we have that step covered and our project structure like this:

.
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

In order to use setuptools for packaging, we need to add a file setup.py, this goes into the root folder of our project:

.
+-- setup.py
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

At the minimum, we specify the metadata for our package, our setup.py would look like this:

from setuptools import setup

setup(
    name='hellostackoverflow',
    version='0.0.1',
    description='a pip-installable package example',
    license='MIT',
    packages=['hellostackoverflow'],
    author='Benjamin Gerfelder',
    author_email='[email protected]',
    keywords=['example'],
    url='https://github.com/bgse/hellostackoverflow'
)

Since we have set license='MIT', we include a copy in our project as LICENCE.txt, alongside a readme file in reStructuredText as README.rst:

.
+-- LICENCE.txt
+-- README.rst
+-- setup.py
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

At this point, we are ready to go to start packaging using setuptools, if we do not have it already installed, we can install it with pip:

pip install setuptools

In order to do that and create a source distribution, at our project root folder we call our setup.py from the command line, specifying we want sdist:

python setup.py sdist

This will create our distribution package and egg-info, and result in a folder structure like this, with our package in dist:

.
+-- dist/
+-- hellostackoverflow.egg-info/
+-- LICENCE.txt
+-- README.rst
+-- setup.py
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

At this point, we have a package we can install using pip, so from our project root (assuming you have all the naming like in this example):

pip install ./dist/hellostackoverflow-0.0.1.tar.gz

If all goes well, we can now open a Python interpreter, I would say somewhere outside our project directory to avoid any confusion, and try to use our shiny new package:

Python 3.5.2 (default, Sep 14 2017, 22:51:06) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from hellostackoverflow import hellostackoverflow
>>> hellostackoverflow.greeting()
'Hello Stack Overflow!'

Now that we have confirmed the package installs and works, we can upload it to PyPI.

Since we do not want to pollute the live repository with our experiments, we create an account for the testing repository, and install twine for the upload process:

pip install twine

Now we're almost there, with our account created we simply tell twine to upload our package, it will ask for our credentials and upload our package to the specified repository:

twine upload --repository-url https://test.pypi.org/legacy/ dist/*

We can now log into our account on the PyPI test repository and marvel at our freshly uploaded package for a while, and then grab it using pip:

pip install --index-url https://test.pypi.org/simple/ hellostackoverflow

As we can see, the basic process is not very complicated. As I said earlier, there is a lot more to it than covered here, so go ahead and read the tutorial for more in-depth explanation.

Getting DOM node from React child element

React.findDOMNode(this.refs.myExample) mentioned in another answer has been deprectaed.

use ReactDOM.findDOMNode from 'react-dom' instead

import ReactDOM from 'react-dom'
let myExample = ReactDOM.findDOMNode(this.refs.myExample)

Use 'import module' or 'from module import'?

As Jan Wrobel mentions, one aspect of the different imports is in which way the imports are disclosed.

Module mymath

from math import gcd
...

Use of mymath:

import mymath
mymath.gcd(30, 42)  # will work though maybe not expected

If I imported gcd only for internal use, not to disclose it to users of mymath, this can be inconvenient. I have this pretty often, and in most cases I want to "keep my modules clean".

Apart from the proposal of Jan Wrobel to obscure this a bit more by using import math instead, I have started to hide imports from disclosure by using a leading underscore:

# for instance...
from math import gcd as _gcd
# or...
import math as _math

In larger projects this "best practice" allows my to exactly control what is disclosed to subsequent imports and what isn't. This keeps my modules clean and pays back at a certain size of project.

How to write multiple conditions of if-statement in Robot Framework

Just make sure put single space before and after "and" Keyword..

HTML: how to force links to open in a new tab, not new window

Simply using "target=_blank" will respect the user/browser preference of whether to use a tab or a new window, which in most cases is "doing the right thing".

If you specify the dimensions of the new window, some browsers will use this as an indicator that a certain size is needed, in which case a new window will always be used. Stack overflow code example Stack Overflow

Windows batch - concatenate multiple text files into one

In Win 7, navigate to the directory where your text files are. On the command prompt use:

copy *.txt combined.txt

Where combined.txt is the name of the newly created text file.

Array or List in Java. Which is faster?

ArrayList internally uses array object to add(or store) the elements. In other words, ArrayList is backed by Array data -structure.The array of ArrayList is resizable (or dynamic).

Array is faster than ArrayList because ArrayList internally uses an array. if we can directly add elements in Array and indirectly add an element in Array through ArrayList always directly mechanism is faster than an indirect mechanism.

There is two overloaded add() methods in ArrayList class:

  1. add(Object): adds an object to the end of the list.
  2. add(int index, Object ): inserts the specified object at the specified position in the list.

How the size of ArrayList grows dynamically?

public boolean add(E e)        
{       
     ensureCapacity(size+1);
     elementData[size++] = e;         
     return true;
}

An important point to note from the above code is that we are checking the capacity of the ArrayList, before adding the element. ensureCapacity() determines what is the current size of occupied elements and what is the maximum size of the array. If the size of the filled elements (including the new element to be added to the ArrayList class) is greater than the maximum size of the array then increase the size of the array. But the size of the array can not be increased dynamically. So what happens internally is new Array is created with the capacity

Till Java 6

int newCapacity = (oldCapacity * 3)/2 + 1;

(Update) From Java 7

 int newCapacity = oldCapacity + (oldCapacity >> 1);

also, data from the old array is copied into the new array.

Having overhead methods in ArrayList that's why Array is faster than ArrayList.

How to detect escape key press with pure JS or jQuery?

Pure JS

you can attach a listener to keyUp event for the document.

Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.

 document.addEventListener('keydown', (event) => {
        
        if (event.key === 'Escape') {
         //if esc key was not pressed in combination with ctrl or alt or shift
            const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
            if (isNotCombinedKey) {
                console.log('Escape key was pressed with out any group keys')
              
            }
        }
    });

Java: Calling a super method which calls an overridden method

The keyword super doesn't "stick". Every method call is handled individually, so even if you got to SuperClass.method1() by calling super, that doesn't influence any other method call that you might make in the future.

That means there is no direct way to call SuperClass.method2() from SuperClass.method1() without going though SubClass.method2() unless you're working with an actual instance of SuperClass.

You can't even achieve the desired effect using Reflection (see the documentation of java.lang.reflect.Method.invoke(Object, Object...)).

[EDIT] There still seems to be some confusion. Let me try a different explanation.

When you invoke foo(), you actually invoke this.foo(). Java simply lets you omit the this. In the example in the question, the type of this is SubClass.

So when Java executes the code in SuperClass.method1(), it eventually arrives at this.method2();

Using super doesn't change the instance pointed to by this. So the call goes to SubClass.method2() since this is of type SubClass.

Maybe it's easier to understand when you imagine that Java passes this as a hidden first parameter:

public class SuperClass
{
    public void method1(SuperClass this)
    {
        System.out.println("superclass method1");
        this.method2(this); // <--- this == mSubClass
    }

    public void method2(SuperClass this)
    {
        System.out.println("superclass method2");
    }

}

public class SubClass extends SuperClass
{
    @Override
    public void method1(SubClass this)
    {
        System.out.println("subclass method1");
        super.method1(this);
    }

    @Override
    public void method2(SubClass this)
    {
        System.out.println("subclass method2");
    }
}



public class Demo 
{
    public static void main(String[] args) 
    {
        SubClass mSubClass = new SubClass();
        mSubClass.method1(mSubClass);
    }
}

If you follow the call stack, you can see that this never changes, it's always the instance created in main().

How to stop a vb script running in windows

I can think of at least 2 different ways:

  1. using Task Manager (Ctrl-Shift-Esc), select the process tab, look for a process name cscript.exe or wscript.exe and use End Process.

  2. From the command line you could use taskkill /fi "imagename eq cscript.exe" (change to wscript.exe as needed)

Another way is using scripting and WMI. Here are some hints: look for the Win32_Process class and the Terminate method.

JMS Topic vs Queues

TOPIC:: topic is one to many communication... (multipoint or publish/subscribe) EX:-imagine a publisher publishes the movie in the youtub then all its subscribers will gets notification.... QUEVE::queve is one-to-one communication ... Ex:-When publish a request for recharge it will go to only one qreciever ... always remember if request goto all qreceivers then multiple recharge happened so while developing analyze which is fit for a application

Getting Date or Time only from a DateTime Object

Sometimes you want to have your GridView as simple as:

  <asp:GridView ID="grid" runat="server" />

You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.

protected void Page_Load(object sender, EventArgs e)
{
  grid.RowDataBound += grid_RowDataBound;
  // Your DB access code here...
  // grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
  // grid.DataBind();
}

void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType != DataControlRowType.DataRow)
    return;
  var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4);
  e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy");
}

The results shown here. DateTime Formatting

HTML text input allow only numeric input

You can also compare input value (which is treated as string by default) to itself forced as numeric, like:

if(event.target.value == event.target.value * 1) {
    // returns true if input value is numeric string
}

However, you need to bind that to event like keyup etc.

Converting cv::Mat to IplImage*

In case of gray image, I am using this function and it works fine! however you must take care about the function features ;)

CvMat * src=  cvCreateMat(300,300,CV_32FC1);      
IplImage *dist= cvCreateImage(cvGetSize(dist),IPL_DEPTH_32F,3);

cvConvertScale(src, dist, 1, 0);

MongoDB vs. Cassandra

I haven't used Cassandra, but I have used MongoDB and think it's awesome.

If you're after simple setup, this is it: You simply untar MongoDB and run the mongod daemon and that's it ... it's running.

Obviously that's only a starter, but to get you started it's easy.

Can I pass parameters by reference in Java?

From James Gosling in "The Java Programming Language":

"...There is exactly one parameter passing mode in Java - pass by value - and that keeps things simple. .."

Cannot send a content-body with this verb-type

Please set the request Content Type before you read the response stream;

 request.ContentType = "text/xml";

How do I add space between items in an ASP.NET RadioButtonList

<asp:RadioButtonList ID="rbn" runat="server" RepeatLayout="Table" RepeatColumns="2"
                        Width="100%" >
                        <asp:ListItem Text="1"></asp:ListItem>
                        <asp:ListItem Text="2"></asp:ListItem>
                        <asp:ListItem Text="3"></asp:ListItem>
                        <asp:ListItem Text="4"></asp:ListItem>
                    </asp:RadioButtonList>

IIS: Where can I find the IIS logs?

I think the Default place for IIS logging is: c:\inetpub\wwwroot\log\w3svc

Chart.js v2 - hiding grid lines

OK, nevermind.. I found the trick:

    scales: {
      yAxes: [
        {
          gridLines: {
                lineWidth: 0
            }
        }
      ]
    }

How to replace a hash key with another key

For Ruby 2.5 or newer with transform_keys and delete_prefix / delete_suffix methods:

hash1 = { '_id' => 'random1' }
hash2 = { 'old_first' => '123456', 'old_second' => '234567' }
hash3 = { 'first_com' => 'google.com', 'second_com' => 'amazon.com' }

hash1.transform_keys { |key| key.delete_prefix('_') }
# => {"id"=>"random1"}
hash2.transform_keys { |key| key.delete_prefix('old_') }
# => {"first"=>"123456", "second"=>"234567"}
hash3.transform_keys { |key| key.delete_suffix('_com') }
# => {"first"=>"google.com", "second"=>"amazon.com"}

filename and line number of Python script

Whether you use currentframe().f_back depends on whether you are using a function or not.

Calling inspect directly:

from inspect import currentframe, getframeinfo

cf = currentframe()
filename = getframeinfo(cf).filename

print "This is line 5, python says line ", cf.f_lineno 
print "The filename is ", filename

Calling a function that does it for you:

from inspect import currentframe

def get_linenumber():
    cf = currentframe()
    return cf.f_back.f_lineno

print "This is line 7, python says line ", get_linenumber()

RESTful Authentication

It's certainly not about "session keys" as it is generally used to refer to sessionless authentication which is performed within all of the constraints of REST. Each request is self-describing, carrying enough information to authorize the request on its own without any server-side application state.

The easiest way to approach this is by starting with HTTP's built-in authentication mechanisms in RFC 2617.

What is the use of adding a null key or value to a HashMap in Java?

I'm not positive what you're asking, but if you're looking for an example of when one would want to use a null key, I use them often in maps to represent the default case (i.e. the value that should be used if a given key isn't present):

Map<A, B> foo;
A search;
B val = foo.containsKey(search) ? foo.get(search) : foo.get(null);

HashMap handles null keys specially (since it can't call .hashCode() on a null object), but null values aren't anything special, they're stored in the map like anything else

Cannot connect to the Docker daemon on macOS

On macOS the docker binary is only a client and you cannot use it to run the docker daemon, because Docker daemon uses Linux-specific kernel features, therefore you can’t run Docker natively in OS X. So you have to install docker-machine in order to create VM and attach to it.

Install docker-machine on macOS

If you don't have docker-machine command yet, install it by using one of the following methods:

  • Using Brew command: brew install docker-machine docker.
  • Manually from Releases page:

    $ curl -L https://github.com/docker/machine/releases/download/v0.16.1/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine
    $ chmod +x /usr/local/bin/docker-machine
    

See: Get started with Docker for Mac.

Install Virtualbox

docker-machine relies on VirtualBox being installed and will fail if this isn't the case. If you already have VirtualBox, you can skip this step.

  • Using Homebrew: brew cask install virtualbox
  • Manually using the releases on Virtualbox.org

You will need to actively accept loading the Virtualbox kernel extension in the OS X Security panel and then proceed to restart the machine for the next commands not to fail with Error: VBoxNetAdpCtl: Error while adding new interface

Configure docker-machine on macOS

Create a default machine (if you don't have one, see: docker-machine ls):

docker-machine create --driver virtualbox default

Then set-up the environment for the Docker client:

eval "$(docker-machine env default)"

Then double-check by listing containers:

docker ps

See: Get started with Docker Machine and a local VM.


Related:

How do you extract IP addresses from files using a regex in a linux shell?

You can use sed. But if you know perl, that might be easier, and more useful to know in the long run:

perl -n '/(\d+\.\d+\.\d+\.\d+)/ && print "$1\n"' < file

Javascript to set hidden form value on drop down change

If you have HTML like this, for example:

<select id='myselect'>
    <option value='1'>A</option>
    <option value='2'>B</option>
    <option value='3'>C</option>
    <option value='4'>D</option>
</select>
<input type='hidden' id='myhidden' value=''>

All you have to do is bind a function to the change event of the select, and do what you need there:

<script type='text/javascript'>
$(function() {
    $('#myselect').change(function() {
        // if changed to, for example, the last option, then
        // $(this).find('option:selected').text() == D
        // $(this).val() == 4
        // get whatever value you want into a variable
        var x = $(this).val();
        // and update the hidden input's value
        $('#myhidden').val(x);
    });
});
</script>

All things considered, if you're going to be doing a lot of jQuery programming, always have the documentation open. It is very easy to find what you need there if you give it a chance.

How to format date and time in Android?

The android Time class provides 3 formatting methods http://developer.android.com/reference/android/text/format/Time.html

This is how I did it:

/**
* This method will format the data from the android Time class (eg. myTime.setToNow())   into the format
* Date: dd.mm.yy Time: hh.mm.ss
*/
private String formatTime(String time)
{
    String fullTime= "";
    String[] sa = new String[2];

    if(time.length()>1)
    {
        Time t = new Time(Time.getCurrentTimezone());
        t.parse(time);
        // or t.setToNow();
        String formattedTime = t.format("%d.%m.%Y %H.%M.%S");
        int x = 0;

        for(String s : formattedTime.split("\\s",2))
        {   
            System.out.println("Value = " + s);
            sa[x] = s;
            x++;
        }
        fullTime = "Date: " + sa[0] + " Time: " + sa[1];
    }
    else{
        fullTime = "No time data";
    }
    return fullTime;
}

I hope thats helpful :-)

Android device is not connected to USB for debugging (Android studio)

I have a Samsung Galaxy S4. Although visible from Devices, my phone was not listed as connected from Android Studio. I tried a few things independently, and then together, and found that only a combination of steps fixed the issue, so this is for you if measures listed above or on another site did not work on their own.

  1. Enable USB debugging from "Developer Options"
  2. Download Kies from Samsung. I believe Samsung US has replaced Kies with a new software called Smart Switch, but this did not resolve anything for me. I found a Samsung UK download of Kies that worked fine.
  3. After connecting your phone to your PC via USB, go to your phone notifications and click on USB settings at the top. Switch it to Camera mode.

I repeat, only all 3 of these together fixed the issue, so if some fixes you have tried haven't worked, use these 3 and it could fix the problem for you. Best of luck.

In which case do you use the JPA @JoinTable annotation?

EDIT 2017-04-29: As pointed to by some of the commenters, the JoinTable example does not need the mappedBy annotation attribute. In fact, recent versions of Hibernate refuse to start up by printing the following error:

org.hibernate.AnnotationException: 
   Associations marked as mappedBy must not define database mappings 
   like @JoinTable or @JoinColumn

Let's pretend that you have an entity named Project and another entity named Task and each project can have many tasks.

You can design the database schema for this scenario in two ways.

The first solution is to create a table named Project and another table named Task and add a foreign key column to the task table named project_id:

Project      Task
-------      ----
id           id
name         name
             project_id

This way, it will be possible to determine the project for each row in the task table. If you use this approach, in your entity classes you won't need a join table:

@Entity
public class Project {

   @OneToMany(mappedBy = "project")
   private Collection<Task> tasks;

}

@Entity
public class Task {

   @ManyToOne
   private Project project;

}

The other solution is to use a third table, e.g. Project_Tasks, and store the relationship between projects and tasks in that table:

Project      Task      Project_Tasks
-------      ----      -------------
id           id        project_id
name         name      task_id

The Project_Tasks table is called a "Join Table". To implement this second solution in JPA you need to use the @JoinTable annotation. For example, in order to implement a uni-directional one-to-many association, we can define our entities as such:

Project entity:

@Entity
public class Project {

    @Id
    @GeneratedValue
    private Long pid;

    private String name;

    @JoinTable
    @OneToMany
    private List<Task> tasks;

    public Long getPid() {
        return pid;
    }

    public void setPid(Long pid) {
        this.pid = pid;
    }

    public String getName() {
        return name;
    }

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

    public List<Task> getTasks() {
        return tasks;
    }

    public void setTasks(List<Task> tasks) {
        this.tasks = tasks;
    }
}

Task entity:

@Entity
public class Task {

    @Id
    @GeneratedValue
    private Long tid;

    private String name;

    public Long getTid() {
        return tid;
    }

    public void setTid(Long tid) {
        this.tid = tid;
    }

    public String getName() {
        return name;
    }

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

}

This will create the following database structure:

ER Diagram 1

The @JoinTable annotation also lets you customize various aspects of the join table. For example, had we annotated the tasks property like this:

@JoinTable(
        name = "MY_JT",
        joinColumns = @JoinColumn(
                name = "PROJ_ID",
                referencedColumnName = "PID"
        ),
        inverseJoinColumns = @JoinColumn(
                name = "TASK_ID",
                referencedColumnName = "TID"
        )
)
@OneToMany
private List<Task> tasks;

The resulting database would have become:

ER Diagram 2

Finally, if you want to create a schema for a many-to-many association, using a join table is the only available solution.

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

If your problem is like the following while using Google Chrome:

[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]

Then create a batch file by following these steps:

Open notepad in Desktop.

  1. Just copy and paste the followings in your currently opened notepad file:

start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit

  1. Note: In the previous line, Replace the full absolute address with your location of chrome installation. [To find it...Right click your short cut of chrome.exe link or icon and Click on Properties and copy-paste the target link][Remember : start to files in one line, & exit in another line by pressing enter]
  2. Save the file as fileName.bat [Very important: .bat]
  3. If you want to change the file later then right-click on the .bat file and click on edit. After modifying, save the file.

This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.

Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.

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

Unexpected end of file means that something else was expected before the PHP parser reached the end of the script.

Judging from your HUGE file, it's probably that you're missing a closing brace (}) from an if statement.

Please at least attempt the following things:

  1. Separate your code from your view logic.
  2. Be consistent, you're using an end ; in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?> vs <?php echo $this->layouts->print_includes() ?>. It's not required, so don't use it (or do, just do one or the other).
  3. Repeated because it's important, separate your concerns. There's no need for all of this code.
  4. Use an IDE, it will help you with errors such as this going forward.

Why is my toFixed() function not working?

You're not assigning the parsed float back to your value var:

value = parseFloat(value).toFixed(2);

should fix things up.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

Adding simple CRUD example with Arrowfunction

 //Arrow Function
 var customers   = [
   {
     name: 'Dave',
     contact:'9192631770'
   },
   {
     name: 'Sarah',
     contact:'9192631770'
   },
   {
     name: 'Akhil',
     contact:'9928462656' 
   }],

// No Param READ
 getFirstCustomer = () => { 
   console.log(this);
   return customers[0];
 };
  console.log("First Customer "+JSON.stringify(getFirstCustomer())); // 'Dave' 

   //1 Param SEARCH
  getNthCustomer = index=>{
    if( index>customers.length)
    {
     return  "No such thing";
   }
   else{
       return customers[index];
     } 
  };
  console.log("Nth Customer is " +JSON.stringify(getNthCustomer(1))); 

   //2params ADD
  addCustomer = (name, contact)=> customers.push({
     'name': name,
     'contact':contact
    });
  addCustomer('Hitesh','8888813275');
  console.log("Added Customer "+JSON.stringify(customers)); 

  //2 param UPDATE
  updateCustomerName = (index, newName)=>{customers[index].name= newName};
  updateCustomerName(customers.length-1,"HiteshSahu");
  console.log("Updated Customer "+JSON.stringify(customers));

  //1 param DELETE
  removeCustomer = (customerToRemove) => customers.pop(customerToRemove);
  removeCustomer(getFirstCustomer());
  console.log("Removed Customer "+JSON.stringify(customers)); 

Concatenate multiple files but include filename as section headers

I like this option

for x in $(ls ./*.php); do echo $x; cat $x | grep -i 'menuItem'; done

Output looks like this:

./debug-things.php
./Facebook.Pixel.Code.php
./footer.trusted.seller.items.php
./GoogleAnalytics.php
./JivositeCode.php
./Live-Messenger.php
./mPopex.php
./NOTIFICATIONS-box.php
./reviewPopUp_Frame.php
            $('#top-nav-scroller-pos-<?=$active**MenuItem**;?>').addClass('active');
            gotTo**MenuItem**();
./Reviews-Frames-PopUps.php
./social.media.login.btns.php
./social-side-bar.php
./staticWalletsAlerst.php
./tmp-fix.php
./top-nav-scroller.php
$active**MenuItem** = '0';
        $active**MenuItem** = '1';
        $active**MenuItem** = '2';
        $active**MenuItem** = '3';
./Waiting-Overlay.php
./Yandex.Metrika.php

split string in two on given index and return both parts

You can also do it like this.
https://jsfiddle.net/Devashish2910/8hbosLj3/1/#&togetherjs=iugeGcColp

var str, result;
str = prompt("Enter Any Number");

var valueSplit = function (value, length) {
    if (length < 7) {
        var index = length - 3;
        return str.slice(0, index) + ',' + str.slice(index);
    }
    else if (length < 10 && length > 6) {
        var index1, index2;
        index1 = length - 6;
        index2 = length - 3;
        return str.slice(0,index1) + "," + str.slice(index1,index2) + "," + str.slice(index2);
    }
}

result = valueSplit(str, str.length);
alert(result);

Javascript split regex question

try this instead

date.split(/\W+/)

In Python, how do I determine if an object is iterable?

Not really "correct" but can serve as quick check of most common types like strings, tuples, floats, etc...

>>> '__iter__' in dir('sds')
True
>>> '__iter__' in dir(56)
False
>>> '__iter__' in dir([5,6,9,8])
True
>>> '__iter__' in dir({'jh':'ff'})
True
>>> '__iter__' in dir({'jh'})
True
>>> '__iter__' in dir(56.9865)
False

Multiple inheritance for an anonymous class

Anonymous classes always extend superclass or implements interfaces. for example:

button.addActionListener(new ActionListener(){ // ActionListener is an interface
    public void actionPerformed(ActionEvent e){
    }
});

Moreover, although anonymous class cannot implement multiple interfaces, you can create an interface that extends other interface and let your anonymous class to implement it.

Creating a div element inside a div element in javascript

Your code works well you just mistyped this line of code:

document.getElementbyId('lc').appendChild(element);

change it with this: (The "B" should be capitalized.)

document.getElementById('lc').appendChild(element);  

HERE IS MY EXAMPLE:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<script>_x000D_
_x000D_
function test() {_x000D_
_x000D_
    var element = document.createElement("div");_x000D_
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
    document.getElementById('lc').appendChild(element);_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
_x000D_
<div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
}" onclick="test();">  _x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Right way to reverse a pandas DataFrame?

None of the existing answers resets the index after reversing the dataframe.

For this, do the following:

 data[::-1].reset_index()

Here's a utility function that also removes the old index column, as per @Tim's comment:

def reset_my_index(df):
  res = df[::-1].reset_index(drop=True)
  return(res)

Simply pass your dataframe into the function

Good Linux (Ubuntu) SVN client

Take a look at SVN Work Bench, it's decent but not perfect

sudo apt-get install svn-workbench

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

A weird thing I found was that the environment variable SYSTEMROOT must be set otherwise getaddrinfo() will fail on Windows 10.

Pandas aggregate count distinct

'nunique' is an option for .agg() since pandas 0.20.0, so:

df.groupby('date').agg({'duration': 'sum', 'user_id': 'nunique'})

Is multiplication and division using shift operators in C actually faster?

Shift and integer multiply instructions have similar performance on most modern CPUs - integer multiply instructions were relatively slow back in the 1980s but in general this is no longer true. Integer multiply instructions may have higher latency, so there may still be cases where a shift is preferable. Ditto for cases where you can keep more execution units busy (although this can cut both ways).

Integer division is still relatively slow though, so using a shift instead of division by a power of 2 is still a win, and most compilers will implement this as an optimisation. Note however that for this optimisation to be valid the dividend needs to be either unsigned or must be known to be positive. For a negative dividend the shift and divide are not equivalent!

#include <stdio.h>

int main(void)
{
    int i;

    for (i = 5; i >= -5; --i)
    {
        printf("%d / 2 = %d, %d >> 1 = %d\n", i, i / 2, i, i >> 1);
    }
    return 0;
}

Output:

5 / 2 = 2, 5 >> 1 = 2
4 / 2 = 2, 4 >> 1 = 2
3 / 2 = 1, 3 >> 1 = 1
2 / 2 = 1, 2 >> 1 = 1
1 / 2 = 0, 1 >> 1 = 0
0 / 2 = 0, 0 >> 1 = 0
-1 / 2 = 0, -1 >> 1 = -1
-2 / 2 = -1, -2 >> 1 = -1
-3 / 2 = -1, -3 >> 1 = -2
-4 / 2 = -2, -4 >> 1 = -2
-5 / 2 = -2, -5 >> 1 = -3

So if you want to help the compiler then make sure the variable or expression in the dividend is explicitly unsigned.

Can you hide the controls of a YouTube embed without enabling autoplay?

Follow this https://developers.google.com/youtube/player_parameters for more info about video controls like:

<iframe id="video_iframe" width="660" height="415" src="http://www.youtube.com/v/{{course_url}}?start=7&autoplay=0&showinfo=0&iv_load_policy=3&rel=0"
                frameborder="0"
                allowfullscreen></iframe>

start=7&autoplay=0&showinfo=0&iv_load_policy=3&rel=0" frameborder="0"

all controls are described in there

-didSelectRowAtIndexPath: not being called

In my case the problem was I had a UITableViewCell subclass and I'd implemented these two methods: touchesBegan:withEvent: & touchesEnded:withEvent to handle a fancy animation on touch. But I'd forgotten to add the [super touchesBegan:touches withEvent:event]; method ad [super touchesEnded:touches withEvent:event]; to also inform the parent of cell of the touch.

So changing the code to following solved my problem:

-(void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{
    [super touchesBegan:touches withEvent:event];
    //blah blah blah
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    //rest of the code
}

extract date only from given timestamp in oracle sql

This format worked for me, for the mentioned date format i.e. MM/DD/YYYY

SELECT to_char(query_date,'MM/DD/YYYY') as query_date 
FROM QMS_INVOICE_TABLE;

Convert an NSURL to an NSString

In Swift :- var str_url = yourUrl.absoluteString

It will result a url in string.

Android: show/hide a view using an animation

Set the attribute android:animateLayoutChanges="true" inside the parent layout .

Put the view in a layout if its not and set android:animateLayoutChanges="true" for that layout.

NOTE: This works only from API Level 11+ (Android 3.0)

Android: Cancel Async Task

I would like to improve the code. When you canel the aSyncTask the onCancelled() (callback method of aSyncTask) gets automatically called, and there you can hide your progressBarDialog.

You can include this code as well:

public class information extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... arg0) {
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            this.cancel(true);
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onCancelled() {
            Toast.makeText(getApplicationContext(), "asynctack cancelled.....", Toast.LENGTH_SHORT).show();
            dialog.hide(); /*hide the progressbar dialog here...*/
            super.onCancelled();
        }

    }

How can I put a ListView into a ScrollView without it collapsing?

You should not put a ListView in a ScrollView because a ListView already is a ScrollView. So that would be like putting a ScrollView in a ScrollView.

What are you trying to accomplish?

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

How to Call a JS function using OnClick event

I removed your document.getElementById("Save").onclick = before your functions, because it's an event already being called on your button. I also had to call the two functions separately by the onclick event.

     <!DOCTYPE html>
      <html>
      <head>
      <script>
       function fun()
        {
         alert("hello");
         //validation code to see State field is mandatory.  
        }   
        function f1()
        {
          alert("f1 called");
           //form validation that recalls the page showing with supplied inputs.    
        }
      </script>
      </head>
      <body>
      <form name="form1" id="form1" method="post">
                State: 
                <select id="state ID">
                   <option></option>
                   <option value="ap">ap</option>
                   <option value="bp">bp</option>
                </select>
       </form>

       <table><tr><td id="Save" onclick="f1(); fun();">click</td></tr></table>

   </body>
   </html>

Maximum number of rows of CSV data in excel sheet

In my memory, excel (versions >= 2007) limits the power 2 of 20: 1.048.576 lines.

Csv is over to this boundary, like ordinary text file. So you will be care of the transfer between two formats.

How to clear memory to prevent "out of memory error" in excel vba?

I've found a workaround. At first it seemed it would take up more time, but it actually makes everything work smoother and faster due to less swapping and more memory available. This is not a scientific approach and it needs some testing before it works.

In the code, make Excel save the workbook every now and then. I had to loop through a sheet with 360 000 lines and it choked badly. After every 10 000 I made the code save the workbook and now it works like a charm even on a 32-bit Excel.

If you start Task Manager at the same time you can see the memory utilization go down drastically after each save.

Div Scrollbar - Any way to style it?

Using javascript you can style the scroll bars. Which works fine in IE as well as FF.

Check the below links

From Twinhelix , Example 2 , Example 3 [or] you can find some 30 type of scroll style types by click the below link 30 scrolling techniques

How do you unit test private methods?

MS Test has a nice feature built in that makes private members and methods available in the project by creating a file called VSCodeGenAccessors

[System.Diagnostics.DebuggerStepThrough()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
    internal class BaseAccessor
    {

        protected Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject m_privateObject;

        protected BaseAccessor(object target, Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType type)
        {
            m_privateObject = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject(target, type);
        }

        protected BaseAccessor(Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType type)
            :
                this(null, type)
        {
        }

        internal virtual object Target
        {
            get
            {
                return m_privateObject.Target;
            }
        }

        public override string ToString()
        {
            return this.Target.ToString();
        }

        public override bool Equals(object obj)
        {
            if (typeof(BaseAccessor).IsInstanceOfType(obj))
            {
                obj = ((BaseAccessor)(obj)).Target;
            }
            return this.Target.Equals(obj);
        }

        public override int GetHashCode()
        {
            return this.Target.GetHashCode();
        }
    }

With classes that derive from BaseAccessor

such as

[System.Diagnostics.DebuggerStepThrough()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
internal class SomeClassAccessor : BaseAccessor
{

    protected static Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType m_privateType = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType(typeof(global::Namespace.SomeClass));

    internal SomeClassAccessor(global::Namespace.Someclass target)
        : base(target, m_privateType)
    {
    }

    internal static string STATIC_STRING
    {
        get
        {
            string ret = ((string)(m_privateType.GetStaticField("STATIC_STRING")));
            return ret;
        }
        set
        {
            m_privateType.SetStaticField("STATIC_STRING", value);
        }
    }

    internal int memberVar    {
        get
        {
            int ret = ((int)(m_privateObject.GetField("memberVar")));
            return ret;
        }
        set
        {
            m_privateObject.SetField("memberVar", value);
        }
    }

    internal int PrivateMethodName(int paramName)
    {
        object[] args = new object[] {
            paramName};
        int ret = (int)(m_privateObject.Invoke("PrivateMethodName", new System.Type[] {
                typeof(int)}, args)));
        return ret;
    }

Calculating sum of repeated elements in AngularJS ng-repeat

This is a simple way to do this with ng-repeat and ng-init to aggregate all the values and extend the model with a item.total property.

<table>
<tr ng-repeat="item in items" ng-init="setTotals(item)">
                    <td>{{item.name}}</td>
                    <td>{{item.quantity}}</td>
                    <td>{{item.unitCost | number:2}}</td>
                    <td>{{item.total | number:2}}</td>
</tr>
<tr class="bg-warning">
                    <td>Totals</td>
                    <td>{{invoiceCount}}</td>
                    <td></td>                    
                    <td>{{invoiceTotal | number:2}}</td>
                </tr>
</table>

The ngInit directive calls the set total function for each item. The setTotals function in the controller calculates each item total. It also uses the invoiceCount and invoiceTotal scope variables to aggregate (sum) the quantity and total for all items.

$scope.setTotals = function(item){
        if (item){
            item.total = item.quantity * item.unitCost;
            $scope.invoiceCount += item.quantity;
            $scope.invoiceTotal += item.total;
        }
    }

for more information and demo look at this link:

http://www.ozkary.com/2015/06/angularjs-calculate-totals-using.html

SCRIPT5: Access is denied in IE9 on xmlhttprequest

  $.ajax({
        url: '//freegeoip.net/json/',
        type: 'POST',
        dataType: 'jsonp',
        success: function(location) {
            alert(location.ip);
        }
    });

This code will work https sites too

How do you get centered content using Twitter Bootstrap?

On my side I define new CSS styles ready to use and easy to remember:

.center { text-align: center;}
.left { text-align: left;}
.right { text-align: right;}
.justify { text-align: justify;}
.fleft { float: left;} /*-> similar to .pull-left already existing in bootstrap*/
.fright { float: right;}  /*-> similar to .pull-right already existing in bootstrap*/
.vab { vertical-align: bottom;}
.bold { font-weight: bold;}
.italic { font-style: italic;}

Is it a good idea? Is there any good practice for this?

Why can't I check if a 'DateTime' is 'Nothing'?

DateTime is a value type, which is why it can't be null. You can check for it to be equal to DateTime.MinValue, or you can use Nullable(Of DateTime) instead.

VB sometimes "helpfully" makes you think it's doing something it's not. When it lets you set a Date to Nothing, it's really setting it to some other value, maybe MinValue.

See this question for an extensive discussion of value types vs. reference types.

Check if a variable is a string in JavaScript

Best way:

var s = 'String';
var a = [1,2,3];
var o = {key: 'val'};

(s.constructor === String) && console.log('its a string');
(a.constructor === Array) && console.log('its an array');
(o.constructor === Object) && console.log('its an object');
(o.constructor === Number || s.constructor === Boolean) && console.log('this won\'t run');

Each of these has been constructed by its appropriate class function, like "new Object()" etc.

Also, Duck-Typing: "If it looks like a duck, walks like a duck, and smells like a duck - it must be an Array" Meaning, check its properties.

Hope this helps.

Edit; 12/05/2016

Remember, you can always use combinations of approaches too. Here's an example of using an inline map of actions with typeof:

var type = { 'number': Math.sqrt.bind(Math), ... }[ typeof datum ];

Here's a more 'real world' example of using inline-maps:

function is(datum) {
    var isnt = !{ null: true, undefined: true, '': true, false: false, 0: false }[ datum ];
    return !isnt;
}
console.log( is(0), is(false), is(undefined), ... );  // >> true true false

This function would use [ custom ] "type-casting" -- rather, "type-/-value-mapping" -- to figure out if a variable actually "exists". Now you can split that nasty hair between null & 0!

Many times you don't even care about its type. Another way to circumvent typing is combining Duck-Type sets:

this.id = "998";  // use a number or a string-equivalent
function get(id) {
    if (!id || !id.toString) return;
    if (id.toString() === this.id.toString()) http( id || +this.id );
    // if (+id === +this.id) ...;
}

Both Number.prototype and String.prototype have a .toString() method. You just made sure that the string-equivalent of the number was the same, and then you made sure that you passed it into the http function as a Number. In other words, we didn't even care what its type was.

Hope that gives you more to work with :)

Including .cpp files

When you say #include "foop.cpp", it is as if you had copied the entire contents of foop.cpp and pasted it into main.cpp.

So when you compile main.cpp, the compiler emits a main.obj that contains the executable code for two functions: main and foo.

When you compile foop.cpp itself, the compiler emits a foop.obj that contains the executable code for function foo.

When you link them together, the compiler sees two definitions for function foo (one from main.obj and the other from foop.obj) and complains that you have multiple definitions.

Calculate the mean by group

There are many ways to do this in R. Specifically, by, aggregate, split, and plyr, cast, tapply, data.table, dplyr, and so forth.

Broadly speaking, these problems are of the form split-apply-combine. Hadley Wickham has written a beautiful article that will give you deeper insight into the whole category of problems, and it is well worth reading. His plyr package implements the strategy for general data structures, and dplyr is a newer implementation performance tuned for data frames. They allow for solving problems of the same form but of even greater complexity than this one. They are well worth learning as a general tool for solving data manipulation problems.

Performance is an issue on very large datasets, and for that it is hard to beat solutions based on data.table. If you only deal with medium-sized datasets or smaller, however, taking the time to learn data.table is likely not worth the effort. dplyr can also be fast, so it is a good choice if you want to speed things up, but don't quite need the scalability of data.table.

Many of the other solutions below do not require any additional packages. Some of them are even fairly fast on medium-large datasets. Their primary disadvantage is either one of metaphor or of flexibility. By metaphor I mean that it is a tool designed for something else being coerced to solve this particular type of problem in a 'clever' way. By flexibility I mean they lack the ability to solve as wide a range of similar problems or to easily produce tidy output.


Examples

base functions

tapply:

tapply(df$speed, df$dive, mean)
#     dive1     dive2 
# 0.5419921 0.5103974

aggregate:

aggregate takes in data.frames, outputs data.frames, and uses a formula interface.

aggregate( speed ~ dive, df, mean )
#    dive     speed
# 1 dive1 0.5790946
# 2 dive2 0.4864489

by:

In its most user-friendly form, it takes in vectors and applies a function to them. However, its output is not in a very manipulable form.:

res.by <- by(df$speed, df$dive, mean)
res.by
# df$dive: dive1
# [1] 0.5790946
# ---------------------------------------
# df$dive: dive2
# [1] 0.4864489

To get around this, for simple uses of by the as.data.frame method in the taRifx library works:

library(taRifx)
as.data.frame(res.by)
#    IDX1     value
# 1 dive1 0.6736807
# 2 dive2 0.4051447

split:

As the name suggests, it performs only the "split" part of the split-apply-combine strategy. To make the rest work, I'll write a small function that uses sapply for apply-combine. sapply automatically simplifies the result as much as possible. In our case, that means a vector rather than a data.frame, since we've got only 1 dimension of results.

splitmean <- function(df) {
  s <- split( df, df$dive)
  sapply( s, function(x) mean(x$speed) )
}
splitmean(df)
#     dive1     dive2 
# 0.5790946 0.4864489 

External packages

data.table:

library(data.table)
setDT(df)[ , .(mean_speed = mean(speed)), by = dive]
#    dive mean_speed
# 1: dive1  0.5419921
# 2: dive2  0.5103974

dplyr:

library(dplyr)
group_by(df, dive) %>% summarize(m = mean(speed))

plyr (the pre-cursor of dplyr)

Here's what the official page has to say about plyr:

It’s already possible to do this with base R functions (like split and the apply family of functions), but plyr makes it all a bit easier with:

  • totally consistent names, arguments and outputs
  • convenient parallelisation through the foreach package
  • input from and output to data.frames, matrices and lists
  • progress bars to keep track of long running operations
  • built-in error recovery, and informative error messages
  • labels that are maintained across all transformations

In other words, if you learn one tool for split-apply-combine manipulation it should be plyr.

library(plyr)
res.plyr <- ddply( df, .(dive), function(x) mean(x$speed) )
res.plyr
#    dive        V1
# 1 dive1 0.5790946
# 2 dive2 0.4864489

reshape2:

The reshape2 library is not designed with split-apply-combine as its primary focus. Instead, it uses a two-part melt/cast strategy to perform a wide variety of data reshaping tasks. However, since it allows an aggregation function it can be used for this problem. It would not be my first choice for split-apply-combine operations, but its reshaping capabilities are powerful and thus you should learn this package as well.

library(reshape2)
dcast( melt(df), variable ~ dive, mean)
# Using dive as id variables
#   variable     dive1     dive2
# 1    speed 0.5790946 0.4864489

Benchmarks

10 rows, 2 groups

library(microbenchmark)
m1 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[, mean(speed), by = dive],
  summarize( group_by(df, dive), m = mean(speed) ),
  summarize( group_by(dt, dive), m = mean(speed) )
)

> print(m1, signif = 3)
Unit: microseconds
                                           expr  min   lq   mean median   uq  max neval      cld
                    by(df$speed, df$dive, mean)  302  325  343.9    342  362  396   100  b      
              aggregate(speed ~ dive, df, mean)  904  966 1012.1   1020 1060 1130   100     e   
                                  splitmean(df)  191  206  249.9    220  232 1670   100 a       
  ddply(df, .(dive), function(x) mean(x$speed)) 1220 1310 1358.1   1340 1380 2740   100      f  
         dcast(melt(df), variable ~ dive, mean) 2150 2330 2440.7   2430 2490 4010   100        h
                   dt[, mean(speed), by = dive]  599  629  667.1    659  704  771   100   c     
 summarize(group_by(df, dive), m = mean(speed))  663  710  774.6    744  782 2140   100    d    
 summarize(group_by(dt, dive), m = mean(speed)) 1860 1960 2051.0   2020 2090 3430   100       g 

autoplot(m1)

benchmark 10 rows

As usual, data.table has a little more overhead so comes in about average for small datasets. These are microseconds, though, so the differences are trivial. Any of the approaches works fine here, and you should choose based on:

  • What you're already familiar with or want to be familiar with (plyr is always worth learning for its flexibility; data.table is worth learning if you plan to analyze huge datasets; by and aggregate and split are all base R functions and thus universally available)
  • What output it returns (numeric, data.frame, or data.table -- the latter of which inherits from data.frame)

10 million rows, 10 groups

But what if we have a big dataset? Let's try 10^7 rows split over ten groups.

df <- data.frame(dive=factor(sample(letters[1:10],10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

m2 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[,mean(speed),by=dive],
  times=2
)

> print(m2, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval      cld
                    by(df$speed, df$dive, mean)   720   770   799.1    791   816   958   100    d    
              aggregate(speed ~ dive, df, mean) 10900 11000 11027.0  11000 11100 11300   100        h
                                  splitmean(df)   974  1040  1074.1   1060  1100  1280   100     e   
  ddply(df, .(dive), function(x) mean(x$speed))  1050  1080  1110.4   1100  1130  1260   100      f  
         dcast(melt(df), variable ~ dive, mean)  2360  2450  2492.8   2490  2520  2620   100       g 
                   dt[, mean(speed), by = dive]   119   120   126.2    120   122   212   100 a       
 summarize(group_by(df, dive), m = mean(speed))   517   521   531.0    522   532   620   100   c     
 summarize(group_by(dt, dive), m = mean(speed))   154   155   174.0    156   189   321   100  b      

autoplot(m2)

benchmark 1e7 rows, 10 groups

Then data.table or dplyr using operating on data.tables is clearly the way to go. Certain approaches (aggregate and dcast) are beginning to look very slow.

10 million rows, 1,000 groups

If you have more groups, the difference becomes more pronounced. With 1,000 groups and the same 10^7 rows:

df <- data.frame(dive=factor(sample(seq(1000),10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

# then run the same microbenchmark as above
print(m3, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval    cld
                    by(df$speed, df$dive, mean)   776   791   816.2    810   828   925   100  b    
              aggregate(speed ~ dive, df, mean) 11200 11400 11460.2  11400 11500 12000   100      f
                                  splitmean(df)  5940  6450  7562.4   7470  8370 11200   100     e 
  ddply(df, .(dive), function(x) mean(x$speed))  1220  1250  1279.1   1280  1300  1440   100   c   
         dcast(melt(df), variable ~ dive, mean)  2110  2190  2267.8   2250  2290  2750   100    d  
                   dt[, mean(speed), by = dive]   110   111   113.5    111   113   143   100 a     
 summarize(group_by(df, dive), m = mean(speed))   625   630   637.1    633   644   701   100  b    
 summarize(group_by(dt, dive), m = mean(speed))   129   130   137.3    131   142   213   100 a     

autoplot(m3)

enter image description here

So data.table continues scaling well, and dplyr operating on a data.table also works well, with dplyr on data.frame close to an order of magnitude slower. The split/sapply strategy seems to scale poorly in the number of groups (meaning the split() is likely slow and the sapply is fast). by continues to be relatively efficient--at 5 seconds, it's definitely noticeable to the user but for a dataset this large still not unreasonable. Still, if you're routinely working with datasets of this size, data.table is clearly the way to go - 100% data.table for the best performance or dplyr with dplyr using data.table as a viable alternative.

What is the difference between Serialization and Marshaling?

My vies is:

Problem: Object belongs to some process(VM) and it's lifetime is the same

Serialisation - transform object state into stream of bytes(JSON, XML...) for saving, sharing, transforming...

Marshalling - contains Serialisation + codebase. Usually it used by Remote procedure call(RPC) -> Java Remote Method Invocation(Java RMI) where you are able to invoke a object's method which is hosted on remote Java processes.

codebase - is a place or URL to class definition where it can be downloaded by ClassLoader. CLASSPATH[About] is as a local codebase

JVM -> Class Loader -> load class definition -> class

Very simple diagram for RMI

Serialisation - state
Marshalling - state + class definition

Official doc

Write to text file without overwriting in Java

You can even use FileOutputStream to get what you need. This is how it can be done,

File file = new File(Environment.getExternalStorageDirectory(), "abc.txt");
FileOutputStream fOut = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("whatever you need to write");
osw.flush();
osw.close();

Conda command is not recognized on Windows 10

You need to add the python.exe in C://.../Anaconda3 installation file as well as C://.../Anaconda3/Scripts to PATH.

First go to your installation directory, in my case it is installed in C://Users/user/Anaconda3 and shift+right click and press "Open command window here" or it might be "Open powershell here", if it is powershell, just write cmd and hit enter to run command window. Then run the following command setx PATH %cd%

Then go to C://Users/user/Anaconda3/Scripts and open the command window there as above, then run the same command "setx PATH %cd%"

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

EDIT (after comment): the below will solve the coding issue, but is highly not recommended to use this approach because a linear regression model is a very poor classifier, which will very likely not separate the classes correctly.

Read the well written answer below by @desertnaut, explaining why this error is an hint of something wrong in the machine learning approach rather than something you have to 'fix'.

accuracy_score(y_true, y_pred.round(), normalize=False)

Java generics: multiple generic parameters?

You can declare multiple type variables on a type or method. For example, using type parameters on the method:

<P, Q> int f(Set<P>, Set<Q>) {
  return 0;
}

EditText, inputType values (xml)

android:inputMethod

is deprecated, instead use inputType :

 android:inputType="numberPassword"

HttpServletRequest - Get query string parameters, no form data

Java 8

return Collections.list(httpServletRequest.getParameterNames())
                  .stream()
                  .collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));

How to Deserialize XML document

How about you just save the xml to a file, and use xsd to generate C# classes?

  1. Write the file to disk (I named it foo.xml)
  2. Generate the xsd: xsd foo.xml
  3. Generate the C#: xsd foo.xsd /classes

Et voila - and C# code file that should be able to read the data via XmlSerializer:

    XmlSerializer ser = new XmlSerializer(typeof(Cars));
    Cars cars;
    using (XmlReader reader = XmlReader.Create(path))
    {
        cars = (Cars) ser.Deserialize(reader);
    }

(include the generated foo.cs in the project)

Changing capitalization of filenames in Git

Set ignorecase to false in git config

As the original post is about "Changing capitalization of filenames in Git":

If you are trying to change capitalisation of a filename in your project, you do not need to force rename it from Git. IMO, I would rather change the capitalisation from my IDE/editor and make sure that I configure Git properly to pick up the renaming.

By default, a Git template is set to ignore case (Git case insensitive). To verify you have the default template, use --get to retrieve the value for a specified key. Use --local and --global to indicate to Git whether to pick up a configuration key-value from your local Git repository configuration or global one. As an example, if you want to lookup your global key core.ignorecase:

git config --global --get core.ignorecase

If this returns true, make sure to set it as:

git config --global core.ignorecase false

(Make sure you have proper permissions to change global.) And there you have it; now your Git installation would not ignore capitalisations and treat them as changes.

As a suggestion, if you are working on multi-language projects and you feel not all projects should be treated as case-sensitive by Git, just update the local core.ignorecase file.

Using CSS to insert text

The answer using jQuery that everyone seems to like has a major flaw, which is it is not scalable (at least as it is written). I think Martin Hansen has the right idea, which is to use HTML5 data-* attributes. And you can even use the apostrophe correctly:

html:

<div class="task" data-task-owner="Joe">mop kitchen</div>
<div class="task" data-task-owner="Charles" data-apos="1">vacuum hallway</div>

css:

div.task:before { content: attr(data-task-owner)"'s task - " ; }
div.task[data-apos]:before { content: attr(data-task-owner)"' task - " ; }

output:

Joe's task - mop kitchen
Charles' task - vacuum hallway

Is there any boolean type in Oracle databases?

Nope.

Can use:

IS_COOL NUMBER(1,0)

1 - true
0 - false

--- enjoy Oracle

Or use char Y/N as described here

"Cloning" row or column vectors

Use numpy.tile:

>>> tile(array([1,2,3]), (3, 1))
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

or for repeating columns:

>>> tile(array([[1,2,3]]).transpose(), (1, 3))
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

Using pip behind a proxy with CNTLM

Open the Windows command prompt.

Set proxy environment variables.

set http_proxy=http://user:password@proxy_ip:port
set https_proxy=https://user:password@proxy_ip:port

Install Python packages using proxy in the same Windows command prompt.

pip install --proxy="user:password@proxy_ip:port" package_name

iptables LOG and DROP in one rule

for china GFW:

sudo iptables -I INPUT -s 173.194.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 173.194.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"

sudo iptables -I INPUT -s 64.233.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 64.233.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"

sudo iptables -I INPUT -s 74.125.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 74.125.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"

Best way to check if MySQL results returned in PHP?

Whenever we do queries to get some data, it is returned as an object. Then most of us convert it to array for looping through the rows easily. In php "empty()" function is used to check if an array is empty i.e. if it has no data in it. So we can check if returned array representation of query isn't empty by doing like this

if(!empty($result)){
           //DO STUFF
}

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

$date = new DateTime($_POST['date']);
$endDate = date_add(new DateTime($_POST['date']),date_interval_create_from_date_string("7 days"));

while ($date <= $endDate) {
    print date_format($date,'d-m-Y')." AND END DATE IS : ".date_format($endDate,'d-m-Y')."\n";
    date_add($date,date_interval_create_from_date_string("1 days"));
}

You can iterate like this also, The $_POST['date'] can be dent from your app or website Instead of $_POST['date'] you can also place your string here "21-12-2019". Both will work.

Is returning out of a switch statement considered a better practice than using break?

A break will allow you continue processing in the function. Just returning out of the switch is fine if that's all you want to do in the function.

Bash Script : what does #!/bin/bash mean?

When the first characters in a script are #!, that is called the shebang. If your file starts with #!/path/to/something the standard is to run something and pass the rest of the file to that program as an input.

With that said, the difference between #!/bin/bash, #!/bin/sh, or even #!/bin/zsh is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash and sh are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh is a link to dash, and on traditional Unix systems (Solaris, Irix, etc) bash is usually a completely different program from sh.

Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python, #!/usr/bin/perl, or even #!/usr/local/bin/my_own_scripting_language.

Mean filter for smoothing images in Matlab

I = imread('peppers.png');
H = fspecial('average', [5 5]);
I = imfilter(I, H);
imshow(I)

Note that filters can be applied to intensity images (2D matrices) using filter2, while on multi-dimensional images (RGB images or 3D matrices) imfilter is used.

Also on Intel processors, imfilter can use the Intel Integrated Performance Primitives (IPP) library to accelerate execution.

Logging request/response messages when using HttpClient

An example of how you could do this:

Some notes:

  • LoggingHandler intercepts the request before it handles it to HttpClientHandler which finally writes to the wire.

  • PostAsJsonAsync extension internally creates an ObjectContent and when ReadAsStringAsync() is called in the LoggingHandler, it causes the formatter inside ObjectContent to serialize the object and that's the reason you are seeing the content in json.

Logging handler:

public class LoggingHandler : DelegatingHandler
{
    public LoggingHandler(HttpMessageHandler innerHandler)
        : base(innerHandler)
    {
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        Console.WriteLine("Request:");
        Console.WriteLine(request.ToString());
        if (request.Content != null)
        {
            Console.WriteLine(await request.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

        Console.WriteLine("Response:");
        Console.WriteLine(response.ToString());
        if (response.Content != null)
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        return response;
    }
}

Chain the above LoggingHandler with HttpClient:

HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));
HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;

Output:

Request:
Method: POST, RequestUri: 'http://kirandesktop:9095/api/values', Version: 1.1, Content: System.Net.Http.ObjectContent`1[
[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:
{
  Content-Type: application/json; charset=utf-8
}
"Hello, World!"

Response:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date: Fri, 20 Sep 2013 20:21:26 GMT
  Server: Microsoft-HTTPAPI/2.0
  Content-Length: 15
  Content-Type: application/json; charset=utf-8
}
"Hello, World!"

How to convert an int value to string in Go?

You can use fmt.Sprintf or strconv.FormatFloat

For example

package main

import (
    "fmt"
)

func main() {
    val := 14.7
    s := fmt.Sprintf("%f", val)
    fmt.Println(s)
}

Python script to convert from UTF-8 to ASCII

import codecs

 ...

fichier = codecs.open(filePath, "r", encoding="utf-8")

 ...

fichierTemp = codecs.open("tempASCII", "w", encoding="ascii", errors="ignore")
fichierTemp.write(contentOfFile)

 ...

How to remove specific session in asp.net?

A single way to remove sessions is setting it to null;

Session["your_session"] = null;

What is the default username and password in Tomcat?

If your apache tomcat asking for password,then just follow these steps: go to the home directory of apache then go to webapps folder open the META-INF inside that you will find an xml file named context.xml--open it in edit mode

and REMOVE THE COMMENT FROM the VALVE tag.

After that you dont need any user name and password.

How to apply a CSS filter to a background image

pen

Abolishing the need for an extra element, along with making the content fit within the document flow rather than being fixed/absolute like other solutions.

Achieved using

_x000D_
_x000D_
.content {
  /* this is needed or the background will be offset by a few pixels at the top */
  overflow: auto;
  position: relative;
}

.content::before {
  content: "";
  position: fixed;
  left: 0;
  right: 0;
  z-index: -1;

  display: block;
  background-image: url('https://i.imgur.com/lL6tQfy.png');
  background-size:cover;
  width: 100%;
  height: 100%;

  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}
_x000D_
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
_x000D_
_x000D_
_x000D_

EDIT If you are interested in removing the white borders at the edges, use a width and height of 110% and a left and top of -5%. This will enlarge your backgrounds a tad - but there should be no solid colour bleeding in from the edges. Thanks Chad Fawcett for the suggestion.

_x000D_
_x000D_
.content {
  /* this is needed or the background will be offset by a few pixels at the top */
  overflow: auto;
  position: relative;
}

.content::before {
  content: "";
  position: fixed;
  top: -5%;
  left: -5%;
  right: -5%;
  z-index: -1;

  display: block;
  background-image: url('https://i.imgur.com/lL6tQfy.png');
  background-size:cover;
  width: 110%;
  height: 110%;

  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}
_x000D_
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
_x000D_
_x000D_
_x000D_

Matlab: Running an m-file from command-line

A command like this runs the m-file successfully:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m'); exit;"

How to get the selected date of a MonthCalendar control in C#

For those who are still trying, this link helped me out, too; it just puts it all together:

http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx

private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);

//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;

//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}

What is the proper way to check if a string is empty in Perl?

The very concept of a "proper" way to do anything, apart from using CPAN, is non existent in Perl.

Anyways those are numeric operators, you should use

if($foo eq "")

or

if(length($foo) == 0)

Centering image and text in R Markdown for a PDF report

If you know your format is PDF, then I don't see how the HTML tag can be useful... It definitely does not seem to work for me. The other pure LaTeX solutions obviously work just fine. But the whole point of Markdown is not to do LaTeX but to allow for multiple format compilation I believe, including HTML.

Therefore, with this in mind, what works for me is a variation of Nicolas Hamilton's answer to Color Text Stackoverflow question:

#############
## CENTER TXT
ctrFmt = function(x){
  if(out_type == 'latex' || out_type == 'beamer')
    paste0("\\begin{center}\n", x, "\n\\end{center}")
  else if(out_type == 'html')
    paste0("<center>\n", x, "\n</center>")
  else
    x
}

I put this inside my initial setup chunk. Then I use it very easily in my .rmd file:

`r ctrFmt("Centered text in html and pdf!")`

Convert Unix timestamp into human readable date using MySQL

What's missing from the other answers (as of this writing) and not directly obvious is that from_unixtime can take a second parameter to specify the format like so:

SELECT
  from_unixtime(timestamp, '%Y %D %M %H:%i:%s')
FROM 
  your_table

How to compile a c++ program in Linux?

Try this:

g++ -o hi hi.cpp

gcc is only for C

How to create a css rule for all elements except one class?

The safest bet is to create a class on those tables and use that. Currently getting something like this to work in all major browsers is unlikely.

UPDATE and REPLACE part of a string

you should use the below update query

UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id IN(1, 2, 3, 4)

UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id <= 4

Either of the above queries should work.

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

You edit an element's value by editing it's .value property.

document.getElementById('DATE').value = 'New Value';

How can I use Timer (formerly NSTimer) in Swift?

I tried to do in a NSObject Class and this worked for me:

DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) {  
print("Bang!") }

"git rebase origin" vs."git rebase origin/master"

git rebase origin means "rebase from the tracking branch of origin", while git rebase origin/master means "rebase from the branch master of origin"

You must have a tracking branch in ~/Desktop/test, which means that git rebase origin knows which branch of origin to rebase with. If no tracking branch exists (in the case of ~/Desktop/fallstudie), git doesn't know which branch of origin it must take, and fails.

To fix this, you can make the branch track origin/master with:

git branch --set-upstream-to=origin/master 

Or, if master isn't the currently checked-out branch:

git branch --set-upstream-to=origin/master master

select into in mysql

Use the CREATE TABLE SELECT syntax.

http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

CREATE TABLE new_tbl SELECT * FROM orig_tbl;

Switch between python 2.7 and python 3.5 on Mac OS X

Similar to John Wilkey's answer I would run python2 by finding which python, something like using /usr/bin/python and then creating an alias in .bash_profile:

alias python2="/usr/bin/python"

I can now run python3 by calling python and python2 by calling python2.

How to use systemctl in Ubuntu 14.04

So you want to remove dangling images? Am I correct?

systemctl enable docker-container-cleanup.timer
systemctl start docker-container-cleanup.timer
systemctl enable docker-image-cleanup.timer 
systemctl start docker-image-cleanup.timer

https://github.com/larsks/docker-tools/tree/master/docker-maintenance-units